"""Structured Expedition PCB COM bridge primitives. The bridge uses only interfaces confirmed in Mentor's registered type libraries. It never relies on window titles or foreground-window state. """ from __future__ import annotations import os from pathlib import Path import time class PcbBridgeError(RuntimeError): def __init__(self, error_code: str, detail: str) -> None: self.error_code = str(error_code) self.detail = str(detail) super().__init__(self.detail) class AutomationLicenseError(PcbBridgeError): def __init__(self, error_code: str, detail: str, *, fallback_allowed: bool) -> None: self.fallback_allowed = bool(fallback_allowed) super().__init__(error_code, detail) _UNAVAILABLE_HRESULTS = { -2147221164, # REGDB_E_CLASSNOTREG -2146959355, # CO_E_SERVER_EXEC_FAILURE -2147023174, # RPC_S_SERVER_UNAVAILABLE } def _hresult(error): value = getattr(error, 'hresult', None) if value is None: arguments = getattr(error, 'args', ()) value = arguments[0] if arguments and isinstance(arguments[0], int) else None return value def validate_document(document, license_factory, *, emit=lambda **event: None): """Acquire and apply an Expedition automation token without exposing it.""" try: key = document.Validate(0) emit(stage='license_key_requested') except Exception as error: raise AutomationLicenseError( 'AUTOMATION_LICENSE_KEY_FAILED', f'无法取得 PCB 授权 key: {error}', fallback_allowed=False, ) from error try: licensing = license_factory() token = licensing.GetToken(key) emit(stage='license_token_received') except Exception as error: fallback_allowed = _hresult(error) in _UNAVAILABLE_HRESULTS raise AutomationLicenseError( 'AUTOMATION_LICENSE_UNAVAILABLE' if fallback_allowed else 'AUTOMATION_LICENSE_TOKEN_FAILED', f'无法取得 PCB automation token: {error}', fallback_allowed=fallback_allowed, ) from error try: document.Validate(token) emit(stage='document_validated') except Exception as error: raise AutomationLicenseError( 'AUTOMATION_LICENSE_REJECTED', f'PCB automation token 被拒绝: {error}', fallback_allowed=False, ) from error def _same_path(first, second) -> bool: return os.path.normcase(os.path.abspath(str(first))) == os.path.normcase(os.path.abspath(str(second))) def require_document_identity(document, job): expected_project = Path(job['project']) expected_pcb = Path(job['pcb']) try: integration = document.ProjectIntegration project_file = str(integration.ProjectFile) document_name = str(document.Name) except Exception as error: raise PcbBridgeError('PCB_IDENTITY_UNAVAILABLE', f'PCB 文档身份不可读: {error}') from error if not _same_path(project_file, expected_project) or document_name.casefold() != expected_pcb.name.casefold(): raise PcbBridgeError( 'PCB_IDENTITY_MISMATCH', f'当前 PCB 工程身份不符: project={project_file}; document={document_name}', ) return integration class ProcessWatch: """Hold this task's native handles; repeated COM attach polls never run WMI.""" def __init__(self, pids): self.pids = set(int(pid) for pid in pids if pid) self.handles = None def __enter__(self): return self def alive(self): import pywintypes, win32api, win32con, win32event if self.handles is None: self.handles = [] try: for pid in self.pids: try: self.handles.append(win32api.OpenProcess(win32con.SYNCHRONIZE, False, pid)) except pywintypes.error as error: if error.winerror != 87: raise except Exception: self.__exit__(None, None, None) raise return any(win32event.WaitForSingleObject(h, 0) != win32con.WAIT_OBJECT_0 for h in self.handles) def __exit__(self, *_): for handle in self.handles or (): handle.Close() self.handles = [] def wait_for_target_document(job, app_provider, *, process_alive, emit=lambda **event: None, error_reader=None, sleep=time.sleep): """Wait for the exact launched document; the parent process owns timeout.""" last_observation = None while process_alive(): if error_reader is not None: detail = error_reader() if detail: raise PcbBridgeError('PCB_STARTUP_FAILED', detail) try: app = app_provider() document = app.ActiveDocument if not document: observation = ('PCB_DOCUMENT_NOT_READY', 'COM 已连接,尚无目标文档') if observation != last_observation: emit(stage='pcb_document_wait', error_code=observation[0], detail=observation[1]) last_observation = observation if document: try: integration = require_document_identity(document, job) except PcbBridgeError as error: observation = (error.error_code, error.detail) if observation != last_observation: emit(stage='identity_wait', error_code=error.error_code, detail=error.detail) last_observation = observation else: emit(stage='identity_verified', project=str(integration.ProjectFile), document=str(document.Name)) return app, document, integration except PcbBridgeError: raise except Exception as error: observation = ('COM_NOT_READY', str(error)) if observation != last_observation: # COM registration is an internal attach wait, not a user # operation. Keep the transient detail out of the workflow # event stream; a final attach failure still raises below. last_observation = observation sleep(.25) raise PcbBridgeError('PCB_EXITED_BEFORE_COM', 'PCB 在 COM 文档就绪前退出') def execution_outcome(*, save_complete: bool, pcb_exited: bool, fatal_error: str = '') -> dict[str, object]: if fatal_error: code, _, detail = str(fatal_error).partition(':') return {'status': 'FAIL', 'error_code': code.strip() or 'FATAL_DIALOG', 'stderr': detail.strip() or str(fatal_error), 'safe_to_continue': True} if not save_complete: return {'status': 'FAIL', 'error_code': 'SAVE_NOT_CONFIRMED', 'stderr': '保存/关闭未完成', 'safe_to_continue': True} if not pcb_exited: return {'status': 'FAIL', 'error_code': 'PCB_EXIT_NOT_CONFIRMED', 'stderr': '保存后未确认 PCB 退出', 'safe_to_continue': True} return {'status': 'PASS', 'stdout': 'Project Integration 已同步;保存、关闭和 PCB 退出均已确认。'}