"""运行日志 Tab 的刷新逻辑(从 runner 内存读取最近若干行)。 从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``refresh_run_log``。 依赖通过显式参数注入: - ``runner`` - 运行控制器(暴露 ``_lock`` 与 ``_log`` 内部属性) - ``text_widget`` - 展示用的 Text/ScrolledText - ``filter_getter`` - 返回筛选关键字 - ``theme_getter`` - 返回当前主题名 """ from __future__ import annotations import tkinter as tk from typing import Any, Callable try: from gui.components.log_color_config import ( apply_operation_color, get_operation_type, ) except ImportError: def get_operation_type(line: str): # type: ignore[no-redef] return None def apply_operation_color(*args, **kwargs): # type: ignore[no-redef] pass def refresh_run_log( runner: Any, *, text_widget: tk.Text, filter_getter: Callable[[], str], theme_getter: Callable[[], str], ) -> None: """从内存中读取最近若干运行日志并在界面中刷新(行为上与行为日志一致)""" try: tail_n = 1000 # 读取 runner 内存日志(线程安全) with runner._lock: total = len(runner._log) cand = runner._log[-tail_n:] if tail_n > 0 else runner._log[:] # 应用筛选关键词 kw = filter_getter() if kw: cand = [ln for ln in cand if kw in (ln or "")] # 保存滚动位置 try: scroll_pos = text_widget.yview()[0] except Exception: scroll_pos = 1.0 text_widget.delete("1.0", "end") if cand: try: current_theme = theme_getter() except Exception: current_theme = "litera" for i, line in enumerate(cand): start_pos = text_widget.index("end-1c") if i > 0: text_widget.insert("end", "\n") text_widget.insert("end", line) end_pos = text_widget.index("end") try: op_type = get_operation_type(line) if op_type: apply_operation_color( text_widget, start_pos, end_pos, line, current_theme ) except Exception: pass else: text_widget.insert("1.0", "暂无匹配的运行日志") try: text_widget.yview_moveto(scroll_pos) except Exception: pass except Exception as e: try: text_widget.delete("1.0", "end") text_widget.insert("1.0", f"刷新运行日志失败:{e}") except Exception: pass