"""Process-bound native opening check. This module never acquires PCB COM. The caller must bind the newly launched PCB command/PID before entering here. The check runs in that worker's private desktop and closes only that session. """ from __future__ import annotations import ctypes from ctypes import wintypes import heapq import hashlib import ntpath import os from pathlib import Path import re import time from .dialog_probe import _bounded_call from .icdb_recovery import LOG_LIMIT, _read_log_delta, decode_log, snapshot_log _MAX_WINDOWS = 128 _MAX_CHILDREN = 512 def _normal(path): return ntpath.normcase(ntpath.normpath(str(path).strip())) def _log_paths(job): project = Path(job['project']).parent pcb_logs = Path(job['pcb']).parent / 'LogFiles' paths = [pcb_logs / 'PCBAutoSave.txt', pcb_logs / 'PCBLogFile.txt'] directory = project / 'database/cdbsvr/log' directories = [] if directory.is_dir(): with os.scandir(directory) as entries: directories = [entry.name for entry in entries if entry.is_dir(follow_symlinks=False)] # Native names start with sortable YYYY-MM-DD HH.MM.SS. Only the # newest candidates can describe this launch; history is never read. for name in heapq.nlargest(8, directories): with os.scandir(directory / name) as entries: logs = heapq.nlargest(2, (entry.name for entry in entries if entry.is_file(follow_symlinks=False) and entry.name.casefold().endswith('.txt'))) paths.extend(directory / name / log for log in logs) return paths, directories def _read_logs(job): result = {} paths, directories = _log_paths(job) for path in paths: try: record = snapshot_log(path) record['mtime_ns'] = path.stat().st_mtime_ns result[str(path)] = record except FileNotFoundError: result[str(path)] = snapshot_log(path) return {'files': result, 'server_directories': directories} def _read_bounded(function): try: return _bounded_call(function, 2) except TimeoutError as error: # Abort this check, rather than spawning another reader while a slow # share still owns the previous read. The daemon performs reads only. raise RuntimeError('DIAGNOSTIC_LOG_READ_TIMEOUT: native evidence unavailable') from error def snapshot_diagnostic_logs(job) -> dict: """Capture pre-launch content, so copied/stale successes cannot pass. Store the returned JSON-compatible value at job['diagnostic_log_baseline']. File count, content size and the entire read are bounded; failure is closed. """ started = time.time_ns() return {'started_ns': started, **_read_bounded(lambda: _read_logs(job))} def _fresh_logs_read(job, baseline): paths, _ = _log_paths(job) fresh = {} for path in paths: try: stat = path.stat() old = baseline['files'].get(str(path)) if stat.st_mtime_ns < baseline['started_ns']: continue if old is None: if path.parent.name in baseline.get('server_directories', ()): continue # An unobserved historical file cannot prove freshness. old = {'size': 0, 'tail_sha256': hashlib.sha256(b'').hexdigest()} if 'error' in old or (old.get('mtime_ns') == stat.st_mtime_ns and old['size'] == stat.st_size): continue content, appended = _read_log_delta(path, old) if not content and stat.st_mtime_ns != old.get('mtime_ns') and stat.st_size == old['size']: # Native PCBLog is overwritten with the same successful text. content, _ = _read_log_delta(path, {'size': 0, 'tail_sha256': ''}) if not appended and old.get('truncated') and stat.st_size > LOG_LIMIT: continue fresh[str(path)] = decode_log(content) except FileNotFoundError: continue return fresh def _fresh_logs(job, baseline): return _read_bounded(lambda: _fresh_logs_read(job, baseline)) def _load_evidence(job, pcb_pid, baseline, *, require_autosave=True): logs = _fresh_logs(job, baseline) project = Path(job['project']).parent pcb = str(Path(job['pcb'])) auto_path = str(Path(job['pcb']).parent / 'LogFiles/PCBAutoSave.txt') read_path = str(Path(job['pcb']).parent / 'LogFiles/PCBLogFile.txt') names = re.findall(r'^Job Name:\s*(.*?)\s*$', logs.get(auto_path, ''), re.M | re.I) if names and any(_normal(name) != _normal(pcb) for name in names): return None if require_autosave and not names: return None if 'Successfully read the design.' not in logs.get(read_path, ''): return None database = _normal(project / 'database') project_file = _normal(job['project']) for path, text in logs.items(): if path in (auto_path, read_path): continue db_paths = re.findall(r'S: Project path \[(.*?)\]', text) prj_paths = re.findall(r'S: Project file \(\.prj\) path \[(.*?)\]', text) startup = re.search(r'S: Started up automatically by iCDB Client: [^\r\n]*:' + str(pcb_pid) + r'\s*$', text, re.M) client = re.search(r'Registered sub-client \[Expedition PCB[^\r\n]*process ID \[' + str(pcb_pid) + r'\]', text) if (db_paths and all(_normal(value) == database for value in db_paths) and prj_paths and all(_normal(value) == project_file for value in prj_paths) and startup and client and 'S: iCDB database loaded' in text): return {'pcb': pcb, 'pcb_pid': pcb_pid, 'logs': [auto_path, read_path, path], 'document_identity': 'native_path_pid_logs'} return None def _target_frame(windows, name): matches = [] for window in windows: if not window['class'].casefold().startswith('afx:') or not window.get('enabled', True): continue if not window['text'].casefold().startswith('expedition pcb') or f'[{name}]'.casefold() not in window['text'].casefold(): continue mdi = {child['hwnd'] for child in window['children'] if child['class'].casefold() == 'mdiclient'} if any(child.get('parent') in mdi and child['text'].casefold() == name.casefold() and child['class'].casefold().startswith('afx:') for child in window['children']): matches.append(window) return matches[0] if len(matches) == 1 else None def _windows(pid): """Read only this PID on the current desktop; cap text and enumeration work.""" import win32api import win32gui import win32process user = ctypes.WinDLL('user32', use_last_error=True) user.GetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int] user.GetWindowTextW.restype = ctypes.c_int deadline = time.monotonic() + .2 def text(hwnd): if time.monotonic() >= deadline: raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s') buffer = ctypes.create_unicode_buffer(4096) # All handles belong to the external PCB PID: GetWindowText reads # Windows' cached caption without sending a message to its UI thread. # Custom controls may have no cached text; missing evidence fails closed. user.GetWindowTextW(hwnd, buffer, len(buffer)) return buffer.value result = [] seen = 0 def collect(hwnd, _): nonlocal seen if win32process.GetWindowThreadProcessId(hwnd)[1] != pid or not win32gui.IsWindowVisible(hwnd): return True seen += 1 if seen > _MAX_WINDOWS: raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: too many windows') cls = win32gui.GetClassName(hwnd) if cls.casefold() in {'uac_inputindicatoroverlaywnd', 'uac input indicator'}: return True children = [] count = 0 def child(ch, _): nonlocal count count += 1 if count > _MAX_CHILDREN: raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: too many controls') child_cls = win32gui.GetClassName(ch) if (cls == '#32770' or cls.casefold() == 'internet explorer_hidden' or child_cls.casefold() == 'mdiclient' or child_cls.casefold().startswith('afx:')): children.append({'hwnd': ch, 'class': child_cls, 'text': text(ch), 'id': win32gui.GetDlgCtrlID(ch), 'parent': win32gui.GetParent(ch), 'enabled': bool(win32gui.IsWindowEnabled(ch))}) return True if cls == '#32770' or cls.casefold().startswith('afx:') or cls.casefold() == 'internet explorer_hidden': win32gui.EnumChildWindows(hwnd, child, None) caption = text(hwnd) if cls.casefold() == 'internet explorer_hidden' and not caption and not children: left, top, right, bottom = win32gui.GetWindowRect(hwnd) if left == right and top == bottom: return True result.append({'hwnd': hwnd, 'pid': pid, 'class': cls, 'text': caption, 'enabled': bool(win32gui.IsWindowEnabled(hwnd)), 'children': children, 'owner': int(win32gui.GetWindow(hwnd, 4) or 0)}) return True win32api.SetLastError(0) try: win32gui.EnumWindows(collect, None) except Exception as error: if getattr(error, 'winerror', None) not in (0, 2) or result: raise return result class _NativeSession: def __init__(self, job, pid, launcher): if launcher is None or not callable(getattr(launcher, 'poll', None)): raise RuntimeError('DIAGNOSTIC_LAUNCHER_REQUIRED: retain the exact launch process handle') import win32api import win32service import win32con import win32event import win32gui self.handles = [] self.pid = int(pid) self.launcher = launcher self.gui = win32gui self.event = win32event desktop = win32service.GetThreadDesktop(win32api.GetCurrentThreadId()) actual = win32service.GetUserObjectInformation(desktop, 2) expected = str(job.get('desktop', '')).split('\\')[-1] if not expected or expected.casefold() in {'default', 'winlogon', 'disconnect'} or actual.casefold() != expected.casefold(): raise RuntimeError('DIAGNOSTIC_DESKTOP_MISMATCH') self.pcb = win32api.OpenProcess(win32con.SYNCHRONIZE, False, int(pid)) self.handles.append(self.pcb) def pcb_alive(self): return self.event.WaitForSingleObject(self.pcb, 0) != 0 def launcher_alive(self): return self.launcher.poll() is None def post(self, hwnd, message): import win32process if not self.pcb_alive() or win32process.GetWindowThreadProcessId(hwnd)[1] != self.pid: raise RuntimeError('DIAGNOSTIC_STALE_WINDOW: target window identity changed') self.gui.PostMessage(hwnd, message, 0, 0) def close(self): for handle in self.handles: handle.Close() self.handles.clear() def _cancel(job): if job.get('cancel_signal') and Path(job['cancel_signal']).exists(): raise RuntimeError('VERIFY_CANCELLED: native opening check cancelled') def _pending_prompt(windows, *, closing=False, frame=None, session=None, clicked=None, pcb_name=''): for window in windows: known_titles = {'expedition pcb', 'expedition pcb - reusable block'} if (window['class'].casefold().startswith('afx:') and not window.get('owner') and (window['text'].casefold() in known_titles or frame is not None and window['hwnd'] == frame['hwnd'])): continue text = ' '.join([window['text'], *(child['text'] for child in window['children'])]).casefold() if not closing and ('select the desired product license' in text or window['text'] == 'Tip of the Day'): return True # The caller's PID-scoped DialogAgent owns startup choices. standard_save = (pcb_name and window['class'] == '#32770' and window['text'] == 'Expedition PCB' and any(child['class'].casefold() == 'static' and child['text'].strip().casefold() == f'Save changes to {pcb_name}?'.casefold() for child in window['children']) and {child.get('id') for child in window['children'] if child['class'].casefold() == 'button'} == {2, 6, 7}) if closing and window.get('owner') == frame['hwnd'] and (standard_save or 'do you want to save the reusable block cell' in text): targets = [child for child in window['children'] if child['class'].casefold() == 'button' and child.get('id') == 7 and child['text'].replace('&', '').strip().casefold() in {'no', '否(n)', '否'} and child.get('enabled', True)] if len(targets) == 1: if window['hwnd'] not in clicked: session.post(targets[0]['hwnd'], 0xF5) clicked.add(window['hwnd']) continue raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown native prompt preserved; ' f"pid={window['pid']} hwnd={window['hwnd']} class={window['class']!r} " f"title={window['text']!r}") return False def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=None) -> dict: """Prove this launch opened its native document, close it, and prove exit. PASS describes opening only; it does not imply refresh READY or unoccupied shared library data. Unknown prompts are preserved for existing recovery. """ baseline = job.get('diagnostic_log_baseline') if not isinstance(baseline, dict) or 'started_ns' not in baseline or 'files' not in baseline: raise RuntimeError('DIAGNOSTIC_BASELINE_REQUIRED: snapshot before native launch') session = _NativeSession(job, int(pcb_pid), launcher_process) try: deadline = time.monotonic() + max(.01, float(job['timeout'])) while True: _cancel(job) error = _read_bounded(error_reader) if error_reader else None if error: raise RuntimeError(str(error)) if not session.pcb_alive(): raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: target PCB exited before loaded evidence') windows = _windows(int(pcb_pid)) if any(window['pid'] != int(pcb_pid) for window in windows): raise RuntimeError('DIAGNOSTIC_PID_MISMATCH') frame = _target_frame(windows, Path(job['pcb']).stem) # Startup splash/control windows are transient. Unknown windows # veto closing only once the target actually has loaded evidence. pending = (_pending_prompt(windows, frame=frame, pcb_name=Path(job['pcb']).name) if frame is not None else True) evidence = (_load_evidence(job, int(pcb_pid), baseline, require_autosave=False) if frame is not None and not pending else None) if evidence is not None: emit(stage='diagnostic_native_loaded_candidate', **evidence) break if time.monotonic() >= deadline: raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: current target MDI/path/PID logs missing') time.sleep(.1) # Re-read the exact PID/frame before the sole close request. _cancel(job) windows = _windows(int(pcb_pid)) _pending_prompt(windows, frame=frame, pcb_name=Path(job['pcb']).name) current = _target_frame(windows, Path(job['pcb']).stem) if current is None or current['hwnd'] != frame['hwnd']: raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: target frame changed') session.post(frame['hwnd'], 0x10) emit(stage='diagnostic_wm_close', pcb_pid=int(pcb_pid), hwnd=frame['hwnd']) close_deadline = time.monotonic() + 30 clicked = set() last_pending = '' while session.pcb_alive() or session.launcher_alive(): # Cancellation stops future work; an accepted normal close must # still finish before its queue slot can be safely released. windows = _windows(int(pcb_pid)) if session.pcb_alive() else [] previous_clicks = set(clicked) pending_error = None try: _pending_prompt(windows, closing=True, frame=frame, session=session, clicked=clicked, pcb_name=Path(job['pcb']).name) except RuntimeError as error: if not str(error).startswith('DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown native prompt'): raise # WM_CLOSE creates and destroys native windows asynchronously; # preserve them and wait for populated controls or process exit. pending_error = error if str(error) != last_pending: last_pending = str(error) emit(stage='diagnostic_close_pending', detail=last_pending) for hwnd in clicked - previous_clicks: emit(stage='diagnostic_save_no', pcb_pid=int(pcb_pid), hwnd=hwnd) if time.monotonic() >= close_deadline: if pending_error is not None: raise pending_error raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: target PCB/launcher still running') time.sleep(.1) # EE7.9 buffers PCBAutoSave's complete Job Name until normal close. # The candidate permits closing only; PASS still needs that exact path. evidence = _load_evidence(job, int(pcb_pid), baseline) if evidence is None: raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: fresh full PCB path not confirmed after close') emit(stage='diagnostic_native_open_confirmed', **evidence) return {'status': 'PASS', 'check': 'native_open_only', 'native_processes_exited': True, 'library_ownership': 'NOT_ASSESSED', 'pcb_pid': int(pcb_pid), 'launcher_pid': getattr(launcher_process, 'pid', None), 'evidence': evidence, 'detail': 'Native target opened and its PCB/launcher exited; refresh readiness and shared library ownership not assessed.'} finally: session.close()