"""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 close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: None, timeout_seconds=20): """Normally close our empty PCB after a diagnosed database startup failure. No COM attach: there is no document, and the global ROT can name another session. Unknown windows, live database addresses and other desktops are retained. WM_CLOSE is cooperative; no save prompt is accepted or killed. """ import 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} try: diagnosed = False diagnosis_path = root/'diagnostics/icdb-recovery.json' if diagnosis_path.is_file(): diagnosis = json.loads(diagnosis_path.read_text('utf-8')) diagnosed = diagnosis.get('error_code') == 'ICDB_REPAIR_REQUIRED' dialogs_path = root/'dialogs.jsonl' if not diagnosed and dialogs_path.is_file(): for line in dialogs_path.read_text('utf-8').splitlines(): try: dialog = json.loads(line) except ValueError: continue if (dialog.get('pid') == pcb_pid and dialog.get('phase') == 'PCB_STARTING' and dialog.get('error_code') == 'MENTOR_DATABASE_LOAD_FAILED'): diagnosed = True if not diagnosed: raise ValueError('STARTUP_FAILURE_UNCONFIRMED') 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 while True: records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid] if not records: result['status'] = 'CLOSED' break _, 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') if not sent: windows = [] def observe(hwnd, _): if (win32process.GetWindowThreadProcessId(hwnd)[1] == pcb_pid and win32gui.IsWindowVisible(hwnd)): windows.append(hwnd) win32gui.EnumWindows(observe, None) 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)] dialogs = any(win32gui.GetClassName(w) == '#32770' for w in windows) documents = [] def child(hwnd, _): if (win32gui.GetClassName(hwnd) == 'MDIClient' and win32gui.GetWindow(hwnd, win32con.GW_CHILD)): documents.append(hwnd) if len(main) == 1: win32gui.EnumChildWindows(main[0], child, None) addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb']) if len(main) == 1 and not dialogs and not documents and 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: 等待空闲窗口和数据库释放' 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