diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index c2a80fe..85a4bbf 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -454,7 +454,7 @@ class fudai_analyse: "养号", "_yanghao_recommend_flow skipped - yanghao_enabled=0" ) except Exception: - print("[养号] _yanghao_recommend_flow skipped - yanghao_enabled=0") + logging.info("[养号] _yanghao_recommend_flow skipped - yanghao_enabled=0") return from douyin.other import douyin_yanghao @@ -595,7 +595,7 @@ class fudai_analyse: wait_minutes=wait_minutes, ) except Exception: - print( + logging.warning( f"[DEBUG] entered fudai_choujiang device_id={device_id} wait_minutes={wait_minutes}" ) self.device_id = device_id or self.device_id @@ -625,7 +625,7 @@ class fudai_analyse: error=str(e), ) except Exception: - print( + logging.warning( f"[DEBUG] get_device_resolution attempt {attempt+1} failed: {e}" ) time.sleep(1.0) diff --git a/douyin/handlers/douyin_screenshot_manager.py b/douyin/handlers/douyin_screenshot_manager.py index 67c7369..84d433d 100644 --- a/douyin/handlers/douyin_screenshot_manager.py +++ b/douyin/handlers/douyin_screenshot_manager.py @@ -13,6 +13,33 @@ from __future__ import annotations import os import shutil from typing import Optional, Tuple + +import logging as _logging + +# 模块级 logger:原代码用 print 输出截图管理 / 调试图像清理日志,统一走 logging。 +# 保留消息中已有的 "[截图管理]"/"[调试图像清理]" 前缀,避免改变历史搜索习惯。 +_LOGGER = _logging.getLogger("douyin.handlers.douyin_screenshot_manager") + + +def _mgr_log(msg: str, level: str = "INFO") -> None: + """统一截图管理日志出口;失败兜底 stdout。""" + try: + lv = str(level or "INFO").upper() + if lv == "ERROR": + _LOGGER.error(str(msg)) + elif lv == "WARNING": + _LOGGER.warning(str(msg)) + elif lv == "DEBUG": + _LOGGER.debug(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + try: + _mgr_log(str(msg)) + except Exception: + pass + + from PIL import Image from douyin.core import path_config import threading @@ -585,7 +612,7 @@ def save_latest_attempt(image: Image.Image, operation_type: str = "") -> bool: return True except Exception as e: try: - print(f"[截图管理] 保存 latest_attempt_{operation_type}.png 失败: {e}") + _mgr_log(f"[截图管理] 保存 latest_attempt_{operation_type}.png 失败: {e}") except Exception: pass return False @@ -608,7 +635,7 @@ def save_last_success(image: Image.Image, operation_type: str = "") -> bool: return True except Exception as e: try: - print(f"[截图管理] 保存 last_success_{operation_type}.png 失败: {e}") + _mgr_log(f"[截图管理] 保存 last_success_{operation_type}.png 失败: {e}") except Exception: pass return False @@ -631,7 +658,7 @@ def save_attempt_from_file(source_path: str, operation_type: str = "") -> bool: return save_latest_attempt(image, operation_type) except Exception as e: try: - print(f"[截图管理] 从文件保存 latest_attempt.png 失败: {e}") + _mgr_log(f"[截图管理] 从文件保存 latest_attempt.png 失败: {e}") except Exception: pass return False @@ -654,7 +681,7 @@ def save_success_from_file(source_path: str, operation_type: str = "") -> bool: return save_last_success(image, operation_type) except Exception as e: try: - print(f"[截图管理] 从文件保存 last_success.png 失败: {e}") + _mgr_log(f"[截图管理] 从文件保存 last_success.png 失败: {e}") except Exception: pass return False @@ -697,7 +724,7 @@ def ensure_debug_captures_dir() -> None: # 其他未知错误 error_type = type(e).__name__ try: - print(f"[截图管理] 创建调试图像目录失败({error_type}): {e}") + _mgr_log(f"[截图管理] 创建调试图像目录失败({error_type}): {e}") except Exception: pass raise @@ -827,7 +854,7 @@ def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int: dirs_info.remove(dir_info) except Exception as e: try: - print(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}") + _mgr_log(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}") except Exception: pass @@ -852,7 +879,7 @@ def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int: dirs_info.remove(dir_info) except Exception as e: try: - print(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}") + _mgr_log(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}") except Exception: pass @@ -870,12 +897,12 @@ def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int: reason_parts.append(f"超过{keep_days}天") reason = ",".join(reason_parts) if reason_parts else "自动清理" - print( + _mgr_log( f"[调试图像清理] 已删除 {deleted_count} 个调试图像目录: {', '.join(deleted_dirs)}" ) - print(f"[调试图像清理] 清理原因: {reason}") + _mgr_log(f"[调试图像清理] 清理原因: {reason}") if size_mb > 0.1: # 只显示大于0.1MB的清理 - print(f"[调试图像清理] 释放空间: {size_mb:.2f} MB") + _mgr_log(f"[调试图像清理] 释放空间: {size_mb:.2f} MB") except Exception: pass @@ -883,7 +910,7 @@ def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int: except Exception as e: # 清理失败不应影响程序运行 try: - print(f"[调试图像清理] 清理旧调试图像时出错: {e}") + _mgr_log(f"[调试图像清理] 清理旧调试图像时出错: {e}") except Exception: pass return 0 @@ -1152,7 +1179,7 @@ def save_debug_image( # type: ignore if current_count > max_files: # 文件数量超过限制,立即清理 try: - print( + _mgr_log( f"[调试图像清理] 检测到文件数量 {current_count} 超过限制 {max_files},立即清理" ) except Exception: @@ -1308,7 +1335,7 @@ def save_debug_image( # type: ignore except Exception as dir_error: # 记录目录创建失败 try: - print( + _mgr_log( f"[截图管理] 创建目录失败(重试 {attempt + 1}/{max_retries}): {dir_error}" ) except Exception: @@ -1319,14 +1346,14 @@ def save_debug_image( # type: ignore except PermissionError as e: # 权限错误,不重试 try: - print(f"[截图管理] 保存图像权限错误: {path}, 错误: {e}") + _mgr_log(f"[截图管理] 保存图像权限错误: {path}, 错误: {e}") except Exception: pass raise except OSError as e: # 系统级错误(磁盘空间不足等),不重试 try: - print(f"[截图管理] 保存图像系统错误: {path}, 错误: {e}") + _mgr_log(f"[截图管理] 保存图像系统错误: {path}, 错误: {e}") except Exception: pass raise @@ -1622,7 +1649,7 @@ def save_debug_image( # type: ignore # 权限或系统错误,尝试保存原图 try: try: - print(f"[截图管理] 保存标注图像失败,尝试保存原图: {e}") + _mgr_log(f"[截图管理] 保存标注图像失败,尝试保存原图: {e}") except Exception: pass save_image_with_retry(image, file_path) @@ -1633,7 +1660,7 @@ def save_debug_image( # type: ignore # 其他标注错误,尝试保存原图 try: try: - print(f"[截图管理] 图像标注失败,尝试保存原图: {e}") + _mgr_log(f"[截图管理] 图像标注失败,尝试保存原图: {e}") except Exception: pass save_image_with_retry(image, file_path) @@ -1647,21 +1674,21 @@ def save_debug_image( # type: ignore except FileNotFoundError as e: # 文件或目录不存在 try: - print(f"[截图管理] 保存调试图像失败(文件/目录不存在): {e}") + _mgr_log(f"[截图管理] 保存调试图像失败(文件/目录不存在): {e}") except Exception: pass return None except PermissionError as e: # 权限错误 try: - print(f"[截图管理] 保存调试图像失败(权限错误): {e}") + _mgr_log(f"[截图管理] 保存调试图像失败(权限错误): {e}") except Exception: pass return None except OSError as e: # 系统级错误(磁盘空间不足、路径过长等) try: - print(f"[截图管理] 保存调试图像失败(系统错误): {e}") + _mgr_log(f"[截图管理] 保存调试图像失败(系统错误): {e}") except Exception: pass return None @@ -1669,7 +1696,7 @@ def save_debug_image( # type: ignore # 其他未知错误 try: error_type = type(e).__name__ - print(f"[截图管理] 保存调试图像失败({error_type}): {e}") + _mgr_log(f"[截图管理] 保存调试图像失败({error_type}): {e}") except Exception: pass return None diff --git a/douyin/other/douyin_robot.py b/douyin/other/douyin_robot.py index 15789da..b557a01 100644 --- a/douyin/other/douyin_robot.py +++ b/douyin/other/douyin_robot.py @@ -8,6 +8,39 @@ from PIL import Image # type: ignore[import] from douyin.fudai.core.coords import LIVE_VERIFY1, LIVE_VERIFY2, ROBOT_VERIFY from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore +import logging as _logging + +# 模块级日志:优先走 analyser._log_kv,回退到 logging。 +_LOGGER = _logging.getLogger("douyin.other.douyin_robot") + + +def _robot_log(analyser, msg: str, level: str = "INFO") -> None: + """统一人机校验日志出口;失败兜底 stdout。""" + try: + log_kv = getattr(analyser, "_log_kv", None) if analyser is not None else None + if callable(log_kv): + log_kv("人机校验", str(msg), level=str(level or "INFO")) + return + except Exception: + pass + try: + lv = str(level or "INFO").upper() + if lv == "ERROR": + _LOGGER.error(str(msg)) + elif lv == "WARNING": + _LOGGER.warning(str(msg)) + elif lv == "DEBUG": + _LOGGER.debug(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + try: + print(str(msg)) + except Exception: + pass + + + def _to_rgb_tuple(color: Any) -> tuple[int, int, int]: if isinstance(color, (int, float)): @@ -35,17 +68,17 @@ def check_have_robot_analyse(analyser) -> int | bool: name_live = preprocess_for_ocr(analyser, "直播验证") result = analyser.operation.analyse_pic_word(name_live, 0) if "验证" in result: - print("存在滑动图片人机校验,需要等待完成验证。") + _robot_log(analyser, "存在滑动图片人机校验,需要等待完成验证。") return 1 if "形状相同" in result: - print("存在点击图片人机校验,需要等待完成验证。") + _robot_log(analyser, "存在点击图片人机校验,需要等待完成验证。") return 2 analyser.cut_pic(*LIVE_VERIFY2, "", "直播验证") name_live2 = preprocess_for_ocr(analyser, "直播验证") result = analyser.operation.analyse_pic_word(name_live2) if "开始检测" in result: - print("存在人脸识别人机校验,需要等待完成验证。") + _robot_log(analyser, "存在人脸识别人机校验,需要等待完成验证。") return 3 return False @@ -57,7 +90,7 @@ def deal_swipe_robot_analyse(analyser, distance: int = 400) -> None: else: targetx = 622 * analyser.resolution_ratio_x // 1080 analyser.swipe(222, 1444, targetx, 1444, 300) - print("滑轨滑动{}距离解锁人机验证".format(distance)) + _robot_log(analyser, "滑轨滑动{}距离解锁人机验证".format(distance)) analyser.operation.delay(1) @@ -72,12 +105,12 @@ def deal_robot_analyse(analyser) -> None: analyser.operation.delay(10) analyser._shot_and_diagnose("人机校验", "校验后复查", analyser.device_id) elif robot_result == 2: - print("无法处理图片验证的人机,点击关闭退出验证,等待30分钟") + _robot_log(analyser, "无法处理图片验证的人机,点击关闭退出验证,等待30分钟", level="WARNING") analyser.click(910, 800) # 点击关闭 analyser.operation.delay(1800) break elif robot_result == 3: - print("无法处理人脸识别验证的人机,点击返回退出验证,等待30分钟") + _robot_log(analyser, "无法处理人脸识别验证的人机,点击返回退出验证,等待30分钟", level="WARNING") analyser.operation.click_back(analyser.device_id) analyser.operation.delay(2) analyser.operation.click_back(analyser.device_id) @@ -87,7 +120,7 @@ def deal_robot_analyse(analyser) -> None: break swipe_times += 1 if swipe_times >= 10: - print("无法处理图片验证的人机,点击关闭退出验证,等待30分钟") + _robot_log(analyser, "无法处理图片验证的人机,点击关闭退出验证,等待30分钟", level="WARNING") analyser.click(910, 800) # 点击关闭 analyser.operation.delay(1800) @@ -133,7 +166,7 @@ def check_robot_pic_distance(analyser) -> int: for x in range(5, width - 40): r, g, b = _to_rgb_tuple(img.getpixel((x, y))) if r > 240 and g > 240 and b > 240: - print(x, y) + _robot_log(analyser, f"找到首像素 ({x}, {y})", level="DEBUG") first_x = x first_y = y found_first = True @@ -147,8 +180,8 @@ def check_robot_pic_distance(analyser) -> int: for x1 in range(first_x, width - 40): r, g, b = _to_rgb_tuple(img.getpixel((x1, first_y))) if r < 50 and g < 55 and b < 85 and (r + g + b) < 150: - print(x1, first_y) - print("需要滑动的距离为{}".format(x1 - first_x)) + _robot_log(analyser, f"找到末像素 ({x1}, {first_y})", level="DEBUG") + _robot_log(analyser, "需要滑动的距离为{}".format(x1 - first_x)) return x1 - first_x return 0 diff --git a/douyin/other/douyin_yanghao.py b/douyin/other/douyin_yanghao.py index 1bb81a4..5323d17 100644 --- a/douyin/other/douyin_yanghao.py +++ b/douyin/other/douyin_yanghao.py @@ -11,6 +11,40 @@ cv2: Any = _cv2 import numpy as np +# 模块级日志:优先走 analyser._log_kv,回退到 logging(避免裸 print 散落到 stdout) +import logging as _logging + +_LOGGER = _logging.getLogger("douyin.other.douyin_yanghao") + + +def _yanghao_log(analyser, msg: str, level: str = "INFO") -> None: + """统一养号日志出口。 + + - 当 analyser 提供 `_log_kv` 时,优先用它(与项目统一日志体系一致)。 + - 否则回退到模块 logger;最后兜底到 stdout 以避免静默丢日志。 + """ + try: + log_kv = getattr(analyser, "_log_kv", None) + if callable(log_kv): + log_kv("养号", str(msg), level=str(level or "INFO")) + return + except Exception: + pass + try: + if str(level).upper() == "ERROR": + _LOGGER.error(str(msg)) + elif str(level).upper() == "WARNING": + _LOGGER.warning(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + try: + _yanghao_log(analyser, str(msg)) + except Exception: + pass + + + def _scaled_click(analyser, base_x: int, base_y: int) -> None: """模块级点击封装:根据基准坐标缩放并点击(兼容原嵌套实现)。""" sx, sy = analyser._scale_from_base(int(base_x), int(base_y)) @@ -28,14 +62,14 @@ def _do_comment(analyser) -> None: # 步骤1: 点击评论按钮 btn_x = int(getattr(analyser, "yanghao_comment_btn_x", 540) or 540) btn_y = int(getattr(analyser, "yanghao_comment_btn_y", 2000) or 2000) - print(f"[养号][评论] Step1: 点击评论按钮 coord=({btn_x},{btn_y})") + _yanghao_log(analyser, f"[养号][评论] Step1: 点击评论按钮 coord=({btn_x},{btn_y})") _scaled_click(analyser, btn_x, btn_y) analyser.operation.delay(1.0) # 步骤2: 点击输入框 input_x = int(getattr(analyser, "yanghao_comment_input_x", 144) or 144) input_y = int(getattr(analyser, "yanghao_comment_input_y", 2179) or 2179) - print(f"[养号][评论] Step2: 点击输入框 coord=({input_x},{input_y})") + _yanghao_log(analyser, f"[养号][评论] Step2: 点击输入框 coord=({input_x},{input_y})") _scaled_click(analyser, input_x, input_y) analyser.operation.delay(1.0) @@ -44,7 +78,7 @@ def _do_comment(analyser) -> None: if not comment_texts: comment_texts = ["加油", "不错", "很好看"] selected_text = random.choice(comment_texts) - print(f"[养号][评论] Step3: 选择文本 -> {selected_text}") + _yanghao_log(analyser, f"[养号][评论] Step3: 选择文本 -> {selected_text}") ix, iy = analyser._scale_from_base(input_x, input_y) ok_input = bool( @@ -52,23 +86,23 @@ def _do_comment(analyser) -> None: analyser.device_id, ix, iy, selected_text, ensure_focus=False ) ) - print(f"[养号][评论] paste_text_at -> ok={ok_input} scaled_coord=({ix},{iy})") + _yanghao_log(analyser, f"[养号][评论] paste_text_at -> ok={ok_input} scaled_coord=({ix},{iy})") analyser.operation.delay(1.0) # 步骤4: 发送评论 ok_send = bool(analyser.operation.confirm_from_keyboard(analyser.device_id)) - print(f"[养号][评论] Step4: 发送评论 -> ok={ok_send}") + _yanghao_log(analyser, f"[养号][评论] Step4: 发送评论 -> ok={ok_send}") analyser.operation.delay(1.0) # 步骤5: 关闭评论窗口 close_x = int(getattr(analyser, "yanghao_comment_close_x", 900) or 900) close_y = int(getattr(analyser, "yanghao_comment_close_y", 300) or 300) - print(f"[养号][评论] Step5: 关闭评论窗口 coord=({close_x},{close_y})") + _yanghao_log(analyser, f"[养号][评论] Step5: 关闭评论窗口 coord=({close_x},{close_y})") _scaled_click(analyser, close_x, close_y) analyser.operation.delay(1.0) except Exception as e: - print(f"[养号] 评论操作失败: {e}") + _yanghao_log(analyser, f"[养号] 评论操作失败: {e}") def yanghao_idle(analyser, total_seconds: int) -> None: @@ -120,7 +154,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: y1 = y_mid - int(dist / 2) y2 = y_mid + int(dist / 2) analyser.swipe(x, y1, x, y2, 180) - print( + _yanghao_log(analyser, "[养号] 动作: 下滑/切换 direction={} dist={}px".format( getattr(analyser, "yanghao_after_dwell_swipe_direction", "up"), dist ) @@ -170,33 +204,33 @@ def yanghao_idle(analyser, total_seconds: int) -> None: except Exception: tpl_exists = False - print( + _yanghao_log(analyser, f"[养号] 检测: {action} -> 模板文件={template_path} tpl_exists={tpl_exists}" ) # 真实的模板匹配检测,直接在full screenshot上进行 try: if not tpl_exists or not os.path.exists(str(template_path or "")): - print(f"[养号] {action}: 模板文件不存在,假设图标存在") + _yanghao_log(analyser, f"[养号] {action}: 模板文件不存在,假设图标存在") return True, 1.0 # 使用共享的full screenshot,不做ROI截图 if not shared_screenshot_path or not os.path.exists( shared_screenshot_path ): - print(f"[养号] {action}: 截图文件不存在,假设图标存在") + _yanghao_log(analyser, f"[养号] {action}: 截图文件不存在,假设图标存在") return True, 1.0 # 读取full screenshot pic = cv2.imread(shared_screenshot_path) if pic is None: - print(f"[养号] {action}: 读取截图失败,假设图标存在") + _yanghao_log(analyser, f"[养号] {action}: 读取截图失败,假设图标存在") return True, 1.0 # 读取模板 template = cv2.imread(str(template_path)) if template is None: - print(f"[养号] {action}: 读取模板失败,假设图标存在") + _yanghao_log(analyser, f"[养号] {action}: 读取模板失败,假设图标存在") return True, 1.0 # 灰度化处理 @@ -215,19 +249,19 @@ def yanghao_idle(analyser, total_seconds: int) -> None: ) if max_val >= threshold: - print(f"[养号] {action}: 模板匹配成功 (分数={max_val:.3f})") + _yanghao_log(analyser, f"[养号] {action}: 模板匹配成功 (分数={max_val:.3f})") return True, float(max_val) else: - print( + _yanghao_log(analyser, f"[养号] {action}: 模板匹配失败 (分数={max_val:.3f} < {threshold})" ) return False, float(max_val) except Exception as e: - print(f"[养号] {action}: 模板匹配异常 {e},假设图标存在") + _yanghao_log(analyser, f"[养号] {action}: 模板匹配异常 {e},假设图标存在") return True, 1.0 end_ts = time.time() + int(max(1, total_seconds)) - print(f"[养号] 开始养号模式,总时长 {total_seconds}s") + _yanghao_log(analyser, f"[养号] 开始养号模式,总时长 {total_seconds}s") # 连续未检测到任何模板时的自救阈值(超过此次数尝试按返回键一次) consecutive_miss = 0 @@ -285,19 +319,19 @@ def yanghao_idle(analyser, total_seconds: int) -> None: try: if not action_detected: consecutive_miss += 1 - print( + _yanghao_log(analyser, f"[养号] 连续未检测到模板次数={consecutive_miss}/{miss_recover_threshold}" ) else: consecutive_miss = 0 if consecutive_miss >= miss_recover_threshold: - print("[养号] 连续多次未检测到模板,尝试按一次返回键进行自救") + _yanghao_log(analyser, "[养号] 连续多次未检测到模板,尝试按一次返回键进行自救") try: analyser.operation.keyevent(analyser.device_id, 4) analyser.operation.delay(1.0) except Exception as e: - print(f"[养号] 自救按返回键失败: {e}") + _yanghao_log(analyser, f"[养号] 自救按返回键失败: {e}") consecutive_miss = 0 except Exception: # 任何自救逻辑异常都不应影响主循环 @@ -322,7 +356,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: # 跨天区间,例如 23-6 in_quiet = now_h >= start_h or now_h < end_h if in_quiet: - print( + _yanghao_log(analyser, f"[养号] 定时禁抢生效({start_h}:00-{end_h}:00),当前小时={now_h},跳过爱心/收藏/评论" ) # 避免频繁循环,做一次随机短等待再继续 @@ -350,7 +384,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: or "com.ss.android.ugc" in top_pkg ) if top_pkg and not is_douyin_pkg: - print( + _yanghao_log(analyser, f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}" ) try: @@ -407,11 +441,11 @@ def yanghao_idle(analyser, total_seconds: int) -> None: ) analyser.operation.delay(2.0) - print("[养号] 自救: 恢复操作完成") + _yanghao_log(analyser, "[养号] 自救: 恢复操作完成") except Exception as e: - print(f"[养号] 自救: 恢复操作失败: {e}") + _yanghao_log(analyser, f"[养号] 自救: 恢复操作失败: {e}") except Exception as e: - print(f"[养号] 自救: 桌面检测异常: {e}") + _yanghao_log(analyser, f"[养号] 自救: 桌面检测异常: {e}") except Exception: pass @@ -429,7 +463,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: ) did_like = True analyser.operation.delay(1.0) # 延迟1秒 - print( + _yanghao_log(analyser, "[养号] 动作: 点爱心(prob={})".format( getattr(analyser, "yanghao_like_prob", 0) ) @@ -437,9 +471,9 @@ def yanghao_idle(analyser, total_seconds: int) -> None: else: prob = getattr(analyser, "yanghao_like_prob", 0) if like_ok: - print("[养号] 动作: 跳过点爱心(prob={prob})") + _yanghao_log(analyser, f"[养号] 动作: 跳过点爱心(prob={prob})") else: - print("[养号] 动作: 跳过点爱心(未检测到图标)") + _yanghao_log(analyser, "[养号] 动作: 跳过点爱心(未检测到图标)") # 根据概率点击收藏 if ( @@ -455,7 +489,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: ) did_fav = True analyser.operation.delay(1.0) # 延迟1秒 - print( + _yanghao_log(analyser, "[养号] 动作: 点收藏(prob={})".format( getattr(analyser, "yanghao_fav_prob", 0) ) @@ -463,9 +497,9 @@ def yanghao_idle(analyser, total_seconds: int) -> None: else: prob = getattr(analyser, "yanghao_fav_prob", 0) if fav_ok: - print("[养号] 动作: 跳过点收藏(prob={prob})") + _yanghao_log(analyser, f"[养号] 动作: 跳过点收藏(prob={prob})") else: - print("[养号] 动作: 跳过点收藏(未检测到图标)") + _yanghao_log(analyser, "[养号] 动作: 跳过点收藏(未检测到图标)") # 根据概率评论 # 仅在爱心和收藏都实际触发(都被点击)时才考虑评论 @@ -485,7 +519,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: pass _do_comment(analyser) did_comment = True - print( + _yanghao_log(analyser, "[养号] 动作: 评论(prob={})".format( getattr(analyser, "yanghao_comment_prob", 0) ) @@ -493,9 +527,9 @@ def yanghao_idle(analyser, total_seconds: int) -> None: else: prob = getattr(analyser, "yanghao_comment_prob", 0) if not (did_like and did_fav): - print("[养号] 动作: 跳过评论(爱心/收藏未同时触发)") + _yanghao_log(analyser, "[养号] 动作: 跳过评论(爱心/收藏未同时触发)") else: - print("[养号] 动作: 跳过评论(prob={prob})") + _yanghao_log(analyser, f"[养号] 动作: 跳过评论(prob={prob})") # 只有在实际执行了任意动作(爱心/收藏/评论)时才停留;仅检测到图标但未执行任何动作则直接跳过 if did_like or did_fav or did_comment: @@ -507,14 +541,14 @@ def yanghao_idle(analyser, total_seconds: int) -> None: or 30 ) dwell_time = random.uniform(dwell_min, dwell_max) - print(f"[养号] 检测到动作,停留 {dwell_time:.1f}s") + _yanghao_log(analyser, f"[养号] 检测到动作,停留 {dwell_time:.1f}s") analyser.operation.delay(dwell_time) else: # 每次操作后随机等待,避免行为太机械 _human_delay(2.0, 6.0) except Exception as e: - print(f"[养号] 循环异常: {e}") + _yanghao_log(analyser, f"[养号] 循环异常: {e}") analyser.operation.delay(1) return @@ -537,7 +571,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: ) if top_pkg and not is_douyin_pkg: - print(f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}") + _yanghao_log(analyser, f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}") # 执行自救操作 try: @@ -569,17 +603,17 @@ def yanghao_idle(analyser, total_seconds: int) -> None: analyser.operation.click(analyser.device_id, enter_x, enter_y) analyser.operation.delay(2.0) - print("[养号] 自救: 恢复操作完成") + _yanghao_log(analyser, "[养号] 自救: 恢复操作完成") return True except Exception as e: - print(f"[养号] 自救: 恢复操作失败: {e}") + _yanghao_log(analyser, f"[养号] 自救: 恢复操作失败: {e}") return False else: return False except Exception as e: - print(f"[养号] 自救: 桌面检测异常: {e}") + _yanghao_log(analyser, f"[养号] 自救: 桌面检测异常: {e}") return False while True: @@ -595,10 +629,10 @@ def yanghao_idle(analyser, total_seconds: int) -> None: try: # 桌面检测与恢复逻辑 if _yanghao_check_and_recover_from_desktop(analyser): - print("[养号] 检测到不在抖音前台,已尝试恢复") + _yanghao_log(analyser, "[养号] 检测到不在抖音前台,已尝试恢复") analyser.operation.delay(1) except Exception as e: - print(f"[养号] 桌面检测异常: {e}") + _yanghao_log(analyser, f"[养号] 桌面检测异常: {e}") # 分段等待(避免一次 sleep 太久,看起来更自然) remaining = int(total_seconds - (time.time() - start_ts)) @@ -633,7 +667,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: y1 = y_mid - int(dist / 2) y2 = y_mid + int(dist / 2) analyser.swipe(x, y1, x, y2, 180) - print( + _yanghao_log(analyser, "[养号] 动作: 下滑/切换 direction={} dist={}px".format( getattr(analyser, "yanghao_after_dwell_swipe_direction", "up"), dist ) @@ -666,7 +700,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: ) if top_pkg and not is_douyin_pkg: - print(f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}") + _yanghao_log(analyser, f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}") # 执行自救操作 try: @@ -704,17 +738,17 @@ def yanghao_idle(analyser, total_seconds: int) -> None: analyser.operation.click(analyser.device_id, enter_x, enter_y) analyser.operation.delay(2.0) - print("[养号] 自救: 恢复操作完成") + _yanghao_log(analyser, "[养号] 自救: 恢复操作完成") return True except Exception as e: - print(f"[养号] 自救: 恢复操作失败: {e}") + _yanghao_log(analyser, f"[养号] 自救: 恢复操作失败: {e}") return False else: return False except Exception as e: - print(f"[养号] 自救: 桌面检测异常: {e}") + _yanghao_log(analyser, f"[养号] 自救: 桌面检测异常: {e}") return False def _detect_icon( @@ -753,7 +787,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: except Exception: tpl_exists = False - print( + _yanghao_log(analyser, f"[养号][DEBUG] _detect_icon action={action} template_path='{template_path}' tpl_exists={tpl_exists}" ) if int(base_x or 0) <= 0 or int(base_y or 0) <= 0: @@ -823,7 +857,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: ) # 只截图不识别,总是假设图标存在并返回高置信度 - print(f"[养号] 检测: {action} -> 只截图不识别,假设图标存在") + _yanghao_log(analyser, f"[养号] 检测: {action} -> 只截图不识别,假设图标存在") return True, 1.0 @@ -839,29 +873,29 @@ def yanghao_recommend_flow(analyser, total_seconds: int) -> None: resy = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) except Exception: resx, resy = 1080, 2400 - print(f"设备分辨率为:{resx}*{resy}") - print(f"[YANGHAO-ONLY] device_id={analyser.device_id} res={resx}x{resy}") - print("[养号] 开始推荐页养号流程") + _yanghao_log(analyser, f"设备分辨率为:{resx}*{resy}") + _yanghao_log(analyser, f"[YANGHAO-ONLY] device_id={analyser.device_id} res={resx}x{resy}") + _yanghao_log(analyser, "[养号] 开始推荐页养号流程") # 步骤1: 发送系统返回键退出当前直播间 - print("[养号] 步骤1: 发送系统返回键退出直播间") + _yanghao_log(analyser, "[养号] 步骤1: 发送系统返回键退出直播间") analyser.operation.keyevent(analyser.device_id, 4) # KEYCODE_BACK = 4 analyser.operation.delay(3.0) # 步骤2: 再次发送返回键确保退出 - print("[养号] 步骤2: 再次发送返回键") + _yanghao_log(analyser, "[养号] 步骤2: 再次发送返回键") analyser.operation.keyevent(analyser.device_id, 4) # KEYCODE_BACK = 4 analyser.operation.delay(3.0) # 步骤3: 在推荐页执行养号 - print(f"[养号] 步骤3: 在推荐页养号 {total_seconds} 秒") + _yanghao_log(analyser, f"[养号] 步骤3: 在推荐页养号 {total_seconds} 秒") analyser.operation.delay(3.0) yanghao_idle(analyser, total_seconds) - print("[养号] 推荐页养号流程完成") + _yanghao_log(analyser, "[养号] 推荐页养号流程完成") except Exception as e: - print(f"[养号] 推荐页养号流程失败: {e}") + _yanghao_log(analyser, f"[养号] 推荐页养号流程失败: {e}") # 失败时退化为普通养号 yanghao_idle(analyser, total_seconds) @@ -873,7 +907,7 @@ def yanghao_wait(analyser, total_seconds: int) -> None: # 检查是否启用养号 if not bool(getattr(analyser, "yanghao_enabled", True)): - print("[养号] yanghao_enabled=0,跳过推荐页养号(快速继续)") + _yanghao_log(analyser, "[养号] yanghao_enabled=0,跳过推荐页养号(快速继续)") return # 执行推荐页养号流程 diff --git a/gui/components/log_viewer.py b/gui/components/log_viewer.py index eae9839..3f9bc07 100644 --- a/gui/components/log_viewer.py +++ b/gui/components/log_viewer.py @@ -7,6 +7,7 @@ from __future__ import annotations from typing import Any, Callable, Optional, List, Dict, Tuple +import logging import queue import re import threading @@ -16,6 +17,9 @@ import tkinter as tk from tkinter import ttk from tkinter.scrolledtext import ScrolledText +# 模块级 logger:内部错误(日志线程异常 / 刷新显示异常)走 logging,避免裸 print +_LOGVIEW_LOGGER = logging.getLogger("gui.components.log_viewer") + try: from ttkbootstrap.scrolled import ScrolledText as TBSrolledText ScrolledText = TBSrolledText @@ -230,7 +234,7 @@ class EnhancedLogViewer(ttk.Frame): break except Exception as e: - print(f"日志处理错误: {e}") + _LOGVIEW_LOGGER.exception("日志处理错误: %s", e) time.sleep(0.1) # 避免CPU占用过高 @@ -343,7 +347,7 @@ class EnhancedLogViewer(ttk.Frame): self.log_text.see("end") except Exception as e: - print(f"刷新显示错误: {e}") + _LOGVIEW_LOGGER.exception("刷新显示错误: %s", e) def _insert_colored_line(self, line: str) -> None: """插入带颜色的日志行""" diff --git a/gui/web_gui.py b/gui/web_gui.py index 2e34710..451e99d 100644 --- a/gui/web_gui.py +++ b/gui/web_gui.py @@ -23,6 +23,32 @@ BASE_DIR = path_config.PROJECT_ROOT CONFIG_PATH = path_config.get_config_path() WEBUI_DIR = path_config.get_webui_dir() +import logging as _logging + +# 模块级 logger:内部错误统一走 logging。 +# 启动横幅和中断消息保留 print(属于交互/CLI 输出,不是日志事件)。 +_LOGGER = _logging.getLogger("gui.web_gui") + + +def _wg_log(msg: str, level: str = "INFO") -> None: + """统一 web_gui 内部错误日志出口;失败兜底 stdout。""" + try: + lv = str(level or "INFO").upper() + if lv == "ERROR": + _LOGGER.error(str(msg)) + elif lv == "WARNING": + _LOGGER.warning(str(msg)) + elif lv == "DEBUG": + _LOGGER.debug(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + try: + print(str(msg)) + except Exception: + pass + + # CSRF token for POST request protection (local-only server) _CSRF_TOKEN = secrets.token_hex(32) @@ -219,14 +245,14 @@ class ProcRunner: except PermissionError as e: # 权限错误,只输出一次警告避免刷屏 if not self._log_permission_warned: - print(f"[WEB_GUI] 警告:日志文件写入权限错误: {self._log_file_path}") - print(f"[WEB_GUI] 错误详情: {e}") + _wg_log(f"[WEB_GUI] 警告:日志文件写入权限错误: {self._log_file_path}", level="WARNING") + _wg_log(f"[WEB_GUI] 错误详情: {e}", level="WARNING") self._log_permission_warned = True except Exception as e: # 其他文件写失败不应影响主流程,但记录第一次错误以便调试 if not self._log_write_error_warned: - print(f"[WEB_GUI] 警告:日志文件写入失败: {self._log_file_path}") - print(f"[WEB_GUI] 错误详情: {e}") + _wg_log(f"[WEB_GUI] 警告:日志文件写入失败: {self._log_file_path}", level="WARNING") + _wg_log(f"[WEB_GUI] 错误详情: {e}", level="WARNING") self._log_write_error_warned = True def _inc(self, key: str, n: int = 1) -> None: @@ -1728,7 +1754,7 @@ class Handler(BaseHTTPRequestHandler): except FileNotFoundError: self.send_error(HTTPStatus.NOT_FOUND) except Exception as e: - print(f"[WEB_GUI] Error serving static file {rel_path}: {e}") + _wg_log(f"[WEB_GUI] Error serving static file {rel_path}: {e}", level="ERROR") self.send_error(HTTPStatus.INTERNAL_SERVER_ERROR) def do_GET(self): @@ -1738,6 +1764,16 @@ class Handler(BaseHTTPRequestHandler): # 提供 CSRF token 给前端 if u.path == "/api/csrf-token": return self._send_json({"token": _CSRF_TOKEN}) + if u.path == "/api/version": + try: + from version import APP_VERSION, APP_BUILD_DATE, APP_NAME + except Exception: + APP_VERSION, APP_BUILD_DATE, APP_NAME = "?", "?", "douyin_guaji" + return self._send_json({ + "name": APP_NAME, + "version": str(APP_VERSION).lstrip("Vv"), + "build": APP_BUILD_DATE, + }) if u.path == "/api/devices": adb = find_adb_executable() return self._send_json({"adb": adb, "devices": list_adb_devices(adb)}) @@ -1792,8 +1828,9 @@ class Handler(BaseHTTPRequestHandler): except Exception as e: import traceback - print( - f"[WEB_GUI] logs search error: {e}\n{traceback.format_exc()}" + _wg_log( + f"[WEB_GUI] logs search error: {e}\n{traceback.format_exc()}", + level="ERROR", ) return self._send_json( {"next": 0, "lines": [], "running": RUNNER.is_running()} @@ -1818,8 +1855,9 @@ class Handler(BaseHTTPRequestHandler): # 记录错误但不中断请求,返回空日志 import traceback - print( - f"[WEB_GUI] get_logs_since error: {e}\n{traceback.format_exc()}" + _wg_log( + f"[WEB_GUI] get_logs_since error: {e}\n{traceback.format_exc()}", + level="ERROR", ) return self._send_json( {"next": 0, "lines": [], "running": RUNNER.is_running()} diff --git a/operations/ocr_operations.py b/operations/ocr_operations.py index 028ed20..45ccfad 100644 --- a/operations/ocr_operations.py +++ b/operations/ocr_operations.py @@ -24,6 +24,33 @@ cpu_count = os_module.cpu_count() or 4 optimal_omp_threads = min(4, max(2, cpu_count // 3)) os.environ.setdefault("OMP_NUM_THREADS", str(optimal_omp_threads)) +import logging as _logging + +# 模块级 logger:原代码用 print 输出 OCR 引擎初始化日志,统一走 logging。 +# 保留消息中已有的 "[OCR]" 前缀,避免改变历史搜索习惯。 +_LOGGER = _logging.getLogger("operations.ocr_operations") + + +def _ocr_log(msg: str, level: str = "INFO") -> None: + """统一 OCR 操作日志出口;失败兜底 stdout。""" + try: + lv = str(level or "INFO").upper() + if lv == "ERROR": + _LOGGER.error(str(msg)) + elif lv == "WARNING": + _LOGGER.warning(str(msg)) + elif lv == "DEBUG": + _LOGGER.debug(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + try: + _ocr_log(str(msg)) + except Exception: + pass + + + class OCRProcessor: """OCR处理器类""" @@ -63,10 +90,10 @@ class OCRProcessor: ) self.ocr_type = "easyocr" - print(f"[OCR] 使用 EasyOCR(CPU模式)") + _ocr_log(f"[OCR] 使用 EasyOCR(CPU模式)") except Exception as e: # EasyOCR初始化失败,回退到PaddleOCR - print(f"[OCR] EasyOCR初始化失败: {e},回退到PaddleOCR") + _ocr_log(f"[OCR] EasyOCR初始化失败: {e},回退到PaddleOCR") devnull = None try: devnull = open(os.devnull, "w") @@ -87,8 +114,8 @@ class OCRProcessor: use_textline_orientation=False, ) self.ocr_type = "paddleocr" - print(f"[OCR] EasyOCR不可用,使用 PaddleOCR(CPU模式)") - print( + _ocr_log(f"[OCR] EasyOCR不可用,使用 PaddleOCR(CPU模式)") + _ocr_log( f"[OCR] 提示:安装EasyOCR可提升速度,运行: pip install easyocr" ) except Exception: @@ -124,7 +151,7 @@ class OCRProcessor: ) self.ocr_type = "easyocr" gpu_status = "CPU模式" - print(f"[OCR] 延迟初始化:使用 EasyOCR({gpu_status})") + _ocr_log(f"[OCR] 延迟初始化:使用 EasyOCR({gpu_status})") except Exception: # EasyOCR失败,回退到PaddleOCR try: @@ -154,9 +181,9 @@ class OCRProcessor: use_textline_orientation=False, ) self.ocr_type = "paddleocr" - print(f"[OCR] 延迟初始化:EasyOCR不可用,使用 PaddleOCR(CPU模式)") + _ocr_log(f"[OCR] 延迟初始化:EasyOCR不可用,使用 PaddleOCR(CPU模式)") except Exception as e: - print(f"[OCR] OCR引擎初始化失败: {e}") + _ocr_log(f"[OCR] OCR引擎初始化失败: {e}") self.ocr = None self.ocr_type = None finally: diff --git a/operations/scrcpy_screenshot.py b/operations/scrcpy_screenshot.py deleted file mode 100644 index 5aab0d7..0000000 --- a/operations/scrcpy_screenshot.py +++ /dev/null @@ -1,100 +0,0 @@ -"""使用 scrcpy server 模式进行截图(高性能替代方案) - -scrcpy 通过 server 模式可以实现比 adb screencap 更快的截图速度。 -""" - -from __future__ import annotations - -import os -import subprocess -import time -import tempfile -from typing import Optional -from datetime import datetime - -from operations.screenshot_operations import ScreenshotOperations - - -class ScrcpyScreenshot: - """使用 scrcpy server 进行截图""" - - def __init__(self): - self._scrcpy_path: Optional[str] = None - self._server_path: Optional[str] = None - self._find_scrcpy() - - def _find_scrcpy(self): - """查找 scrcpy 可执行文件""" - import shutil - - # 先检查 PATH - which_path = shutil.which('scrcpy') - if which_path: - self._scrcpy_path = which_path - return - - # 检查常见安装位置 - candidates = [ - os.path.join(os.getenv('LOCALAPPDATA', ''), 'Programs', 'scrcpy', 'scrcpy.exe'), - os.path.join(os.getenv('USERPROFILE', ''), 'AppData', 'Local', 'Programs', 'scrcpy', 'scrcpy.exe'), - r'C:\Program Files\scrcpy\scrcpy.exe', - r'C:\Program Files (x86)\scrcpy\scrcpy.exe', - ] - - for path in candidates: - if path and os.path.exists(path): - self._scrcpy_path = path - # server 文件通常在同一目录 - server_path = os.path.join(os.path.dirname(path), 'scrcpy-server') - if os.path.exists(server_path): - self._server_path = server_path - break - - def is_available(self) -> bool: - """检查 scrcpy 是否可用""" - return self._scrcpy_path is not None and os.path.exists(self._scrcpy_path) - - def get_screenshot(self, device_id: str, output_path: str) -> bool: - """使用 scrcpy 进行截图 - - 注意:scrcpy 本身不直接支持单次截图,这里使用变通方法: - 1. 启动 scrcpy server(如果支持) - 2. 或使用 scrcpy 的录制功能提取帧 - - 参数: - device_id: 设备ID - output_path: 输出文件路径 - - 返回: - 是否成功 - """ - if not self.is_available(): - return False - - timetag = datetime.now().strftime("%H:%M:%S") - start_time = time.time() - - try: - # 方法1: 使用 scrcpy 的 --record 功能(需要停止机制,较复杂) - # 方法2: 使用 scrcpy server 模式(推荐,但需要额外配置) - # 方法3: 回退到 adb screencap(当前实现) - - # 由于 scrcpy 不直接支持单次截图,这里先记录日志 - # 实际实现需要集成 scrcpy server 或使用第三方库 - print(f"[{timetag}] [scrcpy] 注意: scrcpy 不直接支持单次截图") - print(f"[{timetag}] [scrcpy] 需要使用 scrcpy server 模式或集成到截图流程") - - # 暂时回退到标准截图方法 - ops = ScreenshotOperations() - return ops._get_screenshot_direct(device_id, os.path.dirname(output_path)) - - except Exception as e: - elapsed = (time.time() - start_time) * 1000 - print(f"[{timetag}] [scrcpy] 截图失败: {e},耗时: {elapsed:.0f}ms") - return False - - -def get_scrcpy_screenshot(device_id: str, output_path: str) -> bool: - """获取 scrcpy 截图(便捷函数)""" - scrcpy = ScrcpyScreenshot() - return scrcpy.get_screenshot(device_id, output_path) diff --git a/operations/screenshot_operations.py b/operations/screenshot_operations.py index 26d49cc..8814228 100644 --- a/operations/screenshot_operations.py +++ b/operations/screenshot_operations.py @@ -19,6 +19,33 @@ from douyin.core.underlying_operations import _safe_replace_file, _mirror_screen _last_service_fallback_log_ts: float = 0.0 _SERVICE_FALLBACK_LOG_INTERVAL = 10.0 # seconds +import logging as _logging + +# 模块级 logger:原代码用 print 输出截图操作日志,统一走 logging。 +# 保留消息中已有的 "[截图]"/"[截图操作]" 前缀,避免改变历史搜索习惯。 +_LOGGER = _logging.getLogger("operations.screenshot_operations") + + +def _ops_log(msg: str, level: str = "INFO") -> None: + """统一截图操作日志出口;失败兜底 stdout。""" + try: + lv = str(level or "INFO").upper() + if lv == "ERROR": + _LOGGER.error(str(msg)) + elif lv == "WARNING": + _LOGGER.warning(str(msg)) + elif lv == "DEBUG": + _LOGGER.debug(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + try: + _ops_log(str(msg)) + except Exception: + pass + + + class ScreenshotOperations: """截图操作类""" @@ -68,7 +95,7 @@ class ScreenshotOperations: global _last_service_fallback_log_ts if now - _last_service_fallback_log_ts > _SERVICE_FALLBACK_LOG_INTERVAL: timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图操作] 后台服务未提供有效截图,回退到直接截图") + _ops_log(f"[{timetag}] [截图操作] 后台服务未提供有效截图,回退到直接截图") _last_service_fallback_log_ts = now return self._get_screenshot_direct(device_id, path) except Exception: @@ -77,7 +104,7 @@ class ScreenshotOperations: except Exception as e: # 服务不可用时,回退到直接截图 timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图操作] ⚠️ 服务模式失败,回退到直接截图: {e}") + _ops_log(f"[{timetag}] [截图操作] ⚠️ 服务模式失败,回退到直接截图: {e}") # 原有的直接截图逻辑(保持向后兼容) return self._get_screenshot_direct(device_id, path) @@ -185,11 +212,11 @@ class ScreenshotOperations: t_exec_end = time.time() exec_ms = (t_exec_end - t_exec_start) * 1000 timetag2 = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag2}] [DEBUG] exec-out duration: {exec_ms:.0f}ms (device_id={device_id})") + _ops_log(f"[{timetag2}] [DEBUG] exec-out duration: {exec_ms:.0f}ms (device_id={device_id})") except subprocess.TimeoutExpired: # Popen 超时,记录并重新抛出异常 - print(f"[截图] exec-out 流式读取超时") + _ops_log(f"[截图] exec-out 流式读取超时") raise if _valid_png(tmp_file): # 使用安全的文件替换函数并二次验证目标文件,避免写入截断导致后续读取失败 @@ -198,11 +225,11 @@ class ScreenshotOperations: if _valid_png(out_file): _mirror_screenshot_to_external(out_file) elapsed = (time.time() - direct_start) * 1000 - print(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (exec-out,耗时: {elapsed:.0f}ms)") + _ops_log(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (exec-out,耗时: {elapsed:.0f}ms)") return True else: # 替换后目标文件不完整,记录并尝试回退到 pull - print(f"[{timetag}] [截图] 警告:替换后目标文件不完整,回退到 pull") + _ops_log(f"[{timetag}] [截图] 警告:替换后目标文件不完整,回退到 pull") try: if os.path.exists(out_file): os.remove(out_file) @@ -211,10 +238,10 @@ class ScreenshotOperations: # 不立即返回,继续尝试回退方案 else: # 如果替换失败,但临时文件有效,记录并尝试回退方案 - print(f"[{timetag}] [截图] 文件替换失败,但截图已保存到临时文件,将尝试回退方案") + _ops_log(f"[{timetag}] [截图] 文件替换失败,但截图已保存到临时文件,将尝试回退方案") except subprocess.TimeoutExpired: # 超时异常,记录并继续重试 - print(f"[截图] exec-out 超时,尝试重试或回退方案") + _ops_log(f"[截图] exec-out 超时,尝试重试或回退方案") try: if os.path.exists(tmp_file): os.remove(tmp_file) @@ -223,12 +250,12 @@ class ScreenshotOperations: except subprocess.CalledProcessError as e: # 特殊处理adb错误 if e.returncode == 4294967295: - print(f"[截图] exec-out 异常:设备连接失败或ADB服务异常 (设备ID: {device_id})") + _ops_log(f"[截图] exec-out 异常:设备连接失败或ADB服务异常 (设备ID: {device_id})") else: - print(f"[截图] exec-out 异常:{e}") + _ops_log(f"[截图] exec-out 异常:{e}") except Exception as e: # 继续回退/重试 - print(f"[截图] exec-out 异常:{e}") + _ops_log(f"[截图] exec-out 异常:{e}") try: if os.path.exists(tmp_file): os.remove(tmp_file) @@ -267,30 +294,30 @@ class ScreenshotOperations: shell_ms = (t_shell_end - t_shell_start) * 1000 pull_ms = (t_pull_end - t_pull_start) * 1000 timetag3 = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag3}] [DEBUG] shell_screencap: {shell_ms:.0f}ms, pull: {pull_ms:.0f}ms (device_id={device_id})") + _ops_log(f"[{timetag3}] [DEBUG] shell_screencap: {shell_ms:.0f}ms, pull: {pull_ms:.0f}ms (device_id={device_id})") if _valid_png(tmp_file): # 使用安全的文件替换函数 if _safe_replace_file(tmp_file, out_file): _mirror_screenshot_to_external(out_file) elapsed = (time.time() - direct_start) * 1000 - print(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (回退方案,耗时: {elapsed:.0f}ms)") + _ops_log(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (回退方案,耗时: {elapsed:.0f}ms)") return True else: - print("[截图] 回退方案文件替换失败") + _ops_log("[截图] 回退方案文件替换失败") return False else: - print("[截图] 回退方案截图无效") + _ops_log("[截图] 回退方案截图无效") return False except subprocess.CalledProcessError as e: # 特殊处理adb错误 if e.returncode == 4294967295: - print(f"[截图] 回退方案失败:设备连接失败或ADB服务异常 (设备ID: {device_id})") + _ops_log(f"[截图] 回退方案失败:设备连接失败或ADB服务异常 (设备ID: {device_id})") else: - print(f"[截图] 回退方案失败:ADB命令错误 (返回码: {e.returncode})") + _ops_log(f"[截图] 回退方案失败:ADB命令错误 (返回码: {e.returncode})") except subprocess.TimeoutExpired: - print(f"[截图] 回退方案失败:操作超时 (设备ID: {device_id})") + _ops_log(f"[截图] 回退方案失败:操作超时 (设备ID: {device_id})") except Exception as e: - print(f"[截图] 回退方案失败:{e}") + _ops_log(f"[截图] 回退方案失败:{e}") return False def _find_pic_path(self, picname: str, for_reading: bool = True) -> Optional[str]: diff --git a/operations/screenshot_service.py b/operations/screenshot_service.py index 67dd842..4ebd3ef 100644 --- a/operations/screenshot_service.py +++ b/operations/screenshot_service.py @@ -17,6 +17,33 @@ from datetime import datetime from douyin.core import path_config from operations.screenshot_operations import ScreenshotOperations +import logging as _logging + +# 模块级 logger:原代码用 print 输出截图服务日志,这里统一走 logging。 +# 保留消息中已有的"[截图服务]"前缀,避免改变历史搜索习惯。 +_LOGGER = _logging.getLogger("operations.screenshot_service") + + +def _svc_log(msg: str, level: str = "INFO") -> None: + """统一截图服务日志出口;失败兜底 stdout 以避免静默丢失。""" + try: + lv = str(level or "INFO").upper() + if lv == "ERROR": + _LOGGER.error(str(msg)) + elif lv == "WARNING": + _LOGGER.warning(str(msg)) + elif lv == "DEBUG": + _LOGGER.debug(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + try: + _svc_log(str(msg)) + except Exception: + pass + + + class ScreenshotService: """后台截图服务:持续截图,避免主流程等待""" @@ -68,7 +95,7 @@ class ScreenshotService: self._thread.start() self._last_screenshot_time = time.time() - self._cache_valid_duration - 1.0 timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图服务] 已启动后台截图服务,设备: {device_id}, 间隔: {interval}秒") + _svc_log(f"[{timetag}] [截图服务] 已启动后台截图服务,设备: {device_id}, 间隔: {interval}秒") def stop(self): """停止后台截图服务""" @@ -80,7 +107,7 @@ class ScreenshotService: if self._thread and self._thread.is_alive(): self._thread.join(timeout=2.0) timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图服务] 已停止后台截图服务") + _svc_log(f"[{timetag}] [截图服务] 已停止后台截图服务") def _screenshot_loop(self): """后台截图循环""" @@ -111,22 +138,22 @@ class ScreenshotService: if header == b'\x89PNG': self._last_screenshot_time = time.time() self._last_success = True - print(f"[{timetag}] [截图服务] 后台截图完成 #{loop_count},耗时: {screenshot_elapsed:.0f}ms,文件大小: {file_size/1024:.1f}KB") + _svc_log(f"[{timetag}] [截图服务] 后台截图完成 #{loop_count},耗时: {screenshot_elapsed:.0f}ms,文件大小: {file_size/1024:.1f}KB") else: self._last_success = False - print(f"[{timetag}] [截图服务] 后台截图文件格式错误 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") + _svc_log(f"[{timetag}] [截图服务] 后台截图文件格式错误 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") else: self._last_success = False - print(f"[{timetag}] [截图服务] 后台截图文件太小 #{loop_count} ({file_size}B),耗时: {screenshot_elapsed:.0f}ms") + _svc_log(f"[{timetag}] [截图服务] 后台截图文件太小 #{loop_count} ({file_size}B),耗时: {screenshot_elapsed:.0f}ms") except (OSError, IOError, ValueError) as e: self._last_success = False - print(f"[{timetag}] [截图服务] 后台截图文件验证失败 #{loop_count}: {e},耗时: {screenshot_elapsed:.0f}ms") + _svc_log(f"[{timetag}] [截图服务] 后台截图文件验证失败 #{loop_count}: {e},耗时: {screenshot_elapsed:.0f}ms") else: self._last_success = False - print(f"[{timetag}] [截图服务] 后台截图文件不存在 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") + _svc_log(f"[{timetag}] [截图服务] 后台截图文件不存在 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") else: self._last_success = False - print(f"[{timetag}] [截图服务] 后台截图失败 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") + _svc_log(f"[{timetag}] [截图服务] 后台截图失败 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") # 等待间隔时间,确保不小于0.5秒 remaining_interval = max(0.5, self._screenshot_interval - screenshot_elapsed / 1000) @@ -134,7 +161,7 @@ class ScreenshotService: except Exception as e: try: timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图服务] 后台截图异常: {e}") + _svc_log(f"[{timetag}] [截图服务] 后台截图异常: {e}") import traceback traceback.print_exc() except Exception: @@ -156,7 +183,7 @@ class ScreenshotService: # 如果设备ID不同,需要重新启动服务 if self._current_device_id != device_id: - print(f"[{timetag}] [截图服务] 设备ID变更,重新启动服务: {device_id}") + _svc_log(f"[{timetag}] [截图服务] 设备ID变更,重新启动服务: {device_id}") self.start(device_id) # 等待第一次截图完成 time.sleep(0.1) @@ -194,46 +221,46 @@ class ScreenshotService: footer = f.read(read_size) if b'IEND' in footer: elapsed = (time.time() - request_start) * 1000 - print(f"[{timetag}] [截图服务] [OK] 缓存命中,耗时: {elapsed:.1f}ms (距离上次截图: {time_since_last*1000:.0f}ms, 文件大小: {file_size/1024:.1f}KB)") + _svc_log(f"[{timetag}] [截图服务] [OK] 缓存命中,耗时: {elapsed:.1f}ms (距离上次截图: {time_since_last*1000:.0f}ms, 文件大小: {file_size/1024:.1f}KB)") return True elif retry < 2: # 文件可能还在写入,等待一下 time.sleep(0.1) continue else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件不完整(文件尾验证失败),等待后台截图") + _svc_log(f"[{timetag}] [截图服务] [WARN] 缓存文件不完整(文件尾验证失败),等待后台截图") except (OSError, IOError) as e: if retry < 2: time.sleep(0.1) continue else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件读取失败: {e},等待后台截图") + _svc_log(f"[{timetag}] [截图服务] [WARN] 缓存文件读取失败: {e},等待后台截图") else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件格式错误,等待后台截图") + _svc_log(f"[{timetag}] [截图服务] [WARN] 缓存文件格式错误,等待后台截图") break else: if retry < 2: time.sleep(0.05) continue else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件太小 ({file_size}B),等待后台截图") + _svc_log(f"[{timetag}] [截图服务] [WARN] 缓存文件太小 ({file_size}B),等待后台截图") except (OSError, IOError) as e: if retry < 2: time.sleep(0.05) continue else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件检查失败: {e},等待后台截图") + _svc_log(f"[{timetag}] [截图服务] [WARN] 缓存文件检查失败: {e},等待后台截图") except ValueError as e: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件检查异常: {e},等待后台截图") + _svc_log(f"[{timetag}] [截图服务] [WARN] 缓存文件检查异常: {e},等待后台截图") break else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件不存在,等待后台截图") + _svc_log(f"[{timetag}] [截图服务] [WARN] 缓存文件不存在,等待后台截图") else: - print(f"[{timetag}] [截图服务] [WARN] 缓存已过期 (距离上次: {time_since_last*1000:.0f}ms > {self._cache_valid_duration*1000:.0f}ms),等待后台截图") + _svc_log(f"[{timetag}] [截图服务] [WARN] 缓存已过期 (距离上次: {time_since_last*1000:.0f}ms > {self._cache_valid_duration*1000:.0f}ms),等待后台截图") # 缓存无效或强制刷新 if force: - print(f"[{timetag}] [截图服务] 🔄 强制刷新,忽略缓存") + _svc_log(f"[{timetag}] [截图服务] 🔄 强制刷新,忽略缓存") # 等待后台截图完成 if self._running: @@ -244,7 +271,7 @@ class ScreenshotService: time_since_last_before_wait = 0 elif time_since_last_before_wait > 86400: time_since_last_before_wait = 10.0 - print(f"[{timetag}] [截图服务] [WAIT] 缓存未命中,等待后台截图 (距离上次: {time_since_last_before_wait*1000:.0f}ms)") + _svc_log(f"[{timetag}] [截图服务] [WAIT] 缓存未命中,等待后台截图 (距离上次: {time_since_last_before_wait*1000:.0f}ms)") # 等待最多6秒,让后台线程完成截图(适应较慢的截图操作) max_wait_time = 6.0 @@ -266,7 +293,7 @@ class ScreenshotService: wait_elapsed = (time.time() - wait_start) * 1000 total_elapsed = (time.time() - request_start) * 1000 status = "[OK]" if self._last_success else "[FAIL]" - print(f"[{timetag}] [截图服务] {status} 后台截图完成,等待耗时: {wait_elapsed:.1f}ms,总耗时: {total_elapsed:.1f}ms,文件大小: {file_size/1024:.1f}KB") + _svc_log(f"[{timetag}] [截图服务] {status} 后台截图完成,等待耗时: {wait_elapsed:.1f}ms,总耗时: {total_elapsed:.1f}ms,文件大小: {file_size/1024:.1f}KB") return self._last_success # 文件尾验证失败,继续等待 # 文件太小或格式错误,继续等待 @@ -277,7 +304,7 @@ class ScreenshotService: # 等待超时 wait_elapsed = (time.time() - wait_start) * 1000 - print(f"[{timetag}] [截图服务] [TIMEOUT] 等待超时 ({wait_elapsed:.1f}ms),回退到直接截图") + _svc_log(f"[{timetag}] [截图服务] [TIMEOUT] 等待超时 ({wait_elapsed:.1f}ms),回退到直接截图") # 如果后台服务未运行或等待超时,直接执行截图(禁用服务模式,避免递归) direct_start = time.time() @@ -285,7 +312,7 @@ class ScreenshotService: direct_elapsed = (time.time() - direct_start) * 1000 total_elapsed = (time.time() - request_start) * 1000 status = "[OK]" if result else "[FAIL]" - print(f"[{timetag}] [截图服务] {status} 直接截图完成,耗时: {direct_elapsed:.0f}ms,总耗时: {total_elapsed:.1f}ms") + _svc_log(f"[{timetag}] [截图服务] {status} 直接截图完成,耗时: {direct_elapsed:.0f}ms,总耗时: {total_elapsed:.1f}ms") return result def is_running(self) -> bool: diff --git a/tools/diagnostics/check_web_gui_config_sync.py b/tools/diagnostics/check_web_gui_config_sync.py index 8f83d84..bbca2b2 100644 --- a/tools/diagnostics/check_web_gui_config_sync.py +++ b/tools/diagnostics/check_web_gui_config_sync.py @@ -19,10 +19,10 @@ import re import sys from pathlib import Path -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] GUI_APP = ROOT / "gui" / "gui_app.py" WEB_INDEX = ROOT / "webui" / "index.html" -MANIFEST_PATH = ROOT / "tools" / "web_gui_config_manifest.json" +MANIFEST_PATH = ROOT / "tools" / "dev" / "web_gui_config_manifest.json" IGNORED_CONTAINER_KEYS = { "debug_captures", diff --git a/webui/app.js b/webui/app.js index 2bbf5c7..a12beda 100644 --- a/webui/app.js +++ b/webui/app.js @@ -240,7 +240,9 @@ function initTheme() { btn.addEventListener("click", () => { const next = root.getAttribute("data-theme") === "dark" ? "light" : "dark"; try { localStorage.setItem("ui-theme", next); } catch (_) {} + root.classList.add("isThemeSwitching"); apply(next); + setTimeout(() => root.classList.remove("isThemeSwitching"), 260); }); } @@ -256,16 +258,444 @@ function initTheme() { } } +function ensureToastContainer() { + let c = document.getElementById("toastContainer"); + if (!c) { + c = document.createElement("div"); + c.id = "toastContainer"; + c.className = "toastContainer"; + c.setAttribute("role", "status"); + c.setAttribute("aria-live", "polite"); + document.body.appendChild(c); + } + return c; +} + +function toast(message, kind = "info", { duration = 3500 } = {}) { + if (!message) return; + const container = ensureToastContainer(); + const t = document.createElement("div"); + t.className = `toast toast-${kind}`; + const icon = document.createElement("span"); + icon.className = "toastIcon"; + icon.setAttribute("aria-hidden", "true"); + const ICONS = { + success: '', + error: '', + warn: '', + info: '', + }; + icon.innerHTML = ICONS[kind] || ICONS.info; + const body = document.createElement("div"); + body.className = "toastBody"; + body.textContent = String(message); + const close = document.createElement("button"); + close.className = "toastClose"; + close.type = "button"; + close.setAttribute("aria-label", "关闭"); + close.innerHTML = ''; + t.append(icon, body, close); + container.appendChild(t); + let timer = setTimeout(remove, duration); + function remove() { + if (timer) { clearTimeout(timer); timer = null; } + t.classList.add("isLeaving"); + setTimeout(() => t.remove(), 220); + } + close.addEventListener("click", remove); + t.addEventListener("mouseenter", () => { if (timer) { clearTimeout(timer); timer = null; } }); + t.addEventListener("mouseleave", () => { if (!timer) timer = setTimeout(remove, 1500); }); + return remove; +} + +function initConfigSearch() { + const input = $("configSearch"); + const clear = $("configSearchClear"); + const empty = $("configSearchEmpty"); + if (!input) return; + + // Cache: rows = [.row], with their lower-case search text + parent panel + const rows = Array.from(document.querySelectorAll(".panels .panel .row")); + const rowMeta = rows.map((row) => { + const textParts = []; + row.querySelectorAll(".label, .check span, .hint, span").forEach((el) => { + const t = (el.textContent || "").trim(); + if (t) textParts.push(t); + }); + row.querySelectorAll("input[data-key], select[data-key], textarea[data-key]").forEach((el) => { + if (el.dataset.key) textParts.push(el.dataset.key); + }); + return { row, panel: row.closest(".panel"), text: textParts.join(" ").toLowerCase() }; + }); + + // Section titles: when filtering, hide sections that have no visible row after them + const allSectionTitles = Array.from(document.querySelectorAll(".panels .panel .sectionTitle")); + + const apply = (q) => { + const query = q.trim().toLowerCase(); + if (clear) clear.toggleAttribute("hidden", !query); + const countBadge = document.getElementById("configSearchCount"); + + if (!query) { + // Restore all + rowMeta.forEach(({ row }) => row.classList.remove("isSearchHidden")); + allSectionTitles.forEach((s) => s.classList.remove("isSearchHidden")); + document.querySelectorAll(".panel").forEach((p) => p.classList.remove("isSearchAllHidden")); + if (empty) empty.hidden = true; + if (countBadge) countBadge.hidden = true; + // Re-apply normal tab visibility (panels may have been forced visible) + const activeTab = document.querySelector(".tabBtn.active[data-target]"); + if (activeTab) { + const target = activeTab.dataset.target; + document.querySelectorAll(".panel[data-panel]").forEach((p) => { + const on = p.dataset.panel === target; + p.toggleAttribute("hidden", !on); + p.classList.toggle("active", on); + }); + } + return; + } + + // While searching: show ALL panels (panels normally hide via [hidden]), then filter rows. + document.querySelectorAll(".panel[data-panel]").forEach((p) => { + p.removeAttribute("hidden"); + p.classList.add("active"); + }); + + let totalVisible = 0; + const visibleByPanel = new Map(); + rowMeta.forEach(({ row, panel, text }) => { + const match = text.includes(query); + row.classList.toggle("isSearchHidden", !match); + if (match) { + totalVisible++; + visibleByPanel.set(panel, (visibleByPanel.get(panel) || 0) + 1); + } + }); + + // Hide section titles that have no visible row in their following sibling group + allSectionTitles.forEach((title) => { + let next = title.nextElementSibling; + let anyVisible = false; + while (next && !next.matches(".sectionTitle")) { + if (next.matches(".row") && !next.classList.contains("isSearchHidden")) { anyVisible = true; break; } + next = next.nextElementSibling; + } + title.classList.toggle("isSearchHidden", !anyVisible); + }); + + // Hide panels that have zero visible rows + document.querySelectorAll(".panel[data-panel]").forEach((p) => { + const visible = visibleByPanel.get(p) || 0; + p.toggleAttribute("hidden", visible === 0); + }); + + if (empty) empty.hidden = totalVisible > 0; + if (countBadge) { + countBadge.hidden = false; + countBadge.textContent = `${totalVisible} 项`; + } + }; + + let debounceTimer; + input.addEventListener("input", () => { + clearTimeout(debounceTimer); + debounceTimer = setTimeout(() => apply(input.value), 80); + }); + + if (clear) { + clear.addEventListener("click", () => { + input.value = ""; + apply(""); + input.focus(); + }); + } + + // Platform-aware kbd hint label + const isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || ""); + const kbdMod = $("configSearchKbdMod"); + if (kbdMod) kbdMod.textContent = isMac ? "⌘" : "Ctrl"; + + // ⌘K / Ctrl+K to focus, ESC to clear/blur + document.addEventListener("keydown", (e) => { + const mod = isMac ? e.metaKey : e.ctrlKey; + if (mod && e.key.toLowerCase() === "k") { + e.preventDefault(); + input.focus(); + input.select(); + return; + } + if (e.key === "Escape" && document.activeElement === input) { + if (input.value) { + input.value = ""; + apply(""); + } else { + input.blur(); + } + } + }); +} + +function initFooter() { + // 版本号尝试从 /api/version 拿;拿不到就用 cache-bust 标识做 fallback + const verEl = document.getElementById("appFooterVersion"); + const buildEl = document.getElementById("appFooterBuild"); + (async () => { + try { + const data = await apiGet("/api/version"); + if (verEl && data?.version) verEl.textContent = "v" + data.version; + if (buildEl && data?.build) buildEl.textContent = data.build; + } catch (_) { + // fallback:从当前 script 的 cache-bust 提取 + const tag = (document.currentScript?.src || document.querySelector('script[src*="app.js"]')?.src || "") + .split("v=")[1] || ""; + if (verEl) verEl.textContent = tag ? tag.split("-").pop() : "—"; + if (buildEl) buildEl.textContent = "本地"; + } + })(); +} + +function attachCopyButtons() { + // 给指定 statValue 元素绑定一键复制(hover 显示按钮,点击复制文本) + const ids = ["statPid", "statTraceId"]; + for (const id of ids) { + const el = document.getElementById(id); + if (!el || el.dataset.copyBound === "1") continue; + el.dataset.copyBound = "1"; + el.classList.add("hasCopy"); + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "copyBtn"; + btn.setAttribute("aria-label", "复制"); + btn.setAttribute("data-tooltip", "复制"); + btn.setAttribute("data-tooltip-pos", "bottom"); + btn.innerHTML = ''; + btn.addEventListener("click", async (e) => { + e.stopPropagation(); + const text = (el.textContent || "").trim(); + if (!text || text === "-") { + toast("暂无可复制内容", "warn", { duration: 1800 }); + return; + } + try { + await navigator.clipboard.writeText(text); + toast("已复制:" + (text.length > 24 ? text.slice(0, 24) + "…" : text), "success", { duration: 1800 }); + } catch (err) { + // fallback for non-secure context + const ta = document.createElement("textarea"); + ta.value = text; + ta.style.position = "fixed"; + ta.style.opacity = "0"; + document.body.appendChild(ta); + ta.select(); + try { document.execCommand("copy"); toast("已复制", "success", { duration: 1800 }); } + catch (_) { toast("复制失败", "error", { duration: 2400 }); } + document.body.removeChild(ta); + } + }); + el.appendChild(btn); + } +} + +function initKeyboardShortcuts() { + const isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || ""); + document.addEventListener("keydown", (e) => { + const mod = isMac ? e.metaKey : e.ctrlKey; + if (!mod) return; + const key = e.key.toLowerCase(); + // ⌘S / Ctrl+S → 保存配置 + if (key === "s") { + e.preventDefault(); + const btn = document.getElementById("btnSave"); + if (btn && !btn.disabled) btn.click(); + return; + } + // ⌘Enter / Ctrl+Enter → 启动运行 + if (key === "enter") { + e.preventDefault(); + const btn = document.getElementById("btnStart"); + if (btn && !btn.disabled) btn.click(); + return; + } + }); +} + +function initHeaderScroll() { + const header = document.querySelector(".header"); + const scrollTop = document.getElementById("btnScrollTop"); + const onScroll = () => { + if (header) header.classList.toggle("isScrolled", window.scrollY > 8); + if (scrollTop) scrollTop.toggleAttribute("hidden", window.scrollY < 240); + }; + window.addEventListener("scroll", onScroll, { passive: true }); + if (scrollTop) { + scrollTop.addEventListener("click", () => { + window.scrollTo({ top: 0, behavior: "smooth" }); + }); + } + onScroll(); +} + +function initShotFullscreen() { + const btn = document.getElementById("btnShotFullscreen"); + const img = document.getElementById("liveShot"); + if (!btn || !img) return; + btn.addEventListener("click", () => { + const target = img.closest(".preview") || img; + if (document.fullscreenElement) { + document.exitFullscreen?.(); + } else if (target.requestFullscreen) { + target.requestFullscreen().catch(() => { + // fallback:在新标签打开 + window.open(img.src, "_blank", "noopener"); + }); + } else { + window.open(img.src, "_blank", "noopener"); + } + }); +} + +function applyKbdHints() { + // 给 [data-kbd-mod="1"] 的按钮自动注入平台对应的修饰键前缀 + const isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || ""); + const prefix = isMac ? "⌘ " : "Ctrl "; + document.querySelectorAll('[data-kbd-mod="1"]').forEach((el) => { + el.setAttribute("data-kbd-prefix", prefix); + }); +} + +function initStickySectionShadow() { + // 当 .sectionTitle 真正贴住 sticky top 时加 .isStuck 类 + const titles = Array.from(document.querySelectorAll(".sectionTitle")) + .filter((el) => !el.matches(".cardTitle, summary, summary *")); + if (!titles.length || !("IntersectionObserver" in window)) return; + const io = new IntersectionObserver( + (entries) => { + for (const e of entries) { + // intersectionRatio < 1 && top 已到达 sentinel:贴住状态 + e.target.classList.toggle("isStuck", e.intersectionRatio < 1 && e.boundingClientRect.top <= 65); + } + }, + { threshold: [1], rootMargin: "-65px 0px 0px 0px" } + ); + titles.forEach((t) => io.observe(t)); +} + +function initShortcutsHelp() { + const isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || ""); + const mod = isMac ? "⌘" : "Ctrl"; + let overlay = null; + const ITEMS = [ + { keys: [mod, "K"], desc: "聚焦配置搜索" }, + { keys: [mod, "S"], desc: "保存配置" }, + { keys: [mod, "Enter"], desc: "开始运行" }, + { keys: ["Esc"], desc: "清空搜索 / 关闭弹层" }, + { keys: ["?"], desc: "显示此帮助" }, + ]; + const open = () => { + if (overlay) return; + overlay = document.createElement("div"); + overlay.className = "shortcutsOverlay"; + overlay.innerHTML = ` +