格式统一

This commit is contained in:
duxin
2026-07-01 09:57:27 +08:00
parent c793ea2204
commit a3c20d3e49
37 changed files with 2286 additions and 1978 deletions

View File

@ -16,6 +16,7 @@
ProgressUpdate → {percentage, message} 更新进度条
"""
import html
from datetime import datetime
from PyQt5.QtCore import QObject
@ -27,6 +28,8 @@ from PyQt5.QtWidgets import (
from src.gui.core.event_bus import global_event_bus
_MAX_LOG_LINES = 2000 # 日志行数上限,防止长时间运行内存耗尽
class LogManager(QObject):
"""日志与进度管理器。
@ -48,6 +51,15 @@ class LogManager(QObject):
global_event_bus.subscribe('LogMessage', self._on_log_message)
global_event_bus.subscribe('ProgressUpdate', self._on_progress_update)
# ★ 父控件销毁时自动取消订阅,防止回调泄漏
if parent is not None:
parent.destroyed.connect(self._cleanup)
def _cleanup(self):
"""清理 EventBus 订阅。"""
global_event_bus.unsubscribe('LogMessage', self._on_log_message)
global_event_bus.unsubscribe('ProgressUpdate', self._on_progress_update)
# ═══════════════════════════════════════════════════════════
# 公开 API
# ═══════════════════════════════════════════════════════════
@ -168,13 +180,23 @@ class LogManager(QObject):
"""LogMessage 事件回调:写入日志区。"""
if self._log_text is None:
return
if not isinstance(data, dict):
return
message = data.get('message', '')
level = data.get('level', 'info')
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# ★ HTML 转义:防止日志消息中的 < > & 破坏 HTML 渲染
safe_message = html.escape(str(message))
color_map = {'error': 'red', 'warning': 'orange'}
color = color_map.get(level, 'black')
formatted = f'<span style="color: {color};">[{timestamp}] {message}</span>'
formatted = f'<span style="color: {color};">[{timestamp}] {safe_message}</span>'
self._log_text.append(formatted)
# ★ 日志行数上限:防止长时间运行内存耗尽
if self._log_text.document().blockCount() > _MAX_LOG_LINES + 100:
self._log_text.clear()
self._log_text.append(
f'<span style="color: gray;">[日志已自动清空,达到 {_MAX_LOG_LINES} 行上限]</span>'
)
cursor = self._log_text.textCursor()
cursor.movePosition(QTextCursor.End)
self._log_text.setTextCursor(cursor)