"""Close only an idle document whose native identity was already established.""" import json from contextlib import ExitStack 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): no = next((c for c in snapshot.controls if c.class_name == 'Button' and c.control_id == 7 and c.enabled), None) return ('read_write_access', no) if no is not None else None text = ' '.join(' '.join(c.name for c in snapshot.controls if c.class_name == 'Static').split()) buttons = [c for c in snapshot.controls if c.class_name == 'Button'] if (snapshot.window_class == '#32770' and snapshot.title == 'Expedition PCB' and text == ('Problem encountered while opening one of the database files. ' 'See PCBLogFile.txt for details. Loading of the job has failed. ' 'Do you wish to view the log file now?') and {c.control_id for c in buttons} == {6, 7} and len(buttons) == 2): no = next(c for c in buttons if c.control_id == 7) if no.enabled: return 'database_load_log', no 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 _tip_target(snapshot): from .dialog_agent import DialogActionExecutor if snapshot.title != 'Tip of the Day' or snapshot.window_class != '#32770': return None target = DialogActionExecutor._target(snapshot, {'control_id': 1}) return target if target is not None and target.class_name == 'Button' else None def _startup_license_cancel(snapshot): if snapshot.window_class != '#32770' or snapshot.title: return None controls = snapshot.controls buttons = {(c.control_id, c.name) for c in controls if c.class_name == 'Button' and c.enabled} expected = {(5225, 'Select the desired product license'), (1, 'OK'), (2, 'Cancel')} if (buttons not in (expected, expected | {(57670, '')}) or not any(c.control_id == 1522 and c.class_name == 'GXWND' for c in controls)): return None options = [c for c in controls if c.control_id == 2 and c.class_name == 'Button' and c.name == 'Cancel' and c.enabled] return options[0] if len(options) == 1 else None def _database_log_declined(root, pcb_pid): """The supervisor can dismiss this exact failed-open question before cleanup.""" from dataclasses import fields from .dialog_models import WindowSnapshot path = root/'dialogs.jsonl' try: if path.stat().st_size > 1024*1024: return False for line in path.read_text(encoding='utf-8').splitlines(): record = json.loads(line) if (record.get('pid') != pcb_pid or record.get('phase') != 'PCB_STARTING' or record.get('error_code') != 'MENTOR_DATABASE_LOAD_FAILED' or record.get('action') != 'acknowledge_fatal' or record.get('accepted_control') != [7]): continue snapshot = WindowSnapshot.from_record({f.name:record[f.name] for f in fields(WindowSnapshot) if f.name in record}) target = _cancel_target(snapshot) if target is not None and target[0] == 'database_load_log': return True except (OSError, ValueError, TypeError, KeyError): pass return False def _read_write_declined(job, root, pcb_pid): from .dialog_models import WindowSnapshot from .session_record import IDENTITY_KEYS choice_path = root/'pcb-open-user-choice.json' dialogs_path = root/'dialogs.jsonl' try: if (choice_path.stat().st_size > 1024*1024 or dialogs_path.stat().st_size > 1024*1024 or not job.get('operation_id') or (root/'save.log').exists()): return False choice = json.loads(choice_path.read_text(encoding='utf-8')) binding = {key: job[key] for key in ('operation_id', 'desktop', 'project', 'pcb')} if (any(choice.get(key) != value for key, value in binding.items()) or choice.get('library') != job['lmc_file'] or choice.get('choice') not in ('skip', 'cancel')): return False owner = choice['owner']['target'] if (owner.get('pid') != pcb_pid or not owner.get('owner_sid') or any(owner.get(key) is None for key in IDENTITY_KEYS)): return False original = choice['snapshot'] snapshot = WindowSnapshot.from_record(original) target = _cancel_target(snapshot) if snapshot.pid != pcb_pid or target is None or target[0] != 'read_write_access': return False expected = 'PCB_OPEN_SKIPPED' if choice['choice'] == 'skip' else 'USER_CANCELLED' for line in dialogs_path.read_text(encoding='utf-8').splitlines(): record = json.loads(line) if (record.get('action') == 'user_confirmed_pcb_open' and record.get('accepted_control') == [7] and record.get('error_code') == expected and all(record.get(key) == value for key, value in original.items())): return owner except (OSError, ValueError, TypeError, KeyError, AttributeError): pass return False def cancelled_prewrite_startup(job, pcb_pid=None): """Positive ordinary pre-document cancellation proof; absence of Save is insufficient.""" from .session_record import IDENTITY_KEYS, read_session_record try: if (job.get('diagnostic_only') is not False or job.get('interactive_input') or job.get('native_lm_verify') or job.get('post_repair_consent') or job.get('operation') != 'verify' or not job.get('operation_id') or not job.get('desktop', '').startswith('CbbVerify_')): return None root=Path(job['root']) if not Path(job['cancel_signal']).is_file() or (root/'save.log').exists():return None path=root/'events.jsonl' if path.stat().st_size>1024*1024:return None events=[json.loads(line) for line in path.read_text(encoding='utf-8').splitlines()] if any(str(e.get('stage','')).startswith(('save','integration','validate','failure_close')) or e.get('stage') in ('startup_write_admitted','startup_supervisor_write_possible','identity_verified') for e in events):return None stages=('startup_supervisor_no_write','startup_prewrite_ready','startup_cancelled_prewrite') selected=[] for stage in stages: matches=[(i,e) for i,e in enumerate(events) if e.get('stage')==stage] if len(matches)!=1:return None selected.append(matches[0]) if [i for i,_ in selected]!=sorted(i for i,_ in selected):return None binding={k:job[k] for k in ('operation_id','project','pcb','desktop')} if any(any(e.get(k)!=v for k,v in binding.items()) for _,e in selected):return None ready,cancelled=selected[1][1],selected[2][1] pid=cancelled.get('pcb_pid') if (not pid or pcb_pid is not None and pid!=pcb_pid or cancelled.get('identity_verified') is not False or cancelled.get('write_admitted') is not False):return None if not any(e.get('stage')=='pcb_worker_started' and e.get('pcb_pid')==pid for e in events[selected[1][0]+1:selected[2][0]]):return None session=read_session_record(Path(job['session_record_path']),evidence_root=root) workers=[p for p in session.get('processes',()) if p.get('role')=='worker'] if (session.get('operation_id')!=job['operation_id'] or session.get('desktop')!=job['desktop'] or session.get('library')!=job['library'] or len(workers)!=1 or not set(IDENTITY_KEYS)<=ready.get('worker_identity',{}).keys() or any(ready.get('worker_identity',{}).get(k)!=workers[0].get(k) for k in IDENTITY_KEYS)):return None baseline=ready.get('baseline') if not isinstance(baseline,dict) or not {'started_ns','files'}<=baseline.keys():return None return baseline except (OSError,ValueError,KeyError,TypeError): return None def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: None, timeout_seconds=None, 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, win32event from .mentor_adapter import _process_details from .native_repair_ui import _current_desktop_name from .icdb_ownership import unreleased_addresses from . import residual_sessions 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 handles = ExitStack() 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'])) cancelled_diagnostic = (job.get('diagnostic_only') is True and bool(job.get('cancel_signal')) and Path(job['cancel_signal']).exists() and isinstance(job.get('diagnostic_log_baseline'), dict) and {'started_ns', 'files'} <= job['diagnostic_log_baseline'].keys() and not (root/'save.log').exists()) ordinary_baseline=cancelled_prewrite_startup(job,pcb_pid) cancelled_prewrite=ordinary_baseline is not None # Diagnostic close already owns a 30-second cleanup budget. Start it # once here; the empty-to-loaded transition never resets that deadline. if timeout_seconds is None: timeout_seconds = 30 if cancelled_diagnostic or cancelled_prewrite else 20 deadline = time.monotonic() + max(0, timeout_seconds) sent = False declined_hwnd = None declined_kind = None cancelled_open = _database_log_declined(root, pcb_pid) decline_owner = None dismissed_tips = set() license_cancelled = False close_handle = None close_identity = None close_frame = None diagnostic_state = {'clicked': set()} def cleanup_post(hwnd, message): if (time.monotonic() >= deadline or _current_desktop_name() != desktop or cancelled_prewrite and cancelled_prewrite_startup(job,pcb_pid)!=ordinary_baseline or win32event.WaitForSingleObject(close_handle, 0) != win32con.WAIT_TIMEOUT or residual_sessions._handle_identity(close_handle) != close_identity or win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid): raise ValueError('STARTUP_ACTION_UNCONFIRMED') if decline_owner: actual = {'pid': pcb_pid, **close_identity, **residual_sessions._force_ownership(close_handle, pcb_pid)} if any(actual.get(key) != value for key, value in decline_owner.items()): raise ValueError('STARTUP_ACTION_UNCONFIRMED: 原进程身份变化') win32gui.PostMessage(hwnd, message, 0, 0) while True: # PCB can dismiss the prompt before the supervisor records its action. if not cancelled_open: decline_owner = _read_write_declined(job, root, pcb_pid) if decline_owner: cancelled_open = True result['cancelled_prompt'] = 'read_write_access' records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid] if not records: if (close_handle is not None and win32event.WaitForSingleObject(close_handle, 0) != win32con.WAIT_OBJECT_0): result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 原进程句柄尚未确认退出' if time.monotonic() >= deadline: break time.sleep(.2) continue 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 addresses: result['release']['resource_release_confirmed'] = False 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') if cancelled_diagnostic or cancelled_prewrite: if time.monotonic() >= deadline: result['detail']='STARTUP_CLEANUP_TIMEOUT: original cleanup deadline reached' break if cancelled_prewrite and cancelled_prewrite_startup(job,pcb_pid)!=ordinary_baseline: raise ValueError('STARTUP_IDENTITY_UNCONFIRMED: pre-write phase proof changed') if (cancelled_diagnostic or cancelled_prewrite) and time.monotonic() < deadline: if close_handle is None: close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid)) close_identity = residual_sessions._handle_identity(close_handle) if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe': raise ValueError('STARTUP_PROCESS_UNCONFIRMED') from .diagnostic_open import cancelled_startup_step def ordinary_identity(): from .diagnostic_open import _load_evidence return (cancelled_prewrite_startup(job,pcb_pid)==ordinary_baseline and _load_evidence(job,pcb_pid,ordinary_baseline,require_autosave=False) is not None) closed, acted = cancelled_startup_step(job, pcb_pid, diagnostic_state, closed_frame=close_frame, deadline=deadline, post=cleanup_post, emit=emit, identity_check=ordinary_identity if cancelled_prewrite else None) if closed is not None and not sent: sent, close_frame = True, closed emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=closed, document_identity='native_path_pid_logs', cleanup='cancelled_prewrite' if cancelled_prewrite else 'cancelled_diagnostic') if acted: continue if not sent: 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 dismissed = False for hwnd in windows: if hwnd in dismissed_tips or win32gui.GetClassName(hwnd) != '#32770': continue snapshot = _startup_snapshot(hwnd, pcb_pid) target = _tip_target(snapshot) if target is None: continue current = _startup_snapshot(hwnd, pcb_pid) if current != snapshot or _tip_target(current) != target: raise ValueError('STARTUP_TIP_CHANGED') if cancelled_diagnostic or cancelled_prewrite: cleanup_post(target.handle,win32con.BM_CLICK) else: win32gui.PostMessage(target.handle, win32con.BM_CLICK, 0, 0) dismissed_tips.add(hwnd) dismissed = True emit(stage='startup_tip_dismissed', pcb_pid=pcb_pid, hwnd=hwnd) break if dismissed: continue # Prove the Tip disappeared; it does not prove a cancelled open. if cancelled_prewrite and not license_cancelled: visible = [w for w in windows if win32gui.GetClassName(w) not in ( 'UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator')] if len(visible) == 1 and win32gui.GetClassName(visible[0]) == '#32770': prompt = _startup_snapshot(visible[0], pcb_pid) cancel = _startup_license_cancel(prompt) if cancel is not None and _startup_snapshot(visible[0], pcb_pid) == prompt: cleanup_post(cancel.handle, win32con.BM_CLICK) license_cancelled = True emit(stage='startup_license_cancelled', pcb_pid=pcb_pid, hwnd=visible[0], control_id=cancel.control_id) continue 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 if cancelled_diagnostic or cancelled_prewrite: cleanup_post(cancel.handle,win32con.BM_CLICK) else: 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): if close_handle is None: close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid)) close_identity = residual_sessions._handle_identity(close_handle) if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe': raise ValueError('STARTUP_PROCESS_UNCONFIRMED') if cancelled_diagnostic or cancelled_prewrite or decline_owner: cleanup_post(main[0],win32con.WM_CLOSE) else: win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0) close_frame = main[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: 等待空闲窗口和数据库释放' # WMI fields can disappear during teardown. The held identity binds # any late Tip action to the original process, never a reused PID. if sent and time.monotonic() < deadline: if _current_desktop_name() != desktop: raise ValueError('STARTUP_DESKTOP_UNCONFIRMED') snapshot = residual_sessions._process_windows({pcb_pid}) windows = snapshot.get(pcb_pid, []) if all(w.get('desktop') == desktop for w in windows): dismissed = residual_sessions._dismiss_startup_tip( dict(pid=pcb_pid, name='ExpeditionPCB.exe', scope_confirmed=True, startup_frame=close_frame, **close_identity), close_handle, windows, incomplete=residual_sessions._window_error(snapshot, pcb_pid), dismissed=dismissed_tips, deadline=deadline) if dismissed is not None: dismissed_tips.add(dismissed) emit(stage='startup_tip_dismissed', pcb_pid=pcb_pid, hwnd=dismissed) continue if time.monotonic() >= deadline: if sent: result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 已请求正常关闭,但 PCB 尚未退出' break time.sleep(.2) except Exception as error: result['detail'] = str(error) finally: handles.close() (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