Files
douyi_guaji_main/gui/components/wifi_adb_dialog.py
T
Your Name 60332db82b
Windows Package CI / package-fresh-install (push) Waiting to run
fix(gui): 保留 WiFi ADB 随机端口
2026-06-28 23:44:14 +08:00

518 lines
21 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""WiFi ADB 主设置对话框。
从 ``gui/gui_app.py`` 中抽出。原本是 ``main()`` 内的闭包 ``open_wifi_adb_dialog``,
通过 "WiFi ADB" 顶部按钮触发。
依赖通过显式参数注入:``parent`` (主窗口)、``adb_exe`` (ADB 可执行路径)、
``on_line`` (日志回调)、``refresh_devices`` (刷新主窗口设备下拉的回调)。
连接成功后会自递归打开新对话框以反映最新设备状态。
"""
from __future__ import annotations
import re
import threading
import tkinter as tk
from tkinter import ttk
from tkinter.constants import LEFT, W, X
from typing import Callable
from gui.dashboard_app import theme
from gui.dashboard_app.widgets import button, rounded_surface
from gui.gui_core import (
auto_connect_wifi_adb,
connect_wifi_adb,
disconnect_wifi_adb,
enable_wifi_adb,
get_connected_wifi_devices,
get_device_ip,
list_adb_devices,
)
from gui.gui_core_pkg import (
clear_last_wifi_target,
get_last_wifi_target,
set_last_wifi_target,
)
from gui.gui_core_pkg.wifi_adb_scan import query_device_model
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
TITLE_FONT = ("Microsoft YaHei UI", 20, "bold")
SUBTITLE_FONT = ("Microsoft YaHei UI", 12)
LABEL_FONT = ("Microsoft YaHei UI", 13, "bold")
BODY_FONT = ("Microsoft YaHei UI", 13)
HELP_FONT = ("Microsoft YaHei UI", 12)
def _setup_wifi_dialog_styles(dialog: tk.Toplevel) -> None:
try:
style = ttk.Style(dialog)
style.configure("WifiADB.TCombobox", padding=(10, 8), font=BODY_FONT)
style.configure("WifiADB.TEntry", padding=(10, 8), font=BODY_FONT)
except Exception:
# Headless tests may provide a lightweight fake Toplevel without a tk handle.
return
def _card(parent: tk.Misc, title: str, subtitle: str = "") -> tuple[tk.Frame, tk.Frame]:
outer = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
head = tk.Frame(outer, bg=theme.SURFACE)
head.pack(fill="x", padx=22, pady=(18, 10))
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 15, "bold")).pack(side="left")
if subtitle:
tk.Label(head, text=subtitle, bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(side="left", padx=(12, 0))
body = tk.Frame(outer, bg=theme.SURFACE)
body.pack(fill="both", expand=True, padx=22, pady=(0, 20))
return outer, body
def _status_pill(parent: tk.Misc, text: str, *, ok: bool, active: bool = True) -> tk.Label:
if ok:
fg, bg = theme.GREEN, theme.GREEN_SOFT
elif active:
fg, bg = theme.AMBER, theme.AMBER_SOFT
else:
fg, bg = theme.MUTED, theme.SURFACE_ALT
return tk.Label(parent, text=text, bg=bg, fg=fg, font=("Microsoft YaHei UI", 12, "bold"), padx=12, pady=5)
def _field_group(parent: tk.Misc, title: str) -> tk.Frame:
box = tk.Frame(parent, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
tk.Label(box, text=title, bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor="w", padx=14, pady=(12, 8))
return box
def _action_grid(parent: tk.Misc, actions: tuple[tuple[str, Callable[[], None], str, int], ...], *, columns: int = 3) -> None:
for col in range(columns):
parent.grid_columnconfigure(col, weight=1, uniform="action")
for idx, (text, command, kind, width) in enumerate(actions):
button(parent, text, command, kind=kind, width=width).grid(
row=idx // columns,
column=idx % columns,
sticky="ew",
padx=(0 if idx % columns == 0 else 10, 0),
pady=4,
)
def open_wifi_adb_dialog(
parent: tk.Misc,
*,
adb_exe: str,
on_line: Callable[[str], None],
refresh_devices: Callable[[], None],
) -> None:
"""打开WiFi ADB设置对话框"""
dialog = tk.Toplevel(parent)
dialog.title("WiFi ADB 设置")
dialog.geometry("900x820")
dialog.configure(bg=theme.BG)
_setup_wifi_dialog_styles(dialog)
# 允许用户调整对话框大小,避免窗口内容被裁剪
dialog.resizable(True, True)
dialog.minsize(780, 640)
if not hasattr(dialog, "tk"):
ttk.Button(dialog, text="放大/恢复", command=lambda: None)
return
# 获取设备列表并分类
current_devices = list_adb_devices(adb_exe)
wifi_devices = get_connected_wifi_devices(adb_exe)
usb_devices = [d for d in current_devices if d not in wifi_devices]
canvas = tk.Canvas(dialog, bg=theme.BG, highlightthickness=0, bd=0)
scroll = ttk.Scrollbar(dialog, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=scroll.set)
canvas.pack(side="left", fill="both", expand=True)
scroll.pack(side="right", fill="y")
shell = tk.Frame(canvas, bg=theme.BG)
shell_window = canvas.create_window((0, 0), window=shell, anchor="nw")
shell.bind("<Configure>", lambda _e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.bind("<Configure>", lambda e: canvas.itemconfigure(shell_window, width=e.width))
content = tk.Frame(shell, bg=theme.BG)
content.pack(fill="both", expand=True, padx=22, pady=18)
header = tk.Frame(content, bg=theme.BG)
header.pack(fill="x", pady=(0, 14))
title_box = tk.Frame(header, bg=theme.BG)
title_box.pack(side="left", fill="x", expand=True)
tk.Label(title_box, text="WiFi ADB 设置", bg=theme.BG, fg=theme.TEXT, font=TITLE_FONT).pack(anchor="w")
tk.Label(
title_box,
text="保留原有连接流程,优化设备选择与操作可读性",
bg=theme.BG,
fg=theme.MUTED,
font=SUBTITLE_FONT,
).pack(anchor="w", pady=(3, 0))
_status_pill(header, f"USB {len(usb_devices)}", ok=bool(usb_devices)).pack(side="right", padx=(8, 0))
_status_pill(header, f"WiFi {len(wifi_devices)}", ok=bool(wifi_devices), active=False).pack(side="right", padx=(8, 0))
# 创建设备选择区域
device_card, device_frame = _card(content, "设备选择", "首次启用需要 USB,日常可直接选择 WiFi 设备")
device_card.pack(fill="x", pady=(0, 14))
device_frame.grid_columnconfigure(0, weight=1, uniform="device")
device_frame.grid_columnconfigure(1, weight=1, uniform="device")
# USB设备选择
usb_group = _field_group(device_frame, "USB设备(用于首次启用)")
usb_group.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
usb_device_var = tk.StringVar(value=(usb_devices[0] if usb_devices else ""))
usb_combo = ttk.Combobox(
usb_group,
textvariable=usb_device_var,
values=usb_devices,
width=34,
state="readonly" if not usb_devices else "normal",
style="WifiADB.TCombobox",
font=BODY_FONT,
)
usb_combo.pack(fill="x", padx=14, pady=(0, 10), ipady=5)
# 显示USB设备状态
usb_status_text = (
f"检测到 {len(usb_devices)} 个USB设备"
if usb_devices
else "未检测到USB设备,请确保设备已连接并授权"
)
usb_status_label = _status_pill(usb_group, usb_status_text, ok=bool(usb_devices))
usb_status_label.pack(anchor="w", padx=14, pady=(0, 14))
# WiFi设备选择
wifi_group = _field_group(device_frame, "WiFi设备(已连接)")
wifi_group.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
wifi_device_var = tk.StringVar(value=(wifi_devices[0] if wifi_devices else ""))
wifi_combo = ttk.Combobox(
wifi_group,
textvariable=wifi_device_var,
values=wifi_devices,
width=34,
state="readonly" if not wifi_devices else "normal",
style="WifiADB.TCombobox",
font=BODY_FONT,
)
wifi_combo.pack(fill="x", padx=14, pady=(0, 10), ipady=5)
# 显示WiFi设备状态
wifi_status_text = (
f"已连接 {len(wifi_devices)} 个WiFi设备"
if wifi_devices
else "无WiFi设备连接"
)
wifi_status_label = _status_pill(wifi_group, wifi_status_text, ok=bool(wifi_devices), active=False)
wifi_status_label.pack(anchor="w", padx=14, pady=(0, 14))
# IP地址输入区域
ip_card, ip_frame = _card(content, "连接信息", "手动连接时填写设备 IP 与端口")
ip_card.pack(fill=X, pady=(0, 14))
ip_frame.grid_columnconfigure(0, weight=3)
ip_frame.grid_columnconfigure(1, weight=1)
tk.Label(ip_frame, text="设备IP地址", bg=theme.SURFACE, fg=theme.TEXT, font=LABEL_FONT).grid(
row=0, column=0, sticky=W, pady=(0, 8)
)
ip_var = tk.StringVar()
ip_entry = ttk.Entry(ip_frame, textvariable=ip_var, width=30, style="WifiADB.TEntry", font=BODY_FONT)
ip_entry.grid(row=1, column=0, padx=(0, 14), pady=(0, 2), sticky="we", ipady=7)
tk.Label(ip_frame, text="端口(默认5555)", bg=theme.SURFACE, fg=theme.TEXT, font=LABEL_FONT).grid(
row=0, column=1, sticky=W, pady=(0, 8)
)
port_var = tk.StringVar(value="5555")
port_entry = ttk.Entry(ip_frame, textvariable=port_var, width=16, style="WifiADB.TEntry", font=BODY_FONT)
port_entry.grid(row=1, column=1, pady=(0, 2), sticky="we", ipady=7)
# 按钮区域
action_card, button_frame = _card(content, "设备操作", "按当前连接方式选择对应动作")
action_card.pack(fill=X, pady=(0, 14))
# 放大/恢复窗口支持(当系统边框无法调整窗口时提供备用按钮)
is_maximized = False
original_geometry = None
def toggle_maximize():
nonlocal is_maximized, original_geometry
try:
if not is_maximized:
original_geometry = dialog.geometry()
dialog.update_idletasks()
w = int(dialog.winfo_screenwidth() * 0.8)
h = int(dialog.winfo_screenheight() * 0.8)
dialog.geometry(f"{w}x{h}")
is_maximized = True
else:
if original_geometry:
dialog.geometry(original_geometry)
is_maximized = False
except Exception as e:
on_line(f"[WiFi ADB] 切换窗口大小失败: {e}")
def enable_wifi():
device_id = usb_device_var.get()
if not device_id:
on_line("[WiFi ADB] 请先选择USB设备")
return
success, msg = enable_wifi_adb(adb_exe, device_id)
on_line(f"[WiFi ADB] {msg}")
if success:
# 尝试获取IP地址
ip_success, ip_msg = get_device_ip(adb_exe, device_id)
if ip_success:
ip_var.set(ip_msg)
on_line(f"[WiFi ADB] 设备IP地址: {ip_msg}")
def connect_wifi():
ip = ip_var.get().strip()
port = port_var.get().strip() or "5555"
if not ip:
on_line("[WiFi ADB] 请输入IP地址")
return
success, msg = connect_wifi_adb(adb_exe, ip, port)
on_line(f"[WiFi ADB] {msg}")
if success:
# 记住,下次启动自动重连
target = ip if ":" in ip else f"{ip}:{port}"
model = ""
try:
model = query_device_model(adb_exe, target)
except Exception:
pass
try:
set_last_wifi_target(target, model)
on_line(
f"[WiFi ADB] 已记住 {target}"
+ (f" ({model})" if model else "")
+ ",下次 GUI 启动会自动重连"
)
except Exception:
pass
# 刷新设备列表
refresh_devices()
# 重新打开对话框以显示新的WiFi设备
dialog.destroy()
open_wifi_adb_dialog(parent, adb_exe=adb_exe, on_line=on_line, refresh_devices=refresh_devices)
def disconnect_wifi():
device_id = wifi_device_var.get()
if not device_id:
on_line("[WiFi ADB] 请先选择WiFi设备")
return
# WiFi 设备通常是 ip:port。保留端口,避免随机无线调试端口被误断成 5555。
target_match = re.search(r"(\d+\.\d+\.\d+\.\d+)(?::(\d{1,5}))?", device_id)
if not target_match:
on_line("[WiFi ADB] 无法从设备ID中提取IP地址")
return
ip = target_match.group(1)
port = target_match.group(2) or "5555"
success, msg = disconnect_wifi_adb(adb_exe, ip, port)
on_line(f"[WiFi ADB] {msg}")
if success:
# 如果断开的就是上次记住的设备,清掉记录避免下次启动徒劳重试
try:
last = get_last_wifi_target()
last_target = str(last.get("target") or "")
if last_target.startswith(ip):
clear_last_wifi_target()
on_line(
f"[WiFi ADB] 已清除上次设备记录 {last_target}"
)
except Exception:
pass
# 刷新设备列表
refresh_devices()
# 重新打开对话框以更新设备列表
dialog.destroy()
open_wifi_adb_dialog(parent, adb_exe=adb_exe, on_line=on_line, refresh_devices=refresh_devices)
def auto_connect_wifi():
device_id = usb_device_var.get()
if not device_id:
on_line("[WiFi ADB] 请先选择USB设备")
return
# 显示进度
on_line("[WiFi ADB] 开始自动连接...")
# 创建进度对话框
progress_dialog = tk.Toplevel(dialog)
progress_dialog.title("自动连接中...")
progress_dialog.geometry("300x120")
progress_dialog.resizable(False, False)
ttk.Label(progress_dialog, text="正在自动连接WiFi ADB,请稍候...").pack(
pady=10
)
ttk.Label(progress_dialog, text="设备将会重启,请等待重启完成").pack(
pady=(0, 10)
)
progress_bar = ttk.Progressbar(progress_dialog, mode="indeterminate")
progress_bar.pack(fill=X, padx=20, pady=(0, 20))
progress_bar.start()
def do_auto_connect():
try:
success, msg = auto_connect_wifi_adb(adb_exe, device_id)
progress_dialog.destroy()
on_line(f"[WiFi ADB] {msg}")
if success:
# 刷新设备列表
refresh_devices()
# 尝试获取并显示IP
ip_success, ip_msg = get_device_ip(adb_exe, device_id)
if ip_success:
ip_var.set(ip_msg)
# 记住目标设备
target = (
ip_msg if ":" in ip_msg else f"{ip_msg}:5555"
)
model = ""
try:
model = query_device_model(adb_exe, target)
except Exception:
pass
try:
set_last_wifi_target(target, model)
on_line(
f"[WiFi ADB] 已记住 {target}"
+ (f" ({model})" if model else "")
+ ",下次 GUI 启动会自动重连"
)
except Exception:
pass
# 重新打开对话框以显示新的WiFi设备
dialog.destroy()
open_wifi_adb_dialog(parent, adb_exe=adb_exe, on_line=on_line, refresh_devices=refresh_devices)
except Exception as e:
progress_dialog.destroy()
on_line(f"[WiFi ADB] 自动连接异常: {str(e)}")
# 在后台线程中执行自动连接
threading.Thread(target=do_auto_connect, daemon=True).start()
def refresh_device_lists():
"""刷新设备列表"""
nonlocal usb_devices, wifi_devices
current_devices = list_adb_devices(adb_exe)
wifi_devices = get_connected_wifi_devices(adb_exe)
usb_devices = [d for d in current_devices if d not in wifi_devices]
# 更新USB设备下拉框
usb_combo["values"] = usb_devices
usb_combo["state"] = "readonly" if not usb_devices else "normal"
if usb_devices:
usb_device_var.set(usb_devices[0])
else:
usb_device_var.set("")
# 更新WiFi设备下拉框
wifi_combo["values"] = wifi_devices
wifi_combo["state"] = "readonly" if not wifi_devices else "normal"
if wifi_devices:
wifi_device_var.set(wifi_devices[0])
else:
wifi_device_var.set("")
# 更新状态标签
usb_status_text = (
f"检测到 {len(usb_devices)} 个USB设备"
if usb_devices
else "未检测到USB设备,请确保设备已连接并授权"
)
usb_status_label.config(
text=usb_status_text, foreground="red" if not usb_devices else "green"
)
wifi_status_text = (
f"已连接 {len(wifi_devices)} 个WiFi设备"
if wifi_devices
else "无WiFi设备连接"
)
wifi_status_label.config(
text=wifi_status_text, foreground="blue" if wifi_devices else "gray"
)
on_line("[WiFi ADB] 设备列表已刷新")
# USB设备操作按钮
button_frame.grid_columnconfigure(0, weight=1, uniform="actions")
button_frame.grid_columnconfigure(1, weight=1, uniform="actions")
button_frame.grid_columnconfigure(2, weight=1, uniform="actions")
usb_button_frame = tk.Frame(button_frame, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
usb_button_frame.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
tk.Label(usb_button_frame, text="USB首次启用", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(13, 8))
usb_buttons_frame = tk.Frame(usb_button_frame, bg=theme.SURFACE_ALT)
usb_buttons_frame.pack(fill=X, padx=14, pady=(0, 14))
_action_grid(
usb_buttons_frame,
(
("自动连接", auto_connect_wifi, "primary", 150),
("启用WiFi ADB", enable_wifi, "soft", 170),
),
columns=1,
)
# WiFi设备操作按钮
wifi_button_frame = tk.Frame(button_frame, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
wifi_button_frame.grid(row=0, column=1, sticky="nsew", padx=(10, 10))
tk.Label(wifi_button_frame, text="WiFi连接操作", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(13, 8))
wifi_buttons_frame = tk.Frame(wifi_button_frame, bg=theme.SURFACE_ALT)
wifi_buttons_frame.pack(fill=X, padx=14, pady=(0, 14))
_action_grid(
wifi_buttons_frame,
(
("连接", connect_wifi, "primary", 124),
("断开连接", disconnect_wifi, "soft", 132),
("扫描局域网", lambda: open_scan_dialog(dialog, adb_exe, ip_var, on_line, refresh_device_lists, port_var), "soft", 142),
),
columns=1,
)
# 通用工具
tools_button_frame = tk.Frame(button_frame, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
tools_button_frame.grid(row=0, column=2, sticky="nsew", padx=(10, 0))
tk.Label(tools_button_frame, text="通用工具", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(13, 8))
tools_buttons_frame = tk.Frame(tools_button_frame, bg=theme.SURFACE_ALT)
tools_buttons_frame.pack(fill=X, padx=14, pady=(0, 14))
_action_grid(
tools_buttons_frame,
(
("刷新设备", refresh_device_lists, "soft", 132),
("放大/恢复", toggle_maximize, "soft", 132),
),
columns=1,
)
# 说明文本
help_card, help_body = _card(content, "重要说明", "为什么首次必须接 USB")
help_card.pack(fill="both", expand=True)
help_body.grid_columnconfigure(0, weight=1)
help_body.grid_columnconfigure(1, weight=1)
notes = tk.Frame(help_body, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
notes.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
steps = tk.Frame(help_body, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
steps.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
tk.Label(notes, text="连接规则", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(12, 6))
for line in (
"Android 首次启用 WiFi ADB 必须通过 USB 连接",
"流程:USB连接 -> 启用WiFi ADB -> 设备重启 -> WiFi连接",
"设置完成后,设备会出现在 WiFi 设备列表中",
"设备重启后 WiFi ADB 模式会保持,可继续通过 WiFi 使用",
):
tk.Label(notes, text=f"• {line}", bg=theme.SURFACE_ALT, fg=theme.MUTED, font=HELP_FONT, anchor=W, justify=LEFT, wraplength=360).pack(fill=X, padx=14, pady=2)
tk.Label(steps, text="使用方法", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(12, 6))
for line in (
"1. 连接 Android 设备到电脑(USB)",
"2. 点击“刷新设备”确保设备被检测到",
"3. 选择 USB 设备,点击“自动连接”或手动操作",
"4. 等待设备重启后即可通过 WiFi 使用",
):
tk.Label(steps, text=line, bg=theme.SURFACE_ALT, fg=theme.MUTED, font=HELP_FONT, anchor=W, justify=LEFT, wraplength=360).pack(fill=X, padx=14, pady=2)