diff --git a/gui/components/realtime_viewer.py b/gui/components/realtime_viewer.py new file mode 100644 index 0000000..5f6c9da --- /dev/null +++ b/gui/components/realtime_viewer.py @@ -0,0 +1,176 @@ +"""gui/components/realtime_viewer - "实时查看 - 截图与最简动作流" 对话框 + +从 gui_app.py 的 _open_realtime_viewer_impl 嵌套函数抽出来。功能: +- 弹一个 Toplevel 显示当前 pic/screenshot.png +- 列表展示 logs/actions.log 中包含"耗时"的最近 80 行(用于实时观察) +- 每秒自动刷新 + +入口:open_realtime_viewer(root) -> tk.Toplevel | None +单例:同一个 root 重复调用只会聚焦已有窗口,不会重开。 +""" +from __future__ import annotations + +import os +import re +import tkinter as tk +from tkinter import ttk +from typing import Optional + +from PIL import Image, ImageTk # type: ignore[import] + +from douyin.core.path_config import get_logs_dir, get_screenshot_path + + +# 全局单例:避免同一进程多次开窗 +_active_win: Optional[tk.Toplevel] = None + + +def open_realtime_viewer(root: tk.Tk) -> Optional[tk.Toplevel]: + """打开(或聚焦已有的)实时查看器对话框。 + + Returns: + 新创建或已存在的 Toplevel,None 表示创建失败。 + """ + global _active_win + + try: + if _active_win is not None: + try: + _active_win.lift() + except Exception: + pass + return _active_win + + win = tk.Toplevel(root) + win.title("实时查看 - 截图与最简动作流") + win.geometry("520x520") + _active_win = win + + # 图片与列表 + img_lbl = ttk.Label(win) + img_lbl.pack(fill=tk.X, pady=(6, 4)) + + list_frame = ttk.Frame(win) + list_frame.pack(fill=tk.BOTH, expand=True, padx=6, pady=6) + listbox = tk.Listbox(list_frame, height=12) + listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) + scrollbar = ttk.Scrollbar( + list_frame, orient=tk.VERTICAL, command=listbox.yview + ) + scrollbar.pack(side=tk.RIGHT, fill=tk.Y) + listbox.configure(yscrollcommand=scrollbar.set) + + stop_flag = {"stop": False} + + def close_win() -> None: + global _active_win + stop_flag["stop"] = True + try: + win.destroy() + except Exception: + pass + _active_win = None + + win.protocol("WM_DELETE_WINDOW", close_win) + + def update_loop() -> None: + if stop_flag["stop"]: + return + + # update image + try: + screenshot_path = get_screenshot_path() + if os.path.exists(screenshot_path): + img = Image.open(screenshot_path) + max_w = 480 + w, h = img.size + if w > max_w: + nw = max_w + nh = int(h * (nw / w)) + img = img.resize((nw, nh), Image.LANCZOS) + tkimg = ImageTk.PhotoImage(img) + img_lbl.configure(image=tkimg) + img_lbl.image = tkimg # type: ignore[attr-defined] + else: + img_lbl.configure(image="") + img_lbl.image = None # type: ignore[attr-defined] + except Exception: + img_lbl.configure(image="") + img_lbl.image = None # type: ignore[attr-defined] + + # update minimal action list + try: + path = os.path.join(get_logs_dir(), "actions.log") + lines = _tail_read(path, max_bytes=64 * 1024) + items: list[str] = [] + for line in reversed(lines): + out = _parse_minimal(line) + if out: + items.append(f"{out[0]} {out[1]}") + if len(items) >= 80: + break + items = list(reversed(items)) + listbox.delete(0, tk.END) + if not items: + listbox.insert(tk.END, "暂无动作(仅显示包含 耗时 的行)") + else: + for it in items: + listbox.insert(tk.END, it) + try: + listbox.yview_moveto(1.0) + except Exception: + pass + except Exception: + try: + listbox.delete(0, tk.END) + listbox.insert(tk.END, "更新失败") + except Exception: + pass + + try: + win.after(1000, update_loop) + except Exception: + return + + update_loop() + return win + + except Exception: + return None + + +def _tail_read(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) + sz = f.tell() + f.seek(max(0, sz - max_bytes)) + return f.read().decode(errors="ignore").splitlines() + except Exception: + return [] + + +def _parse_minimal(line: str) -> Optional[tuple[str, str]]: + """从一行日志中提取 (动作名, 耗时) 二元组;不含"耗时"则返回 None。""" + if "耗时" not in line: + return None + m = re.search(r"耗时[:=]?\s*([0-9]+(?:\.[0-9]+)?)\s*s", line) + dur = None + if m: + dur = m.group(1) + "s" + else: + m2 = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*s", line) + if m2: + dur = m2.group(1) + "s" + if not dur: + return None + idx = line.find("耗时") + action = line[:idx].strip() + if not action: + action = line.strip()[:80] + if len(action) > 80: + action = action[:77] + "..." + return (action, dur) diff --git a/gui/gui_app.py b/gui/gui_app.py index 731f9ac..429a003 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -3785,174 +3785,9 @@ def main(): # --------- 实时查看弹窗(紧凑视图) --------- def _open_realtime_viewer_impl(): - try: - # 如果已打开则直接聚焦 - if ( - hasattr(_open_realtime_viewer_impl, "_win") - and _open_realtime_viewer_impl._win - ): - try: - _open_realtime_viewer_impl._win.lift() - except Exception: - pass - return - - win = tk.Toplevel(root) - win.title("实时查看 - 截图与最简动作流") - win.geometry("520x520") - _open_realtime_viewer_impl._win = win - - # 图片与列表 - img_lbl = ttk.Label(win) - img_lbl.pack(fill=X, pady=(6, 4)) - - list_frame = ttk.Frame(win) - list_frame.pack(fill=BOTH, expand=True, padx=6, pady=6) - listbox = tk.Listbox(list_frame, height=12) - listbox.pack(side=LEFT, fill=BOTH, expand=True) - scrollbar = ttk.Scrollbar( - list_frame, orient=tk.VERTICAL, command=listbox.yview - ) - scrollbar.pack(side=RIGHT, fill=Y) - listbox.configure(yscrollcommand=scrollbar.set) - - stop_flag = {"stop": False} - - def close_win(): - stop_flag["stop"] = True - try: - win.destroy() - except Exception: - pass - _open_realtime_viewer_impl._win = None - - win.protocol("WM_DELETE_WINDOW", close_win) - - # use module-level `re` - - def tail_read(path: str, max_bytes: int = 64 * 1024) -> list[str]: - try: - if not os.path.exists(path): - return [] - with open(path, "rb") as f: - f.seek(0, os.SEEK_END) - sz = f.tell() - f.seek(max(0, sz - max_bytes)) - return f.read().decode(errors="ignore").splitlines() - except Exception: - return [] - - def parse_minimal(line: str) -> tuple[str, str] | None: - if "耗时" not in line: - return None - m = re.search(r"耗时[:=]?\s*([0-9]+(?:\.[0-9]+)?)\s*s", line) - dur = None - if m: - dur = m.group(1) + "s" - else: - m2 = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*s", line) - if m2: - dur = m2.group(1) + "s" - if not dur: - return None - idx = line.find("耗时") - action = line[:idx].strip() - if not action: - action = line.strip()[:80] - if len(action) > 80: - action = action[:77] + "..." - return (action, dur) - - def update_loop(): - if stop_flag["stop"]: - return - - # update image - 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) - max_w = 480 - w, h = img.size - if w > max_w: - nw = max_w - nh = int(h * (nw / w)) - img = img.resize((nw, nh), Image.LANCZOS) - tkimg = ImageTk.PhotoImage(img) - img_lbl.configure(image=tkimg) - img_lbl.image = tkimg - else: - img_lbl.configure(image=None) - img_lbl.image = None - except Exception: - img_lbl.configure(image=None) - img_lbl.image = None - - # update minimal list - try: - path = os.path.join(get_logs_dir(), "actions.log") - lines = tail_read(path, max_bytes=64 * 1024) - items: list[str] = [] - for line in reversed(lines): - out = parse_minimal(line) - if out: - items.append(f"{out[0]} {out[1]}") - if len(items) >= 80: - break - items = list(reversed(items)) - listbox.delete(0, tk.END) - if not items: - listbox.insert(tk.END, "暂无动作(仅显示包含 耗时 的行)") - else: - for it in items: - listbox.insert(tk.END, it) - # 自动滚动到末尾 - try: - listbox.yview_moveto(1.0) - except Exception: - pass - except Exception: - try: - listbox.delete(0, tk.END) - listbox.insert(tk.END, "更新失败") - except Exception: - pass - - # schedule next - try: - win.after(1000, update_loop) - except Exception: - return - - # start - update_loop() - - except Exception: - return - - # 搜索工具栏 - log_search_frame = ttk.Frame(log_box) - log_search_frame.pack(fill=X, padx=10, pady=(10, 5)) - - # 关键字筛选(与行为日志一致) - log_filter_var = tk.StringVar(value="") - ttk.Label(log_search_frame, text="筛选:").pack(side=LEFT) - ttk.Entry(log_search_frame, textvariable=log_filter_var, width=16).pack( - side=LEFT, padx=(0, 8) - ) - - log_search_var = tk.StringVar(value="") - log_search_entry = ttk.Entry( - log_search_frame, textvariable=log_search_var, width=20 - ) + """委托到 gui/components/realtime_viewer.open_realtime_viewer。""" + from gui.components.realtime_viewer import open_realtime_viewer + open_realtime_viewer(root) def refresh_run_log(): """从内存中读取最近若干运行日志并在界面中刷新(行为上与行为日志一致)""" diff --git a/tests/test_realtime_viewer.py b/tests/test_realtime_viewer.py new file mode 100644 index 0000000..30ce510 --- /dev/null +++ b/tests/test_realtime_viewer.py @@ -0,0 +1,98 @@ +"""gui/components/realtime_viewer 单元测试。 + +只测纯函数 _tail_read / _parse_minimal。 +open_realtime_viewer 涉及 Tk Toplevel + 后台计时器,单测难度高,跳过。 +""" +from __future__ import annotations + +import pytest + +from gui.components.realtime_viewer import _parse_minimal, _tail_read + + +# ============================================================ +# _tail_read +# ============================================================ + +class TestTailRead: + def test_nonexistent_file_returns_empty(self, tmp_path): + assert _tail_read(str(tmp_path / "nope.log")) == [] + + def test_small_file_returns_all_lines(self, tmp_path): + p = tmp_path / "test.log" + p.write_text("line1\nline2\nline3\n", encoding="utf-8") + result = _tail_read(str(p)) + assert result == ["line1", "line2", "line3"] + + def test_large_file_truncated_to_max_bytes(self, tmp_path): + p = tmp_path / "test.log" + # 写 100 行 + text = "\n".join(f"line{i:04d}" for i in range(1000)) + p.write_text(text, encoding="utf-8") + # max_bytes=200 → 只读末尾 200 字节 + result = _tail_read(str(p), max_bytes=200) + # 末尾几行应该都在 + assert any("line0999" in line for line in result) + # 开头不应在 + assert not any("line0000" in line for line in result) + + def test_invalid_encoding_does_not_crash(self, tmp_path): + p = tmp_path / "binary.log" + p.write_bytes(b"\xff\xfe valid text \n line2\n\xff\xfe") + # decode(errors="ignore") 应该跳过无效字节 + result = _tail_read(str(p)) + assert isinstance(result, list) + + def test_empty_file(self, tmp_path): + p = tmp_path / "empty.log" + p.write_text("", encoding="utf-8") + assert _tail_read(str(p)) == [] + + +# ============================================================ +# _parse_minimal +# ============================================================ + +class TestParseMinimal: + def test_no_耗时_returns_none(self): + assert _parse_minimal("普通日志行 没有 timing 信息") is None + + def test_耗时_with_colon(self): + result = _parse_minimal("点击参与按钮 耗时:1.5s") + assert result == ("点击参与按钮", "1.5s") + + def test_耗时_with_equals(self): + result = _parse_minimal("OCR识别 耗时=2.3s") + assert result == ("OCR识别", "2.3s") + + def test_耗时_no_separator(self): + # "耗时 1.5s" → 应回落到 "([0-9]+s)" pattern + result = _parse_minimal("操作完成 耗时 1.5s") + # action 取 idx="耗时" 之前的文本 = "操作完成 " + assert result is not None + assert result[0] == "操作完成" + assert result[1] == "1.5s" + + def test_耗时_present_but_no_seconds_returns_none(self): + # "耗时未知" 没有数字 → None + assert _parse_minimal("某操作 耗时未知") is None + + def test_action_truncated_to_80_chars(self): + long_action = "a" * 100 + result = _parse_minimal(f"{long_action} 耗时:1.5s") + assert result is not None + action, dur = result + assert len(action) <= 80 + assert action.endswith("...") + assert dur == "1.5s" + + def test_empty_action_uses_line_start(self): + result = _parse_minimal("耗时:0.5s") + assert result is not None + action, dur = result + # action 为空时回退到 line.strip()[:80] + assert action == "耗时:0.5s" + + def test_integer_duration(self): + result = _parse_minimal("步骤A 耗时:5s") + assert result == ("步骤A", "5s")