Peach: Local-first video metadata scraper and media manager.
fix(tray): 提供可关闭的诊断报告窗口与打开操作
longmeidaoc89b176b23db
diff --git a/src/peach/tray.py b/src/peach/tray.pyindex e925f012b..f8180c960 100644--- a/src/peach/tray.py+++ b/src/peach/tray.py@@ -37,6 +37,7 @@ from .mdns import lan_ipv4from .netwatch import NetworkChangeWatcherfrom .mount import mount_share as mount_smb_sharefrom .process_job import assign_to_job, create_kill_on_close_job+from .tray_diagnostics import show_report as show_diagnostic_reportfrom .tray_lifecycle import Lifecyclefrom .tray_detached import handoff_trayfrom .sync import COPY_ACTIONS, SyncPlan, device_id, resolve@@ -88,6 +89,7 @@ TRAY_SOURCES = ("src/peach/tray.py","src/peach/tray_detached.py","src/peach/tray_lifecycle.py",+ "src/peach/tray_diagnostics.py","src/peach/menubar.py","src/peach/versioning.py","src/peach/sync.py",@@ -1037,6 +1039,7 @@ class PeachTray:self.version = self.versions.inspect()self._stop_event = threading.Event()self._action_lock = threading.Lock()+ self._diagnostics_lock = threading.Lock()self._build_checked_at = time.monotonic()self._build_attempted_head: str | None = Noneversion_menu = pystray.Menu(@@ -1209,11 +1212,23 @@ class PeachTray:def export_diagnostics(self, _icon=None, _item=None) -> None:from .support_bundle import save_bundle- try:- path = save_bundle()- show_message("Peach 诊断报告", f"诊断报告已保存:\n{path}")- except Exception as error:- show_message("Peach 诊断报告", error_reporting.failure_details("report-export", error), error=True)+ if not self._diagnostics_lock.acquire(blocking=False):+ return++ def work() -> None:+ try:+ path = save_bundle()+ try:+ show_diagnostic_report(path)+ except OSError as error:+ show_message("Peach 诊断报告", f"诊断报告已保存:\n{path}\n\n窗口或打开操作未完成:{error}", error=True)+ except Exception as error:+ show_message("Peach 诊断报告", error_reporting.failure_details("report-export", error), error=True)+ finally:+ self._diagnostics_lock.release()++ # 菜单回调及时返回;报告窗口在独立线程上使用系统自己的消息循环。+ threading.Thread(target=work, name="PeachDiagnostics", daemon=True).start()def check_updates(self, icon=None, _item=None) -> None:if not self._action_lock.acquire(blocking=False):diff --git a/src/peach/tray_diagnostics.py b/src/peach/tray_diagnostics.pynew file mode 100644index 000000000..f6e280088--- /dev/null+++ b/src/peach/tray_diagnostics.py@@ -0,0 +1,85 @@+"""诊断报告的 Windows 原生结果窗口。"""+from __future__ import annotations++import ctypes+import os+import struct+from ctypes import wintypes+from pathlib import Path+++OPEN_DIRECTORY = 1001+OPEN_FILE = 1002+CLOSE = 2 # IDCANCEL:Esc 与标题栏关闭具有同一个结果。+++def _template(path: Path) -> bytes:+ """按 winuser.h 的 DLGTEMPLATE / DLGITEMTEMPLATE 编码,控件按 DWORD 对齐。"""+ def text(value: str) -> bytes:+ return (value + '\0').encode('utf-16-le')++ # WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_MODALFRAME | DS_CENTER | DS_SETFONT+ data = bytearray(struct.pack('<IIHhhhh', 0x80C808C0, 0, 5, 0, 0, 360, 136))+ data.extend(b'\0\0\0\0' + text('Peach 诊断报告') + struct.pack('<H', 9) + text('Segoe UI'))++ def control(identifier, class_id, label, x, y, width, height, style):+ data.extend(b'\0' * (-len(data) % 4))+ data.extend(struct.pack('<IIhhhhH', 0x50000000 | style, 0,+ x, y, width, height, identifier))+ data.extend(struct.pack('<HH', 0xFFFF, class_id) + text(label) + b'\0\0')++ control(0xFFFF, 0x82, '诊断报告已保存,可打开目录或文件。', 12, 12, 336, 18, 0)+ # 只读多行 EDIT 支持选择、复制和垂直滚动,长路径不依赖标签折行。+ control(1003, 0x81, str(path), 12, 36, 336, 54, 0x00A10844)+ control(OPEN_DIRECTORY, 0x80, '打开目录', 108, 106, 76, 18, 0x10000)+ control(OPEN_FILE, 0x80, '打开文件', 190, 106, 76, 18, 0x10000)+ control(CLOSE, 0x80, '关闭', 272, 106, 76, 18, 0x10001)+ return bytes(data)+++def _windows_choice(path: Path) -> int:+ # DLGPROC 返回 INT_PTR,WPARAM / LPARAM 与 HWND 均使用指针宽度。+ dialog_proc = ctypes.WINFUNCTYPE(ctypes.c_ssize_t, wintypes.HWND, wintypes.UINT,+ wintypes.WPARAM, wintypes.LPARAM)+ user = ctypes.WinDLL('user32', use_last_error=True)+ user.DialogBoxIndirectParamW.argtypes = [wintypes.HINSTANCE, ctypes.c_void_p,+ wintypes.HWND, dialog_proc, wintypes.LPARAM]+ user.DialogBoxIndirectParamW.restype = ctypes.c_ssize_t+ user.EndDialog.argtypes = [wintypes.HWND, ctypes.c_ssize_t]+ user.EndDialog.restype = wintypes.BOOL+ user.GetDlgItem.argtypes = [wintypes.HWND, ctypes.c_int]+ user.GetDlgItem.restype = wintypes.HWND+ user.SetFocus.argtypes = [wintypes.HWND]+ user.SetFocus.restype = wintypes.HWND++ @dialog_proc+ def procedure(hwnd, message, wparam, _lparam):+ if message == 0x110: # WM_INITDIALOG+ user.SetFocus(user.GetDlgItem(hwnd, CLOSE))+ return 0+ if message == 0x10: # WM_CLOSE+ user.EndDialog(hwnd, CLOSE)+ return 1+ if message == 0x111 and (wparam & 0xFFFF) in (OPEN_DIRECTORY, OPEN_FILE, CLOSE):+ user.EndDialog(hwnd, wparam & 0xFFFF)+ return 1+ return 0++ template = ctypes.create_string_buffer(_template(path))+ # Windows 在调用线程内运行此窗口的消息循环,并在 EndDialog 后销毁窗口。+ choice = user.DialogBoxIndirectParamW(None, template, None, procedure, 0)+ if choice == -1:+ raise ctypes.WinError(ctypes.get_last_error())+ return choice+++def show_report(path: Path) -> None:+ """用户选择动作后关闭窗口,再交给系统默认应用打开路径。"""+ if os.name != 'nt':+ print(f'Peach 诊断报告:诊断报告已保存:{path}')+ return+ choice = _windows_choice(path)+ if choice == OPEN_DIRECTORY:+ os.startfile(path.parent)+ elif choice == OPEN_FILE:+ os.startfile(path)diff --git a/tests/test_tray_diagnostics.py b/tests/test_tray_diagnostics.pynew file mode 100644index 000000000..39a3a22f3--- /dev/null+++ b/tests/test_tray_diagnostics.py@@ -0,0 +1,177 @@+import json+import os+import subprocess+import sys+import tempfile+import threading+import unittest+from pathlib import Path+from unittest.mock import Mock, patch++from peach import tray+++class DiagnosticExportTests(unittest.TestCase):+ def make_tray(self):+ instance = object.__new__(tray.PeachTray)+ instance._diagnostics_lock = threading.Lock()+ instance.icon = Mock()+ return instance++ def test_export_returns_while_report_window_is_open_and_rejects_duplicate(self):+ instance = self.make_tray()+ entered = threading.Event()+ release = threading.Event()+ returned = threading.Event()+ path = Path('report.zip')++ def show(_path):+ entered.set()+ release.wait(5)++ def invoke():+ instance.export_diagnostics()+ returned.set()++ with patch('peach.support_bundle.save_bundle', return_value=path) as save, patch(+ 'peach.tray.show_diagnostic_report', side_effect=show, create=True,+ ), patch('peach.tray.show_message', side_effect=lambda *_a, **_k: show(path)):+ caller = threading.Thread(target=invoke)+ caller.start()+ try:+ self.assertTrue(entered.wait(3))+ self.assertTrue(returned.wait(1), '托盘菜单回调必须能返回')+ instance.export_diagnostics()+ self.assertEqual(save.call_count, 1)+ finally:+ release.set()+ caller.join(3)+ with instance._diagnostics_lock:+ pass++ def test_export_failure_releases_lock_and_reports_error(self):+ instance = self.make_tray()+ completed = threading.Event()+ with patch('peach.support_bundle.save_bundle', side_effect=OSError('disk unavailable')), patch(+ 'peach.tray.show_message', side_effect=lambda *_a, **_k: completed.set(),+ ) as message:+ instance.export_diagnostics()+ self.assertTrue(completed.wait(3))+ with instance._diagnostics_lock:+ pass+ self.assertTrue(message.call_args.kwargs['error'])++ def test_open_failure_keeps_the_saved_report_path_available(self):+ instance = self.make_tray()+ completed = threading.Event()+ path = Path('saved-report.zip')+ with patch('peach.support_bundle.save_bundle', return_value=path), patch(+ 'peach.tray.show_diagnostic_report', side_effect=OSError('no association'),+ ), patch('peach.tray.show_message', side_effect=lambda *_a, **_k: completed.set()) as message:+ instance.export_diagnostics()+ self.assertTrue(completed.wait(3))+ with instance._diagnostics_lock:+ pass+ self.assertIn(str(path), message.call_args.args[1])+ self.assertIn('诊断报告已保存', message.call_args.args[1])+ self.assertIn('no association', message.call_args.args[1])++ def test_dialog_module_requires_a_tray_restart(self):+ self.assertTrue(tray.tray_restart_required(('src/peach/tray_diagnostics.py',)))++[email protected](os.name == 'nt', '原生 Windows 对话框')+class NativeReportDialogTests(unittest.TestCase):+ def test_native_buttons_and_dismissal(self):+ for action in ('directory', 'file', 'close', 'window-close', 'escape', 'enter'):+ with self.subTest(action=action):+ result = subprocess.run(+ [sys.executable, '-X', 'utf8', str(Path(__file__).resolve()),+ '--native-harness', action],+ capture_output=True, text=True, encoding='utf-8', timeout=15,+ creationflags=subprocess.CREATE_NO_WINDOW,+ )+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ data = json.loads(result.stdout)+ self.assertEqual(data['opened'], [action] if action in ('file', 'directory') else [])+ self.assertEqual(data['buttons'], ['打开目录', '打开文件', '关闭'])+++def native_harness(action):+ """只向当前隔离进程创建的窗口投递消息。"""+ import ctypes+ import time+ from ctypes import wintypes+ from peach import tray_diagnostics as report_dialog++ user = ctypes.WinDLL('user32', use_last_error=True)+ enum_proc = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)+ user.EnumThreadWindows.argtypes = [wintypes.DWORD, enum_proc, wintypes.LPARAM]+ user.EnumThreadWindows.restype = wintypes.BOOL+ user.GetDlgItem.argtypes = [wintypes.HWND, ctypes.c_int]+ user.GetDlgItem.restype = wintypes.HWND+ user.GetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]+ user.GetWindowTextW.restype = ctypes.c_int+ user.IsWindowVisible.argtypes = [wintypes.HWND]+ user.IsWindowVisible.restype = wintypes.BOOL+ user.PostMessageW.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]+ user.PostMessageW.restype = wintypes.BOOL+ opened = []+ failures = []+ buttons = []+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory).resolve() / '诊断报告 with spaces.zip'+ path.touch()++ def run():+ try:+ report_dialog.show_report(path)+ except BaseException as error:+ failures.append(repr(error))++ def open_path(target):+ opened.append('file' if Path(target) == path else 'directory' if Path(target) == path.parent else 'unexpected')++ with patch.object(os, 'startfile', side_effect=open_path):+ worker = threading.Thread(target=run, daemon=True)+ worker.start()+ deadline = time.monotonic() + 8+ handles = []++ @enum_proc+ def find(hwnd, _data):+ if user.IsWindowVisible(hwnd) and user.GetDlgItem(hwnd, report_dialog.OPEN_FILE):+ handles.append(hwnd)+ return True++ while worker.is_alive() and time.monotonic() < deadline and not handles:+ user.EnumThreadWindows(worker.native_id, find, 0)+ time.sleep(.02)+ if not handles:+ raise AssertionError(f'未取得原生报告窗口:{failures}')+ hwnd = handles[0]+ for identifier in (report_dialog.OPEN_DIRECTORY, report_dialog.OPEN_FILE, report_dialog.CLOSE):+ text = ctypes.create_unicode_buffer(64)+ user.GetWindowTextW(user.GetDlgItem(hwnd, identifier), text, len(text))+ buttons.append(text.value)+ if action == 'window-close':+ user.PostMessageW(hwnd, 0x10, 0, 0)+ elif action in ('escape', 'enter'):+ key = 0x1B if action == 'escape' else 0x0D+ user.PostMessageW(hwnd, 0x100, key, 0)+ user.PostMessageW(hwnd, 0x101, key, 0)+ else:+ identifier = {'directory': report_dialog.OPEN_DIRECTORY,+ 'file': report_dialog.OPEN_FILE, 'close': report_dialog.CLOSE}[action]+ user.PostMessageW(user.GetDlgItem(hwnd, identifier), 0xF5, 0, 0) # BM_CLICK+ worker.join(4)+ if worker.is_alive() or failures:+ raise AssertionError(f'原生对话框未完成:{failures}')+ print(json.dumps({'opened': opened, 'buttons': buttons}, ensure_ascii=False))+++if __name__ == '__main__':+ if len(sys.argv) == 3 and sys.argv[1] == '--native-harness':+ native_harness(sys.argv[2])+ else:+ unittest.main()