220 lines
12 KiB
Python
220 lines
12 KiB
Python
"""Close only an idle document whose native identity was already established."""
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import time
|
|
|
|
|
|
def _command_args(command):
|
|
import ctypes
|
|
from ctypes import wintypes
|
|
shell = ctypes.WinDLL('shell32', use_last_error=True)
|
|
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
|
|
shell.CommandLineToArgvW.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_int)]
|
|
shell.CommandLineToArgvW.restype = ctypes.POINTER(wintypes.LPWSTR)
|
|
kernel.LocalFree.argtypes = [wintypes.HLOCAL]
|
|
kernel.LocalFree.restype = wintypes.HLOCAL
|
|
count = ctypes.c_int()
|
|
args = shell.CommandLineToArgvW(command, ctypes.byref(count))
|
|
if not args:
|
|
raise ctypes.WinError(ctypes.get_last_error())
|
|
try:
|
|
return list(args[:count.value])
|
|
finally:
|
|
kernel.LocalFree(ctypes.cast(args, wintypes.HLOCAL))
|
|
|
|
|
|
def _startup_snapshot(hwnd, pcb_pid):
|
|
import win32gui, win32process
|
|
from .dialog_models import ControlSnapshot, DialogPhase, WindowSnapshot
|
|
if win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid:
|
|
raise ValueError('STARTUP_WINDOW_OWNER_CHANGED')
|
|
children = []
|
|
win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(child), None)
|
|
controls = tuple(ControlSnapshot(child, win32gui.GetDlgCtrlID(child) & 0xffff,
|
|
win32gui.GetClassName(child), win32gui.GetWindowText(child),
|
|
enabled=bool(win32gui.IsWindowEnabled(child))) for child in children)
|
|
return WindowSnapshot(hwnd, pcb_pid, 'ExpeditionPCB.exe', 'pcb',
|
|
win32gui.GetClassName(hwnd), win32gui.GetWindowText(hwnd), DialogPhase.PCB_STARTING, controls)
|
|
|
|
|
|
def _cancel_target(snapshot):
|
|
from .post_repair_consent import exact_prompt
|
|
from .dialog_rules import pcb_version_choice
|
|
if exact_prompt(snapshot):
|
|
return 'read_write_access', next(c for c in snapshot.controls if c.control_id == 7)
|
|
if pcb_version_choice(snapshot) is not None:
|
|
buttons = [c for c in snapshot.controls if c.class_name == 'Button']
|
|
cancel = [c for c in buttons if c.control_id == 2 and c.name == 'Cancel' and c.enabled]
|
|
if (len(cancel) == 1 and {c.control_id for c in buttons} == {6212, 6213, 6206, 1, 2}
|
|
and any(c.control_id == 6211 and c.name == '* Cancelling will load no design.'
|
|
for c in snapshot.controls)):
|
|
return 'pcb_version_choice', cancel[0]
|
|
return None
|
|
|
|
|
|
def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: None,
|
|
timeout_seconds=20, launcher_process=None):
|
|
"""Normally close our empty PCB after a diagnosed database startup failure.
|
|
|
|
No COM attach: the global ROT can name another session. Only the exact
|
|
read/write question is declined; no ownership is taken or version restored.
|
|
Unknown windows and documents are retained. WM_CLOSE is cooperative.
|
|
"""
|
|
import win32api, win32con, win32gui, win32process
|
|
from .mentor_adapter import _process_details
|
|
from .native_repair_ui import _current_desktop_name
|
|
from .icdb_ownership import unreleased_addresses
|
|
root = Path(job['root'])
|
|
result = {'status': 'RETAINED', 'pcb_pid': pcb_pid}
|
|
result['release'] = {'pcb_exited': False, 'launcher_exited': launcher_process is None,
|
|
'safe_to_continue': False}
|
|
if launcher_process is not None:
|
|
result['launcher_pid'] = launcher_process.pid
|
|
try:
|
|
desktop = job.get('desktop', '')
|
|
if (job.get('interactive_input') or not desktop.startswith('CbbVerify_')
|
|
or _current_desktop_name() != desktop):
|
|
raise ValueError('STARTUP_DESKTOP_UNCONFIRMED')
|
|
if not pcb_pid or pcb_pid in baseline_pids:
|
|
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
|
expected = os.path.normcase(os.path.abspath(job['pcb']))
|
|
deadline = time.monotonic() + max(0, timeout_seconds)
|
|
sent = False
|
|
declined_hwnd = None
|
|
declined_kind = None
|
|
cancelled_open = False
|
|
while True:
|
|
records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid]
|
|
if not records:
|
|
if declined_hwnd is not None:
|
|
cancelled_open = True
|
|
result['cancelled_prompt'] = declined_kind
|
|
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
|
|
launcher_exited = launcher_process is None or launcher_process.poll() is not None
|
|
result['release'] = {'pcb_exited': True, 'launcher_exited': launcher_exited,
|
|
'addresses': addresses,
|
|
'safe_to_continue': launcher_exited and (cancelled_open or not addresses)}
|
|
if result['release']['safe_to_continue']:
|
|
result['status'] = 'CLOSED'
|
|
result.pop('detail', None)
|
|
break
|
|
result['detail'] = 'STARTUP_RELEASE_UNCONFIRMED: 等待启动器退出和数据库地址释放'
|
|
if time.monotonic() >= deadline:
|
|
break
|
|
time.sleep(.2)
|
|
continue
|
|
if not sent:
|
|
_, executable, command, _ = records[0]
|
|
args = _command_args(command)
|
|
if (Path(executable).name.casefold() != 'expeditionpcb.exe'
|
|
or '-reusablecircuit' not in [a.casefold() for a in args]
|
|
or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
|
|
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
|
windows = []
|
|
def observe(hwnd, _):
|
|
if (win32process.GetWindowThreadProcessId(hwnd)[1] == pcb_pid
|
|
and win32gui.IsWindowVisible(hwnd)):
|
|
windows.append(hwnd)
|
|
win32api.SetLastError(0)
|
|
win32gui.EnumWindows(observe, None)
|
|
if declined_hwnd is not None and declined_hwnd not in windows:
|
|
cancelled_open = True
|
|
result['cancelled_prompt'] = declined_kind
|
|
if declined_hwnd is None:
|
|
for hwnd in windows:
|
|
if win32gui.GetClassName(hwnd) != '#32770':
|
|
continue
|
|
snapshot = _startup_snapshot(hwnd, pcb_pid)
|
|
target = _cancel_target(snapshot)
|
|
if target is None:
|
|
continue
|
|
# Re-read immediately before declining; never select a version.
|
|
current = _startup_snapshot(hwnd, pcb_pid)
|
|
if _cancel_target(current) != target or current != snapshot:
|
|
raise ValueError('STARTUP_CANCEL_PROMPT_CHANGED')
|
|
declined_kind, cancel = target
|
|
win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0)
|
|
declined_hwnd = hwnd
|
|
emit(stage='startup_open_declined', pcb_pid=pcb_pid, hwnd=hwnd,
|
|
control_id=cancel.control_id, prompt=declined_kind)
|
|
break
|
|
if declined_hwnd is not None:
|
|
continue
|
|
main = [w for w in windows if win32gui.GetClassName(w).startswith('Afx:')
|
|
and win32gui.GetWindowText(w).strip() in (
|
|
'Expedition PCB', 'Expedition PCB - Reusable Block')
|
|
and win32gui.IsWindowEnabled(w)]
|
|
observed = [{'hwnd': w, 'class': win32gui.GetClassName(w),
|
|
'title': win32gui.GetWindowText(w), 'enabled': bool(win32gui.IsWindowEnabled(w))}
|
|
for w in windows]
|
|
benign = [w for w in observed if w['title'] == '' and w['class'] in (
|
|
'UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator')]
|
|
for window in observed:
|
|
if window['class'] == 'Internet Explorer_Hidden' and window['title'] == '':
|
|
window['rect'] = list(win32gui.GetWindowRect(window['hwnd']))
|
|
window['children'] = []
|
|
win32api.SetLastError(0)
|
|
win32gui.EnumChildWindows(window['hwnd'],
|
|
lambda hwnd, _: window['children'].append(int(hwnd)), None)
|
|
left, top, right, bottom = window['rect']
|
|
if left == right and top == bottom and not window['children']:
|
|
benign.append(window)
|
|
unknown = [w for w in observed if w['hwnd'] not in main and w not in benign]
|
|
result.update(owned_windows=observed, unknown_windows=unknown,
|
|
benign_auxiliary_windows=benign)
|
|
documents = []
|
|
def child(hwnd, _):
|
|
if (win32gui.GetClassName(hwnd) == 'MDIClient'
|
|
and win32gui.GetWindow(hwnd, win32con.GW_CHILD)):
|
|
documents.append(hwnd)
|
|
if len(main) == 1:
|
|
win32api.SetLastError(0)
|
|
win32gui.EnumChildWindows(main[0], child, None)
|
|
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
|
|
if len(main) == 1 and not unknown and not documents and (cancelled_open or not addresses):
|
|
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
|
|
sent = True
|
|
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=main[0])
|
|
# Observe exit even when the caller requested no extra wait.
|
|
continue
|
|
result['detail'] = 'STARTUP_IDLE_UNCONFIRMED: 等待空闲窗口和数据库释放'
|
|
# After the single owned WM_CLOSE, WMI may lose the executable/
|
|
# command fields before removing the PID. Only observe exit here;
|
|
# never issue another close or treat missing fields as release.
|
|
if time.monotonic() >= deadline:
|
|
if sent:
|
|
result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 已请求正常关闭,但 PCB 尚未退出'
|
|
break
|
|
time.sleep(.2)
|
|
except Exception as error:
|
|
result['detail'] = str(error)
|
|
(root/'startup-close.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
|
|
emit(stage='startup_close_result', **result)
|
|
return result
|
|
|
|
|
|
def close_failed_document(job, *, emit=lambda **event: None, timeout_seconds=30):
|
|
from .desktop_worker import launch_save_helper
|
|
root = Path(job['root'])
|
|
log_path = root/'failure-close.log'
|
|
command = [str(Path(os.environ.get('WINDIR', r'C:\Windows'))/'SysWOW64/cscript.exe'),
|
|
'//nologo', str(Path(__file__).with_name('close_failed_block.vbs')),
|
|
job['project'], Path(job['pcb']).name]
|
|
with log_path.open('w', encoding='utf-8') as log:
|
|
process = launch_save_helper(command, stdout=log, stderr=log)
|
|
emit(stage='failure_close_started', helper_pid=process.pid)
|
|
deadline = time.monotonic()+max(.1, float(timeout_seconds))
|
|
while process.poll() is None and time.monotonic() < deadline:
|
|
time.sleep(.2)
|
|
# A slow native Close can still be flushing. Retain the helper as well as
|
|
# PCB/iCDB; never force it to abandon the native call at this deadline.
|
|
text = log_path.read_text('utf-8', errors='replace')
|
|
result = {'status': ('CLOSED' if process.poll() == 0 and
|
|
all(marker in text.splitlines() for marker in ('FAILURE_CLOSE_OK', 'FAILURE_QUIT_OK'))
|
|
else 'RETAINED' if process.poll() is None else 'UNCONFIRMED'),
|
|
'helper_pid': process.pid, 'returncode': process.poll(), 'log': str(log_path)}
|
|
(root/'failure-close.json').write_text(json.dumps(result, indent=2), encoding='utf-8')
|
|
emit(stage='failure_close_result', **result)
|
|
return result
|