207 lines
7.9 KiB
Python
207 lines
7.9 KiB
Python
"""实时状态 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
|