refactor(gui): 抽 realtime_tab UI 创建到 components/realtime_tab (2037 → 1878)
This commit is contained in:
1 parent
e784efd5f8
commit
29cef2c578
3 files changed
+226
-174
No files matched your search
@@ -0,0 +1,206 @@
|
||||
"""实时状态 Tab UI 创建逻辑(包含 3 个内部辅助函数 + 后台刷新循环)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 ~170 行的段(被 try/except 包着)。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``parent`` - ``realtime_tab`` (Frame)
|
||||
- ``vars_`` - 名→Var 的字典,需要 show_actions_var/show_screenshot_var/auto_scroll_var
|
||||
- ``root`` - 主窗口(用于自递归 ``after``)
|
||||
- ``ScrolledText_cls`` - ``ScrolledText`` 类(ttkbootstrap 或 tkinter)
|
||||
- ``logs_dir_getter`` - 返回 logs 目录的回调
|
||||
- ``read_config`` - 读 config.json 的回调
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import BOTH, X
|
||||
from typing import Any, Callable, Dict
|
||||
|
||||
from PIL import Image, ImageTk # type: ignore[import]
|
||||
|
||||
|
||||
def setup_realtime_tab(
|
||||
parent: tk.Misc,
|
||||
*,
|
||||
vars_: Dict[str, tk.Variable],
|
||||
root: tk.Misc,
|
||||
ScrolledText_cls: Any,
|
||||
logs_dir_getter: Callable[[], str],
|
||||
read_config: Callable[[], dict],
|
||||
) -> None:
|
||||
# ========== 实时状态 Tab(显示最近动作 + 耗时) ==========
|
||||
try:
|
||||
realtime_frame = ttk.Frame(parent)
|
||||
realtime_frame.pack(fill=BOTH, expand=True, padx=8, pady=8)
|
||||
|
||||
# 截图预览区域(根据选项显示/隐藏)
|
||||
image_label = ttk.Label(realtime_frame)
|
||||
image_label.pack(fill=X)
|
||||
|
||||
realtime_text = ScrolledText_cls(realtime_frame, height=14)
|
||||
realtime_text.pack(fill=BOTH, expand=True)
|
||||
realtime_text.configure(state="disabled")
|
||||
|
||||
# re 已在模块顶部导入,避免重复导入
|
||||
|
||||
realtime_after_id = None
|
||||
|
||||
def tail_read_file(path: str, max_bytes: int = 64 * 1024) -> list[str]:
|
||||
"""从文件尾部读取最多 max_bytes,并返回按行分割的字符串列表(按文件顺序)。"""
|
||||
try:
|
||||
if not os.path.exists(path):
|
||||
return []
|
||||
with open(path, "rb") as f:
|
||||
f.seek(0, os.SEEK_END)
|
||||
file_size = f.tell()
|
||||
seek_from = max(0, file_size - max_bytes)
|
||||
f.seek(seek_from)
|
||||
data = f.read()
|
||||
text = data.decode(errors="ignore")
|
||||
# splitlines 保留不含尾部换行的处理
|
||||
return text.splitlines()
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def parse_action_duration(line: str) -> tuple[str, str] | None:
|
||||
"""从一行日志提取 (action, duration),未找到返回 None。
|
||||
|
||||
支持 ms / s 两种单位(实际 actions.log 写 `耗时=10.00ms`)。
|
||||
"""
|
||||
if "耗时" not in line:
|
||||
return None
|
||||
idx = line.find("耗时")
|
||||
tail = line[idx:] # 在"耗时"之后搜,避免把前缀里的数字当成耗时
|
||||
|
||||
num = r"([0-9]+(?:\.[0-9]+)?)"
|
||||
# 优先 ms(必须先于 s 匹配,否则 \s*s 会先吃掉 "10ms" 的 m)
|
||||
m_ms = re.search(r"耗时[:=]?\s*" + num + r"\s*ms", tail)
|
||||
m_s = re.search(r"耗时[:=]?\s*" + num + r"\s*s(?![a-zA-Z])", tail)
|
||||
|
||||
if m_ms:
|
||||
dur = m_ms.group(1) + "ms"
|
||||
elif m_s:
|
||||
dur = m_s.group(1) + "s"
|
||||
else:
|
||||
m2 = re.search(num + r"\s*ms", tail)
|
||||
if m2:
|
||||
dur = m2.group(1) + "ms"
|
||||
else:
|
||||
m3 = re.search(num + r"\s*s(?![a-zA-Z])", tail)
|
||||
if m3:
|
||||
dur = m3.group(1) + "s"
|
||||
else:
|
||||
return None
|
||||
|
||||
# 动作名取耗时之前的文本片段,最多保留 60 字符
|
||||
action = line[:idx].strip()
|
||||
if not action:
|
||||
# 兜底:取整行前 60 字符
|
||||
action = line.strip()[:60]
|
||||
if len(action) > 60:
|
||||
action = action[:57] + "..."
|
||||
return (action, dur)
|
||||
|
||||
def refresh_realtime_tab():
|
||||
nonlocal realtime_after_id
|
||||
cfg = read_config()
|
||||
gui_cfg = cfg.get("gui", {}).get("realtime_status", {})
|
||||
refresh_ms = int(gui_cfg.get("refresh_interval_ms", 1000))
|
||||
tail_items = int(gui_cfg.get("tail_items", 50))
|
||||
|
||||
path = os.path.join(logs_dir_getter(), "actions.log")
|
||||
lines = tail_read_file(path)
|
||||
parsed: list[tuple[str, str]] = []
|
||||
# 从文件末尾向前解析,保持原始顺序输出最近项
|
||||
for line in reversed(lines):
|
||||
try:
|
||||
out = parse_action_duration(line)
|
||||
if out:
|
||||
parsed.append(out)
|
||||
if len(parsed) >= tail_items:
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
parsed = list(reversed(parsed))
|
||||
|
||||
# 更新截图(若选中)
|
||||
if vars_["show_screenshot_var"].get():
|
||||
try:
|
||||
try:
|
||||
from douyin.core.path_config import get_screenshot_path
|
||||
|
||||
screenshot_path = get_screenshot_path()
|
||||
except Exception:
|
||||
from douyin.core import path_config
|
||||
|
||||
screenshot_path = path_config.get_screenshot_path()
|
||||
|
||||
if os.path.exists(screenshot_path):
|
||||
img = Image.open(screenshot_path)
|
||||
# 缩放以适应宽度(保持纵横比),最大宽度 420
|
||||
max_w = 420
|
||||
w, h = img.size
|
||||
if w > max_w:
|
||||
nw = max_w
|
||||
nh = int(h * (nw / w))
|
||||
img = img.resize((nw, nh), Image.LANCZOS)
|
||||
tk_img = ImageTk.PhotoImage(img)
|
||||
image_label.configure(image=tk_img)
|
||||
image_label.image = tk_img
|
||||
image_label.pack(fill=X)
|
||||
else:
|
||||
image_label.configure(image="")
|
||||
image_label.image = None
|
||||
image_label.pack_forget()
|
||||
except Exception:
|
||||
image_label.configure(image="")
|
||||
image_label.image = None
|
||||
image_label.pack_forget()
|
||||
else:
|
||||
image_label.configure(image="")
|
||||
image_label.image = None
|
||||
image_label.pack_forget()
|
||||
|
||||
# 更新动作流文本(若选中)
|
||||
if vars_["show_actions_var"].get():
|
||||
realtime_text.configure(state="normal")
|
||||
realtime_text.delete("1.0", "end")
|
||||
if not parsed:
|
||||
realtime_text.insert("1.0", "暂无动作日志(仅显示包含“耗时”的行)")
|
||||
else:
|
||||
for action, dur in parsed:
|
||||
realtime_text.insert("end", f"{action} {dur}\n")
|
||||
# 自动滚动
|
||||
if vars_["auto_scroll_var"].get():
|
||||
try:
|
||||
realtime_text.see("end")
|
||||
except Exception:
|
||||
try:
|
||||
realtime_text.yview_moveto(1.0)
|
||||
except Exception:
|
||||
pass
|
||||
realtime_text.configure(state="disabled")
|
||||
else:
|
||||
# 隐藏文本内容但保留控件
|
||||
realtime_text.configure(state="normal")
|
||||
realtime_text.delete("1.0", "end")
|
||||
realtime_text.configure(state="disabled")
|
||||
|
||||
# 安排下一次刷新
|
||||
try:
|
||||
realtime_after_id = root.after(refresh_ms, refresh_realtime_tab)
|
||||
except Exception:
|
||||
realtime_after_id = None
|
||||
|
||||
# 启动刷新(仅在 Tab 被创建时启动)
|
||||
try:
|
||||
refresh_realtime_tab()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
+13
-172
@@ -93,6 +93,7 @@ from gui.components.yanghao_tab import setup_yanghao_tab
|
||||
from gui.components.reservation_tab import setup_reservation_tab
|
||||
from gui.components.run_tab import setup_run_tab
|
||||
from gui.components.filter_tab import setup_filter_tab
|
||||
from gui.components.realtime_tab import setup_realtime_tab
|
||||
|
||||
# 导入日志颜色配置模块
|
||||
try:
|
||||
@@ -1164,178 +1165,18 @@ def main():
|
||||
log_box = ttk.Frame(log_tab)
|
||||
log_box.pack(fill=BOTH, expand=True)
|
||||
|
||||
# ========== 实时状态 Tab(显示最近动作 + 耗时) ==========
|
||||
try:
|
||||
realtime_frame = ttk.Frame(realtime_tab)
|
||||
realtime_frame.pack(fill=BOTH, expand=True, padx=8, pady=8)
|
||||
|
||||
# 截图预览区域(根据选项显示/隐藏)
|
||||
image_label = ttk.Label(realtime_frame)
|
||||
image_label.pack(fill=X)
|
||||
|
||||
realtime_text = ScrolledText(realtime_frame, height=14)
|
||||
realtime_text.pack(fill=BOTH, expand=True)
|
||||
realtime_text.configure(state="disabled")
|
||||
|
||||
# re 已在模块顶部导入,避免重复导入
|
||||
|
||||
realtime_after_id = None
|
||||
|
||||
def tail_read_file(path: str, max_bytes: int = 64 * 1024) -> list[str]:
|
||||
"""从文件尾部读取最多 max_bytes,并返回按行分割的字符串列表(按文件顺序)。"""
|
||||
try:
|
||||
if not os.path.exists(path):
|
||||
return []
|
||||
with open(path, "rb") as f:
|
||||
f.seek(0, os.SEEK_END)
|
||||
file_size = f.tell()
|
||||
seek_from = max(0, file_size - max_bytes)
|
||||
f.seek(seek_from)
|
||||
data = f.read()
|
||||
text = data.decode(errors="ignore")
|
||||
# splitlines 保留不含尾部换行的处理
|
||||
return text.splitlines()
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def parse_action_duration(line: str) -> tuple[str, str] | None:
|
||||
"""从一行日志提取 (action, duration),未找到返回 None。
|
||||
|
||||
支持 ms / s 两种单位(实际 actions.log 写 `耗时=10.00ms`)。
|
||||
"""
|
||||
if "耗时" not in line:
|
||||
return None
|
||||
idx = line.find("耗时")
|
||||
tail = line[idx:] # 在"耗时"之后搜,避免把前缀里的数字当成耗时
|
||||
|
||||
num = r"([0-9]+(?:\.[0-9]+)?)"
|
||||
# 优先 ms(必须先于 s 匹配,否则 \s*s 会先吃掉 "10ms" 的 m)
|
||||
m_ms = re.search(r"耗时[:=]?\s*" + num + r"\s*ms", tail)
|
||||
m_s = re.search(r"耗时[:=]?\s*" + num + r"\s*s(?![a-zA-Z])", tail)
|
||||
|
||||
if m_ms:
|
||||
dur = m_ms.group(1) + "ms"
|
||||
elif m_s:
|
||||
dur = m_s.group(1) + "s"
|
||||
else:
|
||||
m2 = re.search(num + r"\s*ms", tail)
|
||||
if m2:
|
||||
dur = m2.group(1) + "ms"
|
||||
else:
|
||||
m3 = re.search(num + r"\s*s(?![a-zA-Z])", tail)
|
||||
if m3:
|
||||
dur = m3.group(1) + "s"
|
||||
else:
|
||||
return None
|
||||
|
||||
# 动作名取耗时之前的文本片段,最多保留 60 字符
|
||||
action = line[:idx].strip()
|
||||
if not action:
|
||||
# 兜底:取整行前 60 字符
|
||||
action = line.strip()[:60]
|
||||
if len(action) > 60:
|
||||
action = action[:57] + "..."
|
||||
return (action, dur)
|
||||
|
||||
def refresh_realtime_tab():
|
||||
nonlocal realtime_after_id
|
||||
cfg = read_config()
|
||||
gui_cfg = cfg.get("gui", {}).get("realtime_status", {})
|
||||
refresh_ms = int(gui_cfg.get("refresh_interval_ms", 1000))
|
||||
tail_items = int(gui_cfg.get("tail_items", 50))
|
||||
|
||||
path = os.path.join(get_logs_dir(), "actions.log")
|
||||
lines = tail_read_file(path)
|
||||
parsed: list[tuple[str, str]] = []
|
||||
# 从文件末尾向前解析,保持原始顺序输出最近项
|
||||
for line in reversed(lines):
|
||||
try:
|
||||
out = parse_action_duration(line)
|
||||
if out:
|
||||
parsed.append(out)
|
||||
if len(parsed) >= tail_items:
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
parsed = list(reversed(parsed))
|
||||
|
||||
# 更新截图(若选中)
|
||||
if show_screenshot_var.get():
|
||||
try:
|
||||
try:
|
||||
from douyin.core.path_config import get_screenshot_path
|
||||
|
||||
screenshot_path = get_screenshot_path()
|
||||
except Exception:
|
||||
from douyin.core import path_config
|
||||
|
||||
screenshot_path = path_config.get_screenshot_path()
|
||||
|
||||
if os.path.exists(screenshot_path):
|
||||
img = Image.open(screenshot_path)
|
||||
# 缩放以适应宽度(保持纵横比),最大宽度 420
|
||||
max_w = 420
|
||||
w, h = img.size
|
||||
if w > max_w:
|
||||
nw = max_w
|
||||
nh = int(h * (nw / w))
|
||||
img = img.resize((nw, nh), Image.LANCZOS)
|
||||
tk_img = ImageTk.PhotoImage(img)
|
||||
image_label.configure(image=tk_img)
|
||||
image_label.image = tk_img
|
||||
image_label.pack(fill=X)
|
||||
else:
|
||||
image_label.configure(image="")
|
||||
image_label.image = None
|
||||
image_label.pack_forget()
|
||||
except Exception:
|
||||
image_label.configure(image="")
|
||||
image_label.image = None
|
||||
image_label.pack_forget()
|
||||
else:
|
||||
image_label.configure(image="")
|
||||
image_label.image = None
|
||||
image_label.pack_forget()
|
||||
|
||||
# 更新动作流文本(若选中)
|
||||
if show_actions_var.get():
|
||||
realtime_text.configure(state="normal")
|
||||
realtime_text.delete("1.0", "end")
|
||||
if not parsed:
|
||||
realtime_text.insert("1.0", "暂无动作日志(仅显示包含“耗时”的行)")
|
||||
else:
|
||||
for action, dur in parsed:
|
||||
realtime_text.insert("end", f"{action} {dur}\n")
|
||||
# 自动滚动
|
||||
if auto_scroll_var.get():
|
||||
try:
|
||||
realtime_text.see("end")
|
||||
except Exception:
|
||||
try:
|
||||
realtime_text.yview_moveto(1.0)
|
||||
except Exception:
|
||||
pass
|
||||
realtime_text.configure(state="disabled")
|
||||
else:
|
||||
# 隐藏文本内容但保留控件
|
||||
realtime_text.configure(state="normal")
|
||||
realtime_text.delete("1.0", "end")
|
||||
realtime_text.configure(state="disabled")
|
||||
|
||||
# 安排下一次刷新
|
||||
try:
|
||||
realtime_after_id = root.after(refresh_ms, refresh_realtime_tab)
|
||||
except Exception:
|
||||
realtime_after_id = None
|
||||
|
||||
# 启动刷新(仅在 Tab 被创建时启动)
|
||||
try:
|
||||
refresh_realtime_tab()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
setup_realtime_tab(
|
||||
realtime_tab,
|
||||
vars_={
|
||||
"show_actions_var": show_actions_var,
|
||||
"show_screenshot_var": show_screenshot_var,
|
||||
"auto_scroll_var": auto_scroll_var,
|
||||
},
|
||||
root=root,
|
||||
ScrolledText_cls=ScrolledText,
|
||||
logs_dir_getter=get_logs_dir,
|
||||
read_config=read_config,
|
||||
)
|
||||
|
||||
# --------- 实时查看弹窗(紧凑视图) ---------
|
||||
def _open_realtime_viewer_impl():
|
||||
|
||||
@@ -25,6 +25,8 @@ GUI_APP = ROOT / "gui" / "gui_app.py"
|
||||
# 但 GUI 启动时仍通过 main() 内的薄包装调用它们。本工具的同步检查需要从
|
||||
# config_io.py 抽 cfg/cfg2 赋值,从 gui_app.py 抽 gui_cfg 引用(仍在 main 里)。
|
||||
GUI_CONFIG_IO = ROOT / "gui" / "components" / "config_io.py"
|
||||
# realtime_tab UI 抽到 components/realtime_tab.py 后,gui_cfg 引用也跟过去了。
|
||||
GUI_REALTIME_TAB = ROOT / "gui" / "components" / "realtime_tab.py"
|
||||
WEB_INDEX = ROOT / "webui" / "index.html"
|
||||
MANIFEST_PATH = ROOT / "tools" / "dev" / "web_gui_config_manifest.json"
|
||||
|
||||
@@ -106,11 +108,14 @@ def extract_web_keys(source: str) -> set[str]:
|
||||
def build_manifest() -> dict[str, object]:
|
||||
gui_source = _read(GUI_APP)
|
||||
config_io_source = _read(GUI_CONFIG_IO)
|
||||
realtime_tab_source = _read(GUI_REALTIME_TAB)
|
||||
web_source = _read(WEB_INDEX)
|
||||
|
||||
# save/load 函数现在在 components/config_io.py 里;gui_cfg 引用仍在 gui_app.py
|
||||
# save/load 函数现在在 components/config_io.py 里;gui_cfg 引用在 realtime_tab.py
|
||||
gui_saved = extract_gui_saved_keys(config_io_source)
|
||||
gui_loaded = extract_gui_loaded_keys(config_io_source + "\n" + gui_source)
|
||||
gui_loaded = extract_gui_loaded_keys(
|
||||
config_io_source + "\n" + gui_source + "\n" + realtime_tab_source
|
||||
)
|
||||
web_keys = extract_web_keys(web_source)
|
||||
|
||||
expected_gui_keys = web_keys - GUI_RUNTIME_ONLY_KEYS
|
||||
|
||||
Reference in new issue
Block a user