Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(runtime): 命令行按 Win32 的三条规则劈,找源码托盘先筛便宜的判据

longmeidao5b4d34e6620a
diff --git a/src/peach/windows_restart.py b/src/peach/windows_restart.py
index ac4bc82ac..c77a2a7ca 100644
--- a/src/peach/windows_restart.py
+++ b/src/peach/windows_restart.py
@@ -15,7 +15,7 @@ import time
from ctypes import wintypes
from dataclasses import dataclass
from pathlib import Path
-from typing import Callable
+from typing import Callable, Iterable
from .windows_update import replace_with_retry, swap_tray_binary
@@ -53,15 +53,20 @@ def parse_windows_command_line(script: str | None) -> list[str]:
"""按 CommandLineToArgvW 的规则拆开一条命令行。
托盘的自定义 bootstrap 里既有引号又有字面引号内的单引号,`shlex` 的
- posix 反斜杠规则在 Windows 上不成立,所以要照 Win32 的两条规则自己劈:
- 2n 个反斜杠后跟引号 → n 个反斜杠加一个定界引号;2n+1 个 → n 个反斜杠加字面引号。
+ posix 反斜杠规则在 Windows 上不成立,所以照 Win32 的三条规则自己劈:
+ 2n 个反斜杠后跟引号 → n 个反斜杠加一个定界引号;2n+1 个 → n 个反斜杠加字面
+ 引号;引号里再遇到一个引号,后面紧跟的还是引号时出一个字面引号,否则收界。
分隔空白不带引号才算分隔,别把路径里的盘符斜杠拆成碎块。
+
+ 不直接调 shell32 的 CommandLineToArgvW,是为了让这一段在 macOS 上也跑得了
+ 测试:整个模块只在 Windows 上工作,但拆命令行是纯字符串的事,没有理由把它
+ 的判据锁死在一个平台上。
"""
if not script:
return []
argv: list[str] = []
current: list[str] = []
- slashes = 0
+ quoted = False
in_quotes = False
index = 0
while index < len(script):
@@ -71,47 +76,57 @@ def parse_windows_command_line(script: str | None) -> list[str]:
while index < len(script) and script[index] == "\\":
count += 1
index += 1
- followed_quote = index < len(script) and script[index] == '"'
- if followed_quote:
+ if index < len(script) and script[index] == '"':
current.append("\\" * (count // 2))
if count % 2:
+ # 奇数个反斜杠把这个引号转义成字面量,它不再收界。
current.append('"')
index += 1
- else:
- pass
else:
current.append("\\" * count)
continue
if char == '"':
- if in_quotes:
- in_quotes = False
- else:
- in_quotes = True
index += 1
+ if in_quotes and index < len(script) and script[index] == '"':
+ # 引号里的 "" 是一个字面引号,仍然在引号中。
+ current.append('"')
+ index += 1
+ continue
+ in_quotes = not in_quotes
+ quoted = True
continue
if not in_quotes and char.isspace():
- if current:
+ if current or quoted:
+ # `a "" b` 中间那个是真的空参数,不能因为没攒到字符就丢掉。
argv.append("".join(current))
current = []
+ quoted = False
index += 1
continue
current.append(char)
index += 1
- if current:
+ if current or quoted:
argv.append("".join(current))
return argv
-def _command_lines() -> dict[int, str]:
- """按 pid 读全部 Win32 进程的命令行,读不到就返回空。
+def _command_lines(process_ids: Iterable[int] = ()) -> dict[int, str]:
+ """按 pid 读 Win32 进程的命令行,读不到就返回空。
找源码托盘要认的就是这条命令行里的 `peach.tray`;失败不抛——这条
路径宁可安静地确认「没有源码托盘」,也不误伤别的窗口。
+
+ 给了 pid 就只问这几个:这个函数起一个 PowerShell,而重启要在等待循环里
+ 反复问,整机枚举一轮几百个进程的代价会乘上轮数。
"""
+ wanted = sorted({int(pid) for pid in process_ids})
+ query = "Get-CimInstance Win32_Process"
+ if wanted:
+ clause = " or ".join(f"ProcessId={pid}" for pid in wanted)
+ query = f"{query} -Filter '{clause}'"
result = subprocess.run(
["powershell.exe", "-NoProfile", "-NonInteractive", "-Command",
- "Get-CimInstance Win32_Process | ForEach-Object {"
- " \"$($_.ProcessId)|$($_.CommandLine)\" }"],
+ f"{query} | ForEach-Object {{ \"$($_.ProcessId)|$($_.CommandLine)\" }}"],
capture_output=True, check=False,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
encoding="utf-8", errors="replace")
@@ -132,13 +147,16 @@ def find_source_tray_windows() -> tuple[TrayWindow, ...]:
的托盘是 venv 的 pythonw 启动的,桌面启动器和 `--show` 参数都在命令行里,
所以按同一窗口类名加「命令行含 peach.tray 找」。返回的仍是一道窗口,跟
restart_tray 用的是同一套唯一性检验。
+
+ 两步走:类名和映像路径都是纯 ctypes 的便宜判据,先用它们筛出候选,只有候选
+ 非空时才去问命令行。重启要在等待循环里反复调这个函数,而问命令行要起一个
+ PowerShell——没有候选的那些轮次不该付这份钱。
"""
if os.name != "nt":
return ()
user32 = ctypes.WinDLL("user32", use_last_error=True)
paths, _parents = _process_paths_and_parents()
- command_lines = _command_lines()
- found: list[TrayWindow] = []
+ candidates: list[TrayWindow] = []
callback_type = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
user32.EnumWindows.argtypes = [callback_type, wintypes.LPARAM]
user32.EnumWindows.restype = wintypes.BOOL
@@ -151,14 +169,12 @@ def find_source_tray_windows() -> tuple[TrayWindow, ...]:
user32.GetWindowThreadProcessId(window, ctypes.byref(process_id))
process_id = int(process_id.value)
image = paths.get(process_id, "")
- command = command_lines.get(process_id, "")
buffer = ctypes.create_unicode_buffer(512)
user32.GetClassNameW(window, buffer, len(buffer))
class_name = buffer.value
if (class_name.startswith("Peach") and class_name.endswith("SystemTrayIcon")
- and image.lower().endswith("pythonw.exe")
- and "peach.tray" in command):
- found.append(TrayWindow(process_id, int(window)))
+ and image.lower().endswith("pythonw.exe")):
+ candidates.append(TrayWindow(process_id, int(window)))
return True
ctypes.set_last_error(0)
@@ -166,7 +182,11 @@ def find_source_tray_windows() -> tuple[TrayWindow, ...]:
error = ctypes.get_last_error()
if error:
raise ctypes.WinError(error)
- return tuple(found)
+ if not candidates:
+ return ()
+ commands = _command_lines({window.process_id for window in candidates})
+ return tuple(window for window in candidates
+ if "peach.tray" in commands.get(window.process_id, ""))
def _process_paths_and_parents() -> tuple[dict[int, str], dict[int, int]]:
@@ -415,7 +435,7 @@ def restart_source_tray(
stop_window: Callable[[int], bool] = post_stop,
alive: Callable[[int], bool] = process_alive,
command_lines: Callable[[], dict[int, str]] = _command_lines,
- start: Callable[[list[str]], subprocess.Popen] = None,
+ start: Callable[[list[str]], subprocess.Popen] | None = None,
services: Callable[[int, Path], tuple[int, ...]] = owned_service_pids,
sleep: Callable[[float], None] = time.sleep,
) -> RestartResult:
@@ -428,7 +448,9 @@ def restart_source_tray(
"""
def start_argv(argv: list[str]) -> subprocess.Popen:
if start is None:
- working_directory = Path(argv[0]).parents[2]
+ # `<项目根>\.venv\Scripts\pythonw.exe` 往上两级就是项目根。逐级取而不是
+ # parents[2]:层级不够时 `.parent` 停在盘符,索引却会直接抛。
+ working_directory = Path(argv[0]).parent.parent.parent
return subprocess.Popen(
argv, cwd=str(working_directory), stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
@@ -439,16 +461,16 @@ def restart_source_tray(
windows = find_windows()
process_ids = {window.process_id for window in windows}
- if len(process_ids) != 1 or not windows:
+ if len(process_ids) != 1:
return RestartResult(False, "拒绝重启:没有找到唯一且命令行匹配的源码托盘窗口")
old_process_id = next(iter(process_ids))
argv = parse_windows_command_line(command_lines().get(old_process_id))
if len(argv) < 2 or "peach.tray" not in " ".join(argv):
- return RestartResult(False, "拒绝重启:托盘窗口的命令行没有 peach.tray"
- "可信起步,无法照原样重启",
+ return RestartResult(False, "拒绝重启:托盘窗口的命令行里没有 peach.tray,"
+ "照原样重启会起错东西",
old_tray_pid=old_process_id)
service_executable = Path(argv[0]).parent / "peach.exe"
- if service_executable.name.lower() != "peach.exe" or not service_executable.is_file():
+ if not service_executable.is_file():
return RestartResult(False, f"拒绝重启:源码托盘旁没有服务入口 {service_executable}",
old_tray_pid=old_process_id)
if not all(stop_window(window.handle) for window in windows):
diff --git a/tests/test_restart_windows_tray.py b/tests/test_restart_windows_tray.py
index 04d8d1bbe..0a8ecca00 100644
--- a/tests/test_restart_windows_tray.py
+++ b/tests/test_restart_windows_tray.py
@@ -70,6 +70,27 @@ class RestartWindowsTrayTests(unittest.TestCase):
self.assertEqual(argv, [f"{self.service.parent / 'pythonw.exe'}",
"-c", self.BOOTSTRAP, "--show"])
+ def test_the_command_line_rules_that_only_show_up_in_odd_arguments(self):
+ """三条 Win32 规则各要一条判据:反斜杠、引号里的引号、真的空参数。
+
+ 照抄命令行重启,argv 差一格起的就是另一个东西,所以这里比对的是逐项相等,
+ 不是「大致长这样」。
+ """
+ cases = {
+ r'a "b c" d': ["a", "b c", "d"],
+ # 2n 个反斜杠后跟引号:反斜杠减半,引号收界。
+ r'"C:\dir\\" next': ["C:\\dir\\", "next"],
+ # 2n+1 个:反斜杠减半,引号变字面量。
+ r'"say \"hi\"" done': ['say "hi"', "done"],
+ # 引号里的 "" 是一个字面引号,不收界。
+ r'"a""b"': ['a"b'],
+ # 空参数是真参数,不能因为没攒到字符就丢掉。
+ 'first "" last': ["first", "", "last"],
+ }
+ for line, expected in cases.items():
+ with self.subTest(line=line):
+ self.assertEqual(windows_restart.parse_windows_command_line(line), expected)
+
def test_source_restart_reruns_the_recorded_command_line(self):
pythonw = self.service.parent / "pythonw.exe"
pythonw.write_bytes(b"shim")