Import CBB refresh verify r4 stability baseline
Preserve tested Verify source, authoritative READY checks, bounded bridge retries, diagnostics and failure-only reporting. Include 336-test suite and packaging assets; exclude live Mentor samples, field logs, backups and distributions.
This commit is contained in:
commit
11a2b2e46e
130 files changed
+19267
No files matched your search
@@ -0,0 +1 @@
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,2 @@
|
||||
from cbb_refresh_verify.application import main
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,126 @@
|
||||
from __future__ import annotations
|
||||
import argparse, os, sys
|
||||
from pathlib import Path
|
||||
from typing import Sequence
|
||||
from .runtime_logging import configure
|
||||
|
||||
|
||||
def configure_qt_application(app):
|
||||
"""Apply a predictable light palette across machines and Qt themes."""
|
||||
from PySide6.QtGui import QColor, QPalette
|
||||
|
||||
app.setStyle('Fusion')
|
||||
palette = app.palette()
|
||||
colors = {
|
||||
QPalette.ColorRole.Window: '#f5f6f8',
|
||||
QPalette.ColorRole.WindowText: '#202124',
|
||||
QPalette.ColorRole.Base: '#ffffff',
|
||||
QPalette.ColorRole.AlternateBase: '#eef1f5',
|
||||
QPalette.ColorRole.Text: '#202124',
|
||||
QPalette.ColorRole.Button: '#eef1f5',
|
||||
QPalette.ColorRole.ButtonText: '#202124',
|
||||
QPalette.ColorRole.Highlight: '#2f6fed',
|
||||
QPalette.ColorRole.HighlightedText: '#ffffff',
|
||||
QPalette.ColorRole.ToolTipBase: '#ffffff',
|
||||
QPalette.ColorRole.ToolTipText: '#202124',
|
||||
QPalette.ColorRole.PlaceholderText: '#6b7280',
|
||||
}
|
||||
for role, color in colors.items():
|
||||
palette.setColor(role, QColor(color))
|
||||
app.setPalette(palette)
|
||||
app.setStyleSheet(
|
||||
'QWidget { color: #202124; }'
|
||||
'QTableWidget, QLineEdit, QTextEdit, QSpinBox { '
|
||||
'background: #ffffff; color: #202124; selection-color: #202124; }'
|
||||
'QHeaderView::section { background: #e9edf2; color: #202124; }'
|
||||
'QPushButton, QToolButton { color: #202124; }'
|
||||
)
|
||||
return app
|
||||
|
||||
def resolve_data_root(cli_value: Path | None) -> Path:
|
||||
if cli_value is not None: return cli_value.expanduser().resolve()
|
||||
if getattr(sys, "frozen", False): return Path(sys.executable).resolve().parent / "data"
|
||||
local = os.environ.get("LOCALAPPDATA")
|
||||
return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve()
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
|
||||
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS)
|
||||
parser.add_argument('--libspec', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(list(argv) if argv is not None else None)
|
||||
if args.collect_failure_logs:
|
||||
from .verify_diagnostics import failure_logs_main
|
||||
return failure_logs_main(args.collect_failure_logs)
|
||||
if args.dialog_agent:
|
||||
from .dialog_agent import dialog_agent_main
|
||||
return dialog_agent_main(args.dialog_agent)
|
||||
if args.verify_worker:
|
||||
from .mentor_adapter import worker_main
|
||||
import contextlib
|
||||
with args.verify_worker.with_name('worker.log').open('a', encoding='utf-8') as log:
|
||||
with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
|
||||
return worker_main(args.verify_worker)
|
||||
context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start")
|
||||
try:
|
||||
if args.batch_lmc:
|
||||
from .verify_runner import (VerifyRequest, native_lm_verify_enabled,
|
||||
run_batch, write_batch_report, failure_report_path)
|
||||
from .library_reader import read_library_fast
|
||||
from .batch_status import authoritative_status_map
|
||||
from .network_path import LibraryPathLease, select_library_file
|
||||
with LibraryPathLease.acquire(args.batch_lmc) as lease:
|
||||
mentor_path = select_library_file(lease.mentor_path)
|
||||
logger.info(
|
||||
'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s',
|
||||
lease.display_path, mentor_path, lease.drive or '-',
|
||||
lease.remote_root or '-', lease.created)
|
||||
names = list(args.block)
|
||||
if not names:
|
||||
library = read_library_fast(
|
||||
mentor_path,
|
||||
status_reader=lambda path, names: authoritative_status_map(
|
||||
names, path, context.root/'status-scan.jsonl'),
|
||||
)
|
||||
if library.error: raise RuntimeError(library.error)
|
||||
names = [record.name for record in library.records if record.status != 'READY']
|
||||
if not names: raise RuntimeError('中心库未读取到需要校验的 CBB')
|
||||
requests = [VerifyRequest(mentor_path, name, context.root/'evidence',
|
||||
libspec=args.libspec, dms_login_config=args.dms_login_config,
|
||||
mentor_bin=args.mentor_bin, logging_context=context,
|
||||
mapped_drive=lease.drive,
|
||||
mapped_remote_root=lease.remote_root,
|
||||
native_lm_verify=native_lm_verify_enabled())
|
||||
for name in names]
|
||||
results = run_batch(requests)
|
||||
report = write_batch_report(requests, results, context.root/'reports')
|
||||
logger.info('batch_report path=%s', report)
|
||||
logger.info('failure_report path=%s', failure_report_path(report))
|
||||
code = 0 if all(result.status == 'PASS' for result in results) else 2
|
||||
logger.info('application_clean_shutdown exit_code=%s', code)
|
||||
return code
|
||||
from .ui.main_window import MainWindow, application_icon_path
|
||||
if args.smoke_test:
|
||||
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
|
||||
from PySide6.QtWidgets import QApplication
|
||||
app = QApplication.instance() or QApplication([sys.executable])
|
||||
configure_qt_application(app)
|
||||
window = MainWindow(logging_context=context); window.show()
|
||||
icon_path = application_icon_path()
|
||||
if icon_path.is_file():
|
||||
from PySide6.QtGui import QIcon
|
||||
app.setWindowIcon(QIcon(str(icon_path)))
|
||||
if args.smoke_test:
|
||||
from PySide6.QtCore import QTimer
|
||||
logger.info('gui_smoke_window_created title=%s', window.windowTitle())
|
||||
QTimer.singleShot(250, app.quit)
|
||||
code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code
|
||||
except Exception: logger.exception("application_startup_failure"); return 1
|
||||
finally:
|
||||
for handler in logger.handlers: handler.flush()
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 264 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.8 KiB |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
|
||||
<rect x="3" y="3" width="58" height="58" rx="10" fill="#0f766e"/>
|
||||
<rect x="11" y="12" width="42" height="32" rx="4" fill="#f8fafc"/>
|
||||
<rect x="15" y="16" width="34" height="24" rx="2" fill="#dbeafe"/>
|
||||
<path d="M20 29l6 6 14-14" fill="none" stroke="#16a34a" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<rect x="25" y="47" width="14" height="4" rx="2" fill="#f8fafc"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 489 B |
@@ -0,0 +1,128 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"rules": [
|
||||
{
|
||||
"rule_id": "license-selector",
|
||||
"priority": 100,
|
||||
"category": "SAFE_RECOVERY",
|
||||
"phases": ["PCB_STARTING", "LICENSE_ACQUISITION", "DOCUMENT_ATTACH"],
|
||||
"semantic_all": ["select the desired product license"],
|
||||
"required_control_classes": ["GXWND", "Button"],
|
||||
"action": "accept_license",
|
||||
"channels": ["interface", "uia_select", "win32_button_click", "win32_mouse_click", "uia_invoke"],
|
||||
"postcondition": "window_gone"
|
||||
},
|
||||
{
|
||||
"rule_id": "database-restoration",
|
||||
"priority": 95,
|
||||
"category": "SAFE_RECOVERY",
|
||||
"phases": ["PCB_STARTING", "DATABASE_RECOVERY", "DOCUMENT_ATTACH"],
|
||||
"semantic_any": ["database restoration", "last user saved database", "数据库恢复"],
|
||||
"action": "restore_last_saved",
|
||||
"channels": ["uia_select", "win32_button_click", "uia_invoke"],
|
||||
"postcondition": "window_gone"
|
||||
},
|
||||
{
|
||||
"rule_id": "open-lock-confirm",
|
||||
"priority": 90,
|
||||
"category": "SAFE_RECOVERY",
|
||||
"phases": ["PCB_STARTING", "DOCUMENT_ATTACH"],
|
||||
"semantic_any": ["continue to open the design with read/write access permission", "confirm that no other users have the design open"],
|
||||
"action": "confirm_open_lock",
|
||||
"channels": ["win32_button_click", "uia_invoke"],
|
||||
"postcondition": "window_gone"
|
||||
},
|
||||
{
|
||||
"rule_id": "forward-annotation-confirm",
|
||||
"priority": 85,
|
||||
"category": "SAFE_CONFIRM",
|
||||
"phases": ["PCB_STARTING", "DOCUMENT_ATTACH", "PROJECT_INTEGRATION"],
|
||||
"semantic_all": ["new changes are ready for forward annotation", "do you want to forward annotate now"],
|
||||
"action": "confirm_forward_annotation",
|
||||
"channels": ["win32_button_click", "uia_invoke"],
|
||||
"postcondition": "window_gone"
|
||||
},
|
||||
{
|
||||
"rule_id": "reusable-block-save",
|
||||
"priority": 90,
|
||||
"category": "SAFE_CONFIRM",
|
||||
"phases": ["SAVE", "CLOSE"],
|
||||
"semantic_all": ["do you want to save the reusable block cell"],
|
||||
"action": "save_reusable_block",
|
||||
"channels": ["win32_button_click", "uia_invoke"],
|
||||
"postcondition": "window_gone"
|
||||
},
|
||||
{
|
||||
"rule_id": "integration-progress",
|
||||
"priority": 80,
|
||||
"category": "OBSERVE_PROGRESS",
|
||||
"phases": ["PROJECT_INTEGRATION"],
|
||||
"semantic_all": ["your task is being processed", "elapsed time"],
|
||||
"semantic_none": ["error", "failed"],
|
||||
"postcondition": "signature_changed"
|
||||
},
|
||||
{
|
||||
"rule_id": "project-integration-panel",
|
||||
"priority": 110,
|
||||
"category": "OBSERVE_PROGRESS",
|
||||
"phases": ["PROJECT_INTEGRATION"],
|
||||
"semantic_all": ["project file and design", "forward annotation required"],
|
||||
"semantic_none": ["there were errors", "error saving the reusable block"],
|
||||
"postcondition": "signature_changed"
|
||||
},
|
||||
{
|
||||
"rule_id": "integration-error",
|
||||
"priority": 120,
|
||||
"category": "FATAL_ACK",
|
||||
"phases": ["PROJECT_INTEGRATION"],
|
||||
"semantic_all": ["there were errors"],
|
||||
"action": "acknowledge_fatal",
|
||||
"channels": ["win32_button_click", "uia_invoke"],
|
||||
"postcondition": "window_gone",
|
||||
"error_code": "PROJECT_INTEGRATION_FAILED"
|
||||
},
|
||||
{
|
||||
"rule_id": "save-error",
|
||||
"priority": 120,
|
||||
"category": "FATAL_ACK",
|
||||
"phases": ["SAVE", "CLOSE"],
|
||||
"semantic_all": ["error saving the reusable block"],
|
||||
"action": "acknowledge_fatal",
|
||||
"channels": ["win32_button_click", "uia_invoke"],
|
||||
"postcondition": "window_gone",
|
||||
"error_code": "SAVE_REUSABLE_BLOCK_FAILED"
|
||||
},
|
||||
{
|
||||
"rule_id": "design-server-error",
|
||||
"priority": 120,
|
||||
"category": "FATAL_ACK",
|
||||
"phases": ["PCB_STARTING", "DOCUMENT_ATTACH"],
|
||||
"semantic_any": ["could not run server", "could not bring it alive"],
|
||||
"action": "acknowledge_fatal",
|
||||
"channels": ["win32_button_click", "uia_invoke"],
|
||||
"postcondition": "window_gone",
|
||||
"error_code": "DESIGN_SERVER_FAILED"
|
||||
},
|
||||
{
|
||||
"rule_id": "database-load-error",
|
||||
"priority": 120,
|
||||
"category": "FATAL_ACK",
|
||||
"phases": ["PCB_STARTING", "DATABASE_RECOVERY", "DOCUMENT_ATTACH"],
|
||||
"semantic_all": ["database load is being terminated"],
|
||||
"action": "acknowledge_fatal",
|
||||
"channels": ["win32_button_click", "uia_invoke"],
|
||||
"postcondition": "window_gone",
|
||||
"error_code": "DATABASE_LOAD_FAILED"
|
||||
},
|
||||
{
|
||||
"rule_id": "tip-of-day",
|
||||
"priority": 50,
|
||||
"category": "SAFE_CONFIRM",
|
||||
"phases": ["PCB_STARTING", "DOCUMENT_ATTACH"],
|
||||
"semantic_all": ["tip of the day"],
|
||||
"action": "dismiss_tip",
|
||||
"channels": ["win32_button_click", "uia_invoke"],
|
||||
"postcondition": "window_gone"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
"""Persistent, authoritative batch status scanning for CBB libraries.
|
||||
|
||||
This module only reads status through the Mentor bridge. It deliberately does
|
||||
not infer ``READY`` from files, icons, or previous UI observations.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
from .status_bridge import (BridgeResponseError, BridgeResult, BridgeUnavailable,
|
||||
StatusBridgeClient, StatusBridgeServer)
|
||||
from .network_path import absolute_preserving_drive
|
||||
|
||||
|
||||
TERMINAL_ERRORS = frozenset({"ERROR", "TIMEOUT", "UNAVAILABLE", "MALFORMED", "CRASHED"})
|
||||
VALID_STATUSES = frozenset({"READY", "PENDING"}) | TERMINAL_ERRORS
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LmcFingerprint:
|
||||
path: str
|
||||
size: int
|
||||
mtime_ns: int
|
||||
sha256: str
|
||||
reusable_blocks_sha256: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BatchStatusRequest:
|
||||
block_name: str
|
||||
lmc_file: Path
|
||||
block_type: str = "RULP"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BatchStatusRecord:
|
||||
block_name: str
|
||||
status: str
|
||||
source: str = ""
|
||||
raw_status: int | str | None = None
|
||||
detail: str = ""
|
||||
fingerprint: str = ""
|
||||
timestamp: str = ""
|
||||
|
||||
@property
|
||||
def completed(self) -> bool:
|
||||
return self.status in VALID_STATUSES
|
||||
|
||||
def to_json(self) -> dict[str, object]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def _sha256_file(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _fingerprint_tree(root: Path) -> str:
|
||||
"""Fingerprint only the top-level CBB set; never descend into payloads."""
|
||||
digest = hashlib.sha256()
|
||||
if not root.is_dir():
|
||||
digest.update(b"<missing>")
|
||||
return digest.hexdigest()
|
||||
entries: list[tuple[str, int]] = []
|
||||
try:
|
||||
children = os.scandir(root)
|
||||
except OSError:
|
||||
digest.update(b"<unavailable>")
|
||||
return digest.hexdigest()
|
||||
with children:
|
||||
for entry in children:
|
||||
try:
|
||||
if not entry.is_dir(follow_symlinks=False):
|
||||
continue
|
||||
metadata = entry.stat(follow_symlinks=False)
|
||||
entries.append((entry.name, metadata.st_mtime_ns))
|
||||
except OSError:
|
||||
entries.append((entry.name, 0))
|
||||
for name, mtime_ns in sorted(entries, key=lambda item: item[0].casefold()):
|
||||
digest.update(name.encode("utf-8", errors="surrogatepass"))
|
||||
digest.update(b"\0" + str(mtime_ns).encode("ascii") + b"\n")
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def fingerprint_library(lmc: Path) -> LmcFingerprint:
|
||||
"""Return a checkpoint fingerprint without reading the reusable payload.
|
||||
|
||||
The lightweight cache key includes LMC metadata and the top-level CBB set.
|
||||
Authoritative state is still queried from Mentor; no CBB payload tree is
|
||||
recursively traversed merely to decide whether a status scan can resume.
|
||||
"""
|
||||
path = absolute_preserving_drive(lmc)
|
||||
stat = path.stat()
|
||||
reusable = path.parent / "ReusableBlocksLP"
|
||||
reusable_sha256 = _fingerprint_tree(reusable)
|
||||
# Metadata alone is not a safe checkpoint key: on network shares and on
|
||||
# file systems with coarse timestamp resolution, two different LMC
|
||||
# contents can have the same size and mtime. Include the actual file
|
||||
# digest so a changed central library can never reuse an old status row.
|
||||
content_sha256 = _sha256_file(path)
|
||||
combined = hashlib.sha256()
|
||||
combined.update(content_sha256.encode("ascii"))
|
||||
combined.update(b"\0" + str(stat.st_size).encode("ascii"))
|
||||
combined.update(b"\0" + str(stat.st_mtime_ns).encode("ascii") + b"\0")
|
||||
combined.update(reusable_sha256.encode("ascii"))
|
||||
return LmcFingerprint(
|
||||
path=str(path),
|
||||
size=stat.st_size,
|
||||
mtime_ns=stat.st_mtime_ns,
|
||||
sha256=combined.hexdigest(),
|
||||
reusable_blocks_sha256=reusable_sha256,
|
||||
)
|
||||
|
||||
|
||||
class BatchCheckpoint:
|
||||
"""Read and append complete JSONL records without trusting torn lines."""
|
||||
|
||||
def __init__(self, records: dict[str, BatchStatusRecord] | None = None) -> None:
|
||||
self.records = dict(records or {})
|
||||
|
||||
@property
|
||||
def completed_names(self) -> set[str]:
|
||||
return set(self.records)
|
||||
|
||||
def get(self, name: str) -> BatchStatusRecord | None:
|
||||
return self.records.get(name)
|
||||
|
||||
@classmethod
|
||||
def load(cls, path: Path) -> "BatchCheckpoint":
|
||||
records: dict[str, BatchStatusRecord] = {}
|
||||
checkpoint = Path(path)
|
||||
if not checkpoint.is_file():
|
||||
return cls(records)
|
||||
with checkpoint.open("r", encoding="utf-8") as handle:
|
||||
for line in handle:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
payload = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
# A process may have been interrupted during the final write.
|
||||
continue
|
||||
if not isinstance(payload, dict):
|
||||
continue
|
||||
name = str(payload.get("block_name") or "").strip()
|
||||
status = str(payload.get("status") or "").upper()
|
||||
if not name or status not in VALID_STATUSES:
|
||||
continue
|
||||
records[name] = BatchStatusRecord(
|
||||
block_name=name,
|
||||
status=status,
|
||||
source=str(payload.get("source") or ""),
|
||||
raw_status=payload.get("raw_status"),
|
||||
detail=str(payload.get("detail") or ""),
|
||||
fingerprint=str(payload.get("fingerprint") or ""),
|
||||
timestamp=str(payload.get("timestamp") or ""),
|
||||
)
|
||||
return cls(records)
|
||||
|
||||
def append(self, path: Path, record: BatchStatusRecord) -> None:
|
||||
checkpoint = Path(path)
|
||||
checkpoint.parent.mkdir(parents=True, exist_ok=True)
|
||||
with checkpoint.open("a", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write(json.dumps(record.to_json(), ensure_ascii=False, separators=(",", ":")) + "\n")
|
||||
handle.flush()
|
||||
self.records[record.block_name] = record
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
class BatchStatusSession:
|
||||
"""Supervised serial bridge session with checkpoint recovery."""
|
||||
|
||||
def __init__(self, bridge: StatusBridgeClient, *, timeout_seconds: float = 10.0,
|
||||
rotate_every: int = 500) -> None:
|
||||
self.bridge = bridge
|
||||
self.timeout_seconds = max(0.1, float(timeout_seconds))
|
||||
self.rotate_every = max(1, int(rotate_every))
|
||||
self.restart_count = 0
|
||||
|
||||
def scan(self, names: Iterable[str], lmc_file: Path, checkpoint_path: Path,
|
||||
*, block_type: str = "RULP", resume: bool = True) -> list[BatchStatusRecord]:
|
||||
fingerprint = fingerprint_library(Path(lmc_file))
|
||||
if resume:
|
||||
checkpoint = BatchCheckpoint.load(checkpoint_path)
|
||||
else:
|
||||
checkpoint = BatchCheckpoint()
|
||||
checkpoint_file = Path(checkpoint_path)
|
||||
checkpoint_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
checkpoint_file.write_text('', encoding='utf-8')
|
||||
results: list[BatchStatusRecord] = []
|
||||
names = tuple(str(name) for name in names)
|
||||
server = self.bridge if all(callable(getattr(self.bridge, method, None))
|
||||
for method in ("start", "restart", "close")) else None
|
||||
if server is not None:
|
||||
server.start()
|
||||
try:
|
||||
queried = 0
|
||||
for index, name in enumerate(names):
|
||||
previous = checkpoint.get(name)
|
||||
if previous and previous.fingerprint == fingerprint.sha256:
|
||||
results.append(previous)
|
||||
continue
|
||||
try:
|
||||
result: BridgeResult = self.bridge.query(
|
||||
Path(lmc_file), name, block_type=block_type,
|
||||
timeout_seconds=self.timeout_seconds,
|
||||
)
|
||||
record = BatchStatusRecord(
|
||||
block_name=name, status=result.status, source=result.source,
|
||||
raw_status=result.raw_status, detail=result.detail,
|
||||
fingerprint=fingerprint.sha256, timestamp=_now(),
|
||||
)
|
||||
except BridgeUnavailable as error:
|
||||
record = BatchStatusRecord(block_name=name, status="UNAVAILABLE",
|
||||
detail=str(error), fingerprint=fingerprint.sha256,
|
||||
timestamp=_now())
|
||||
except BridgeResponseError as error:
|
||||
message = str(error)
|
||||
lower_message = message.casefold()
|
||||
unavailable = any(marker in message for marker in ("LMCDLL70", "私有 MFC", "未找到可用"))
|
||||
malformed = (any(marker in message for marker in (
|
||||
"路径不匹配", "请求标识不匹配", "CBB 标识不匹配",
|
||||
)) or "mismatch" in lower_message)
|
||||
status = ("TIMEOUT" if "超时" in message or "timeout" in lower_message
|
||||
else "UNAVAILABLE" if unavailable
|
||||
else "MALFORMED" if malformed else "ERROR")
|
||||
record = BatchStatusRecord(block_name=name, status=status, detail=message,
|
||||
fingerprint=fingerprint.sha256, timestamp=_now())
|
||||
if server is not None and status not in {"UNAVAILABLE", "MALFORMED"}:
|
||||
try:
|
||||
server.restart()
|
||||
except BridgeUnavailable:
|
||||
pass
|
||||
except Exception as error: # bridge failures isolate one CBB
|
||||
record = BatchStatusRecord(block_name=name, status="ERROR", detail=str(error),
|
||||
fingerprint=fingerprint.sha256, timestamp=_now())
|
||||
if server is not None:
|
||||
try:
|
||||
server.restart()
|
||||
except BridgeUnavailable:
|
||||
pass
|
||||
checkpoint.append(checkpoint_path, record)
|
||||
results.append(record)
|
||||
if record.status in {"UNAVAILABLE", "MALFORMED"} and index + 1 < len(names):
|
||||
# Startup/protocol failures cannot be repaired by retrying
|
||||
# the same request contract for every CBB.
|
||||
# Preserve a terminal record for each remaining name so a
|
||||
# later run can resume after the environment is fixed.
|
||||
for remaining in names[index + 1:]:
|
||||
unavailable_record = BatchStatusRecord(
|
||||
block_name=remaining, status=record.status, detail=record.detail,
|
||||
fingerprint=fingerprint.sha256, timestamp=_now(),
|
||||
)
|
||||
checkpoint.append(checkpoint_path, unavailable_record)
|
||||
results.append(unavailable_record)
|
||||
break
|
||||
queried += 1
|
||||
if server is not None and queried % self.rotate_every == 0 and name != names[-1]:
|
||||
server.restart()
|
||||
finally:
|
||||
if server is not None:
|
||||
server.close()
|
||||
return results
|
||||
|
||||
|
||||
def authoritative_status_map(names: Iterable[str], lmc_file: Path, checkpoint_path: Path,
|
||||
*, bridge_path: Path | None = None,
|
||||
timeout_seconds: float = 10.0) -> dict[str, str]:
|
||||
"""Return only bridge-backed statuses for an optional UI integration.
|
||||
|
||||
A missing bridge is represented as ``UNAVAILABLE``/``UNKNOWN`` by callers;
|
||||
it is never promoted to ``READY``.
|
||||
"""
|
||||
bridge = StatusBridgeServer(bridge_path, env={"CBB_STATUS_BRIDGE_ALLOW_PRIVATE": "1"})
|
||||
try:
|
||||
names = tuple(str(name) for name in names)
|
||||
try:
|
||||
records = BatchStatusSession(bridge, timeout_seconds=timeout_seconds).scan(
|
||||
names, lmc_file, checkpoint_path, resume=False)
|
||||
return {record.block_name: record.status for record in records}
|
||||
except BridgeUnavailable:
|
||||
return {name: "UNAVAILABLE" for name in names}
|
||||
finally:
|
||||
bridge.close()
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Shared execution defaults for GUI, batch requests and integration."""
|
||||
|
||||
DEFAULT_TIMEOUT_SECONDS = 600
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Launch automation on a private Windows desktop, never the input desktop."""
|
||||
import subprocess
|
||||
import win32con
|
||||
import win32event
|
||||
import win32job
|
||||
import win32process
|
||||
import win32service
|
||||
|
||||
|
||||
def startup_desktop_name(name, *, interactive_input=False):
|
||||
"""Return the CreateProcess desktop target for a worker.
|
||||
|
||||
The normal route gets an isolated desktop. The explicit compatibility
|
||||
route inherits the caller's input desktop so Mentor's navigator can use
|
||||
its physical-cursor hit test; it is never selected implicitly.
|
||||
"""
|
||||
if interactive_input:
|
||||
return None
|
||||
return 'winsta0\\' + str(name)
|
||||
|
||||
|
||||
class DesktopWorker:
|
||||
def __init__(self, command, name, *, interactive_input=False):
|
||||
self.name = name
|
||||
self.interactive_input = bool(interactive_input)
|
||||
self.desktop = None if self.interactive_input else win32service.CreateDesktop(
|
||||
name, 0, win32con.GENERIC_ALL, None)
|
||||
# The worker spawns Expedition PCB and a cscript helper. Bind the whole
|
||||
# tree to a job so a supervisor kill can never orphan a process.
|
||||
self.job = win32job.CreateJobObject(None, '')
|
||||
self.job_bound = False
|
||||
self.companions = []
|
||||
self.companion_pids = []
|
||||
startup = win32process.STARTUPINFO()
|
||||
# subprocess.STARTUPINFO does NOT pass lpDesktop to CreateProcess.
|
||||
startup.lpDesktop = startup_desktop_name(name, interactive_input=self.interactive_input)
|
||||
self.handle, thread, self.pid, _ = win32process.CreateProcess(
|
||||
command[0], subprocess.list2cmdline(command), None, None, False,
|
||||
win32con.CREATE_NO_WINDOW, None, None, startup)
|
||||
thread.Close()
|
||||
try:
|
||||
info = win32job.QueryInformationJobObject(self.job, win32job.JobObjectExtendedLimitInformation)
|
||||
info['BasicLimitInformation']['LimitFlags'] |= win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
win32job.SetInformationJobObject(self.job, win32job.JobObjectExtendedLimitInformation, info)
|
||||
win32job.AssignProcessToJobObject(self.job, self.handle)
|
||||
self.job_bound = True
|
||||
except Exception:
|
||||
# Kill-through-job is a cleanup guarantee, not a launch requirement.
|
||||
self.job_bound = False
|
||||
|
||||
def start_companion(self, command):
|
||||
startup = win32process.STARTUPINFO()
|
||||
startup.lpDesktop = startup_desktop_name(
|
||||
self.name, interactive_input=getattr(self, 'interactive_input', False))
|
||||
handle, thread, pid, _ = win32process.CreateProcess(
|
||||
command[0], subprocess.list2cmdline(command), None, None, False,
|
||||
win32con.CREATE_NO_WINDOW, None, None, startup)
|
||||
thread.Close()
|
||||
try:
|
||||
if self.job_bound:
|
||||
win32job.AssignProcessToJobObject(self.job, handle)
|
||||
except Exception:
|
||||
try:
|
||||
win32process.TerminateProcess(handle, 1)
|
||||
finally:
|
||||
handle.Close()
|
||||
raise
|
||||
self.companions.append(handle)
|
||||
if not hasattr(self, 'companion_pids'):
|
||||
self.companion_pids = []
|
||||
self.companion_pids.append(int(pid))
|
||||
return int(pid)
|
||||
|
||||
def poll(self):
|
||||
code = win32process.GetExitCodeProcess(self.handle)
|
||||
return None if code == 259 else code
|
||||
|
||||
@property
|
||||
def returncode(self):
|
||||
return self.poll()
|
||||
|
||||
def kill(self):
|
||||
if self.job_bound:
|
||||
try:
|
||||
win32job.TerminateJobObject(self.job, 1)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
# Fallback: terminate the worker and every descendant it launched.
|
||||
try:
|
||||
subprocess.run(['taskkill', '/PID', str(self.pid), '/T', '/F'],
|
||||
capture_output=True, timeout=20,
|
||||
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
except Exception:
|
||||
try:
|
||||
win32process.TerminateProcess(self.handle, 1)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def wait(self, timeout=5):
|
||||
if win32event.WaitForSingleObject(self.handle, int(timeout*1000)) != win32con.WAIT_OBJECT_0:
|
||||
raise TimeoutError('Automation worker did not exit')
|
||||
return self.poll()
|
||||
|
||||
def close(self):
|
||||
# A job may be unavailable on a machine where the worker is already
|
||||
# assigned to another job. In that case merely closing our handles
|
||||
# would orphan PCB/cscript descendants, so terminate the tree before
|
||||
# releasing the desktop and job handles.
|
||||
try:
|
||||
if self.poll() is None:
|
||||
self.kill()
|
||||
except Exception:
|
||||
pass
|
||||
for companion in self.companions:
|
||||
try:
|
||||
companion.Close()
|
||||
except Exception:
|
||||
pass
|
||||
self.companions.clear()
|
||||
self.companion_pids.clear()
|
||||
self.handle.Close()
|
||||
# Closing the last job handle reaps any survivor thanks to
|
||||
# KILL_ON_JOB_CLOSE; this also covers a supervisor crash.
|
||||
self.job.Close()
|
||||
if self.desktop is not None:
|
||||
self.desktop.CloseDesktop()
|
||||
@@ -0,0 +1,498 @@
|
||||
"""Private-desktop dialog agent with bounded, in-memory loopback IPC."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
import json
|
||||
import socket
|
||||
from collections import deque
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from .dialog_models import (
|
||||
DialogPhase,
|
||||
WindowSnapshot,
|
||||
compatible_window_identity,
|
||||
stable_fingerprint,
|
||||
)
|
||||
from .dialog_probe import WindowProbe, WindowProbeError
|
||||
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
class DialogAgentProtocolError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ActionResult:
|
||||
channel: str = ""
|
||||
accepted_controls: tuple[int, ...] = ()
|
||||
error_code: str = ""
|
||||
detail: str = ""
|
||||
|
||||
def to_record(self):
|
||||
return asdict(self)
|
||||
|
||||
@classmethod
|
||||
def from_record(cls, record):
|
||||
values = dict(record or {})
|
||||
values["accepted_controls"] = tuple(values.get("accepted_controls", ()))
|
||||
return cls(**values)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AgentPaths:
|
||||
config: Path
|
||||
port: int
|
||||
token: str
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, config_path: Path) -> "AgentPaths":
|
||||
config_path = Path(config_path)
|
||||
document = json.loads(config_path.read_text(encoding="utf-8"))
|
||||
if document.get("schema_version") != SCHEMA_VERSION:
|
||||
raise DialogAgentProtocolError("Unsupported dialog-agent schema")
|
||||
return cls(config_path, int(document["port"]), str(document["token"]))
|
||||
|
||||
|
||||
class JsonChannel:
|
||||
"""One connection, newline-framed JSON, no polling traffic written to disk."""
|
||||
def __init__(self, connection):
|
||||
self.connection = connection
|
||||
self.buffer = b""
|
||||
|
||||
def send(self, document, timeout_seconds=2.0):
|
||||
self.connection.settimeout(timeout_seconds)
|
||||
payload = json.dumps(document, ensure_ascii=False).encode("utf-8") + b"\n"
|
||||
self.connection.sendall(payload)
|
||||
|
||||
def receive(self, timeout_seconds):
|
||||
deadline = time.monotonic() + timeout_seconds
|
||||
while b"\n" not in self.buffer:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("dialog-agent receive timed out")
|
||||
self.connection.settimeout(remaining)
|
||||
data = self.connection.recv(65536)
|
||||
if not data:
|
||||
raise EOFError("dialog-agent disconnected")
|
||||
self.buffer += data
|
||||
if len(self.buffer) > 8 * 1024 * 1024:
|
||||
raise DialogAgentProtocolError("dialog-agent message too large")
|
||||
line, self.buffer = self.buffer.split(b"\n", 1)
|
||||
return json.loads(line.decode("utf-8"))
|
||||
|
||||
def close(self):
|
||||
self.connection.close()
|
||||
|
||||
|
||||
def dialog_agent_command(config_path: Path):
|
||||
if getattr(sys, "frozen", False):
|
||||
return [sys.executable, "--dialog-agent", str(config_path)]
|
||||
return [sys.executable, "-m", "cbb_refresh_verify", "--dialog-agent", str(config_path)]
|
||||
|
||||
|
||||
class DialogActionExecutor:
|
||||
def __init__(self, *, win32gui=None, win32con=None, uia_wrapper=None):
|
||||
if win32gui is None:
|
||||
import win32gui as win32gui_module
|
||||
win32gui = win32gui_module
|
||||
if win32con is None:
|
||||
import win32con as win32con_module
|
||||
win32con = win32con_module
|
||||
self.win32gui = win32gui
|
||||
self.win32con = win32con
|
||||
self.uia_wrapper = uia_wrapper or self._default_uia_wrapper
|
||||
|
||||
@staticmethod
|
||||
def _default_uia_wrapper(handle):
|
||||
from pywinauto import Desktop
|
||||
return Desktop(backend="uia").window(handle=handle).wrapper_object()
|
||||
|
||||
@staticmethod
|
||||
def _target(snapshot: WindowSnapshot, target: dict):
|
||||
candidates = tuple(control for control in snapshot.controls if control.enabled)
|
||||
if "control_id" in target:
|
||||
candidates = tuple(c for c in candidates if c.control_id == int(target["control_id"]))
|
||||
if "automation_id" in target:
|
||||
candidates = tuple(c for c in candidates if c.automation_id == str(target["automation_id"]))
|
||||
if "control_type" in target:
|
||||
candidates = tuple(c for c in candidates
|
||||
if c.control_type.casefold() == str(target["control_type"]).casefold())
|
||||
if "name_contains" in target:
|
||||
token = str(target["name_contains"]).casefold()
|
||||
candidates = tuple(c for c in candidates if token in c.name.casefold())
|
||||
if not target:
|
||||
candidates = tuple(c for c in candidates
|
||||
if c.class_name.casefold() == "button"
|
||||
and c.control_id in {1, 6})
|
||||
return candidates[0] if len(candidates) == 1 else None
|
||||
|
||||
@staticmethod
|
||||
def _license_target(snapshot: WindowSnapshot):
|
||||
selectors = tuple(
|
||||
control for control in snapshot.controls
|
||||
if control.enabled and (
|
||||
"selectionitem" in {value.casefold() for value in control.patterns}
|
||||
or control.control_type.casefold() == "listitem"
|
||||
)
|
||||
)
|
||||
if any(control.selected or control.checked for control in selectors):
|
||||
confirmations = tuple(
|
||||
control for control in snapshot.controls
|
||||
if control.enabled and control.class_name.casefold() == "button"
|
||||
and control.control_id == 1
|
||||
)
|
||||
return confirmations[0] if len(confirmations) == 1 else None
|
||||
unselected = tuple(control for control in selectors
|
||||
if not control.selected and not control.checked)
|
||||
if len(unselected) == 1:
|
||||
return unselected[0]
|
||||
# Some EE7.9 installations expose the license chooser as a GXWND
|
||||
# pane without exposing any selectable child. Clicking that pane (or
|
||||
# its group button) is a no-op; the dialog's default license is
|
||||
# accepted by the real OK control instead. Prefer that confirmation
|
||||
# target whenever no SelectionItem/ListItem was found.
|
||||
confirmations = tuple(
|
||||
control for control in snapshot.controls
|
||||
if control.enabled and control.class_name.casefold() == "button"
|
||||
and control.control_id == 1
|
||||
)
|
||||
if len(confirmations) == 1:
|
||||
return confirmations[0]
|
||||
opener = tuple(
|
||||
control for control in snapshot.controls
|
||||
if control.enabled and control.class_name.casefold() == "button"
|
||||
and control.control_id == 5225
|
||||
)
|
||||
return opener[0] if len(opener) == 1 else None
|
||||
|
||||
@staticmethod
|
||||
def _restore_database_target(snapshot: WindowSnapshot):
|
||||
"""Select the user-saved database before confirming restoration."""
|
||||
controls = tuple(control for control in snapshot.controls if control.enabled)
|
||||
marker = ("last user saved database", "最后一次用户保存", "最后保存", "用户保存")
|
||||
choice = next(
|
||||
(control for control in controls
|
||||
if control.control_type.casefold() in {"radiobutton", "button", "listitem"}
|
||||
and any(token in control.name.casefold() for token in marker)
|
||||
and not (control.selected or control.checked)),
|
||||
None,
|
||||
)
|
||||
if choice is not None:
|
||||
return choice
|
||||
return next(
|
||||
(control for control in controls
|
||||
if control.class_name.casefold() == "button"
|
||||
and control.control_id == 1),
|
||||
None,
|
||||
)
|
||||
|
||||
def _private_mouse_click(self, target, parent_hwnd: int):
|
||||
"""Click a custom control on the companion's private desktop.
|
||||
|
||||
GX/MFC controls can ignore a zero-coordinate posted click even though
|
||||
the message is accepted. Use the control's center in client coordinates
|
||||
and synchronously deliver the message so the owner processes it before
|
||||
the postcondition probe runs. No foreground activation or real cursor
|
||||
movement is involved.
|
||||
"""
|
||||
left = top = right = bottom = 0
|
||||
try:
|
||||
rect = self.win32gui.GetClientRect(target.handle)
|
||||
left, top, right, bottom = (int(value) for value in rect)
|
||||
except Exception:
|
||||
try:
|
||||
rect = self.win32gui.GetWindowRect(target.handle)
|
||||
left, top, right, bottom = (int(value) for value in rect)
|
||||
right, bottom = right - left, bottom - top
|
||||
left, top = 0, 0
|
||||
except Exception:
|
||||
# Preserve the legacy message-only fallback for probe/test
|
||||
# backends that cannot provide geometry.
|
||||
left = top = right = bottom = 0
|
||||
x = max(0, (right - left) // 2)
|
||||
y = max(0, (bottom - top) // 2)
|
||||
lparam = (y << 16) | (x & 0xFFFF)
|
||||
down = 0x0201 # WM_LBUTTONDOWN
|
||||
up = 0x0202 # WM_LBUTTONUP
|
||||
send_message = getattr(self.win32gui, "SendMessage", None)
|
||||
if send_message is not None:
|
||||
send_message(target.handle, down, 1, lparam)
|
||||
send_message(target.handle, up, 0, lparam)
|
||||
else:
|
||||
self.win32gui.PostMessage(target.handle, down, 1, lparam)
|
||||
self.win32gui.PostMessage(target.handle, up, 0, lparam)
|
||||
# Some owner-drawn buttons do not synthesize BN_CLICKED from mouse
|
||||
# messages. Forward the equivalent command to the dialog owner.
|
||||
if send_message is not None and parent_hwnd:
|
||||
send_message(parent_hwnd, 0x0111, int(target.control_id), target.handle)
|
||||
|
||||
def perform(self, snapshot: WindowSnapshot, action: dict) -> ActionResult:
|
||||
channels = tuple(action.get("channels", ()))
|
||||
action_name = action.get("action")
|
||||
if action_name == "accept_license":
|
||||
target = self._license_target(snapshot)
|
||||
elif action_name == "restore_last_saved":
|
||||
target = self._restore_database_target(snapshot)
|
||||
else:
|
||||
target = self._target(snapshot, dict(action.get("target", {})))
|
||||
if target is None:
|
||||
return ActionResult(error_code="ACTION_TARGET_NOT_UNIQUE",
|
||||
detail="没有找到唯一且可用的目标控件")
|
||||
if action_name == "restore_last_saved" and target.control_id != 1:
|
||||
# EE7.9's custom radio button can block a UIA SelectionItem call
|
||||
# on Win10. BM_CLICK is asynchronous and keeps the agent
|
||||
# responsive; UIA remains an explicit fallback if Win32 fails.
|
||||
channels = ("win32_button_click",
|
||||
*(channel for channel in channels
|
||||
if channel != "win32_button_click"))
|
||||
for channel in channels:
|
||||
if channel == "interface":
|
||||
continue
|
||||
if channel.startswith("uia_"):
|
||||
try:
|
||||
patterns = {value.casefold() for value in target.patterns}
|
||||
if channel == "uia_select" and "selectionitem" not in patterns:
|
||||
continue
|
||||
if channel == "uia_toggle" and "toggle" not in patterns:
|
||||
continue
|
||||
if channel == "uia_invoke" and not (
|
||||
"invoke" in patterns or target.class_name.casefold() == "button"):
|
||||
continue
|
||||
wrapper = self.uia_wrapper(target.handle)
|
||||
if channel == "uia_invoke":
|
||||
wrapper.invoke()
|
||||
elif channel == "uia_select":
|
||||
wrapper.select()
|
||||
elif channel == "uia_toggle":
|
||||
wrapper.toggle()
|
||||
else:
|
||||
continue
|
||||
return ActionResult(channel=channel, accepted_controls=(target.control_id,))
|
||||
except Exception:
|
||||
continue
|
||||
if channel == "win32_button_click" and target.class_name.casefold() == "button":
|
||||
try:
|
||||
self.win32gui.PostMessage(
|
||||
target.handle, getattr(self.win32con, "BM_CLICK", 0x00F5), 0, 0)
|
||||
return ActionResult(channel=channel, accepted_controls=(target.control_id,))
|
||||
except Exception:
|
||||
continue
|
||||
if channel == "win32_mouse_click" and action.get("action") == "accept_license":
|
||||
try:
|
||||
self._private_mouse_click(target, snapshot.hwnd)
|
||||
return ActionResult(channel=channel, accepted_controls=(target.control_id,))
|
||||
except Exception:
|
||||
continue
|
||||
return ActionResult(error_code="ACTION_CHANNEL_FAILED",
|
||||
detail=f"动作通道均失败: {', '.join(channels)}")
|
||||
|
||||
|
||||
class DialogAgentServer:
|
||||
def __init__(self, paths: AgentPaths, *, probe, executor=None, poll_seconds=0.02):
|
||||
self.paths = paths
|
||||
self.probe = probe
|
||||
self.executor = executor or DialogActionExecutor()
|
||||
self.poll_seconds = max(0.005, float(poll_seconds))
|
||||
self.sequence = 0
|
||||
self.requests = deque(maxlen=1)
|
||||
self.responses = deque(maxlen=1)
|
||||
connection = socket.create_connection(("127.0.0.1", paths.port), timeout=10)
|
||||
connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
||||
self.channel = JsonChannel(connection)
|
||||
self.channel.send({"token": paths.token}, timeout_seconds=10)
|
||||
self.observed_snapshots = {}
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, config_path: Path, *, probe, executor=None):
|
||||
return cls(AgentPaths.from_config(config_path), probe=probe, executor=executor)
|
||||
|
||||
def _response(self, request, **values):
|
||||
self.sequence += 1
|
||||
response = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"request_id": request.get("request_id", ""),
|
||||
"sequence": self.sequence,
|
||||
**values,
|
||||
}
|
||||
self.channel.send(response)
|
||||
self.responses.append(response)
|
||||
|
||||
def _handle(self, request):
|
||||
self.requests.append(request)
|
||||
if request.get("schema_version") != SCHEMA_VERSION:
|
||||
self._response(request, error_code="DIALOG_PROTOCOL_ERROR", detail="schema_version 不匹配")
|
||||
return
|
||||
try:
|
||||
phase = DialogPhase(request["phase"])
|
||||
if request.get("op") == "observe":
|
||||
snapshots = self.probe.capture(phase)
|
||||
self.observed_snapshots.clear()
|
||||
for snapshot in snapshots:
|
||||
self.observed_snapshots[stable_fingerprint(snapshot)] = snapshot
|
||||
self._response(request, result=[item.to_record() for item in snapshots])
|
||||
return
|
||||
if request.get("op") == "perform":
|
||||
expected = self.observed_snapshots.get(request.get("fingerprint"))
|
||||
if expected is None:
|
||||
self._response(request, result=ActionResult(
|
||||
error_code="STALE_DIALOG",
|
||||
detail="窗口已消失或指纹已变化",
|
||||
).to_record())
|
||||
return
|
||||
else:
|
||||
# The supervisor just observed this exact fingerprint. A
|
||||
# second full child/UIA scan can block on EE7.9's native
|
||||
# license dialog, so execute against that validated
|
||||
# snapshot instead of rescanning it synchronously.
|
||||
snapshot = expected
|
||||
result = self.executor.perform(snapshot, dict(request.get("action", {})))
|
||||
self._response(request, result=result.to_record())
|
||||
return
|
||||
self._response(request, error_code="DIALOG_PROTOCOL_ERROR", detail="未知 op")
|
||||
except WindowProbeError as error:
|
||||
self._response(request, error_code=error.error_code, detail=error.detail)
|
||||
except Exception as error:
|
||||
self._response(request, error_code="DIALOG_AGENT_ERROR", detail=str(error))
|
||||
|
||||
def serve_once(self) -> bool:
|
||||
try:
|
||||
request = self.channel.receive(self.poll_seconds)
|
||||
except TimeoutError:
|
||||
return False
|
||||
self._handle(request)
|
||||
return True
|
||||
|
||||
def serve_forever(self) -> int:
|
||||
try:
|
||||
while True:
|
||||
self.serve_once()
|
||||
except (EOFError, ConnectionError, OSError):
|
||||
return 0
|
||||
finally:
|
||||
self.channel.close()
|
||||
|
||||
|
||||
class DialogAgentClient:
|
||||
def __init__(self, paths: AgentPaths, listener, *, timeout_seconds: float = 2.0):
|
||||
self.paths = paths
|
||||
self.listener = listener
|
||||
self.channel = None
|
||||
self.timeout_seconds = max(0.1, float(timeout_seconds))
|
||||
self.last_sequence = 0
|
||||
|
||||
@classmethod
|
||||
def prepare(cls, root: Path, *, desktop_name: str, timeout_seconds=2.0):
|
||||
root = Path(root)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
try:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen(1)
|
||||
paths = AgentPaths(root / "dialog-agent.json", listener.getsockname()[1], uuid4().hex)
|
||||
paths.config.write_text(json.dumps({
|
||||
"schema_version": SCHEMA_VERSION, "transport": "loopback_memory",
|
||||
"desktop_name": desktop_name, "port": paths.port, "token": paths.token,
|
||||
}, ensure_ascii=False), encoding="utf-8")
|
||||
return cls(paths, listener, timeout_seconds=timeout_seconds)
|
||||
except Exception:
|
||||
listener.close()
|
||||
raise
|
||||
|
||||
@classmethod
|
||||
def start(cls, worker, root: Path, *, timeout_seconds: float = 2.0):
|
||||
client = cls.prepare(root, desktop_name=worker.name, timeout_seconds=timeout_seconds)
|
||||
try:
|
||||
worker.start_companion(dialog_agent_command(client.paths.config))
|
||||
client._accept(timeout_seconds=10.0)
|
||||
return client
|
||||
except Exception:
|
||||
client.close()
|
||||
raise
|
||||
|
||||
def _accept(self, timeout_seconds):
|
||||
if self.channel is not None:
|
||||
return
|
||||
self.listener.settimeout(timeout_seconds)
|
||||
connection, _address = self.listener.accept()
|
||||
channel = JsonChannel(connection)
|
||||
try:
|
||||
connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
||||
hello = channel.receive(timeout_seconds)
|
||||
if hello.get("token") != self.paths.token:
|
||||
raise DialogAgentProtocolError("dialog-agent authentication failed")
|
||||
self.channel = channel
|
||||
except Exception:
|
||||
channel.close()
|
||||
raise
|
||||
finally:
|
||||
self.listener.close()
|
||||
|
||||
def _request(self, op: str, phase: DialogPhase, **values):
|
||||
try:
|
||||
self._accept(self.timeout_seconds)
|
||||
request_id = uuid4().hex
|
||||
self.channel.send({
|
||||
"schema_version": SCHEMA_VERSION, "request_id": request_id,
|
||||
"op": op, "phase": phase.value, **values,
|
||||
}, self.timeout_seconds)
|
||||
response = self.channel.receive(self.timeout_seconds)
|
||||
except (OSError, EOFError) as error:
|
||||
raise DialogAgentProtocolError(f"DIALOG_PROTOCOL_TIMEOUT_OR_DISCONNECT: {op}: {error}") from error
|
||||
if response.get("schema_version") != SCHEMA_VERSION:
|
||||
raise DialogAgentProtocolError("响应 schema_version 不匹配")
|
||||
if response.get("request_id") != request_id:
|
||||
raise DialogAgentProtocolError("响应 request_id 不匹配")
|
||||
sequence = int(response.get("sequence", 0))
|
||||
if sequence <= self.last_sequence:
|
||||
raise DialogAgentProtocolError("响应 sequence 非单调递增")
|
||||
self.last_sequence = sequence
|
||||
if response.get("error_code"):
|
||||
raise DialogAgentProtocolError(f"{response['error_code']}: {response.get('detail', '')}")
|
||||
return response.get("result")
|
||||
|
||||
def observe(self, phase: DialogPhase) -> tuple[WindowSnapshot, ...]:
|
||||
result = self._request("observe", phase)
|
||||
return tuple(WindowSnapshot.from_record(item) for item in (result or ()))
|
||||
|
||||
def perform(self, *, hwnd: int, fingerprint: str, action: dict,
|
||||
phase: DialogPhase) -> ActionResult:
|
||||
result = self._request(
|
||||
"perform", phase, hwnd=int(hwnd), fingerprint=str(fingerprint), action=dict(action))
|
||||
return ActionResult.from_record(result)
|
||||
|
||||
def close(self):
|
||||
if self.channel is not None:
|
||||
self.channel.close()
|
||||
self.listener.close()
|
||||
|
||||
|
||||
class _CurrentDesktop:
|
||||
@staticmethod
|
||||
def EnumDesktopWindows():
|
||||
import win32gui
|
||||
handles = []
|
||||
|
||||
def collect(handle, _context):
|
||||
handles.append(int(handle))
|
||||
return True
|
||||
|
||||
win32gui.EnumWindows(collect, None)
|
||||
return tuple(handles)
|
||||
|
||||
|
||||
def dialog_agent_main(config_path: Path) -> int:
|
||||
import pythoncom
|
||||
|
||||
pythoncom.CoInitialize()
|
||||
try:
|
||||
probe = WindowProbe(desktop=_CurrentDesktop())
|
||||
return DialogAgentServer.from_config(config_path, probe=probe).serve_forever()
|
||||
finally:
|
||||
pythoncom.CoUninitialize()
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Stable, serializable window evidence used by dialog supervision."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
from enum import Enum
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
|
||||
class DialogPhase(str, Enum):
|
||||
PCB_STARTING = "PCB_STARTING"
|
||||
LICENSE_ACQUISITION = "LICENSE_ACQUISITION"
|
||||
DATABASE_RECOVERY = "DATABASE_RECOVERY"
|
||||
DOCUMENT_ATTACH = "DOCUMENT_ATTACH"
|
||||
IDENTITY_CHECK = "IDENTITY_CHECK"
|
||||
PROJECT_INTEGRATION = "PROJECT_INTEGRATION"
|
||||
VALIDATE = "VALIDATE"
|
||||
SAVE = "SAVE"
|
||||
CLOSE = "CLOSE"
|
||||
POST_VERIFY_STATUS = "POST_VERIFY_STATUS"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ControlSnapshot:
|
||||
handle: int
|
||||
control_id: int
|
||||
class_name: str
|
||||
name: str
|
||||
automation_id: str = ""
|
||||
control_type: str = ""
|
||||
enabled: bool = True
|
||||
selected: bool = False
|
||||
checked: bool = False
|
||||
patterns: tuple[str, ...] = ()
|
||||
|
||||
@classmethod
|
||||
def from_record(cls, record: dict[str, Any]) -> "ControlSnapshot":
|
||||
values = dict(record)
|
||||
values["patterns"] = tuple(values.get("patterns", ()))
|
||||
return cls(**values)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WindowSnapshot:
|
||||
hwnd: int
|
||||
pid: int
|
||||
process_name: str
|
||||
process_role: str
|
||||
window_class: str
|
||||
title: str
|
||||
phase: DialogPhase
|
||||
controls: tuple[ControlSnapshot, ...]
|
||||
owner_hwnd: int = 0
|
||||
diagnostics: tuple[str, ...] = ()
|
||||
|
||||
@property
|
||||
def texts(self) -> tuple[str, ...]:
|
||||
return tuple(control.name for control in self.controls if control.name.strip())
|
||||
|
||||
@property
|
||||
def signature(self) -> tuple[object, ...]:
|
||||
return (
|
||||
self.title,
|
||||
tuple((control.control_id, control.class_name, control.name,
|
||||
control.enabled, control.checked, control.selected)
|
||||
for control in self.controls),
|
||||
)
|
||||
|
||||
def to_record(self) -> dict[str, Any]:
|
||||
record = asdict(self)
|
||||
record["phase"] = self.phase.value
|
||||
return record
|
||||
|
||||
@classmethod
|
||||
def from_record(cls, record: dict[str, Any]) -> "WindowSnapshot":
|
||||
values = dict(record)
|
||||
values["phase"] = DialogPhase(values["phase"])
|
||||
values["controls"] = tuple(ControlSnapshot.from_record(item)
|
||||
for item in values.get("controls", ()))
|
||||
values["diagnostics"] = tuple(values.get("diagnostics", ()))
|
||||
return cls(**values)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RuleDecision:
|
||||
rule_id: str = ""
|
||||
category: str = ""
|
||||
action: str = ""
|
||||
channels: tuple[str, ...] = ()
|
||||
target: tuple[tuple[str, object], ...] = ()
|
||||
postcondition: str = ""
|
||||
error_code: str = ""
|
||||
detail: str = ""
|
||||
|
||||
|
||||
_GUID = re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", re.I)
|
||||
_WINDOWS_PATH = re.compile(r"(?i)(?:[a-z]:\\|\\\\)[^\s|]+")
|
||||
_NUMBER = re.compile(r"\b\d+(?:\.\d+)?\b")
|
||||
_SPACE = re.compile(r"\s+")
|
||||
|
||||
|
||||
def normalize_text(value: str) -> str:
|
||||
text = str(value or "").casefold()
|
||||
text = _GUID.sub("<guid>", text)
|
||||
text = _WINDOWS_PATH.sub("<path>", text)
|
||||
text = _NUMBER.sub("<n>", text)
|
||||
return _SPACE.sub(" ", text).strip()
|
||||
|
||||
|
||||
def stable_fingerprint(snapshot: WindowSnapshot) -> str:
|
||||
controls = sorted(
|
||||
(
|
||||
control.control_id,
|
||||
control.class_name.casefold(),
|
||||
normalize_text(control.name),
|
||||
control.automation_id.casefold(),
|
||||
control.control_type.casefold(),
|
||||
tuple(sorted(pattern.casefold() for pattern in control.patterns)),
|
||||
)
|
||||
for control in snapshot.controls
|
||||
)
|
||||
stable = {
|
||||
"phase": snapshot.phase.value,
|
||||
"process_name": snapshot.process_name.casefold(),
|
||||
"process_role": snapshot.process_role.casefold(),
|
||||
"window_class": snapshot.window_class.casefold(),
|
||||
"owned": bool(snapshot.owner_hwnd),
|
||||
"title": normalize_text(snapshot.title),
|
||||
"controls": controls,
|
||||
}
|
||||
payload = json.dumps(stable, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def compatible_window_identity(expected: WindowSnapshot, actual: WindowSnapshot) -> bool:
|
||||
"""Allow transient control-tree changes without accepting a new window."""
|
||||
return (
|
||||
expected.hwnd == actual.hwnd
|
||||
and expected.pid == actual.pid
|
||||
and expected.process_name.casefold() == actual.process_name.casefold()
|
||||
and expected.window_class.casefold() == actual.window_class.casefold()
|
||||
and normalize_text(expected.title) == normalize_text(actual.title)
|
||||
)
|
||||
@@ -0,0 +1,296 @@
|
||||
"""Class-agnostic Win32 discovery with best-effort UI Automation evidence."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import queue
|
||||
import threading
|
||||
from typing import Callable
|
||||
|
||||
from .dialog_models import ControlSnapshot, DialogPhase, WindowSnapshot
|
||||
|
||||
|
||||
class WindowProbeError(RuntimeError):
|
||||
def __init__(self, error_code: str, detail: str) -> None:
|
||||
self.error_code = error_code
|
||||
self.detail = detail
|
||||
super().__init__(detail)
|
||||
|
||||
|
||||
def _winerror(error: BaseException):
|
||||
value = getattr(error, "winerror", None)
|
||||
if value is None:
|
||||
arguments = getattr(error, "args", ())
|
||||
value = arguments[0] if arguments else None
|
||||
return value
|
||||
|
||||
|
||||
def _bounded_call(function: Callable[[], object], timeout_seconds: float):
|
||||
results: queue.Queue[tuple[bool, object]] = queue.Queue(maxsize=1)
|
||||
|
||||
def run():
|
||||
try:
|
||||
results.put((True, function()))
|
||||
except BaseException as error:
|
||||
results.put((False, error))
|
||||
|
||||
threading.Thread(target=run, daemon=True, name="CbbDialogUiaProbe").start()
|
||||
try:
|
||||
succeeded, value = results.get(timeout=max(0.05, float(timeout_seconds)))
|
||||
except queue.Empty as error:
|
||||
raise TimeoutError(f"UIA probe exceeded {timeout_seconds:g}s") from error
|
||||
if not succeeded:
|
||||
raise value
|
||||
return value
|
||||
|
||||
|
||||
class PywinautoUiaFacade:
|
||||
"""Read UIA metadata only; this class never activates or clicks a window."""
|
||||
|
||||
@staticmethod
|
||||
def _patterns(wrapper) -> tuple[str, ...]:
|
||||
names = []
|
||||
for name, attribute in (
|
||||
("Invoke", "iface_invoke"),
|
||||
("SelectionItem", "iface_selection_item"),
|
||||
("Toggle", "iface_toggle"),
|
||||
("Value", "iface_value"),
|
||||
("Window", "iface_window"),
|
||||
):
|
||||
try:
|
||||
if getattr(wrapper, attribute, None) is not None:
|
||||
names.append(name)
|
||||
except Exception:
|
||||
pass
|
||||
return tuple(names)
|
||||
|
||||
def controls(self, hwnd: int):
|
||||
from pywinauto import Desktop
|
||||
|
||||
root = Desktop(backend="uia").window(handle=int(hwnd)).wrapper_object()
|
||||
wrappers = (root, *root.descendants())
|
||||
records = []
|
||||
for wrapper in wrappers:
|
||||
info = wrapper.element_info
|
||||
selected = False
|
||||
checked = False
|
||||
try:
|
||||
selected = bool(wrapper.is_selected())
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
checked = int(wrapper.get_toggle_state()) != 0
|
||||
except Exception:
|
||||
pass
|
||||
records.append({
|
||||
"handle": int(getattr(info, "handle", 0) or 0),
|
||||
"control_id": int(getattr(info, "control_id", 0) or 0),
|
||||
"class_name": str(getattr(info, "class_name", "") or ""),
|
||||
"name": str(getattr(info, "name", "") or ""),
|
||||
"automation_id": str(getattr(info, "automation_id", "") or ""),
|
||||
"control_type": str(getattr(info, "control_type", "") or ""),
|
||||
"enabled": bool(getattr(info, "enabled", True)),
|
||||
"selected": selected,
|
||||
"checked": checked,
|
||||
"patterns": self._patterns(wrapper),
|
||||
})
|
||||
return tuple(records)
|
||||
|
||||
|
||||
def _default_process_name_reader(pid: int) -> str:
|
||||
import win32api
|
||||
import win32con
|
||||
import win32process
|
||||
|
||||
access = getattr(win32con, "PROCESS_QUERY_LIMITED_INFORMATION", 0x1000)
|
||||
try:
|
||||
process = win32api.OpenProcess(access, False, int(pid))
|
||||
except Exception:
|
||||
process = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ,
|
||||
False, int(pid))
|
||||
try:
|
||||
try:
|
||||
path = win32process.QueryFullProcessImageName(process, 0)
|
||||
except Exception:
|
||||
path = win32process.GetModuleFileNameEx(process, 0)
|
||||
return Path(path).name
|
||||
finally:
|
||||
process.Close()
|
||||
|
||||
|
||||
def _process_role(process_name: str) -> str:
|
||||
lowered = process_name.casefold()
|
||||
if any(token in lowered for token in ("expedition", "xtremedesign", "mgcpcb")):
|
||||
return "pcb"
|
||||
if "license" in lowered:
|
||||
return "license"
|
||||
if any(token in lowered for token in ("cdbsvr", "designserver", "cscript")):
|
||||
return "helper"
|
||||
return "unknown"
|
||||
|
||||
|
||||
class WindowProbe:
|
||||
_IGNORED_WINDOW_CLASSES = frozenset({
|
||||
"uac_inputindicatoroverlaywnd",
|
||||
"uac input indicator",
|
||||
# ExpeditionPCB creates this hidden browser host while attaching a
|
||||
# document. It is not a modal prompt, and UIA probing it repeatedly
|
||||
# costs up to the full probe timeout while producing no actionable
|
||||
# controls (the latest failed runs generated dozens of these records).
|
||||
"internet explorer_hidden",
|
||||
})
|
||||
|
||||
def __init__(self, *, desktop, win32gui=None, win32process=None,
|
||||
process_name_reader=None, uia=None, uia_timeout_seconds: float = 0.75) -> None:
|
||||
if win32gui is None:
|
||||
import win32gui as win32gui_module
|
||||
win32gui = win32gui_module
|
||||
if win32process is None:
|
||||
import win32process as win32process_module
|
||||
win32process = win32process_module
|
||||
self.desktop = desktop
|
||||
self.win32gui = win32gui
|
||||
self.win32process = win32process
|
||||
self.process_name_reader = process_name_reader or _default_process_name_reader
|
||||
self.uia = uia or PywinautoUiaFacade()
|
||||
self.uia_timeout_seconds = max(0.05, float(uia_timeout_seconds))
|
||||
|
||||
def _handles(self) -> tuple[int, ...]:
|
||||
try:
|
||||
return tuple(int(handle) for handle in self.desktop.EnumDesktopWindows())
|
||||
except Exception as error:
|
||||
if _winerror(error) in (0, 2):
|
||||
return ()
|
||||
raise WindowProbeError("WINDOW_ENUM_ERROR", f"EnumDesktopWindows 失败: {error}") from error
|
||||
|
||||
def _children(self, hwnd: int) -> tuple[int, ...]:
|
||||
children: list[int] = []
|
||||
|
||||
def collect(handle, _context):
|
||||
children.append(int(handle))
|
||||
return True
|
||||
|
||||
try:
|
||||
self.win32gui.EnumChildWindows(hwnd, collect, None)
|
||||
except Exception as error:
|
||||
raise WindowProbeError("WINDOW_ENUM_ERROR", f"EnumChildWindows({hwnd}) 失败: {error}") from error
|
||||
return tuple(children)
|
||||
|
||||
def _win32_control(self, hwnd: int) -> ControlSnapshot:
|
||||
gui = self.win32gui
|
||||
class_name = str(gui.GetClassName(hwnd) or "")
|
||||
checked = False
|
||||
selected = False
|
||||
try:
|
||||
if class_name.casefold() == "button":
|
||||
checked = bool(gui.SendMessage(hwnd, 0x00F0, 0, 0))
|
||||
elif class_name.casefold() == "combobox":
|
||||
selected = int(gui.SendMessage(hwnd, 0x0147, 0, 0)) >= 0
|
||||
elif class_name.casefold() == "listbox":
|
||||
selected = int(gui.SendMessage(hwnd, 0x0188, 0, 0)) >= 0
|
||||
except Exception:
|
||||
pass
|
||||
return ControlSnapshot(
|
||||
handle=int(hwnd),
|
||||
control_id=int(gui.GetDlgCtrlID(hwnd)),
|
||||
class_name=class_name,
|
||||
name=str(gui.GetWindowText(hwnd) or ""),
|
||||
control_type=class_name,
|
||||
enabled=bool(gui.IsWindowEnabled(hwnd)),
|
||||
checked=checked,
|
||||
selected=selected,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _merge_controls(win32_controls, uia_records):
|
||||
by_handle = {control.handle: control for control in win32_controls}
|
||||
extras = []
|
||||
for record in uia_records:
|
||||
uia_control = ControlSnapshot.from_record(dict(record))
|
||||
existing = by_handle.get(uia_control.handle)
|
||||
if existing is None:
|
||||
extras.append(uia_control)
|
||||
continue
|
||||
by_handle[uia_control.handle] = ControlSnapshot(
|
||||
handle=existing.handle,
|
||||
control_id=uia_control.control_id or existing.control_id,
|
||||
class_name=uia_control.class_name or existing.class_name,
|
||||
name=uia_control.name or existing.name,
|
||||
automation_id=uia_control.automation_id,
|
||||
control_type=uia_control.control_type or existing.control_type,
|
||||
enabled=uia_control.enabled,
|
||||
selected=uia_control.selected or existing.selected,
|
||||
checked=uia_control.checked or existing.checked,
|
||||
patterns=uia_control.patterns,
|
||||
)
|
||||
ordered = [by_handle[control.handle] for control in win32_controls]
|
||||
return tuple((*ordered, *extras))
|
||||
|
||||
def capture_one(self, hwnd: int, phase: DialogPhase) -> WindowSnapshot | None:
|
||||
gui = self.win32gui
|
||||
try:
|
||||
if not gui.IsWindowVisible(hwnd):
|
||||
return None
|
||||
pid = int(self.win32process.GetWindowThreadProcessId(hwnd)[1])
|
||||
try:
|
||||
process_name = str(self.process_name_reader(pid) or "")
|
||||
except Exception:
|
||||
process_name = ""
|
||||
controls = tuple(self._win32_control(child) for child in self._children(hwnd))
|
||||
diagnostics = []
|
||||
try:
|
||||
uia_records = _bounded_call(lambda: self.uia.controls(hwnd), self.uia_timeout_seconds)
|
||||
controls = self._merge_controls(controls, uia_records)
|
||||
except Exception as error:
|
||||
diagnostics.append(f"UIA_ERROR: {error}")
|
||||
owner = 0
|
||||
try:
|
||||
owner = int(gui.GetWindow(hwnd, 4) or 0) # GW_OWNER
|
||||
except Exception:
|
||||
pass
|
||||
return WindowSnapshot(
|
||||
hwnd=int(hwnd),
|
||||
pid=pid,
|
||||
process_name=process_name,
|
||||
process_role=_process_role(process_name),
|
||||
window_class=str(gui.GetClassName(hwnd) or ""),
|
||||
title=str(gui.GetWindowText(hwnd) or ""),
|
||||
phase=phase,
|
||||
controls=controls,
|
||||
owner_hwnd=owner,
|
||||
diagnostics=tuple(diagnostics),
|
||||
)
|
||||
except WindowProbeError:
|
||||
raise
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def capture(self, phase: DialogPhase) -> tuple[WindowSnapshot, ...]:
|
||||
snapshots = []
|
||||
for hwnd in self._handles():
|
||||
try:
|
||||
window_class = str(self.win32gui.GetClassName(hwnd) or "")
|
||||
except Exception:
|
||||
window_class = ""
|
||||
lowered_class = window_class.casefold()
|
||||
# Windows may create input-indicator overlays and MFC Afx host
|
||||
# windows on the private desktop while PCB is starting. They are
|
||||
# not actionable dialogs and probing their child/UIA trees can
|
||||
# block the JSONL agent after a license dialog closes.
|
||||
if lowered_class in self._IGNORED_WINDOW_CLASSES or lowered_class.startswith("afx:"):
|
||||
continue
|
||||
if phase == DialogPhase.PROJECT_INTEGRATION:
|
||||
try:
|
||||
title = str(self.win32gui.GetWindowText(hwnd) or "").strip().casefold()
|
||||
except Exception:
|
||||
title = ""
|
||||
# Project Integration is the COM-driven owner panel. It is
|
||||
# intentionally observed through ProjectIntegration.Status;
|
||||
# probing its very large MFC/UIA tree can block the dialog
|
||||
# agent and falsely abort a valid refresh.
|
||||
if title in {"project integration", "项目集成"}:
|
||||
continue
|
||||
snapshot = self.capture_one(hwnd, phase)
|
||||
if snapshot is not None:
|
||||
snapshots.append(snapshot)
|
||||
return tuple(snapshots)
|
||||
@@ -0,0 +1,224 @@
|
||||
"""Declarative, phase-aware rules for Mentor dialog decisions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, fields, replace
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from typing import Any, Sequence
|
||||
|
||||
from .dialog_models import DialogPhase, RuleDecision, WindowSnapshot, normalize_text
|
||||
|
||||
|
||||
class RuleConfigError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def default_rules_path() -> Path:
|
||||
source = Path(__file__).resolve().parent / "assets" / "dialog_rules.v1.json"
|
||||
frozen = Path(getattr(sys, "_MEIPASS", source.parent.parent)) / "cbb_refresh_verify" / "assets" / "dialog_rules.v1.json"
|
||||
return frozen if frozen.is_file() else source
|
||||
|
||||
|
||||
_CATEGORIES = {"OBSERVE_PROGRESS", "SAFE_RECOVERY", "SAFE_CONFIRM", "FATAL_ACK"}
|
||||
_CHANNELS = {"interface", "uia_invoke", "uia_select", "uia_toggle", "win32_button_click", "win32_mouse_click"}
|
||||
_POSTCONDITIONS = {"", "window_gone", "control_selected", "control_enabled", "signature_changed", "next_phase"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DialogRule:
|
||||
rule_id: str
|
||||
priority: int
|
||||
category: str
|
||||
phases: tuple[DialogPhase, ...]
|
||||
enabled: bool = True
|
||||
process_names: tuple[str, ...] = ()
|
||||
process_roles: tuple[str, ...] = ()
|
||||
window_classes: tuple[str, ...] = ()
|
||||
semantic_all: tuple[str, ...] = ()
|
||||
semantic_any: tuple[str, ...] = ()
|
||||
semantic_none: tuple[str, ...] = ()
|
||||
required_control_types: tuple[str, ...] = ()
|
||||
required_control_classes: tuple[str, ...] = ()
|
||||
action: str = ""
|
||||
channels: tuple[str, ...] = ()
|
||||
target: tuple[tuple[str, object], ...] = ()
|
||||
postcondition: str = ""
|
||||
error_code: str = ""
|
||||
|
||||
|
||||
def _tuple_strings(value: Any) -> tuple[str, ...]:
|
||||
if value is None:
|
||||
return ()
|
||||
if not isinstance(value, list):
|
||||
raise RuleConfigError("规则列表字段必须是 JSON array")
|
||||
return tuple(str(item) for item in value)
|
||||
|
||||
|
||||
def _parse_rule(raw: dict[str, Any]) -> DialogRule:
|
||||
known = {field.name for field in fields(DialogRule)}
|
||||
unknown = set(raw) - known
|
||||
if unknown:
|
||||
raise RuleConfigError(f"规则包含未知字段: {', '.join(sorted(unknown))}")
|
||||
try:
|
||||
phases = tuple(DialogPhase(value) for value in raw["phases"])
|
||||
target_value = raw.get("target", {})
|
||||
if not isinstance(target_value, dict):
|
||||
raise RuleConfigError("target 必须是 JSON object")
|
||||
rule = DialogRule(
|
||||
rule_id=str(raw["rule_id"]),
|
||||
priority=int(raw["priority"]),
|
||||
category=str(raw["category"]),
|
||||
phases=phases,
|
||||
enabled=bool(raw.get("enabled", True)),
|
||||
process_names=_tuple_strings(raw.get("process_names")),
|
||||
process_roles=_tuple_strings(raw.get("process_roles")),
|
||||
window_classes=_tuple_strings(raw.get("window_classes")),
|
||||
semantic_all=_tuple_strings(raw.get("semantic_all")),
|
||||
semantic_any=_tuple_strings(raw.get("semantic_any")),
|
||||
semantic_none=_tuple_strings(raw.get("semantic_none")),
|
||||
required_control_types=_tuple_strings(raw.get("required_control_types")),
|
||||
required_control_classes=_tuple_strings(raw.get("required_control_classes")),
|
||||
action=str(raw.get("action", "")),
|
||||
channels=_tuple_strings(raw.get("channels")),
|
||||
target=tuple(sorted(target_value.items())),
|
||||
postcondition=str(raw.get("postcondition", "")),
|
||||
error_code=str(raw.get("error_code", "")),
|
||||
)
|
||||
except (KeyError, TypeError, ValueError) as error:
|
||||
if isinstance(error, RuleConfigError):
|
||||
raise
|
||||
raise RuleConfigError(f"无效规则: {raw.get('rule_id', '<missing>')}: {error}") from error
|
||||
if not rule.rule_id or not rule.phases:
|
||||
raise RuleConfigError("rule_id 和 phases 不能为空")
|
||||
if rule.category not in _CATEGORIES:
|
||||
raise RuleConfigError(f"未知 category: {rule.category}")
|
||||
unknown_channels = set(rule.channels) - _CHANNELS
|
||||
if unknown_channels:
|
||||
raise RuleConfigError(f"未知 action channel: {', '.join(sorted(unknown_channels))}")
|
||||
if rule.postcondition not in _POSTCONDITIONS:
|
||||
raise RuleConfigError(f"未知 postcondition: {rule.postcondition}")
|
||||
return rule
|
||||
|
||||
|
||||
def _read_document(path: Path) -> list[dict[str, Any]]:
|
||||
try:
|
||||
document = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as error:
|
||||
raise RuleConfigError(f"无法读取规则 {path}: {error}") from error
|
||||
if document.get("schema_version") != 1:
|
||||
raise RuleConfigError(f"不支持的 schema_version: {document.get('schema_version')}")
|
||||
rules = document.get("rules")
|
||||
if not isinstance(rules, list):
|
||||
raise RuleConfigError("rules 必须是 JSON array")
|
||||
return rules
|
||||
|
||||
|
||||
def load_rules(default_path: Path, override_path: Path | None = None) -> tuple[DialogRule, ...]:
|
||||
ordered: list[str] = []
|
||||
raw_by_id: dict[str, dict[str, Any]] = {}
|
||||
for raw in _read_document(default_path):
|
||||
rule_id = str(raw.get("rule_id", ""))
|
||||
if not rule_id or rule_id in raw_by_id:
|
||||
raise RuleConfigError(f"默认规则 ID 重复或为空: {rule_id}")
|
||||
ordered.append(rule_id)
|
||||
raw_by_id[rule_id] = dict(raw)
|
||||
if override_path is not None and Path(override_path).is_file():
|
||||
seen: set[str] = set()
|
||||
for override in _read_document(override_path):
|
||||
rule_id = str(override.get("rule_id", ""))
|
||||
if not rule_id or rule_id in seen:
|
||||
raise RuleConfigError(f"现场规则 ID 重复或为空: {rule_id}")
|
||||
seen.add(rule_id)
|
||||
if rule_id in raw_by_id:
|
||||
raw_by_id[rule_id].update(override)
|
||||
else:
|
||||
ordered.append(rule_id)
|
||||
raw_by_id[rule_id] = dict(override)
|
||||
return tuple(_parse_rule(raw_by_id[rule_id]) for rule_id in ordered)
|
||||
|
||||
|
||||
def _semantic_text(snapshot: WindowSnapshot) -> str:
|
||||
return normalize_text(" ".join((snapshot.title, *snapshot.texts)))
|
||||
|
||||
|
||||
def _matches(rule: DialogRule, snapshot: WindowSnapshot, *, include_phase: bool) -> bool:
|
||||
if not rule.enabled:
|
||||
return False
|
||||
if include_phase and snapshot.phase not in rule.phases:
|
||||
return False
|
||||
if rule.process_names and snapshot.process_name.casefold() not in {v.casefold() for v in rule.process_names}:
|
||||
return False
|
||||
if rule.process_roles and snapshot.process_role.casefold() not in {v.casefold() for v in rule.process_roles}:
|
||||
return False
|
||||
if rule.window_classes and snapshot.window_class.casefold() not in {v.casefold() for v in rule.window_classes}:
|
||||
return False
|
||||
semantic = _semantic_text(snapshot)
|
||||
all_tokens = tuple(normalize_text(value) for value in rule.semantic_all)
|
||||
any_tokens = tuple(normalize_text(value) for value in rule.semantic_any)
|
||||
none_tokens = tuple(normalize_text(value) for value in rule.semantic_none)
|
||||
if any(token not in semantic for token in all_tokens):
|
||||
return False
|
||||
if any_tokens and not any(token in semantic for token in any_tokens):
|
||||
return False
|
||||
if any(token in semantic for token in none_tokens):
|
||||
return False
|
||||
control_types = {control.control_type.casefold() for control in snapshot.controls}
|
||||
control_classes = {control.class_name.casefold() for control in snapshot.controls}
|
||||
if not {value.casefold() for value in rule.required_control_types}.issubset(control_types):
|
||||
return False
|
||||
if not {value.casefold() for value in rule.required_control_classes}.issubset(control_classes):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _decision(rule: DialogRule) -> RuleDecision:
|
||||
return RuleDecision(
|
||||
rule_id=rule.rule_id,
|
||||
category=rule.category,
|
||||
action=rule.action,
|
||||
channels=rule.channels,
|
||||
target=rule.target,
|
||||
postcondition=rule.postcondition,
|
||||
error_code=rule.error_code if rule.category == "FATAL_ACK" else "",
|
||||
)
|
||||
|
||||
|
||||
def decide(snapshot: WindowSnapshot, rules: Sequence[DialogRule]) -> RuleDecision:
|
||||
# Windows Text Services Framework language-bar window exposed by Mentor's
|
||||
# process is not a Mentor modal: it has no controls and must not abort a run.
|
||||
if (snapshot.window_class.casefold() == 'cicerouiwndframe'
|
||||
and normalize_text(snapshot.title) == 'tf_floatinglangbar_wndtitle'
|
||||
and not snapshot.controls):
|
||||
return RuleDecision(rule_id='ime-floating-language-bar', category='OBSERVE_PROGRESS')
|
||||
combined = normalize_text(' '.join((snapshot.title, *snapshot.texts)))
|
||||
if ('problem encountered while opening one of the database files' in combined
|
||||
and 'loading of the job has failed' in combined):
|
||||
return RuleDecision(
|
||||
rule_id='mentor-database-open-failed', category='FATAL_ACK',
|
||||
action='acknowledge_fatal',
|
||||
channels=('win32_button_click', 'uia_invoke'),
|
||||
target=(('control_id', 7),), postcondition='window_gone',
|
||||
error_code='MENTOR_DATABASE_LOAD_FAILED', detail=' | '.join(snapshot.texts))
|
||||
matches = [rule for rule in rules if _matches(rule, snapshot, include_phase=True)]
|
||||
if matches:
|
||||
best_priority = max(rule.priority for rule in matches)
|
||||
best = [rule for rule in matches if rule.priority == best_priority]
|
||||
if len(best) != 1:
|
||||
ids = ", ".join(sorted(rule.rule_id for rule in best))
|
||||
return RuleDecision(error_code="DIALOG_RULE_CONFLICT", detail=f"同优先级规则冲突: {ids}")
|
||||
return _decision(best[0])
|
||||
out_of_phase = [rule for rule in rules if _matches(rule, snapshot, include_phase=False)]
|
||||
if out_of_phase:
|
||||
best = max(out_of_phase, key=lambda rule: rule.priority)
|
||||
return RuleDecision(
|
||||
rule_id=best.rule_id,
|
||||
category=best.category,
|
||||
error_code="DIALOG_OUT_OF_PHASE",
|
||||
detail=f"规则 {best.rule_id} 不允许在阶段 {snapshot.phase.value} 执行",
|
||||
)
|
||||
return RuleDecision(
|
||||
error_code="UNKNOWN_DIALOG",
|
||||
detail=" | ".join(snapshot.texts) or snapshot.title or "无标题窗口",
|
||||
)
|
||||
@@ -0,0 +1,624 @@
|
||||
"""Confirmed, bounded handling for modal dialogs owned by a Verify job."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import time
|
||||
from typing import Protocol, Sequence
|
||||
|
||||
from .dialog_agent import ActionResult
|
||||
from .dialog_models import DialogPhase, WindowSnapshot, stable_fingerprint
|
||||
from .dialog_rules import DialogRule, decide
|
||||
|
||||
|
||||
class DialogObservationError(RuntimeError):
|
||||
def __init__(self, error_code: str, detail: str) -> None:
|
||||
self.error_code = str(error_code)
|
||||
self.detail = str(detail)
|
||||
super().__init__(self.detail)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DialogControl:
|
||||
handle: int
|
||||
control_id: int
|
||||
class_name: str
|
||||
text: str
|
||||
enabled: bool
|
||||
checked: bool = False
|
||||
selected: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DialogSnapshot:
|
||||
hwnd: int
|
||||
pid: int
|
||||
title: str
|
||||
controls: tuple[DialogControl, ...]
|
||||
|
||||
@property
|
||||
def texts(self) -> tuple[str, ...]:
|
||||
return tuple(control.text for control in self.controls if control.text.strip())
|
||||
|
||||
@property
|
||||
def signature(self) -> tuple[object, ...]:
|
||||
return (
|
||||
self.title,
|
||||
tuple((control.control_id, control.class_name, control.text,
|
||||
control.enabled, control.checked, control.selected)
|
||||
for control in self.controls),
|
||||
)
|
||||
|
||||
def as_log_record(self) -> dict[str, object]:
|
||||
return {
|
||||
"hwnd": self.hwnd,
|
||||
"pid": self.pid,
|
||||
"title": self.title,
|
||||
"controls": [
|
||||
{
|
||||
"handle": control.handle,
|
||||
"id": control.control_id,
|
||||
"class": control.class_name,
|
||||
"text": control.text,
|
||||
"enabled": control.enabled,
|
||||
"checked": control.checked,
|
||||
"selected": control.selected,
|
||||
}
|
||||
for control in self.controls
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DialogDecision:
|
||||
action: str = ""
|
||||
error_code: str = ""
|
||||
detail: str = ""
|
||||
observe_only: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DialogPollResult:
|
||||
activity: bool = False
|
||||
action_sent: bool = False
|
||||
resolved: bool = False
|
||||
error_code: str = ""
|
||||
detail: str = ""
|
||||
snapshot: DialogSnapshot | None = None
|
||||
accepted_controls: tuple[int, ...] = ()
|
||||
action: str = ""
|
||||
rule_id: str = ""
|
||||
channel: str = ""
|
||||
observed_snapshots: tuple[object, ...] = ()
|
||||
|
||||
|
||||
class DialogBackend(Protocol):
|
||||
def observe(self) -> Sequence[DialogSnapshot]: ...
|
||||
def perform(self, snapshot: DialogSnapshot, action: str) -> Sequence[int]: ...
|
||||
|
||||
|
||||
class AgentDialogBackend:
|
||||
"""Adapt the private-desktop JSONL client to the supervisor backend."""
|
||||
|
||||
def __init__(self, client) -> None:
|
||||
self.client = client
|
||||
|
||||
def observe(self, phase: DialogPhase):
|
||||
return self.client.observe(phase)
|
||||
|
||||
def perform(self, snapshot: WindowSnapshot, action: dict, phase: DialogPhase) -> ActionResult:
|
||||
return self.client.perform(
|
||||
hwnd=snapshot.hwnd,
|
||||
fingerprint=stable_fingerprint(snapshot),
|
||||
action=action,
|
||||
phase=phase,
|
||||
)
|
||||
|
||||
|
||||
class Win32DialogBackend:
|
||||
"""Observe and act on dialogs without moving focus, cursor, or desktop."""
|
||||
|
||||
def __init__(self, pids, *, desktop=None, win32gui=None, win32process=None,
|
||||
win32con=None) -> None:
|
||||
if win32gui is None:
|
||||
import win32gui as win32gui_module
|
||||
win32gui = win32gui_module
|
||||
if win32process is None:
|
||||
import win32process as win32process_module
|
||||
win32process = win32process_module
|
||||
if win32con is None:
|
||||
import win32con as win32con_module
|
||||
win32con = win32con_module
|
||||
self.pids = pids
|
||||
self.desktop = desktop
|
||||
self.win32gui = win32gui
|
||||
self.win32process = win32process
|
||||
self.win32con = win32con
|
||||
|
||||
def _allowed_pids(self) -> set[int]:
|
||||
values = self.pids() if callable(self.pids) else self.pids
|
||||
return {int(value) for value in (values or ()) if value is not None}
|
||||
|
||||
def _window_handles(self) -> tuple[int, ...]:
|
||||
if self.desktop is not None:
|
||||
try:
|
||||
return tuple(int(handle) for handle in self.desktop.EnumDesktopWindows())
|
||||
except Exception as error:
|
||||
# EnumDesktopWindows returns FALSE when a newly-created
|
||||
# private desktop has no windows yet. pywin32 exposes that
|
||||
# normal startup state as winerror 0 or, on some Windows
|
||||
# builds, stale winerror 2. Keep polling until the worker
|
||||
# creates its first window; genuine access/handle failures
|
||||
# remain structured errors below.
|
||||
error_code = getattr(error, 'winerror', None)
|
||||
if error_code is None:
|
||||
arguments = getattr(error, 'args', ())
|
||||
error_code = arguments[0] if arguments else None
|
||||
if error_code in (0, 2):
|
||||
return ()
|
||||
raise DialogObservationError(
|
||||
"WINDOW_ENUM_ERROR", f"EnumDesktopWindows 失败: {error}"
|
||||
) from error
|
||||
handles: list[int] = []
|
||||
|
||||
def collect(handle, _context):
|
||||
handles.append(int(handle))
|
||||
return True
|
||||
|
||||
try:
|
||||
self.win32gui.EnumWindows(collect, None)
|
||||
except Exception as error:
|
||||
raise DialogObservationError(
|
||||
"WINDOW_ENUM_ERROR", f"EnumWindows 失败: {error}"
|
||||
) from error
|
||||
return tuple(handles)
|
||||
|
||||
def _children(self, hwnd: int) -> tuple[int, ...]:
|
||||
children: list[int] = []
|
||||
|
||||
def collect(handle, _context):
|
||||
children.append(int(handle))
|
||||
return True
|
||||
|
||||
try:
|
||||
self.win32gui.EnumChildWindows(hwnd, collect, None)
|
||||
except Exception as error:
|
||||
raise DialogObservationError(
|
||||
"WINDOW_ENUM_ERROR", f"EnumChildWindows({hwnd}) 失败: {error}"
|
||||
) from error
|
||||
return tuple(children)
|
||||
|
||||
def _control(self, hwnd: int) -> DialogControl:
|
||||
gui = self.win32gui
|
||||
class_name = str(gui.GetClassName(hwnd) or "")
|
||||
checked = False
|
||||
selected = False
|
||||
try:
|
||||
if class_name.casefold() == "button":
|
||||
checked = bool(gui.SendMessage(hwnd, 0x00F0, 0, 0)) # BM_GETCHECK
|
||||
elif class_name.casefold() == "combobox":
|
||||
selected = int(gui.SendMessage(hwnd, 0x0147, 0, 0)) >= 0 # CB_GETCURSEL
|
||||
elif class_name.casefold() == "listbox":
|
||||
selected = int(gui.SendMessage(hwnd, 0x0188, 0, 0)) >= 0 # LB_GETCURSEL
|
||||
except Exception:
|
||||
pass
|
||||
return DialogControl(
|
||||
handle=int(hwnd),
|
||||
control_id=int(gui.GetDlgCtrlID(hwnd)),
|
||||
class_name=class_name,
|
||||
text=str(gui.GetWindowText(hwnd) or ""),
|
||||
enabled=bool(gui.IsWindowEnabled(hwnd)),
|
||||
checked=checked,
|
||||
selected=selected,
|
||||
)
|
||||
|
||||
def observe(self) -> tuple[DialogSnapshot, ...]:
|
||||
gui = self.win32gui
|
||||
allowed = self._allowed_pids()
|
||||
snapshots = []
|
||||
for hwnd in self._window_handles():
|
||||
try:
|
||||
if not gui.IsWindowVisible(hwnd) or gui.GetClassName(hwnd) != "#32770":
|
||||
continue
|
||||
pid = int(self.win32process.GetWindowThreadProcessId(hwnd)[1])
|
||||
# A newly-created private desktop is already an isolation
|
||||
# boundary and can contain helper-process dialogs. On the
|
||||
# input desktop, retain strict PID scoping.
|
||||
if self.desktop is None and pid not in allowed:
|
||||
continue
|
||||
controls = tuple(self._control(child) for child in self._children(hwnd))
|
||||
snapshots.append(DialogSnapshot(
|
||||
hwnd=int(hwnd), pid=pid, title=str(gui.GetWindowText(hwnd) or ""),
|
||||
controls=controls,
|
||||
))
|
||||
except DialogObservationError:
|
||||
raise
|
||||
except Exception:
|
||||
# A window can disappear between enumeration and inspection.
|
||||
continue
|
||||
return tuple(snapshots)
|
||||
|
||||
@staticmethod
|
||||
def _has_any(value: str, tokens: tuple[str, ...]) -> bool:
|
||||
lowered = value.casefold()
|
||||
return any(token in lowered for token in tokens)
|
||||
|
||||
def _buttons(self, snapshot: DialogSnapshot) -> tuple[DialogControl, ...]:
|
||||
return tuple(control for control in snapshot.controls
|
||||
if control.class_name.casefold() == "button" and control.enabled)
|
||||
|
||||
def _click(self, control: DialogControl) -> int:
|
||||
self.win32gui.PostMessage(control.handle, getattr(self.win32con, "BM_CLICK", 0x00F5), 0, 0)
|
||||
return control.control_id
|
||||
|
||||
def perform(self, snapshot: DialogSnapshot, action: str) -> tuple[int, ...]:
|
||||
buttons = self._buttons(snapshot)
|
||||
positive = ("yes", "ok", "continue", "retry", "restore", "open", "use", "load",
|
||||
"是", "确定", "继续", "重试", "恢复", "打开", "使用", "加载")
|
||||
negative = ("cancel", "no", "abort", "stop", "close", "exit",
|
||||
"否", "取消", "终止", "停止", "关闭", "退出")
|
||||
|
||||
if action == "restore_last_saved":
|
||||
marker = ("last user saved database", "最后一次用户保存", "最后保存", "用户保存")
|
||||
selection = next((button for button in buttons if self._has_any(button.text, marker)), None)
|
||||
accepted = []
|
||||
if selection is not None and not selection.checked:
|
||||
return (self._click(selection),)
|
||||
confirm = next((button for button in buttons
|
||||
if button.control_id == 1 or button.text.casefold() in ("ok", "确定")), None)
|
||||
if confirm is not None:
|
||||
accepted.append(self._click(confirm))
|
||||
return tuple(accepted)
|
||||
|
||||
if action == "accept_license":
|
||||
selector_button = next(
|
||||
(control for control in buttons
|
||||
if self._has_any(control.text, ("select the desired product license",
|
||||
"选择所需产品许可证"))),
|
||||
None,
|
||||
)
|
||||
selectors = tuple(
|
||||
control for control in snapshot.controls
|
||||
if (control.class_name.casefold() in {"combobox", "listbox"}
|
||||
or (control.class_name.casefold() == "button"
|
||||
and control.control_id not in {1, 2, 6, 7}))
|
||||
)
|
||||
if selector_button is not None:
|
||||
# EE7.9.5 exposes the product-license chooser as a Button
|
||||
# next to a custom GXWND list. Open it first; the selected
|
||||
# license is only observable after the chooser is expanded.
|
||||
return (self._click(selector_button),)
|
||||
if selectors and not any(control.selected or control.checked for control in selectors):
|
||||
return ()
|
||||
|
||||
if action == "decline_database_log":
|
||||
# Do not fall back to the affirmative button and open a log viewer.
|
||||
target = next((button for button in buttons if button.control_id == 7), None)
|
||||
return (self._click(target),) if target is not None else ()
|
||||
|
||||
preferred_ids = {
|
||||
"accept_license": (1,),
|
||||
"save_reusable_block": (6,),
|
||||
"confirm_open_lock": (6,),
|
||||
"dismiss_tip": (1, 2),
|
||||
"acknowledge_fatal": (1, 2),
|
||||
}.get(action, ())
|
||||
target = next((button for control_id in preferred_ids for button in buttons
|
||||
if button.control_id == control_id), None)
|
||||
if target is None:
|
||||
target = next((button for button in buttons
|
||||
if self._has_any(button.text, positive)
|
||||
and not self._has_any(button.text, negative)), None)
|
||||
if target is None and action in {"dismiss_tip", "acknowledge_fatal"}:
|
||||
target = next((button for button in buttons
|
||||
if not self._has_any(button.text, negative)), None)
|
||||
return (self._click(target),) if target is not None else ()
|
||||
|
||||
|
||||
@dataclass
|
||||
class _PendingDialog:
|
||||
signature: tuple[object, ...]
|
||||
action: str
|
||||
attempts: int = 0
|
||||
last_attempt: float = float("-inf")
|
||||
|
||||
|
||||
@dataclass
|
||||
class _PendingRuleAction:
|
||||
hwnd: int
|
||||
fingerprint: str
|
||||
rule_id: str
|
||||
action: str
|
||||
channels: tuple[str, ...]
|
||||
target: tuple[tuple[str, object], ...]
|
||||
postcondition: str
|
||||
signature: tuple[object, ...]
|
||||
attempts: int = 0
|
||||
last_attempt: float = float("-inf")
|
||||
|
||||
|
||||
_FATAL_MARKERS = (
|
||||
("error saving the reusable block", "SAVE_REUSABLE_BLOCK_FAILED"),
|
||||
("could not run server", "DESIGN_SERVER_FAILED"),
|
||||
("could not bring it alive", "DESIGN_SERVER_FAILED"),
|
||||
("database load is being terminated", "DATABASE_LOAD_FAILED"),
|
||||
("there were errors", "PROJECT_INTEGRATION_FAILED"),
|
||||
)
|
||||
|
||||
|
||||
def classify_dialog(snapshot: DialogSnapshot) -> DialogDecision:
|
||||
title = snapshot.title.casefold()
|
||||
joined = " ".join(snapshot.texts).casefold()
|
||||
combined = f"{title} {joined}"
|
||||
|
||||
if ("problem encountered while opening one of the database files" in combined
|
||||
and "loading of the job has failed" in combined):
|
||||
return DialogDecision(action="decline_database_log",
|
||||
error_code="MENTOR_DATABASE_LOAD_FAILED",
|
||||
detail=" | ".join(snapshot.texts) or snapshot.title)
|
||||
|
||||
for marker, error_code in _FATAL_MARKERS:
|
||||
if marker in combined:
|
||||
return DialogDecision(
|
||||
action="acknowledge_fatal",
|
||||
error_code=error_code,
|
||||
detail=" | ".join(snapshot.texts) or snapshot.title,
|
||||
)
|
||||
|
||||
if "your task is being" in joined and "elapsed time" in joined:
|
||||
return DialogDecision(observe_only=True)
|
||||
if ("database restoration" in title
|
||||
or ("restore database" in joined and "last user saved database" in joined)
|
||||
or "数据库恢复" in joined):
|
||||
return DialogDecision(action="restore_last_saved")
|
||||
if "select the desired product license" in joined:
|
||||
return DialogDecision(action="accept_license")
|
||||
if "do you want to save the reusable block cell" in joined:
|
||||
return DialogDecision(action="save_reusable_block")
|
||||
if ("continue to open the design with read/write access permission" in joined
|
||||
or "confirm that no other users have the design open" in joined):
|
||||
return DialogDecision(action="confirm_open_lock")
|
||||
if "tip of the day" in combined:
|
||||
return DialogDecision(action="dismiss_tip")
|
||||
|
||||
return DialogDecision(
|
||||
error_code="UNKNOWN_DIALOG",
|
||||
detail=" | ".join(snapshot.texts) or snapshot.title or "无标题弹窗",
|
||||
)
|
||||
|
||||
|
||||
class DialogSupervisor:
|
||||
"""Retry known actions and declare success only after state transition."""
|
||||
|
||||
def __init__(self, backend: DialogBackend, *, retry_seconds: float = 0.75,
|
||||
max_attempts: int = 3, clock=None,
|
||||
rules: Sequence[DialogRule] | None = None) -> None:
|
||||
self.backend = backend
|
||||
self.retry_seconds = max(0.0, float(retry_seconds))
|
||||
self.max_attempts = max(1, int(max_attempts))
|
||||
self._clock = clock or time.monotonic
|
||||
self._pending: dict[int, _PendingDialog] = {}
|
||||
self._observed: dict[int, tuple[object, ...]] = {}
|
||||
self.rules = tuple(rules) if rules is not None else None
|
||||
self._rule_pending: dict[tuple[str, str], _PendingRuleAction] = {}
|
||||
self._rule_observed: dict[str, tuple[object, ...]] = {}
|
||||
|
||||
@staticmethod
|
||||
def _candidate(snapshot: WindowSnapshot) -> bool:
|
||||
class_name = snapshot.window_class.casefold()
|
||||
return bool(
|
||||
snapshot.owner_hwnd
|
||||
or class_name in {"#32770", "gxwnd", "taskdialog"}
|
||||
or snapshot.process_role == "license"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _postcondition_met(pending: _PendingRuleAction,
|
||||
snapshot: WindowSnapshot | None,
|
||||
phase: DialogPhase) -> bool:
|
||||
if pending.postcondition == "window_gone":
|
||||
return snapshot is None
|
||||
if snapshot is None:
|
||||
return False
|
||||
if pending.postcondition == "signature_changed":
|
||||
return snapshot.signature != pending.signature
|
||||
if pending.postcondition == "control_selected":
|
||||
return any(control.selected or control.checked for control in snapshot.controls)
|
||||
if pending.postcondition == "control_enabled":
|
||||
return any(control.enabled for control in snapshot.controls)
|
||||
if pending.postcondition == "next_phase":
|
||||
return snapshot.phase != phase
|
||||
return snapshot.signature != pending.signature
|
||||
|
||||
def _poll_rules(self, phase: DialogPhase) -> DialogPollResult:
|
||||
try:
|
||||
all_snapshots = tuple(self.backend.observe(phase))
|
||||
except Exception as error:
|
||||
code = getattr(error, "error_code", "DIALOG_PROTOCOL_ERROR")
|
||||
detail = getattr(error, "detail", str(error))
|
||||
return DialogPollResult(error_code=code, detail=detail)
|
||||
snapshots = tuple(snapshot for snapshot in all_snapshots if self._candidate(snapshot))
|
||||
current_by_hwnd = {snapshot.hwnd: snapshot for snapshot in snapshots}
|
||||
resolved = False
|
||||
activity = False
|
||||
|
||||
for key, pending in tuple(self._rule_pending.items()):
|
||||
snapshot = current_by_hwnd.get(pending.hwnd)
|
||||
if self._postcondition_met(pending, snapshot, phase):
|
||||
del self._rule_pending[key]
|
||||
resolved = True
|
||||
activity = True
|
||||
|
||||
now = self._clock()
|
||||
for snapshot in snapshots:
|
||||
fingerprint = stable_fingerprint(snapshot)
|
||||
decision = decide(snapshot, self.rules or ())
|
||||
if (decision.error_code
|
||||
and decision.category not in {"FATAL_ACK", "OBSERVE_PROGRESS"}):
|
||||
return DialogPollResult(
|
||||
activity=True,
|
||||
resolved=resolved,
|
||||
error_code=decision.error_code,
|
||||
detail=decision.detail,
|
||||
snapshot=snapshot,
|
||||
rule_id=decision.rule_id,
|
||||
observed_snapshots=snapshots,
|
||||
)
|
||||
if decision.category == "OBSERVE_PROGRESS":
|
||||
previous = self._rule_observed.get(fingerprint)
|
||||
if previous != snapshot.signature:
|
||||
self._rule_observed[fingerprint] = snapshot.signature
|
||||
activity = True
|
||||
continue
|
||||
|
||||
key = (snapshot.hwnd, decision.rule_id)
|
||||
pending = self._rule_pending.get(key)
|
||||
if pending is None:
|
||||
pending = _PendingRuleAction(
|
||||
hwnd=snapshot.hwnd,
|
||||
fingerprint=fingerprint,
|
||||
rule_id=decision.rule_id,
|
||||
action=decision.action,
|
||||
channels=decision.channels,
|
||||
target=decision.target,
|
||||
postcondition=decision.postcondition,
|
||||
signature=snapshot.signature,
|
||||
)
|
||||
self._rule_pending[key] = pending
|
||||
activity = True
|
||||
if now - pending.last_attempt < self.retry_seconds:
|
||||
continue
|
||||
if pending.attempts >= self.max_attempts:
|
||||
return DialogPollResult(
|
||||
activity=activity,
|
||||
resolved=resolved,
|
||||
error_code="DIALOG_ACTION_STUCK",
|
||||
detail=(f"规则 {pending.rule_id} 已尝试 {pending.attempts} 次,"
|
||||
"动作后置条件仍未满足"),
|
||||
snapshot=snapshot,
|
||||
action=pending.action,
|
||||
rule_id=pending.rule_id,
|
||||
observed_snapshots=snapshots,
|
||||
)
|
||||
action_payload = {
|
||||
"action": pending.action,
|
||||
"channels": list(pending.channels),
|
||||
"target": dict(pending.target),
|
||||
"postcondition": pending.postcondition,
|
||||
"rule_id": pending.rule_id,
|
||||
}
|
||||
result = self.backend.perform(snapshot, action_payload, phase)
|
||||
pending.attempts += 1
|
||||
pending.last_attempt = now
|
||||
fatal_code = decision.error_code if decision.category == "FATAL_ACK" else ""
|
||||
error_code = fatal_code or result.error_code
|
||||
detail = decision.detail or result.detail
|
||||
return DialogPollResult(
|
||||
activity=True,
|
||||
action_sent=bool(result.accepted_controls),
|
||||
resolved=resolved,
|
||||
error_code=error_code,
|
||||
detail=detail,
|
||||
snapshot=snapshot,
|
||||
accepted_controls=result.accepted_controls,
|
||||
action=pending.action,
|
||||
rule_id=pending.rule_id,
|
||||
channel=result.channel,
|
||||
observed_snapshots=snapshots,
|
||||
)
|
||||
|
||||
active_fingerprints = {stable_fingerprint(snapshot) for snapshot in snapshots}
|
||||
for fingerprint in tuple(self._rule_observed):
|
||||
if fingerprint not in active_fingerprints:
|
||||
del self._rule_observed[fingerprint]
|
||||
activity = True
|
||||
resolved = True
|
||||
return DialogPollResult(activity=activity, resolved=resolved,
|
||||
observed_snapshots=snapshots)
|
||||
|
||||
def poll(self, phase: DialogPhase | None = None) -> DialogPollResult:
|
||||
if phase is not None:
|
||||
if self.rules is None:
|
||||
raise RuntimeError("phase-aware dialog supervision requires rules")
|
||||
return self._poll_rules(phase)
|
||||
try:
|
||||
snapshots = tuple(self.backend.observe())
|
||||
except DialogObservationError as error:
|
||||
return DialogPollResult(
|
||||
error_code=error.error_code,
|
||||
detail=error.detail,
|
||||
)
|
||||
current = {snapshot.hwnd: snapshot for snapshot in snapshots}
|
||||
resolved = False
|
||||
activity = False
|
||||
|
||||
for hwnd, pending in tuple(self._pending.items()):
|
||||
snapshot = current.get(hwnd)
|
||||
if snapshot is None or snapshot.signature != pending.signature:
|
||||
del self._pending[hwnd]
|
||||
resolved = True
|
||||
activity = True
|
||||
for hwnd in tuple(self._observed):
|
||||
if hwnd not in current:
|
||||
del self._observed[hwnd]
|
||||
resolved = True
|
||||
activity = True
|
||||
|
||||
now = self._clock()
|
||||
for snapshot in snapshots:
|
||||
decision = classify_dialog(snapshot)
|
||||
if decision.error_code:
|
||||
accepted: tuple[int, ...] = ()
|
||||
if decision.action:
|
||||
accepted = tuple(int(value) for value in self.backend.perform(snapshot, decision.action))
|
||||
return DialogPollResult(
|
||||
activity=True,
|
||||
action_sent=bool(accepted),
|
||||
resolved=resolved,
|
||||
error_code=decision.error_code,
|
||||
detail=decision.detail,
|
||||
snapshot=snapshot,
|
||||
accepted_controls=accepted,
|
||||
action=decision.action,
|
||||
)
|
||||
if decision.observe_only:
|
||||
previous = self._observed.get(snapshot.hwnd)
|
||||
if previous != snapshot.signature:
|
||||
self._observed[snapshot.hwnd] = snapshot.signature
|
||||
activity = True
|
||||
continue
|
||||
|
||||
if snapshot.hwnd in self._observed:
|
||||
del self._observed[snapshot.hwnd]
|
||||
activity = True
|
||||
|
||||
pending = self._pending.get(snapshot.hwnd)
|
||||
if pending is None:
|
||||
pending = _PendingDialog(snapshot.signature, decision.action)
|
||||
self._pending[snapshot.hwnd] = pending
|
||||
activity = True
|
||||
if now - pending.last_attempt < self.retry_seconds:
|
||||
continue
|
||||
if pending.attempts >= self.max_attempts:
|
||||
return DialogPollResult(
|
||||
activity=activity,
|
||||
resolved=resolved,
|
||||
error_code="DIALOG_STUCK",
|
||||
detail=(f"弹窗操作 {pending.action} 已尝试 {pending.attempts} 次仍未关闭: "
|
||||
f"{' | '.join(snapshot.texts) or snapshot.title}"),
|
||||
snapshot=snapshot,
|
||||
action=pending.action,
|
||||
)
|
||||
accepted = tuple(int(value) for value in self.backend.perform(snapshot, pending.action))
|
||||
pending.attempts += 1
|
||||
pending.last_attempt = now
|
||||
return DialogPollResult(
|
||||
activity=activity,
|
||||
action_sent=bool(accepted),
|
||||
resolved=resolved,
|
||||
snapshot=snapshot,
|
||||
accepted_controls=accepted,
|
||||
action=pending.action,
|
||||
)
|
||||
|
||||
return DialogPollResult(activity=activity, resolved=resolved)
|
||||
@@ -0,0 +1,121 @@
|
||||
"""State-driven Project Integration refresh; no UI or COM creation here."""
|
||||
import time
|
||||
|
||||
from .mentor_adapter import ActivityDeadline
|
||||
from .defaults import DEFAULT_TIMEOUT_SECONDS
|
||||
|
||||
|
||||
ACTIONS = (
|
||||
('ForwardAnnotation', 'ForwardAnnotate'),
|
||||
('SynchCES', 'SynchCES'),
|
||||
('LoadCES', 'LoadCES'),
|
||||
('BackAnnotation', 'BackAnnotate'),
|
||||
)
|
||||
|
||||
|
||||
class IntegrationError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def value(obj, name):
|
||||
result = getattr(obj, name)
|
||||
return result() if callable(result) else result
|
||||
|
||||
|
||||
def statuses(pi):
|
||||
return {name: int(value(pi, name + 'Status')) for name, _ in ACTIONS}
|
||||
|
||||
|
||||
def refresh_integration(pi, *, emit=lambda **event: None, settle_seconds=5, timeout_seconds=DEFAULT_TIMEOUT_SECONDS,
|
||||
error_reader=None, sleep=time.sleep, clock=None):
|
||||
clock = clock or time.monotonic
|
||||
|
||||
def check_error():
|
||||
if error_reader is None:
|
||||
return
|
||||
detail = error_reader()
|
||||
if detail:
|
||||
emit(stage='integration_error', detail=detail)
|
||||
raise IntegrationError(f'Project Integration error: {detail}')
|
||||
|
||||
deadline = ActivityDeadline(timeout_seconds, clock=clock) if timeout_seconds is not None else None
|
||||
in_flight = {}
|
||||
executed = set()
|
||||
action_history = []
|
||||
green_entry = None
|
||||
previous_state = None
|
||||
while True:
|
||||
check_error()
|
||||
state = statuses(pi)
|
||||
if state != previous_state:
|
||||
emit(stage='integration_status', statuses=state)
|
||||
if green_entry is None:
|
||||
green_entry = all(status == 2 for status in state.values())
|
||||
if previous_state is not None and state != previous_state and deadline is not None:
|
||||
deadline.touch()
|
||||
previous_state = state
|
||||
for name, status in state.items():
|
||||
# NoCES=3 is recorded as unsupported, never claimed green.
|
||||
if status not in (1, 2):
|
||||
raise IntegrationError(f'{name}: unsupported status {status}')
|
||||
for name in tuple(in_flight):
|
||||
if state[name] == 2:
|
||||
started, call_elapsed = in_flight.pop(name)
|
||||
emit(stage='integration_action_complete', action=dict(ACTIONS)[name], status=2,
|
||||
elapsed_seconds=round(clock() - started, 6),
|
||||
call_elapsed_seconds=round(call_elapsed, 6))
|
||||
# When all four lamps start green, mirror the manual refresh: one
|
||||
# ForwardAnnotate, then only repair statuses that actually become Required.
|
||||
# Non-green entry keeps the previously validated four-action route.
|
||||
refreshed = ('ForwardAnnotation' in executed if green_entry
|
||||
else len(executed) == len(ACTIONS))
|
||||
if refreshed and not in_flight and all(status == 2 for status in state.values()):
|
||||
emit(stage='integration_complete', statuses=state, actions=action_history,
|
||||
policy='green_first_only' if green_entry else 'required_full_sequence')
|
||||
return state
|
||||
if deadline is not None and deadline.expired():
|
||||
raise IntegrationError('Project Integration timeout')
|
||||
if in_flight:
|
||||
sleep(.2)
|
||||
continue
|
||||
action_started = False
|
||||
for name, method in ACTIONS:
|
||||
if state[name] == 2 and (name in executed or
|
||||
(green_entry and name != 'ForwardAnnotation')):
|
||||
continue
|
||||
allowed = bool(value(pi, 'Is' + name + 'Allowed'))
|
||||
# A green item still has to receive one Verify refresh attempt.
|
||||
# Mentor may report the capability as false for that item; this
|
||||
# flag is a gate only for a genuinely Required (status=1) item.
|
||||
if state[name] != 2 and not allowed:
|
||||
emit(stage='integration_action_unavailable', action=method,
|
||||
initial_status=state[name], reason='mentor_not_allowed')
|
||||
raise IntegrationError(f'{name}: required but not allowed')
|
||||
emit(stage='integration_action', action=method, initial_status=state[name],
|
||||
reason='required_verification' if name not in executed else 'resynchronize')
|
||||
started = clock()
|
||||
try:
|
||||
action_result = value(pi, method)
|
||||
except Exception as error:
|
||||
emit(stage='integration_error', action=method, detail=str(error),
|
||||
elapsed_seconds=round(clock() - started, 6))
|
||||
raise IntegrationError(f'{method}: {error}') from error
|
||||
if not action_result:
|
||||
raise IntegrationError(f'{method} returned false')
|
||||
in_flight[name] = (started, clock() - started)
|
||||
executed.add(name)
|
||||
action_history.append(method)
|
||||
action_started = True
|
||||
if deadline is not None:
|
||||
deadline.touch()
|
||||
until = clock() + settle_seconds
|
||||
previous = state
|
||||
while statuses(pi) == state and clock() < until:
|
||||
check_error()
|
||||
sleep(.2)
|
||||
if statuses(pi) != previous:
|
||||
if deadline is not None:
|
||||
deadline.touch()
|
||||
break # Every operation may change other statuses; always reread.
|
||||
if not action_started:
|
||||
sleep(.2)
|
||||
@@ -0,0 +1,299 @@
|
||||
"""Library Manager's native CBB Verify entry point.
|
||||
|
||||
The Verify action belongs to Library Manager, not to an independently started
|
||||
Expedition PCB process. This module runs inside the worker's private Windows
|
||||
desktop, resolves the exact LMC and CBB tree item, opens that item's native
|
||||
context menu, and invokes the unique Verify menu item through UI Automation.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import ctypes
|
||||
from pathlib import Path
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
|
||||
def same_path(first: str | Path, second: str | Path) -> bool:
|
||||
return os.path.normcase(os.path.abspath(str(first))) == os.path.normcase(os.path.abspath(str(second)))
|
||||
|
||||
|
||||
def _sdd_home_from_bin(value: str | Path | None) -> Path | None:
|
||||
if not value:
|
||||
return None
|
||||
candidate = Path(value)
|
||||
if candidate.is_file():
|
||||
candidate = candidate.parent
|
||||
for parent in (candidate, *candidate.parents):
|
||||
if parent.name.casefold() == "sdd_home":
|
||||
return parent
|
||||
return None
|
||||
|
||||
|
||||
def library_manager_path(mentor_bin: str | Path | None = None) -> Path:
|
||||
from .mentor_paths import discover_sdd_home
|
||||
|
||||
discovered = discover_sdd_home(mentor_bin)
|
||||
if discovered is not None:
|
||||
return discovered / "lm" / "win32" / "bin" / "LibraryManager.exe"
|
||||
root = _sdd_home_from_bin(mentor_bin)
|
||||
if root is None:
|
||||
configured = os.environ.get("SDD_HOME", r"D:\Mentor\7.9.5EE\SDD_HOME")
|
||||
root = Path(configured)
|
||||
return root / "lm" / "win32" / "bin" / "LibraryManager.exe"
|
||||
|
||||
|
||||
def _library_processes() -> list[tuple[int, str, str]]:
|
||||
import win32com.client
|
||||
|
||||
service = win32com.client.GetObject("winmgmts:")
|
||||
return [
|
||||
(int(process.ProcessId), str(process.ExecutablePath or ""), str(process.CommandLine or ""))
|
||||
for process in service.ExecQuery(
|
||||
"SELECT ProcessId, ExecutablePath, CommandLine "
|
||||
"FROM Win32_Process WHERE Name='LibraryManager.exe'"
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def _fresh_library_pids(before: set[int], current: set[int], launcher_pid: int) -> set[int]:
|
||||
"""Return only this invocation's LM processes, including its launcher."""
|
||||
return (set(current) - {int(pid) for pid in before}) | {int(launcher_pid)}
|
||||
|
||||
|
||||
def _rect_edges(rect) -> tuple[int, int, int, int]:
|
||||
"""Return rectangle edges from Win32 tuples or pywinauto RECT objects."""
|
||||
if all(hasattr(rect, name) for name in ("left", "top", "right", "bottom")):
|
||||
return tuple(int(getattr(rect, name)) for name in ("left", "top", "right", "bottom"))
|
||||
left, top, right, bottom = rect
|
||||
return int(left), int(top), int(right), int(bottom)
|
||||
|
||||
|
||||
def _menu_click_lparam(menu_rect, item_rect) -> int:
|
||||
"""Encode a popup-menu item center as client-relative mouse coordinates."""
|
||||
menu_left, menu_top, _menu_right, _menu_bottom = _rect_edges(menu_rect)
|
||||
item_left, item_top, item_right, item_bottom = _rect_edges(item_rect)
|
||||
x = max(0, ((item_left + item_right) // 2) - menu_left)
|
||||
y = max(0, ((item_top + item_bottom) // 2) - menu_top)
|
||||
return ((y & 0xFFFF) << 16) | (x & 0xFFFF)
|
||||
|
||||
|
||||
def _post_menu_item_click(menu_handle: int, item_rect) -> None:
|
||||
"""Activate a popup item with messages on the private desktop only."""
|
||||
import win32con
|
||||
import win32gui
|
||||
|
||||
popup_rect = win32gui.GetWindowRect(int(menu_handle))
|
||||
lparam = _menu_click_lparam(popup_rect, item_rect)
|
||||
win32gui.PostMessage(int(menu_handle), win32con.WM_MOUSEMOVE, 0, lparam)
|
||||
win32gui.PostMessage(int(menu_handle), win32con.WM_LBUTTONDOWN,
|
||||
win32con.MK_LBUTTON, lparam)
|
||||
win32gui.PostMessage(int(menu_handle), win32con.WM_LBUTTONUP, 0, lparam)
|
||||
|
||||
|
||||
def _post_tree_context_menu(tree_handle: int, lparam: int) -> None:
|
||||
import win32con
|
||||
import win32gui
|
||||
|
||||
# Library Manager resolves the hit item from its preceding mouse-move
|
||||
# message. Sending the complete private-window message sequence avoids
|
||||
# activating the user's input desktop.
|
||||
win32gui.PostMessage(tree_handle, win32con.WM_MOUSEMOVE, 0, lparam)
|
||||
win32gui.PostMessage(tree_handle, win32con.WM_RBUTTONDOWN, win32con.MK_RBUTTON, lparam)
|
||||
win32gui.PostMessage(tree_handle, win32con.WM_RBUTTONUP, 0, lparam)
|
||||
|
||||
|
||||
def _invoke_interactive_verify(target, item) -> None:
|
||||
"""Prepare the real input desktop before opening the native context menu.
|
||||
|
||||
EE7.9 resolves the context-menu owner from the focused Library Manager
|
||||
window and the physical cursor position. Selecting the tree item alone
|
||||
is not sufficient: UI Automation may report a successful right-click
|
||||
while the MFC command is never dispatched. Keep this sequence isolated
|
||||
to the explicit interactive compatibility path.
|
||||
"""
|
||||
target.set_focus()
|
||||
item.select()
|
||||
item.click_input(button='right')
|
||||
|
||||
|
||||
def _find_target_window(desktop: Any, library: Path, fresh_pids: set[int]):
|
||||
for window in desktop.windows():
|
||||
try:
|
||||
title = window.window_text()
|
||||
if not window.is_visible() or not title.startswith("Library Manager:"):
|
||||
continue
|
||||
if not same_path(title.split(":", 1)[1].strip(), library):
|
||||
continue
|
||||
if window.process_id() in fresh_pids:
|
||||
return window
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
@dataclass
|
||||
class LibraryVerifySession:
|
||||
target: Any
|
||||
process: subprocess.Popen
|
||||
tree_handle: int
|
||||
library: Path
|
||||
block_name: str
|
||||
|
||||
def close(self) -> None:
|
||||
try:
|
||||
self.target.close()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if self.process.poll() is None:
|
||||
self.process.terminate()
|
||||
self.process.wait(timeout=5)
|
||||
except Exception:
|
||||
try:
|
||||
self.process.kill()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def launch_library_verify(
|
||||
library: str | Path,
|
||||
block_name: str,
|
||||
emit,
|
||||
deadline: float,
|
||||
*,
|
||||
mentor_bin: str | Path | None = None,
|
||||
interactive_input: bool = False,
|
||||
) -> LibraryVerifySession:
|
||||
"""Invoke Verify from the exact Library Manager LMC context."""
|
||||
from pywinauto import Desktop
|
||||
from pywinauto.controls.common_controls import TreeViewWrapper
|
||||
from pywinauto import win32defines
|
||||
|
||||
library = Path(library)
|
||||
executable = library_manager_path(mentor_bin)
|
||||
if not executable.is_file():
|
||||
raise RuntimeError(f"找不到 Library Manager: {executable}")
|
||||
|
||||
before = {pid for pid, _, _ in _library_processes()}
|
||||
launch_kwargs = {}
|
||||
if not interactive_input:
|
||||
launch_kwargs['creationflags'] = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
||||
process = subprocess.Popen([str(executable), str(library)], **launch_kwargs)
|
||||
emit(
|
||||
stage="lm_started",
|
||||
lm_pid=int(process.pid),
|
||||
command=[str(executable), str(library)],
|
||||
library=str(library),
|
||||
block=block_name,
|
||||
)
|
||||
session = None
|
||||
try:
|
||||
# The worker already owns a private desktop. Enumerating this desktop
|
||||
# never changes the user's foreground window or cursor.
|
||||
desktop = Desktop(backend="win32")
|
||||
while time.monotonic() < deadline:
|
||||
current = {pid for pid, _, _ in _library_processes()}
|
||||
fresh = _fresh_library_pids(before, current, int(process.pid))
|
||||
target = _find_target_window(desktop, library, fresh)
|
||||
if target is not None:
|
||||
break
|
||||
time.sleep(0.2)
|
||||
else:
|
||||
raise RuntimeError("后台 Library Manager 窗口未就绪")
|
||||
|
||||
emit(
|
||||
stage="lm_ready",
|
||||
lm_pid=int(target.process_id()),
|
||||
library=str(library),
|
||||
block=block_name,
|
||||
)
|
||||
|
||||
trees = [window for window in target.descendants() if "TreeView" in window.class_name()]
|
||||
if len(trees) != 1:
|
||||
raise RuntimeError("后台 Library Manager 导航树不唯一")
|
||||
tree = TreeViewWrapper(trees[0].handle)
|
||||
root_name = library.name
|
||||
item = tree.get_item(
|
||||
["Central Libraries", root_name, "Reusable Blocks", "Logical-Physical", block_name],
|
||||
exact=True,
|
||||
)
|
||||
item.ensure_visible()
|
||||
tree.send_message(win32defines.TVM_SELECTITEM, win32defines.TVGN_CARET, item.elem)
|
||||
if not item.is_selected():
|
||||
raise RuntimeError(f"后台 CBB 选择校验失败: {block_name}")
|
||||
|
||||
ui_window = Desktop(backend="uia").window(handle=target.handle)
|
||||
matches = [
|
||||
entry for entry in ui_window.descendants(control_type="TreeItem")
|
||||
if entry.window_text() == block_name
|
||||
]
|
||||
if len(matches) != 1:
|
||||
raise RuntimeError(f"后台无法唯一定位 CBB: {block_name}")
|
||||
if interactive_input:
|
||||
# EE7.9's navigator determines the context-menu owner from the
|
||||
# physical cursor, ignoring the posted lParam. This branch is
|
||||
# explicit and inherits the caller's input desktop; the default
|
||||
# production path remains isolated and message-only.
|
||||
_invoke_interactive_verify(target, item)
|
||||
else:
|
||||
rect = matches[0].rectangle()
|
||||
lparam = ctypes.c_uint32(
|
||||
((int(rect.mid_point().y) & 0xFFFF) << 16) | (int(rect.mid_point().x) & 0xFFFF)
|
||||
).value
|
||||
_post_tree_context_menu(tree.handle, lparam)
|
||||
time.sleep(0.25)
|
||||
|
||||
menus = [menu for menu in Desktop(backend="uia").windows(control_type="Menu") if menu.is_visible()]
|
||||
actions = [
|
||||
(menu, entry)
|
||||
for menu in menus
|
||||
for entry in menu.descendants(control_type="MenuItem")
|
||||
if entry.window_text().replace("&", "") == "Verify"
|
||||
and entry.is_enabled()
|
||||
]
|
||||
if len(actions) != 1:
|
||||
raise RuntimeError(f"{block_name}: 后台 Verify 菜单不可用")
|
||||
menu, verify_action = actions[0]
|
||||
from .post_verify_diagnostics import invoke_with_evidence
|
||||
invoke_with_evidence(
|
||||
verify_action.invoke,
|
||||
lambda event: emit(**event),
|
||||
{
|
||||
'library': str(library), 'block': block_name,
|
||||
'lm_pid': target.process_id(),
|
||||
'menu_automation_id': str(verify_action.element_info.automation_id or ''),
|
||||
},
|
||||
)
|
||||
# Win10's UIA provider can acknowledge InvokePattern on the native
|
||||
# #32768 popup without dispatching the MFC command. The private
|
||||
# popup coordinate message is retained only as the final observed
|
||||
# fallback; menu closure is diagnostic evidence, not Verify success.
|
||||
menu_handle = int(getattr(getattr(menu, 'element_info', None), 'handle', 0) or
|
||||
getattr(menu, 'handle', 0) or 0)
|
||||
if menu_handle and not interactive_input:
|
||||
time.sleep(0.35)
|
||||
try:
|
||||
still_visible = bool(menu.is_visible())
|
||||
except Exception:
|
||||
still_visible = True
|
||||
if still_visible:
|
||||
_post_menu_item_click(menu_handle, verify_action.rectangle())
|
||||
emit(
|
||||
stage='verify_menu_fallback',
|
||||
lm_pid=target.process_id(),
|
||||
menu_hwnd=menu_handle,
|
||||
channel='private_popup_message',
|
||||
)
|
||||
session = LibraryVerifySession(target, process, int(tree.handle), library, block_name)
|
||||
return session
|
||||
except Exception:
|
||||
if session is None:
|
||||
try:
|
||||
process.terminate()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
@@ -0,0 +1,396 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
import logging
|
||||
import json
|
||||
from collections import Counter, defaultdict
|
||||
from .models import CbbRecord, LibraryReadResult
|
||||
from .network_path import absolute_preserving_drive
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
CACHE_SCHEMA_VERSION = 2
|
||||
|
||||
|
||||
def infer_image_status_map(tree_images, status_by_name, names):
|
||||
"""Derive the current machine's image-ID map from persisted observations."""
|
||||
observations = defaultdict(set)
|
||||
ready_counts = Counter()
|
||||
for name in tuple(names):
|
||||
image = tree_images.get(name)
|
||||
status = str(status_by_name.get(name, 'UNKNOWN') or 'UNKNOWN').upper()
|
||||
if image is not None and status in {'READY', 'PENDING'}:
|
||||
observations[image].add(status)
|
||||
if status == 'READY':
|
||||
ready_counts[image] += 1
|
||||
# A current Pending observation is stronger than a stale complete Cert
|
||||
# tree: an item can retain Cert artifacts after a user clicks Unverify.
|
||||
# Resolve mixed observations to Pending so the live icon cannot be hidden
|
||||
# by historical filesystem output.
|
||||
has_pending_anchor = any('PENDING' in statuses for statuses in observations.values())
|
||||
if has_pending_anchor:
|
||||
return {
|
||||
image: 'PENDING' if 'PENDING' in statuses else 'READY'
|
||||
for image, statuses in observations.items()
|
||||
if statuses
|
||||
}
|
||||
# When every persisted row says Ready, an item manually changed to
|
||||
# Unverify has no filesystem anchor. Keep only the modal Ready ID as the
|
||||
# positive anchor; an additional ID is handled as an unseen Pending ID.
|
||||
if not ready_counts:
|
||||
return {}
|
||||
modal_count = max(ready_counts.values())
|
||||
modal_ids = {image for image, count in ready_counts.items() if count == modal_count}
|
||||
return {image: 'READY' for image in modal_ids}
|
||||
|
||||
|
||||
def _read_image_status_cache(path, library=None):
|
||||
if path is None:
|
||||
return {}
|
||||
try:
|
||||
payload = json.loads(Path(path).read_text(encoding='utf-8'))
|
||||
if isinstance(payload, dict):
|
||||
if payload.get('schema_version') != CACHE_SCHEMA_VERSION:
|
||||
logger.info('image_status_cache_legacy_or_unknown_schema path=%s schema=%s',
|
||||
path, payload.get('schema_version'))
|
||||
return {}
|
||||
if library is not None:
|
||||
stored_library = str(payload.get('library', '') or '')
|
||||
current_library = str(absolute_preserving_drive(library))
|
||||
if stored_library and stored_library.casefold() != current_library.casefold():
|
||||
logger.info('image_status_cache_library_mismatch path=%s stored=%s current=%s',
|
||||
path, stored_library, library)
|
||||
return {}
|
||||
raw = payload.get('image_status_map', {}) if isinstance(payload, dict) else {}
|
||||
return {int(image): str(status).upper() for image, status in raw.items()
|
||||
if str(status).upper() in {'READY', 'PENDING'}}
|
||||
except (OSError, ValueError, TypeError):
|
||||
return {}
|
||||
|
||||
|
||||
def _write_image_status_cache(path, image_status_map, library=None):
|
||||
if path is None or not image_status_map:
|
||||
return
|
||||
try:
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps({
|
||||
'schema_version': CACHE_SCHEMA_VERSION,
|
||||
'library': str(absolute_preserving_drive(library)) if library is not None else '',
|
||||
'image_status_map': {str(image): status for image, status in image_status_map.items()},
|
||||
}, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
except OSError as error:
|
||||
logger.warning('image_status_cache_write_failed path=%s error=%s', path, error)
|
||||
|
||||
|
||||
def infer_tree_statuses(tree_images, filesystem_statuses, names, *, image_status_map=None):
|
||||
"""Calibrate icon indices from independent persisted evidence.
|
||||
|
||||
``iImage`` is a resource-list position, not a stable Mentor API. An
|
||||
index is usable only when all CBBs with that index have the same known
|
||||
Cert-derived status. Ambiguous or unanchored indices remain UNKNOWN.
|
||||
"""
|
||||
calibrated = (dict(image_status_map) if image_status_map is not None
|
||||
else infer_image_status_map(tree_images, filesystem_statuses, names))
|
||||
ready_ids = {image for image, status in calibrated.items() if status == 'READY'}
|
||||
return {
|
||||
name: calibrated.get(
|
||||
tree_images.get(name),
|
||||
'PENDING' if tree_images.get(name) is not None and ready_ids else 'UNKNOWN',
|
||||
)
|
||||
for name in tuple(names)
|
||||
}
|
||||
|
||||
|
||||
def reconcile_statuses(tree_statuses, filesystem_statuses, names):
|
||||
"""Reconcile live icon evidence with persisted Cert/Work evidence.
|
||||
|
||||
Complete persisted evidence is sufficient when the tree ID cannot be read
|
||||
(for example when LM is already busy). Once an ID has been calibrated from
|
||||
the current library, the live tree status wins because Cert artifacts can
|
||||
remain after a user clicks Unverify.
|
||||
"""
|
||||
result = {}
|
||||
for name in tuple(names):
|
||||
tree = str(tree_statuses.get(name, 'UNKNOWN') or 'UNKNOWN').upper()
|
||||
filesystem = str(filesystem_statuses.get(name, 'UNKNOWN') or 'UNKNOWN').upper()
|
||||
if tree in {'READY', 'PENDING'}:
|
||||
result[name] = tree
|
||||
elif filesystem in {'READY', 'PENDING'}:
|
||||
result[name] = filesystem
|
||||
else:
|
||||
result[name] = 'UNKNOWN'
|
||||
return result
|
||||
|
||||
def _item(collection, index):
|
||||
item = getattr(collection, 'Item', None)
|
||||
if callable(item): return item(index)
|
||||
try: return collection(index)
|
||||
except TypeError: return getattr(collection, str(index))
|
||||
|
||||
|
||||
def _value(obj, name, default=None):
|
||||
value = getattr(obj, name, default)
|
||||
return value() if callable(value) else value
|
||||
|
||||
|
||||
def filesystem_evidence_map(library: Path, names):
|
||||
"""Collect independent persisted dimensions for each CBB.
|
||||
|
||||
The result deliberately exposes each Work/Cert artifact instead of
|
||||
collapsing the decision into one file check. A complete set of six
|
||||
artifacts is the persisted ``READY`` observation; an otherwise valid Work
|
||||
project with an incomplete Cert set is ``PENDING``. An imported block with
|
||||
no usable Work project is also ``PENDING`` so it can anchor the current
|
||||
machine's unverified icon ID; PCB preflight may still skip it later.
|
||||
"""
|
||||
library = Path(library)
|
||||
root = library.parent / 'ReusableBlocksLP'
|
||||
result = {}
|
||||
for name in tuple(names):
|
||||
evidence = {
|
||||
'status': 'UNKNOWN',
|
||||
'project_count': 0,
|
||||
'work_project': False,
|
||||
'work_pcb': False,
|
||||
'work_layout': False,
|
||||
'cert_project': False,
|
||||
'cert_pcb': False,
|
||||
'cert_layout': False,
|
||||
}
|
||||
block = root / str(name)
|
||||
work = block / 'Work'
|
||||
projects = list(work.glob('*.prj')) if work.is_dir() else []
|
||||
evidence['project_count'] = len(projects)
|
||||
if len(projects) != 1:
|
||||
evidence['status'] = 'PENDING'
|
||||
result[name] = evidence
|
||||
continue
|
||||
project = projects[0]
|
||||
evidence['work_project'] = project.is_file()
|
||||
try:
|
||||
content = project.read_text(encoding='utf-8', errors='replace')
|
||||
match = re.search(r'^KEY PCBDesignPath "([^"]+)"', content, re.M)
|
||||
pcb = absolute_preserving_drive(project.parent / match.group(1)) if match else None
|
||||
if pcb is None or not pcb.is_relative_to(absolute_preserving_drive(work)):
|
||||
evidence['status'] = 'PENDING'
|
||||
result[name] = evidence
|
||||
continue
|
||||
cert = block / 'Cert'
|
||||
cert_project = cert / project.name
|
||||
cert_pcb = cert / pcb.relative_to(work)
|
||||
cert_layout = cert_pcb.parent / 'Layout' / 'LayoutDB.lyt'
|
||||
work_layout = pcb.parent / 'Layout' / 'LayoutDB.lyt'
|
||||
paths = {
|
||||
'work_project': project,
|
||||
'work_pcb': pcb,
|
||||
'work_layout': work_layout,
|
||||
'cert_project': cert_project,
|
||||
'cert_pcb': cert_pcb,
|
||||
'cert_layout': cert_layout,
|
||||
}
|
||||
for key, path in paths.items():
|
||||
evidence[key] = path.is_file()
|
||||
work_valid = all(evidence[key] for key in ('work_project', 'work_pcb', 'work_layout'))
|
||||
cert_valid = all(evidence[key] for key in ('cert_project', 'cert_pcb', 'cert_layout'))
|
||||
evidence['status'] = 'READY' if work_valid and cert_valid else 'PENDING'
|
||||
result[name] = evidence
|
||||
except (OSError, ValueError):
|
||||
result[name] = evidence
|
||||
return result
|
||||
|
||||
|
||||
def filesystem_status_map(library: Path, names):
|
||||
"""Return only the persisted status derived from all six artifacts."""
|
||||
return {name: details['status'] for name, details in filesystem_evidence_map(library, names).items()}
|
||||
|
||||
def read_library_fast(path: Path, *, status_reader=None):
|
||||
"""List CBBs from ReusableBlocksLP without touching COM or the .lmc.
|
||||
|
||||
Useful when Library Manager is unavailable or already running: the folder
|
||||
is the same source the LM tree shows, and an optional status_reader can
|
||||
supply each item's flag without a full COM session.
|
||||
"""
|
||||
try:
|
||||
path = Path(path)
|
||||
if not path.is_file():
|
||||
return LibraryReadResult((), f'中心库不存在: {path}')
|
||||
folder = path.parent/'ReusableBlocksLP'
|
||||
if not folder.is_dir():
|
||||
return LibraryReadResult((), f'缺少 ReusableBlocksLP 目录: {folder}')
|
||||
entries = [entry for entry in folder.iterdir() if entry.is_dir()]
|
||||
names = tuple(sorted((entry.name for entry in entries), key=str.casefold))
|
||||
statuses = {}
|
||||
if status_reader is not None and names:
|
||||
try:
|
||||
statuses = dict(status_reader(path, names))
|
||||
except TypeError:
|
||||
for name in names:
|
||||
try:
|
||||
statuses[name] = status_reader(name)
|
||||
except Exception:
|
||||
statuses[name] = 'UNKNOWN'
|
||||
except Exception as error:
|
||||
# Do not turn a failed authoritative probe into a silent
|
||||
# UNKNOWN list. UNKNOWN is calibration-only; a bridge or
|
||||
# reader failure must remain visible and must not look like a
|
||||
# valid scan that happened to find no statuses.
|
||||
logger.warning('library_status_reader_failed path=%s error=%s', path, error)
|
||||
statuses = {name: 'UNAVAILABLE' for name in names}
|
||||
records = []
|
||||
for entry in entries:
|
||||
status = str(statuses.get(entry.name, 'UNKNOWN') or 'UNKNOWN')
|
||||
if status not in {'READY', 'PENDING', 'UNKNOWN', 'UNAVAILABLE', 'ERROR', 'TIMEOUT'}:
|
||||
status = 'UNKNOWN'
|
||||
records.append(CbbRecord(entry.name, 'Reusable Blocks', status=status))
|
||||
return LibraryReadResult(tuple(sorted(records, key=lambda item: item.name)))
|
||||
except Exception as error:
|
||||
return LibraryReadResult((), str(error))
|
||||
|
||||
|
||||
def scan_open_library_status(library: Path, names, *, tree_image_reader=None,
|
||||
mapping_store=None):
|
||||
"""Read verification icons from an already-open LM, without launching it."""
|
||||
names = tuple(names)
|
||||
persisted_evidence = filesystem_evidence_map(library, names)
|
||||
fallback = {name: details['status'] for name, details in persisted_evidence.items()}
|
||||
|
||||
def finish(tree_images):
|
||||
tree_images = dict(tree_images or {})
|
||||
current_map = infer_image_status_map(tree_images, fallback, names)
|
||||
cached_map = _read_image_status_cache(mapping_store, library)
|
||||
image_status_map = dict(cached_map)
|
||||
cache_actions = {}
|
||||
has_cached_ready = any(status == 'READY' for status in cached_map.values())
|
||||
for image, status_value in current_map.items():
|
||||
# The native image index is the machine-local status key. Once an
|
||||
# index has been calibrated, a transient filesystem snapshot must
|
||||
# not rewrite it: Cert/Work files can lag behind the TreeView
|
||||
# after Verify. New indices are still learned from this scan, so
|
||||
# an Unverify transition remains visible as a new Pending index.
|
||||
if image in cached_map:
|
||||
image_status_map[image] = cached_map[image]
|
||||
cache_actions[image] = 'cached_image_id_authoritative'
|
||||
elif has_cached_ready and status_value == 'READY':
|
||||
# With an existing Ready anchor, an unseen icon cannot be
|
||||
# promoted from stale Cert files alone. Keep it out of the
|
||||
# map so infer_tree_statuses classifies it as Pending.
|
||||
cache_actions[image] = 'unseen_tree_id_pending'
|
||||
else:
|
||||
image_status_map[image] = status_value
|
||||
cache_actions[image] = 'current_evidence_calibrated'
|
||||
if not image_status_map:
|
||||
image_status_map = current_map
|
||||
_write_image_status_cache(mapping_store, image_status_map, library)
|
||||
tree_statuses = infer_tree_statuses(tree_images, fallback, names,
|
||||
image_status_map=image_status_map)
|
||||
status = reconcile_statuses(tree_statuses, fallback, names)
|
||||
uncalibrated = [name for name in names if status.get(name, 'UNKNOWN') == 'UNKNOWN']
|
||||
# The UI must never use UNKNOWN as a skip signal. Queue it as Pending
|
||||
# so it receives the real Verify flow instead of being silently omitted.
|
||||
effective = {name: ('PENDING' if value == 'UNKNOWN' else value)
|
||||
for name, value in status.items()}
|
||||
logger.info(
|
||||
'library_status_sources names=%s image_histogram=%s current_image_map=%s cached_image_map=%s image_status_map=%s cache_actions=%s filesystem=%s calibrated_tree=%s final=%s uncalibrated_sample=%s conflicts=%s ready_anchor_ids=%s unseen_tree_ids=%s',
|
||||
len(names), dict(Counter(str(value) for value in tree_images.values() if value is not None)),
|
||||
dict(current_map), dict(cached_map),
|
||||
dict(image_status_map),
|
||||
dict(cache_actions),
|
||||
dict(Counter(fallback.get(name, 'UNKNOWN') for name in names)),
|
||||
dict(Counter(tree_statuses.get(name, 'UNKNOWN') for name in names)),
|
||||
dict(Counter(effective.get(name, 'PENDING') for name in names)),
|
||||
uncalibrated[:20],
|
||||
[name for name in names if tree_statuses.get(name) in {'READY', 'PENDING'}
|
||||
and fallback.get(name) in {'READY', 'PENDING'}
|
||||
and tree_statuses.get(name) != fallback.get(name)][:20],
|
||||
sorted(image for image, value in image_status_map.items() if value == 'READY'),
|
||||
sorted(image for image in tree_images.values()
|
||||
if image is not None and image not in image_status_map),
|
||||
)
|
||||
for name in names:
|
||||
image_id = tree_images.get(name)
|
||||
persisted = fallback.get(name, 'UNKNOWN')
|
||||
tree = tree_statuses.get(name, 'UNKNOWN')
|
||||
final = effective.get(name, 'PENDING')
|
||||
if image_id is not None and image_id not in image_status_map and tree == 'PENDING':
|
||||
reason = ('unseen_tree_id_vs_cached_ready_anchor' if cached_map
|
||||
else 'unseen_tree_id_vs_ready_anchor')
|
||||
elif persisted in {'READY', 'PENDING'} and tree in {'READY', 'PENDING'}:
|
||||
reason = 'tree_id_and_persisted_match' if persisted == tree else 'tree_id_conflicts_persisted'
|
||||
elif persisted in {'READY', 'PENDING'}:
|
||||
reason = 'persisted_only'
|
||||
elif tree in {'READY', 'PENDING'}:
|
||||
reason = 'tree_id_calibrated'
|
||||
else:
|
||||
reason = 'insufficient_evidence'
|
||||
logger.info(
|
||||
'library_status_item name=%s image_id=%s filesystem=%s tree=%s final=%s evidence=%s dimensions=%s',
|
||||
name, image_id, persisted, tree, final, reason, persisted_evidence.get(name, {}),
|
||||
)
|
||||
return effective
|
||||
|
||||
try:
|
||||
from pywinauto import Desktop
|
||||
from pywinauto.controls.common_controls import TreeViewWrapper
|
||||
from cbb_refresh_verify.mentor_adapter import _tree_image, same_path
|
||||
target = None
|
||||
for window in Desktop(backend='win32').windows():
|
||||
title = window.window_text()
|
||||
if title.startswith('Library Manager:') and same_path(title.split(':', 1)[1].strip(), library):
|
||||
target = window
|
||||
break
|
||||
if target is None:
|
||||
if tree_image_reader is None:
|
||||
from cbb_refresh_verify.mentor_adapter import read_library_tree_image_map
|
||||
tree_image_reader = read_library_tree_image_map
|
||||
return finish(tree_image_reader(library, names))
|
||||
trees = [w for w in target.descendants() if 'TreeView' in w.class_name()]
|
||||
if len(trees) != 1:
|
||||
return finish({})
|
||||
tree = TreeViewWrapper(trees[0].handle)
|
||||
root_name = Path(library).name
|
||||
images = {}
|
||||
missing = []
|
||||
for name in names:
|
||||
try:
|
||||
item = tree.get_item(['Central Libraries', root_name, 'Reusable Blocks', 'Logical-Physical', name], exact=True)
|
||||
from cbb_refresh_verify.mentor_adapter import _tree_image_details
|
||||
details = _tree_image_details(item, tree)
|
||||
images[name] = details['image_id']
|
||||
logger.info('library_tree_image_item name=%s image_id=%s selected_image_id=%s state_image_id=%s image_color=%s selected_image_color=%s state_image_color=%s',
|
||||
name, details['image_id'], details['selected_image_id'],
|
||||
details['state_image_id'], details['image_color'],
|
||||
details['selected_image_color'], details['state_image_color'])
|
||||
except Exception:
|
||||
images[name] = None
|
||||
missing.append(name)
|
||||
logger.info('library_tree_image_probe requested=%s read=%s missing=%s',
|
||||
len(names), len(names) - len(missing), missing[:20])
|
||||
return finish(images)
|
||||
except Exception as error:
|
||||
logger.warning('library_status_probe_failed path=%s error=%s', library, error)
|
||||
return finish({})
|
||||
|
||||
|
||||
def read_library(path: Path, *, dispatch=None):
|
||||
try:
|
||||
if not Path(path).exists() and dispatch is None:
|
||||
return LibraryReadResult((), f'中心库不存在: {path}')
|
||||
if dispatch is None:
|
||||
import win32com.client
|
||||
dispatch = win32com.client.Dispatch
|
||||
app=dispatch('LibraryManager.Application')
|
||||
lib=app.OpenLibrary(str(path))
|
||||
out=[]
|
||||
# LibraryManager exposes Partitions as an indexed method (not a COM collection).
|
||||
parts = lib.Partitions(7)
|
||||
count = int(_value(parts, 'Count', 0) or 0)
|
||||
for i in range(1, count + 1):
|
||||
partition = _item(parts, i)
|
||||
for j in range(1, int(_value(partition, 'Count', 0) or 0) + 1):
|
||||
x=_item(partition, j)
|
||||
out.append(CbbRecord(str(_value(x, 'Name', x)), str(_value(x, 'PartitionName', 'Reusable Blocks'))))
|
||||
if not out:
|
||||
folder = Path(path).parent / 'ReusableBlocksLP'
|
||||
if folder.is_dir(): out.extend(CbbRecord(x.name, 'Reusable Blocks') for x in folder.iterdir() if x.is_dir())
|
||||
return LibraryReadResult(tuple(sorted(set(out), key=lambda x:x.name)))
|
||||
except Exception as error:
|
||||
return LibraryReadResult((), str(error))
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,183 @@
|
||||
"""Bounded discovery of a Mentor EE installation.
|
||||
|
||||
Mentor is commonly installed on a non-system drive and the product name and
|
||||
version directory vary between machines. This module only inspects explicit
|
||||
configuration and a small set of conventional directories; it never walks an
|
||||
entire drive.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from functools import lru_cache
|
||||
import ctypes
|
||||
import os
|
||||
from typing import Iterable
|
||||
|
||||
|
||||
_KNOWN_RELATIVE_BINARIES = (
|
||||
Path('lm/win32/bin/LibraryManager.exe'),
|
||||
Path('lm/win32/bin/ReuseBlockImporter.exe'),
|
||||
Path('common/win32/bin/ExpeditionPCB.exe'),
|
||||
Path('wg/win32/bin/ExpeditionPCB.exe'),
|
||||
)
|
||||
|
||||
|
||||
def _sdd_home_from_value(value: str | Path | None) -> Path | None:
|
||||
if not value:
|
||||
return None
|
||||
candidate = Path(value)
|
||||
if candidate.is_file():
|
||||
candidate = candidate.parent
|
||||
for parent in (candidate, *candidate.parents):
|
||||
if parent.name.casefold() == 'sdd_home':
|
||||
return parent
|
||||
return None
|
||||
|
||||
|
||||
def _configured_values(explicit: str | Path | None, environ: dict[str, str]) -> Iterable[Path]:
|
||||
if explicit:
|
||||
value = _sdd_home_from_value(explicit)
|
||||
if value is not None:
|
||||
yield value
|
||||
for name in ('SDD_HOME', 'SDD_LM_BIN', 'CBB_MENTOR_BIN'):
|
||||
value = _sdd_home_from_value(environ.get(name))
|
||||
if value is not None:
|
||||
yield value
|
||||
|
||||
|
||||
def _search_roots(environ: dict[str, str], roots: Iterable[str | Path] | None) -> tuple[Path, ...]:
|
||||
if roots is not None:
|
||||
return tuple(Path(root) for root in roots)
|
||||
configured = tuple(
|
||||
Path(value) for value in environ.get('CBB_MENTOR_SEARCH_ROOTS', '').split(';')
|
||||
if value.strip()
|
||||
)
|
||||
if configured:
|
||||
return configured
|
||||
roots = []
|
||||
# Avoid probing disconnected mapped drives. GetDriveTypeW keeps the
|
||||
# automatic scan local; network installations remain supported through an
|
||||
# explicit SDD_HOME/SDD_LM_BIN or CBB_MENTOR_SEARCH_ROOTS.
|
||||
if os.name == 'nt':
|
||||
try:
|
||||
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
|
||||
mask = int(kernel32.GetLogicalDrives())
|
||||
get_drive_type = kernel32.GetDriveTypeW
|
||||
get_drive_type.argtypes = [ctypes.c_wchar_p]
|
||||
get_drive_type.restype = ctypes.c_uint
|
||||
for index in range(26):
|
||||
if not (mask & (1 << index)):
|
||||
continue
|
||||
root = f'{chr(ord("A") + index)}:\\'
|
||||
# DRIVE_REMOVABLE=2, DRIVE_FIXED=3
|
||||
if int(get_drive_type(root)) in (2, 3):
|
||||
roots.append(Path(root))
|
||||
except (AttributeError, OSError):
|
||||
pass
|
||||
if not roots:
|
||||
anchor = Path.cwd().anchor
|
||||
roots = [Path(anchor)] if anchor else []
|
||||
return tuple(roots)
|
||||
|
||||
|
||||
def _candidate_homes(roots: Iterable[Path]) -> Iterable[Path]:
|
||||
seen: set[str] = set()
|
||||
for root in roots:
|
||||
candidates = [root]
|
||||
if root.name.casefold() != 'sdd_home':
|
||||
candidates.extend((
|
||||
root / 'SDD_HOME',
|
||||
root / 'Mentor' / 'SDD_HOME',
|
||||
root / 'MentorGraphics' / 'SDD_HOME',
|
||||
root / 'Program Files' / 'Mentor Graphics' / 'SDD_HOME',
|
||||
root / 'Program Files (x86)' / 'Mentor Graphics' / 'SDD_HOME',
|
||||
))
|
||||
for parent_name in ('Mentor', 'MentorGraphics', 'Mentor Graphics'):
|
||||
for version_root in (root / parent_name, root / 'Program Files' / parent_name,
|
||||
root / 'Program Files (x86)' / parent_name):
|
||||
try:
|
||||
candidates.extend(version_root.glob('*/SDD_HOME'))
|
||||
except OSError:
|
||||
continue
|
||||
for candidate in candidates:
|
||||
try:
|
||||
key = os.path.normcase(str(candidate))
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
yield candidate
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
|
||||
|
||||
def _has_known_binary(home: Path) -> bool:
|
||||
try:
|
||||
return any((home / relative).is_file() for relative in _KNOWN_RELATIVE_BINARIES)
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def discover_sdd_home(
|
||||
explicit: str | Path | None = None,
|
||||
*,
|
||||
environ: dict[str, str] | None = None,
|
||||
search_roots: Iterable[str | Path] | None = None,
|
||||
) -> Path | None:
|
||||
"""Return the best matching SDD_HOME, or ``None`` if none is installed.
|
||||
|
||||
Explicit values and environment variables win. Auto-discovery then
|
||||
checks bounded conventional Mentor layouts. A candidate is accepted only
|
||||
when at least one known Mentor executable exists below it.
|
||||
"""
|
||||
environ = dict(os.environ if environ is None else environ)
|
||||
roots = tuple(str(root) for root in _search_roots(environ, search_roots))
|
||||
return _discover_sdd_home_cached(
|
||||
str(explicit or ''),
|
||||
environ.get('SDD_HOME', ''),
|
||||
environ.get('SDD_LM_BIN', ''),
|
||||
environ.get('CBB_MENTOR_BIN', ''),
|
||||
roots,
|
||||
)
|
||||
|
||||
|
||||
@lru_cache(maxsize=64)
|
||||
def _discover_sdd_home_cached(
|
||||
explicit: str,
|
||||
sdd_home: str,
|
||||
lm_bin: str,
|
||||
mentor_bin: str,
|
||||
roots: tuple[str, ...],
|
||||
) -> Path | None:
|
||||
environ = {
|
||||
'SDD_HOME': sdd_home,
|
||||
'SDD_LM_BIN': lm_bin,
|
||||
'CBB_MENTOR_BIN': mentor_bin,
|
||||
}
|
||||
ordered: list[Path] = list(_configured_values(explicit, environ))
|
||||
ordered.extend(_candidate_homes(Path(root) for root in roots))
|
||||
seen: set[str] = set()
|
||||
for home in ordered:
|
||||
try:
|
||||
key = os.path.normcase(str(home))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
if _has_known_binary(home):
|
||||
return home
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def describe_installation(home: Path | None) -> dict[str, str | bool]:
|
||||
"""Return stable, non-sensitive discovery evidence for runtime logs."""
|
||||
if home is None:
|
||||
return {'found': False, 'sdd_home': ''}
|
||||
return {
|
||||
'found': True,
|
||||
'sdd_home': str(home),
|
||||
'library_manager': str(home / 'lm/win32/bin/LibraryManager.exe'),
|
||||
'reuse_block_importer': str(home / 'lm/win32/bin/ReuseBlockImporter.exe'),
|
||||
'expedition_common': str(home / 'common/win32/bin/ExpeditionPCB.exe'),
|
||||
'expedition_wg': str(home / 'wg/win32/bin/ExpeditionPCB.exe'),
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CbbRecord:
|
||||
name: str
|
||||
partition_name: str
|
||||
logical_type: str = "LP"
|
||||
status: str = "UNKNOWN"
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LibraryReadResult:
|
||||
records: tuple[CbbRecord, ...]
|
||||
error: str | None = None
|
||||
@@ -0,0 +1,246 @@
|
||||
"""Bounded UNC-to-drive leases for Mentor tools that require drive paths."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
import ntpath
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
|
||||
|
||||
class NetworkPathError(RuntimeError):
|
||||
"""A network library could not be exposed through a stable Mentor path."""
|
||||
|
||||
|
||||
class WNetBackend(Protocol):
|
||||
def mappings(self) -> dict[str, str]: ...
|
||||
def used_drives(self) -> set[str]: ...
|
||||
def add_mapping(self, drive: str, remote: str) -> None: ...
|
||||
def cancel_mapping(self, drive: str) -> None: ...
|
||||
|
||||
|
||||
class _NETRESOURCEW(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("dwScope", wintypes.DWORD),
|
||||
("dwType", wintypes.DWORD),
|
||||
("dwDisplayType", wintypes.DWORD),
|
||||
("dwUsage", wintypes.DWORD),
|
||||
("lpLocalName", wintypes.LPWSTR),
|
||||
("lpRemoteName", wintypes.LPWSTR),
|
||||
("lpComment", wintypes.LPWSTR),
|
||||
("lpProvider", wintypes.LPWSTR),
|
||||
]
|
||||
|
||||
|
||||
class WindowsWNetBackend:
|
||||
"""Small ctypes wrapper that uses only the current Windows credentials."""
|
||||
|
||||
ERROR_NOT_CONNECTED = 2250
|
||||
RESOURCETYPE_DISK = 1
|
||||
CONNECT_TEMPORARY = 4
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._mpr = ctypes.WinDLL("mpr", use_last_error=True)
|
||||
self._kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
|
||||
def mappings(self) -> dict[str, str]:
|
||||
result: dict[str, str] = {}
|
||||
for code in range(ord("D"), ord("Z") + 1):
|
||||
drive = f"{chr(code)}:"
|
||||
size = wintypes.DWORD(32768)
|
||||
buffer = ctypes.create_unicode_buffer(size.value)
|
||||
error = self._mpr.WNetGetConnectionW(drive, buffer, ctypes.byref(size))
|
||||
if error == 0:
|
||||
result[drive] = buffer.value
|
||||
elif error != self.ERROR_NOT_CONNECTED:
|
||||
raise OSError(error, f"WNetGetConnectionW({drive})")
|
||||
return result
|
||||
|
||||
def used_drives(self) -> set[str]:
|
||||
mask = int(self._kernel32.GetLogicalDrives())
|
||||
return {
|
||||
f"{chr(ord('A') + index)}:"
|
||||
for index in range(26)
|
||||
if mask & (1 << index)
|
||||
}
|
||||
|
||||
def add_mapping(self, drive: str, remote: str) -> None:
|
||||
resource = _NETRESOURCEW()
|
||||
resource.dwType = self.RESOURCETYPE_DISK
|
||||
resource.lpLocalName = drive
|
||||
resource.lpRemoteName = remote
|
||||
error = self._mpr.WNetAddConnection2W(
|
||||
ctypes.byref(resource), None, None, self.CONNECT_TEMPORARY
|
||||
)
|
||||
if error:
|
||||
raise OSError(error, f"WNetAddConnection2W({drive}, {remote})")
|
||||
|
||||
def cancel_mapping(self, drive: str) -> None:
|
||||
error = self._mpr.WNetCancelConnection2W(drive, 0, False)
|
||||
if error and error != self.ERROR_NOT_CONNECTED:
|
||||
raise OSError(error, f"WNetCancelConnection2W({drive})")
|
||||
|
||||
|
||||
def _same_remote(left: str, right: str) -> bool:
|
||||
return ntpath.normcase(ntpath.normpath(left)) == ntpath.normcase(ntpath.normpath(right))
|
||||
|
||||
|
||||
def ensure_mapped_drive_visible(drive: str, remote_root: str, *,
|
||||
backend: WNetBackend | None = None) -> dict[str, object]:
|
||||
"""Ensure a worker process can see the mapped drive used by Mentor.
|
||||
|
||||
Windows drive mappings are associated with a logon/security context. A
|
||||
PCB or iCDB child started from an elevated/private worker can therefore
|
||||
lose a mapping that is visible to the UI process. Reuse an identical
|
||||
mapping, create it only when absent, and reject a conflicting mapping.
|
||||
The function never disconnects a mapping; ownership remains with the
|
||||
user's session.
|
||||
"""
|
||||
raw_drive = str(drive or '').strip().rstrip('\\/')
|
||||
raw_remote = str(remote_root or '').strip()
|
||||
if not raw_drive or not raw_remote:
|
||||
return {'drive': raw_drive, 'remote_root': raw_remote, 'created': False}
|
||||
if not raw_drive.endswith(':'):
|
||||
raw_drive = raw_drive[:2] if len(raw_drive) >= 2 and raw_drive[1] == ':' else raw_drive
|
||||
normalized_drive = raw_drive.upper()
|
||||
backend = backend or WindowsWNetBackend()
|
||||
try:
|
||||
mappings = backend.mappings()
|
||||
except OSError as error:
|
||||
raise NetworkPathError(
|
||||
f"NETWORK_UNAVAILABLE: 无法读取网络盘映射 {normalized_drive}: {error}"
|
||||
) from error
|
||||
current = next((value for key, value in mappings.items()
|
||||
if str(key).upper().rstrip('\\/') == normalized_drive), None)
|
||||
if current:
|
||||
if _same_remote(current, raw_remote):
|
||||
return {'drive': normalized_drive, 'remote_root': current, 'created': False}
|
||||
raise NetworkPathError(
|
||||
f"NETWORK_UNAVAILABLE: 映射冲突 {normalized_drive}: 当前={current}, 需要={raw_remote}"
|
||||
)
|
||||
try:
|
||||
backend.add_mapping(normalized_drive, raw_remote)
|
||||
except OSError as error:
|
||||
raise NetworkPathError(
|
||||
f"NETWORK_UNAVAILABLE: 无法在 worker 会话恢复映射 {normalized_drive} -> {raw_remote}: {error}"
|
||||
) from error
|
||||
return {'drive': normalized_drive, 'remote_root': raw_remote, 'created': True}
|
||||
|
||||
|
||||
def absolute_preserving_drive(path) -> Path:
|
||||
"""Make a path absolute without resolving a mapped drive back to UNC."""
|
||||
return Path(os.path.abspath(str(path)))
|
||||
|
||||
|
||||
def _normalize_input_path(path) -> str:
|
||||
raw = str(path).strip()
|
||||
if raw.startswith("/"):
|
||||
raw = raw.replace("/", "\\")
|
||||
if raw.startswith("\\") and not raw.startswith("\\\\"):
|
||||
raise NetworkPathError(
|
||||
"NETWORK_UNAVAILABLE: UNC 路径必须以两个反斜杠开头,例如 \\\\server\\share"
|
||||
)
|
||||
if raw.startswith("\\\\"):
|
||||
raw = "\\\\" + raw.lstrip("\\").replace("/", "\\")
|
||||
return raw
|
||||
|
||||
|
||||
def select_library_file(path) -> Path:
|
||||
"""Return a concrete LMC, accepting a directory with exactly one LMC."""
|
||||
candidate = Path(path)
|
||||
if candidate.is_file():
|
||||
if candidate.suffix.casefold() != ".lmc":
|
||||
raise NetworkPathError(f"中心库文件必须是 .lmc: {candidate}")
|
||||
return candidate
|
||||
if candidate.is_dir():
|
||||
files = sorted(
|
||||
(item for item in candidate.iterdir()
|
||||
if item.is_file() and item.suffix.casefold() == ".lmc"),
|
||||
key=lambda item: item.name.casefold(),
|
||||
)
|
||||
if len(files) != 1:
|
||||
raise NetworkPathError(
|
||||
f"中心库目录必须包含唯一的 .lmc 文件,当前找到 {len(files)} 个: {candidate}"
|
||||
)
|
||||
return files[0]
|
||||
raise NetworkPathError(f"中心库路径不存在或不可访问: {candidate}")
|
||||
|
||||
|
||||
@dataclass
|
||||
class LibraryPathLease:
|
||||
display_path: Path
|
||||
mentor_path: Path
|
||||
drive: str = ""
|
||||
remote_root: str = ""
|
||||
created: bool = False
|
||||
_backend: WNetBackend | None = None
|
||||
_closed: bool = False
|
||||
|
||||
@classmethod
|
||||
def acquire(cls, path, *, backend: WNetBackend | None = None) -> "LibraryPathLease":
|
||||
raw = _normalize_input_path(path)
|
||||
if not raw.startswith("\\\\"):
|
||||
local = Path(path)
|
||||
drive, _ = ntpath.splitdrive(raw)
|
||||
if drive:
|
||||
try:
|
||||
backend = backend or WindowsWNetBackend()
|
||||
remote = next((value for key, value in backend.mappings().items()
|
||||
if str(key).upper().rstrip('\\/') == drive.upper()), '')
|
||||
except (OSError, AttributeError):
|
||||
remote = ''
|
||||
return cls(local, local, drive.upper(), remote, False, backend)
|
||||
return cls(local, local)
|
||||
|
||||
remote_root, tail = ntpath.splitdrive(raw)
|
||||
if not remote_root or remote_root.count("\\") < 3:
|
||||
raise NetworkPathError(f"NETWORK_UNAVAILABLE: 非法 UNC 中心库路径: {raw}")
|
||||
backend = backend or WindowsWNetBackend()
|
||||
try:
|
||||
mappings = backend.mappings()
|
||||
for drive, remote in mappings.items():
|
||||
if _same_remote(remote, remote_root):
|
||||
mentor = Path(drive + "\\" + tail.lstrip("\\/"))
|
||||
return cls(Path(raw), mentor, drive, remote_root, False, backend)
|
||||
|
||||
used = {drive.upper().rstrip("\\") for drive in backend.used_drives()}
|
||||
drive = next(
|
||||
(f"{letter}:" for letter in reversed("DEFGHIJKLMNOPQRSTUVWXYZ")
|
||||
if f"{letter}:" not in used),
|
||||
"",
|
||||
)
|
||||
if not drive:
|
||||
raise NetworkPathError("NETWORK_UNAVAILABLE: 没有可用的临时网络盘符")
|
||||
backend.add_mapping(drive, remote_root)
|
||||
mentor = Path(drive + "\\" + tail.lstrip("\\/"))
|
||||
return cls(Path(raw), mentor, drive, remote_root, True, backend)
|
||||
except NetworkPathError:
|
||||
raise
|
||||
except OSError as error:
|
||||
raise NetworkPathError(
|
||||
f"NETWORK_UNAVAILABLE: 无法挂载中心库 {remote_root}: {error}"
|
||||
) from error
|
||||
|
||||
def close(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
if not self.created or self._backend is None or not self.drive:
|
||||
return
|
||||
try:
|
||||
current = self._backend.mappings().get(self.drive)
|
||||
if current and _same_remote(current, self.remote_root):
|
||||
self._backend.cancel_mapping(self.drive)
|
||||
except OSError as error:
|
||||
raise NetworkPathError(
|
||||
f"NETWORK_UNAVAILABLE: 释放临时盘符 {self.drive} 失败: {error}"
|
||||
) from error
|
||||
|
||||
def __enter__(self) -> "LibraryPathLease":
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback) -> None:
|
||||
self.close()
|
||||
@@ -0,0 +1,143 @@
|
||||
"""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
|
||||
|
||||
|
||||
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 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 退出均已确认。'}
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Read-only observations while Library Manager invokes Verify."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def invoke_with_evidence(invoke, emit, metadata):
|
||||
emit({'stage': 'verify_invoke', **metadata})
|
||||
invoke()
|
||||
emit({'stage': 'verify_invoke_returned', **metadata})
|
||||
|
||||
|
||||
def build_snapshot(processes, windows, expected_pcb, preexisting_pids):
|
||||
from .mentor_adapter import is_reusable_circuit_pcb
|
||||
|
||||
expected = str(expected_pcb).casefold()
|
||||
return {
|
||||
'processes': [
|
||||
{
|
||||
'pid': int(pid), 'name': str(name), 'executable': str(executable),
|
||||
'command': str(command), 'preexisting': int(pid) in preexisting_pids,
|
||||
'target_path_in_command': expected in str(command).casefold(),
|
||||
'matches_current_filter': is_reusable_circuit_pcb(executable, command, expected_pcb),
|
||||
}
|
||||
for pid, name, executable, command in processes
|
||||
],
|
||||
'windows': list(windows),
|
||||
}
|
||||
|
||||
|
||||
def _related_processes():
|
||||
import win32com.client
|
||||
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
query = ("SELECT ProcessId, Name, ExecutablePath, CommandLine FROM Win32_Process "
|
||||
"WHERE Name='LibraryManager.exe' OR Name LIKE '%PCB%' OR Name LIKE '%Xtreme%'")
|
||||
return [(int(p.ProcessId), str(p.Name or ''), str(p.ExecutablePath or ''),
|
||||
str(p.CommandLine or '')) for p in service.ExecQuery(query)]
|
||||
|
||||
|
||||
def _private_windows(desktop, related_pids):
|
||||
import win32gui
|
||||
import win32process
|
||||
|
||||
windows = []
|
||||
for hwnd in desktop.EnumDesktopWindows():
|
||||
try:
|
||||
pid = int(win32process.GetWindowThreadProcessId(hwnd)[1])
|
||||
if pid not in related_pids or not win32gui.IsWindowVisible(hwnd):
|
||||
continue
|
||||
class_name = win32gui.GetClassName(hwnd)
|
||||
title = win32gui.GetWindowText(hwnd)
|
||||
owner = int(win32gui.GetWindow(hwnd, 4) or 0)
|
||||
texts = []
|
||||
if owner or class_name in ('#32770', 'GXWND', 'TaskDialog'):
|
||||
children = []
|
||||
win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(child) or True, None)
|
||||
for child in children[:32]:
|
||||
value = win32gui.GetWindowText(child)
|
||||
if value:
|
||||
texts.append(value)
|
||||
windows.append({'pid': pid, 'hwnd': int(hwnd), 'class_name': class_name,
|
||||
'title': title, 'owner_hwnd': owner, 'texts': texts})
|
||||
except Exception:
|
||||
# A window may close between enumeration and inspection.
|
||||
continue
|
||||
return windows
|
||||
|
||||
|
||||
def observe_post_verify(desktop, expected_pcb, preexisting_pids, lm_pid):
|
||||
processes = _related_processes()
|
||||
related_pids = {pid for pid, _, _, _ in processes}
|
||||
if lm_pid is not None:
|
||||
related_pids.add(int(lm_pid))
|
||||
return build_snapshot(processes, _private_windows(desktop, related_pids),
|
||||
Path(expected_pcb), preexisting_pids)
|
||||
@@ -0,0 +1,33 @@
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import hashlib
|
||||
|
||||
def configure(root: Path):
|
||||
try:
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging, install_exception_hooks
|
||||
context = configure_logging(root); install_exception_hooks(context)
|
||||
# Reuse the mature rotating/UTC logger implementation, but keep product identity CBB-specific.
|
||||
context.logger.name = "cbb_refresh_verify." + hashlib.sha256(str(root.resolve()).encode("utf-8")).hexdigest()[:16]
|
||||
context.logger.info("cbb_logging_configured root=%s application_log=%s", context.root, context.application_log_path)
|
||||
for handler in context.logger.handlers: handler.flush()
|
||||
return context
|
||||
except ImportError:
|
||||
import logging
|
||||
from logging.handlers import RotatingFileHandler
|
||||
root.mkdir(parents=True, exist_ok=True); (root/'logs').mkdir(exist_ok=True)
|
||||
logger=logging.getLogger('cbb_refresh_verify'); logger.handlers.clear(); logger.setLevel(logging.INFO)
|
||||
# Keep the standalone fallback bounded as well. The packaged build
|
||||
# normally uses the replacement tool's rotating logger, but a target
|
||||
# machine may intentionally omit that optional dependency.
|
||||
logger.addHandler(RotatingFileHandler(
|
||||
root/'logs'/'application.log', maxBytes=10 * 1024 * 1024,
|
||||
backupCount=5, encoding='utf-8'))
|
||||
return type('Context',(),{'root':root,'logger':logger,'application_log_path':root/'logs'/'application.log'})()
|
||||
|
||||
def capture(context, *, operation, returncode, stdout, stderr):
|
||||
try:
|
||||
from dx_productivity.trial_task_center.logging_setup import capture_subprocess_output
|
||||
capture_subprocess_output(context, operation=operation, returncode=returncode, stdout=stdout, stderr=stderr)
|
||||
except ImportError:
|
||||
context.logger.info('operation=%s returncode=%s stdout=%s stderr=%s', operation, returncode, stdout.rstrip(), stderr.rstrip())
|
||||
for handler in context.logger.handlers: handler.flush()
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Measured run durations, not estimates derived from wall-clock log timestamps."""
|
||||
import math
|
||||
import time
|
||||
|
||||
ACTION_KEYS = {
|
||||
'ForwardAnnotate': 'forward_annotation', 'SynchCES': 'synch_ces',
|
||||
'LoadCES': 'load_ces', 'BackAnnotate': 'back_annotation',
|
||||
}
|
||||
|
||||
|
||||
def parse_save_progress(text):
|
||||
markers, durations = [], {}
|
||||
for line in text.splitlines():
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
if not line.startswith('TIMING|'):
|
||||
markers.append(line)
|
||||
continue
|
||||
parts = line.split('|')
|
||||
if len(parts) != 3:
|
||||
continue
|
||||
try:
|
||||
seconds = float(parts[2])
|
||||
except ValueError:
|
||||
continue
|
||||
if math.isfinite(seconds) and seconds >= 0:
|
||||
durations[parts[1]] = seconds
|
||||
return {'markers': markers, 'timings_seconds': durations}
|
||||
|
||||
|
||||
class RunTimings:
|
||||
def __init__(self, *, clock=None):
|
||||
self.clock = clock or time.monotonic
|
||||
self.started = self.clock()
|
||||
self.elapsed = {}
|
||||
self.running = {}
|
||||
self._action_totals = {}
|
||||
self._save_markers = set()
|
||||
|
||||
def begin(self, name, at=None):
|
||||
self.running.setdefault(name, self.clock() if at is None else at)
|
||||
|
||||
def end(self, name, at=None):
|
||||
started = self.running.pop(name, None)
|
||||
if started is not None:
|
||||
self.elapsed[name] = self.elapsed.get(name, 0.0) + max(
|
||||
0.0, (self.clock() if at is None else at) - started)
|
||||
|
||||
def record(self, event):
|
||||
now = event.get('monotonic_seconds')
|
||||
if now is None:
|
||||
now = self.clock()
|
||||
stage = event.get('stage')
|
||||
if stage in ('lm_launch', 'pcb_launch'):
|
||||
self.end('worker_setup', now)
|
||||
self.begin('pcb_startup', now)
|
||||
elif stage == 'identity_verified':
|
||||
self.end('pcb_startup', now)
|
||||
self.begin('integration', now)
|
||||
elif stage == 'integration_action':
|
||||
key = ACTION_KEYS.get(event.get('action'))
|
||||
if key:
|
||||
self.begin(key, now)
|
||||
elif stage == 'integration_action_complete':
|
||||
key = ACTION_KEYS.get(event.get('action'))
|
||||
if key:
|
||||
self.end(key, now)
|
||||
# These are measured inside the worker and include COM blocking,
|
||||
# independent of delayed supervisor polling or disk writes.
|
||||
if 'elapsed_seconds' in event:
|
||||
# Replace the just-observed span with the worker's duration.
|
||||
# Keep repeat actions as separate accumulated work.
|
||||
prior = self._action_totals.get(key, 0.0)
|
||||
self._action_totals[key] = prior + float(event['elapsed_seconds'])
|
||||
self.elapsed[key] = self._action_totals[key]
|
||||
if 'call_elapsed_seconds' in event:
|
||||
call = key + '_call'
|
||||
self.elapsed[call] = self.elapsed.get(call, 0.0) + float(event['call_elapsed_seconds'])
|
||||
elif stage == 'integration_complete':
|
||||
self.end('integration', now)
|
||||
elif stage == 'save_start':
|
||||
self.begin('save_close', now)
|
||||
elif stage == 'save_progress':
|
||||
boundaries = {
|
||||
'VALIDATE_START': ('begin', 'validate'), 'LICENSE_OK': ('end', 'validate'),
|
||||
'SAVE_START': ('begin', 'save'), 'SAVE_OK': ('end', 'save'),
|
||||
'POST_SAVE_CHECK': ('begin', 'post_save_check'),
|
||||
'POST_SAVE_SYNCHRONIZED': ('end', 'post_save_check'),
|
||||
'CLOSE_START': ('begin', 'close'), 'CLOSE_OK': ('end', 'close'),
|
||||
}
|
||||
for marker in event.get('markers', ()):
|
||||
if marker in self._save_markers:
|
||||
continue
|
||||
self._save_markers.add(marker)
|
||||
if marker in boundaries:
|
||||
operation, name = boundaries[marker]
|
||||
getattr(self, operation)(name, now)
|
||||
measured = event.get('timings_seconds', {})
|
||||
for name in measured:
|
||||
# A helper duration proves the COM call returned, even if its
|
||||
# Boolean result was false and no success marker followed.
|
||||
self.running.pop(name, None)
|
||||
self.elapsed.update(measured)
|
||||
elif stage == 'saved_and_closed':
|
||||
self.end('save_close', now)
|
||||
self.begin('pcb_exit', now)
|
||||
elif stage == 'complete':
|
||||
self.end('pcb_exit', now)
|
||||
|
||||
def snapshot(self):
|
||||
now = self.clock()
|
||||
values = dict(self.elapsed)
|
||||
for name, started in self.running.items():
|
||||
values[name] = values.get(name, 0.0) + max(0.0, now - started)
|
||||
values['total'] = max(0.0, now - self.started)
|
||||
return {key: round(value, 6) for key, value in values.items()}, tuple(self.running)
|
||||
@@ -0,0 +1,58 @@
|
||||
Option Explicit
|
||||
Dim app, doc, pi, licensing, token, expected, attempt, stable, measuredStart, operationOK
|
||||
expected = WScript.Arguments(0)
|
||||
Set app = GetObject(, "MGCPCB.Application")
|
||||
Set doc = app.ActiveDocument
|
||||
Set pi = doc.ProjectIntegration
|
||||
If LCase(pi.ProjectFile) <> LCase(expected) Then WScript.Quit 2
|
||||
If pi.ForwardAnnotationStatus <> 2 Or pi.SynchCESStatus <> 2 Or pi.LoadCESStatus <> 2 Or pi.BackAnnotationStatus <> 2 Then WScript.Quit 3
|
||||
WScript.Echo "VALIDATE_START"
|
||||
measuredStart = Timer
|
||||
Set licensing = CreateObject("MGCPCBAutomationLicensing.Application")
|
||||
token = licensing.GetToken(doc.Validate(0))
|
||||
doc.Validate token
|
||||
LogElapsed "validate", measuredStart
|
||||
WScript.Echo "LICENSE_OK"
|
||||
WScript.Echo "SAVE_START"
|
||||
measuredStart = Timer
|
||||
operationOK = doc.Save()
|
||||
LogElapsed "save", measuredStart
|
||||
If Not operationOK Then WScript.Quit 4
|
||||
WScript.Echo "SAVE_OK"
|
||||
measuredStart = Timer
|
||||
operationOK = doc.IsSaved()
|
||||
LogElapsed "is_saved", measuredStart
|
||||
If Not operationOK Then WScript.Quit 5
|
||||
WScript.Echo "IS_SAVED"
|
||||
stable = False
|
||||
WScript.Echo "POST_SAVE_CHECK"
|
||||
measuredStart = Timer
|
||||
For attempt = 1 To 50
|
||||
Set pi = doc.ProjectIntegration
|
||||
If pi.ForwardAnnotationStatus = 2 And pi.SynchCESStatus = 2 And pi.LoadCESStatus = 2 And pi.BackAnnotationStatus = 2 Then
|
||||
stable = True
|
||||
Exit For
|
||||
End If
|
||||
WScript.Sleep 200
|
||||
Next
|
||||
LogElapsed "post_save_check", measuredStart
|
||||
If Not stable Then WScript.Quit 7
|
||||
WScript.Echo "POST_SAVE_SYNCHRONIZED"
|
||||
If Not doc.IsSaved() Then WScript.Quit 8
|
||||
WScript.Echo "CLOSE_START"
|
||||
measuredStart = Timer
|
||||
operationOK = doc.Close(True)
|
||||
LogElapsed "close", measuredStart
|
||||
If Not operationOK Then WScript.Quit 6
|
||||
WScript.Echo "CLOSE_OK"
|
||||
measuredStart = Timer
|
||||
app.Quit
|
||||
LogElapsed "quit", measuredStart
|
||||
WScript.Echo "QUIT_OK"
|
||||
|
||||
Sub LogElapsed(phaseName, started)
|
||||
Dim elapsed
|
||||
elapsed = Timer - started
|
||||
If elapsed < 0 Then elapsed = elapsed + 86400
|
||||
WScript.Echo "TIMING|" & phaseName & "|" & Replace(CStr(Round(elapsed, 3)), ",", ".")
|
||||
End Sub
|
||||
@@ -0,0 +1,329 @@
|
||||
"""Optional read-only Mentor Verify status bridge client.
|
||||
|
||||
The Mentor EE 7.9 libraries are 32-bit MFC binaries. This module deliberately
|
||||
does not load them from Python. It talks to a separately compiled x86 helper
|
||||
over one JSON line at a time and treats a missing or malformed helper as an
|
||||
unavailable authoritative source.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import ntpath
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import queue
|
||||
import sys
|
||||
import threading
|
||||
from typing import Any, Sequence
|
||||
from uuid import uuid4
|
||||
|
||||
from .network_path import absolute_preserving_drive
|
||||
|
||||
|
||||
class BridgeResponseError(RuntimeError):
|
||||
"""The helper returned a response that cannot prove Verify state."""
|
||||
|
||||
|
||||
class BridgeUnavailable(RuntimeError):
|
||||
"""The optional x86 helper is not available on this machine."""
|
||||
|
||||
def __init__(self, path: Path, detail: str = "未找到可用的 32-bit Mentor 状态桥") -> None:
|
||||
self.path = Path(path)
|
||||
super().__init__(f"{detail}: {self.path}")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BridgeResult:
|
||||
status: str
|
||||
source: str
|
||||
raw_status: int | str | None = None
|
||||
detail: str = ""
|
||||
response: dict[str, Any] | None = None
|
||||
request_id: str = ""
|
||||
block_name: str = ""
|
||||
lmc_file: str = ""
|
||||
|
||||
|
||||
def _normalized_path(value: str | Path) -> str:
|
||||
raw = str(value).strip().replace("/", "\\")
|
||||
if raw.startswith("\\\\"):
|
||||
raw = "\\\\" + "\\".join(
|
||||
part for part in raw.lstrip("\\").split("\\") if part
|
||||
)
|
||||
return ntpath.normcase(ntpath.normpath(raw))
|
||||
|
||||
|
||||
def parse_bridge_response(
|
||||
line: str,
|
||||
*,
|
||||
expected_request_id: str | None = None,
|
||||
expected_block: str | None = None,
|
||||
expected_lmc: str | Path | None = None,
|
||||
) -> BridgeResult:
|
||||
"""Parse one bridge response and require an authoritative status.
|
||||
|
||||
``UNKNOWN`` is intentionally rejected here. The caller can represent a
|
||||
missing bridge separately, but a helper must never claim success without a
|
||||
concrete Mentor status source.
|
||||
"""
|
||||
try:
|
||||
payload = json.loads(line)
|
||||
except (TypeError, ValueError) as error:
|
||||
raise BridgeResponseError(f"状态桥返回非法 JSON: {error}") from error
|
||||
if not isinstance(payload, dict):
|
||||
raise BridgeResponseError("状态桥响应不是 JSON 对象")
|
||||
if not payload.get("ok"):
|
||||
raise BridgeResponseError(str(payload.get("error") or "状态桥调用失败"))
|
||||
request_id = str(payload.get("request_id") or "")
|
||||
block_name = str(payload.get("block_name") or "")
|
||||
lmc_file = str(payload.get("mentor_lmc_file") or payload.get("lmc_file") or "")
|
||||
if expected_request_id is not None and request_id != expected_request_id:
|
||||
raise BridgeResponseError(
|
||||
f"状态桥请求标识不匹配: expected={expected_request_id!r}, actual={request_id!r}"
|
||||
)
|
||||
if expected_block is not None and block_name != expected_block:
|
||||
raise BridgeResponseError(
|
||||
f"状态桥 CBB 标识不匹配: expected={expected_block!r}, actual={block_name!r}"
|
||||
)
|
||||
if expected_lmc is not None and (
|
||||
not lmc_file or _normalized_path(lmc_file) != _normalized_path(expected_lmc)
|
||||
):
|
||||
raise BridgeResponseError(
|
||||
f"状态桥中心库路径不匹配: expected={str(expected_lmc)!r}, actual={lmc_file!r}"
|
||||
)
|
||||
status = str(payload.get("status") or "").upper()
|
||||
source = str(payload.get("source") or "").strip()
|
||||
if status not in {"READY", "PENDING"} or not source:
|
||||
raise BridgeResponseError(
|
||||
"状态桥未返回 authoritative Verify 状态"
|
||||
)
|
||||
return BridgeResult(
|
||||
status=status,
|
||||
source=source,
|
||||
raw_status=payload.get("raw_status"),
|
||||
detail=str(payload.get("detail") or ""),
|
||||
response=payload,
|
||||
request_id=request_id,
|
||||
block_name=block_name,
|
||||
lmc_file=lmc_file,
|
||||
)
|
||||
|
||||
|
||||
def default_bridge_path() -> Path:
|
||||
configured = os.environ.get("CBB_STATUS_BRIDGE", "").strip()
|
||||
if configured:
|
||||
return Path(configured).expanduser()
|
||||
package_root = Path(__file__).resolve().parent
|
||||
frozen_root = Path(getattr(sys, "_MEIPASS", package_root))
|
||||
candidates = (
|
||||
package_root / "status_bridge32.exe",
|
||||
package_root / "bridge" / "CbbStatusBridge32.exe",
|
||||
Path(sys.executable).resolve().parent / "tools" / "status_bridge" / "bin" / "CbbStatusBridge32.exe",
|
||||
frozen_root / "tools" / "status_bridge" / "bin" / "CbbStatusBridge32.exe",
|
||||
package_root.parent.parent / "tools" / "status_bridge" / "bin" / "CbbStatusBridge32.exe",
|
||||
)
|
||||
for candidate in candidates:
|
||||
if candidate.is_file():
|
||||
return candidate
|
||||
return candidates[0]
|
||||
|
||||
|
||||
class StatusBridgeClient:
|
||||
"""Query a compiled x86 bridge without importing Mentor DLLs in Python."""
|
||||
|
||||
def __init__(self, executable: Path | None = None, *, env: dict[str, str] | None = None) -> None:
|
||||
self.executable = Path(executable) if executable is not None else default_bridge_path()
|
||||
self.env = dict(env or {})
|
||||
|
||||
def query(
|
||||
self,
|
||||
lmc_file: Path,
|
||||
block_name: str,
|
||||
*,
|
||||
block_type: str = "RULP",
|
||||
timeout_seconds: float = 10,
|
||||
) -> BridgeResult:
|
||||
if not self.executable.is_file():
|
||||
raise BridgeUnavailable(self.executable)
|
||||
request_id = uuid4().hex
|
||||
resolved_lmc = str(absolute_preserving_drive(lmc_file))
|
||||
request = {
|
||||
"op": "is_verified",
|
||||
"request_id": request_id,
|
||||
"lmc_file": resolved_lmc,
|
||||
"block_name": str(block_name),
|
||||
"block_type": str(block_type),
|
||||
}
|
||||
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
||||
child_env = os.environ.copy()
|
||||
child_env.update(self.env)
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
[str(self.executable)],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
creationflags=creationflags,
|
||||
env=child_env,
|
||||
)
|
||||
except OSError as error:
|
||||
raise BridgeUnavailable(self.executable, f"无法启动 32-bit Mentor 状态桥: {error}") from error
|
||||
try:
|
||||
stdout, stderr = process.communicate(
|
||||
json.dumps(request, ensure_ascii=False) + "\n",
|
||||
timeout=max(0.1, float(timeout_seconds)),
|
||||
)
|
||||
except subprocess.TimeoutExpired as error:
|
||||
try:
|
||||
process.kill()
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
process.communicate(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
raise BridgeResponseError("状态桥响应超时") from error
|
||||
if process.returncode not in (0, None):
|
||||
detail = (stderr or stdout).strip() or f"退出码 {process.returncode}"
|
||||
raise BridgeResponseError(f"状态桥进程失败: {detail}")
|
||||
line = next((item.strip() for item in stdout.splitlines() if item.strip()), "")
|
||||
if not line:
|
||||
raise BridgeResponseError("状态桥没有返回 JSON 响应")
|
||||
return parse_bridge_response(
|
||||
line,
|
||||
expected_request_id=request_id,
|
||||
expected_block=str(block_name),
|
||||
expected_lmc=resolved_lmc,
|
||||
)
|
||||
|
||||
|
||||
class StatusBridgeServer:
|
||||
"""Persistent JSONL bridge process with per-request deadlines."""
|
||||
|
||||
def __init__(self, executable: Path | None = None, *, env: dict[str, str] | None = None,
|
||||
extra_args: Sequence[str] = ()) -> None:
|
||||
self.executable = Path(executable) if executable is not None else default_bridge_path()
|
||||
self.env = dict(env or {})
|
||||
self.extra_args = tuple(extra_args)
|
||||
self.process: subprocess.Popen[str] | None = None
|
||||
self._responses: queue.Queue[str | BaseException | None] = queue.Queue()
|
||||
self._reader: threading.Thread | None = None
|
||||
self.restart_count = 0
|
||||
self._warmup = False
|
||||
|
||||
def _command(self) -> list[str]:
|
||||
if self.executable.suffix.casefold() == ".py":
|
||||
return [sys.executable, str(self.executable), "--server", *self.extra_args]
|
||||
return [str(self.executable), "--server", *self.extra_args]
|
||||
|
||||
def start(self) -> None:
|
||||
if self.process is not None and self.process.poll() is None:
|
||||
return
|
||||
if not self.executable.is_file():
|
||||
raise BridgeUnavailable(self.executable)
|
||||
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
||||
child_env = os.environ.copy()
|
||||
child_env.update(self.env)
|
||||
try:
|
||||
self.process = subprocess.Popen(
|
||||
self._command(), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace",
|
||||
bufsize=1, creationflags=creationflags, env=child_env,
|
||||
)
|
||||
except OSError as error:
|
||||
raise BridgeUnavailable(self.executable, f"无法启动常驻状态桥: {error}") from error
|
||||
self._responses = queue.Queue()
|
||||
self._warmup = True
|
||||
self._reader = threading.Thread(target=self._read_responses, daemon=True)
|
||||
self._reader.start()
|
||||
|
||||
def _read_responses(self) -> None:
|
||||
process = self.process
|
||||
responses = self._responses
|
||||
if process is None or process.stdout is None:
|
||||
return
|
||||
try:
|
||||
for line in process.stdout:
|
||||
responses.put(line.strip())
|
||||
except BaseException as error: # the supervisor converts this to one item failure
|
||||
responses.put(error)
|
||||
finally:
|
||||
responses.put(None)
|
||||
|
||||
def query(self, lmc_file: Path, block_name: str, *, block_type: str = "RULP",
|
||||
timeout_seconds: float = 10) -> BridgeResult:
|
||||
self.start()
|
||||
process = self.process
|
||||
if process is None or process.stdin is None:
|
||||
raise BridgeUnavailable(self.executable, "状态桥进程未运行")
|
||||
request_id = uuid4().hex
|
||||
resolved_lmc = str(absolute_preserving_drive(lmc_file))
|
||||
request = {
|
||||
"op": "is_verified", "request_id": request_id, "lmc_file": resolved_lmc,
|
||||
"block_name": str(block_name), "block_type": str(block_type),
|
||||
}
|
||||
try:
|
||||
process.stdin.write(json.dumps(request, ensure_ascii=False) + "\n")
|
||||
process.stdin.flush()
|
||||
except (OSError, ValueError) as error:
|
||||
raise BridgeResponseError(f"状态桥写入失败: {error}") from error
|
||||
try:
|
||||
deadline = max(0.1, float(timeout_seconds))
|
||||
# Process startup is outside the item operation. Give a freshly
|
||||
# spawned Python/x86 helper a small one-time warm-up allowance so
|
||||
# a short item deadline cannot turn interpreter startup into a
|
||||
# false timeout.
|
||||
if self._warmup:
|
||||
deadline = max(deadline, 2.0)
|
||||
response = self._responses.get(timeout=deadline)
|
||||
except queue.Empty as error:
|
||||
self.close()
|
||||
raise BridgeResponseError("状态桥响应超时") from error
|
||||
if response is None:
|
||||
detail = f"退出码 {process.poll()}"
|
||||
self.close()
|
||||
raise BridgeResponseError(f"状态桥进程提前退出: {detail}")
|
||||
if isinstance(response, BaseException):
|
||||
self.close()
|
||||
raise BridgeResponseError(f"状态桥读取失败: {response}") from response
|
||||
self._warmup = False
|
||||
return parse_bridge_response(
|
||||
response,
|
||||
expected_request_id=request_id,
|
||||
expected_block=str(block_name),
|
||||
expected_lmc=resolved_lmc,
|
||||
)
|
||||
|
||||
def restart(self) -> None:
|
||||
self.close()
|
||||
self.restart_count += 1
|
||||
self.start()
|
||||
|
||||
def close(self) -> None:
|
||||
process, self.process = self.process, None
|
||||
if process is None:
|
||||
return
|
||||
try:
|
||||
if process.stdin is not None:
|
||||
process.stdin.close()
|
||||
except OSError:
|
||||
pass
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=2)
|
||||
except subprocess.TimeoutExpired:
|
||||
try:
|
||||
process.kill()
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
process.wait(timeout=2)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
Whitespace-only changes.
@@ -0,0 +1,427 @@
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
import os
|
||||
import time
|
||||
from collections import Counter
|
||||
|
||||
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt
|
||||
from PySide6.QtGui import QColor, QIcon
|
||||
from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout,
|
||||
QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton,
|
||||
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox)
|
||||
from PySide6.QtWidgets import QStyle
|
||||
try:
|
||||
from dx_productivity.trial_task_center.ui.workers import ServiceWorker
|
||||
except ImportError:
|
||||
from cbb_refresh_verify.ui.workers import ServiceWorker
|
||||
from cbb_refresh_verify.library_reader import read_library_fast, scan_open_library_status
|
||||
from cbb_refresh_verify.batch_status import authoritative_status_map
|
||||
from cbb_refresh_verify.defaults import DEFAULT_TIMEOUT_SECONDS
|
||||
from cbb_refresh_verify.network_path import LibraryPathLease, select_library_file
|
||||
from cbb_refresh_verify.verify_runner import (VerifyRequest, preflight_skip_reason, run_verify,
|
||||
run_batch, write_batch_report, failure_report_path,
|
||||
native_lm_verify_enabled)
|
||||
|
||||
|
||||
class ProgressSignals(QObject):
|
||||
event = Signal(object)
|
||||
|
||||
|
||||
STATUS_LABELS = {
|
||||
'READY': '绿色 / Ready',
|
||||
'PENDING': '待校验',
|
||||
'UNKNOWN': '未知 / 需确认',
|
||||
'UNAVAILABLE': '状态桥不可用',
|
||||
'ERROR': '状态读取失败',
|
||||
'TIMEOUT': '状态读取超时',
|
||||
'MALFORMED': '状态桥协议错误',
|
||||
'CRASHED': '状态桥崩溃',
|
||||
}
|
||||
|
||||
|
||||
def application_icon_path():
|
||||
return Path(__file__).resolve().parents[1] / 'assets' / 'cbb_refresh_verify.ico'
|
||||
|
||||
|
||||
class MainWindow(QWidget):
|
||||
def __init__(self, reader=None, verifier=None, logging_context=None, data_root=None,
|
||||
authoritative_status=True, path_lease_factory=None):
|
||||
super().__init__()
|
||||
self.setWindowTitle('CBB 刷新校验')
|
||||
icon_path = application_icon_path()
|
||||
if icon_path.is_file():
|
||||
self.setWindowIcon(QIcon(str(icon_path)))
|
||||
self.resize(850, 560)
|
||||
self.verifier = verifier
|
||||
self.logging_context = logging_context
|
||||
self.path_lease_factory = path_lease_factory or LibraryPathLease.acquire
|
||||
self.library_lease = None
|
||||
self.mentor_lmc_path = None
|
||||
self.data_root = Path(data_root or (logging_context.root if logging_context else Path(os.environ.get('LOCALAPPDATA', '.'))/'CbbRefreshVerify'))
|
||||
if reader is not None:
|
||||
self.reader = reader
|
||||
elif authoritative_status and os.environ.get('CBB_STATUS_BRIDGE_MODE', 'authoritative').casefold() != 'legacy':
|
||||
self.reader = lambda path: read_library_fast(
|
||||
path,
|
||||
status_reader=lambda p, names: authoritative_status_map(
|
||||
names, p, self.data_root / 'status-scan.jsonl'),
|
||||
)
|
||||
else:
|
||||
# Legacy icon/filesystem reader remains opt-in until the bridge is
|
||||
# accepted on the target Mentor installation. It cannot override
|
||||
# the authoritative path when that path is enabled explicitly.
|
||||
self.reader = lambda path: read_library_fast(
|
||||
path,
|
||||
status_reader=lambda p, names: scan_open_library_status(
|
||||
p, names, mapping_store=self.data_root/'image-status-map.json'),
|
||||
)
|
||||
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
|
||||
self.busy = False; self.loaded_path = None; self.stop = Event(); self.ready_names = set()
|
||||
self._row_by_name = {}
|
||||
self.skipped_names = set(); self.skip_reasons = {}
|
||||
self.signals = ProgressSignals(self); self.signals.event.connect(self._progress)
|
||||
self.lmc_edit = QLineEdit()
|
||||
self.libspec_edit = QLineEdit(os.environ.get('CBB_LIBSPEC', 'EE7.9'))
|
||||
self.dms_edit = QLineEdit(os.environ.get('CBB_DMS_LOGIN_CONFIG', ''))
|
||||
self.mentor_bin_edit = QLineEdit(os.environ.get('SDD_LM_BIN', ''))
|
||||
self.native_lm_verify_check = QCheckBox('使用 Library Manager 原生 Verify(Win10 兼容测试)')
|
||||
self.native_lm_verify_check.setChecked(native_lm_verify_enabled())
|
||||
self.native_lm_verify_check.setToolTip(
|
||||
'仅在 Win10 兼容测试时启用;默认仍使用已验证的 ReusableCircuit 直接流程。')
|
||||
self.advanced_toggle = QToolButton(); self.advanced_toggle.setText('高级设置')
|
||||
self.advanced_toggle.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_TitleBarUnshadeButton))
|
||||
self.advanced_toggle.setCheckable(True); self.advanced_toggle.setChecked(False)
|
||||
self.advanced_panel = QWidget()
|
||||
advanced_layout = QFormLayout(self.advanced_panel)
|
||||
advanced_layout.addRow('LibSpec', self.libspec_edit)
|
||||
advanced_layout.addRow('DMS 登录配置', self.dms_edit)
|
||||
advanced_layout.addRow('Mentor bin', self.mentor_bin_edit)
|
||||
advanced_layout.addRow('触发方式', self.native_lm_verify_check)
|
||||
self.advanced_panel.setVisible(False)
|
||||
self.advanced_toggle.toggled.connect(self.advanced_panel.setVisible)
|
||||
self.cbb_table = QTableWidget(0, 4)
|
||||
self.cbb_table.setHorizontalHeaderLabels(['CBB 名称', '分区', '状态', '环境检查'])
|
||||
self.cbb_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
|
||||
for column in (1, 2, 3):
|
||||
self.cbb_table.horizontalHeader().setSectionResizeMode(column, QHeaderView.ResizeToContents)
|
||||
self.cbb_table.setSelectionBehavior(QTableWidget.SelectRows)
|
||||
self.cbb_table.setMinimumHeight(150)
|
||||
self.cbb_table.itemChanged.connect(lambda _item: self._update())
|
||||
self.timeout_spin = QSpinBox(); self.timeout_spin.setRange(30, 1800); self.timeout_spin.setValue(DEFAULT_TIMEOUT_SECONDS); self.timeout_spin.setSuffix(' 秒 / 无进展')
|
||||
self.load_button = QPushButton('读取 CBB'); self.load_button.clicked.connect(self.load_library)
|
||||
self.browse_button = QPushButton('选择'); self.browse_button.clicked.connect(self.choose_library)
|
||||
self.selected_batch_button = QPushButton('批量校验已选'); self.selected_batch_button.clicked.connect(self.verify_selected)
|
||||
self.batch_button = QPushButton('批量校验全部 CBB'); self.batch_button.clicked.connect(self.verify_all)
|
||||
self.stop_button = QPushButton('当前项完成后停止'); self.stop_button.clicked.connect(self.request_stop)
|
||||
self.logs_button = QPushButton('打开日志目录'); self.logs_button.clicked.connect(self.open_logs)
|
||||
self.recovery_button = QPushButton('打开异常证据'); self.recovery_button.setEnabled(False)
|
||||
style = self.style()
|
||||
self.load_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_BrowserReload))
|
||||
self.browse_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon))
|
||||
self.selected_batch_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_ArrowRight))
|
||||
self.batch_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MediaPlay))
|
||||
self.stop_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MediaStop))
|
||||
self.logs_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon))
|
||||
self.recovery_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MessageBoxWarning))
|
||||
self.recovery_button.setToolTip('打开当前异常 CBB 的证据目录,不切换 Windows 桌面。')
|
||||
self.recovery_button.clicked.connect(self.recover)
|
||||
self.recovery_path = None
|
||||
self.status_label = QLabel('请选择并读取中心库。校验期间可以使用其他前台应用。')
|
||||
self.status_label.setWordWrap(True)
|
||||
self.output = QTextEdit(); self.output.setReadOnly(True)
|
||||
# Integration emits repeated status snapshots. Keep the visible
|
||||
# diagnostic buffer bounded so a 3,000-CBB run cannot grow the GUI
|
||||
# document without limit.
|
||||
self.output.document().setMaximumBlockCount(2000)
|
||||
layout = QFormLayout(self)
|
||||
row = QHBoxLayout(); row.addWidget(self.lmc_edit); row.addWidget(self.browse_button); row.addWidget(self.load_button)
|
||||
layout.addRow('中心库 .lmc', row); layout.addRow(self.advanced_toggle); layout.addRow(self.advanced_panel)
|
||||
layout.addRow('CBB 清单(勾选后可批量)', self.cbb_table); layout.addRow('超时', self.timeout_spin)
|
||||
layout.addRow(QLabel('逐个刷新:命令行启动 ReusableCircuit PCB → Project Integration → 保存并关闭,全程不切换桌面、不移动鼠标。'
|
||||
'填写 LibSpec 与 DMS 登录配置后,会先执行一次 ReuseBlockImporter 内容检查。'))
|
||||
controls = QHBoxLayout()
|
||||
for widget in (self.selected_batch_button, self.batch_button, self.stop_button, self.logs_button): controls.addWidget(widget)
|
||||
layout.addRow(controls); layout.addRow(self.status_label); layout.addRow(self.output)
|
||||
layout.addRow(self.recovery_button)
|
||||
self.lmc_edit.textChanged.connect(self._invalidate)
|
||||
for field in (self.libspec_edit, self.dms_edit, self.mentor_bin_edit):
|
||||
field.textChanged.connect(lambda _text: self._update())
|
||||
self.native_lm_verify_check.toggled.connect(lambda _checked: self._update())
|
||||
self._update()
|
||||
|
||||
def _invalidate(self):
|
||||
if self.loaded_path is not None and self.lmc_edit.text() != self.loaded_path:
|
||||
self._release_library_lease()
|
||||
self.loaded_path = None; self.mentor_lmc_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {}
|
||||
self.ready_names = set(); self.skipped_names = set(); self.skip_reasons = {}; self._update()
|
||||
|
||||
def _release_library_lease(self):
|
||||
lease, self.library_lease = self.library_lease, None
|
||||
if lease is None:
|
||||
return
|
||||
try:
|
||||
lease.close()
|
||||
except Exception as error:
|
||||
if self.logging_context:
|
||||
self.logging_context.logger.warning('library_lease_release_failed error=%s', error)
|
||||
|
||||
def _update(self):
|
||||
# The refresh flow needs only the library and a CBB; LibSpec/DMS config
|
||||
# are optional and only enable the extra contents check.
|
||||
ready = not self.busy and self.loaded_path == self.lmc_edit.text() and self.cbb_table.rowCount() > 0
|
||||
self.batch_button.setEnabled(ready and any(self.cbb_table.item(row, 0).text() not in self.ready_names
|
||||
and self.cbb_table.item(row, 0).text() not in self.skipped_names
|
||||
for row in range(self.cbb_table.rowCount())))
|
||||
self.selected_batch_button.setEnabled(ready and bool(self._selected_names()))
|
||||
for widget in (self.lmc_edit, self.browse_button, self.load_button, self.cbb_table,
|
||||
self.timeout_spin, self.advanced_toggle, self.advanced_panel):
|
||||
widget.setEnabled(not self.busy)
|
||||
self.stop_button.setEnabled(self.busy and self.loaded_path is not None and not self.stop.is_set())
|
||||
|
||||
def choose_library(self):
|
||||
path = QFileDialog.getOpenFileName(self, '选择中心库', '', 'LMC (*.lmc)')[0]
|
||||
if path: self.lmc_edit.setText(path); self.load_library()
|
||||
|
||||
def _start(self, action, callback):
|
||||
self.busy = True; self._update()
|
||||
self.worker = ServiceWorker(action)
|
||||
self.worker.signals.succeeded.connect(callback)
|
||||
self.worker.signals.failed.connect(self._failed)
|
||||
self.worker.signals.finished.connect(self._finished)
|
||||
self.pool.start(self.worker)
|
||||
|
||||
def load_library(self):
|
||||
if self.busy or not self.lmc_edit.text(): return
|
||||
self._release_library_lease()
|
||||
self.loaded_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {}; self.ready_names = set()
|
||||
self.skipped_names = set(); self.skip_reasons = {}
|
||||
path = self.lmc_edit.text()
|
||||
self.status_label.setText('正在读取中心库…')
|
||||
def read():
|
||||
import pythoncom
|
||||
started = time.monotonic()
|
||||
if self.logging_context:
|
||||
self.logging_context.logger.info('library_load_start path=%s', path)
|
||||
pythoncom.CoInitialize()
|
||||
try:
|
||||
lease = self.path_lease_factory(Path(path))
|
||||
mentor_path = (select_library_file(lease.mentor_path)
|
||||
if lease.mentor_path.is_dir() else lease.mentor_path)
|
||||
if self.logging_context:
|
||||
self.logging_context.logger.info(
|
||||
'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s',
|
||||
lease.display_path, mentor_path, lease.drive or '-',
|
||||
lease.remote_root or '-', lease.created)
|
||||
result = self.reader(mentor_path)
|
||||
if self.logging_context:
|
||||
statuses = Counter(record.status for record in result.records)
|
||||
unknown = [record.name for record in result.records if record.status in {'UNKNOWN', 'UNAVAILABLE'}]
|
||||
self.logging_context.logger.info(
|
||||
'library_scan_result records=%s elapsed_ms=%s statuses=%s unknown_sample=%s',
|
||||
len(result.records), int((time.monotonic() - started) * 1000),
|
||||
dict(statuses), unknown[:20])
|
||||
skip_reasons = {}
|
||||
if not result.error:
|
||||
for record in result.records:
|
||||
if record.status != 'READY':
|
||||
reason = preflight_skip_reason(mentor_path, record.name)
|
||||
if reason:
|
||||
skip_reasons[record.name] = reason
|
||||
return result, skip_reasons, lease, mentor_path
|
||||
except Exception:
|
||||
if 'lease' in locals():
|
||||
lease.close()
|
||||
raise
|
||||
finally: pythoncom.CoUninitialize()
|
||||
def loaded(payload):
|
||||
result, skip_reasons, lease, mentor_path = payload
|
||||
if path != self.lmc_edit.text():
|
||||
lease.close()
|
||||
return
|
||||
if result.error:
|
||||
lease.close()
|
||||
self.status_label.setText(result.error); return
|
||||
self.library_lease = lease
|
||||
self.mentor_lmc_path = mentor_path
|
||||
self.loaded_path = path
|
||||
self.cbb_table.setRowCount(0)
|
||||
self.ready_names = {r.name for r in result.records if r.status == 'READY'}
|
||||
self.skip_reasons = dict(skip_reasons)
|
||||
self.skipped_names = set(skip_reasons)
|
||||
# Populating a large library emits itemChanged for every cell.
|
||||
# Block those signals and refresh controls once after the batch;
|
||||
# otherwise _update() repeatedly scans the growing table (O(n^2)).
|
||||
self.cbb_table.blockSignals(True)
|
||||
self.cbb_table.setUpdatesEnabled(False)
|
||||
try:
|
||||
self.cbb_table.setRowCount(len(result.records))
|
||||
for row, record in enumerate(result.records):
|
||||
self._row_by_name[record.name] = row
|
||||
item = QTableWidgetItem(record.name)
|
||||
if record.status == 'READY' or record.name in self.skipped_names:
|
||||
# Already green: nothing left to verify, so it cannot be queued.
|
||||
item.setFlags(item.flags() & ~Qt.ItemIsUserCheckable)
|
||||
else:
|
||||
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
|
||||
item.setCheckState(Qt.Unchecked)
|
||||
self.cbb_table.setItem(row, 0, item)
|
||||
self.cbb_table.setItem(row, 1, QTableWidgetItem(record.partition_name))
|
||||
status_text = STATUS_LABELS.get(record.status, record.status)
|
||||
if record.name in self.skipped_names:
|
||||
status_text = '跳过:缺少工程/PCB'
|
||||
self.cbb_table.setItem(row, 2, QTableWidgetItem(status_text))
|
||||
# Preflight touches each CBB's project and was previously run
|
||||
# synchronously in this GUI callback, making large libraries
|
||||
# appear frozen. The verify worker performs it when queued.
|
||||
self.cbb_table.setItem(row, 3, QTableWidgetItem('未检查'))
|
||||
if record.status == 'READY':
|
||||
self._mark_row_ready(row)
|
||||
elif record.name in self.skipped_names:
|
||||
self.cbb_table.item(row, 0).setToolTip(self.skip_reasons[record.name])
|
||||
self.cbb_table.item(row, 2).setToolTip(self.skip_reasons[record.name])
|
||||
self.cbb_table.item(row, 3).setText('跳过')
|
||||
for column in range(self.cbb_table.columnCount()):
|
||||
cell = self.cbb_table.item(row, column)
|
||||
if cell is not None:
|
||||
cell.setBackground(QColor('#FFF8E1'))
|
||||
finally:
|
||||
self.cbb_table.setUpdatesEnabled(True)
|
||||
self.cbb_table.blockSignals(False)
|
||||
ready_count = len(self.ready_names)
|
||||
unavailable_count = sum(record.status == 'UNAVAILABLE' for record in result.records)
|
||||
read_error_count = sum(record.status in {'ERROR', 'TIMEOUT', 'MALFORMED', 'CRASHED'}
|
||||
for record in result.records)
|
||||
suffix = ''
|
||||
if unavailable_count:
|
||||
suffix += f' 状态桥不可用 {unavailable_count} 个。'
|
||||
if read_error_count:
|
||||
suffix += f' 状态读取失败 {read_error_count} 个。'
|
||||
self.status_label.setText(
|
||||
f'已读取 {len(result.records)} 个 CBB,其中 Ready {ready_count} 个,'
|
||||
f'缺文件跳过 {len(self.skipped_names)} 个。{suffix}')
|
||||
self._start(read, loaded)
|
||||
|
||||
def _request(self, name):
|
||||
return VerifyRequest(Path(self.mentor_lmc_path or self.loaded_path), name, self.data_root/'evidence',
|
||||
libspec=self.libspec_edit.text().strip(),
|
||||
dms_login_config=self.dms_edit.text().strip(),
|
||||
mentor_bin=self.mentor_bin_edit.text().strip(),
|
||||
mapped_drive=getattr(self.library_lease, 'drive', ''),
|
||||
mapped_remote_root=getattr(self.library_lease, 'remote_root', ''),
|
||||
timeout_seconds=self.timeout_spin.value(), logging_context=self.logging_context,
|
||||
native_lm_verify=self.native_lm_verify_check.isChecked())
|
||||
|
||||
def _selected_names(self):
|
||||
names = []
|
||||
for row in range(self.cbb_table.rowCount()):
|
||||
item = self.cbb_table.item(row, 0)
|
||||
if item and item.checkState() == Qt.Checked and (item.flags() & Qt.ItemIsUserCheckable):
|
||||
names.append(item.text())
|
||||
return names
|
||||
|
||||
def verify_selected(self):
|
||||
self._run(self._selected_names())
|
||||
|
||||
def verify_all(self):
|
||||
names = [self.cbb_table.item(row, 0).text() for row in range(self.cbb_table.rowCount())]
|
||||
self._run([name for name in names if name not in self.ready_names and name not in self.skipped_names])
|
||||
|
||||
def _run(self, names):
|
||||
if self.busy or not self.loaded_path: return
|
||||
names = [name for name in names if name not in self.ready_names and name not in self.skipped_names]
|
||||
if not names:
|
||||
self.status_label.setText('没有需要校验的 CBB(全部已经是绿色 / Ready)。')
|
||||
self._update()
|
||||
return
|
||||
requests = [self._request(name) for name in names]
|
||||
self.stop.clear(); self.recovery_path = None; self.recovery_button.setEnabled(False)
|
||||
self.output.clear(); self.status_label.setText(f'正在校验:共 {len(names)} 个 CBB')
|
||||
def action():
|
||||
from cbb_refresh_verify.verify_runner import read_library_flag_if_available, run_verify
|
||||
verifier = self.verifier or (lambda req: run_verify(
|
||||
req, progress=lambda e: self.signals.event.emit(e),
|
||||
flag_reader=read_library_flag_if_available))
|
||||
results = run_batch(requests, verifier=verifier, stop=self.stop,
|
||||
progress=lambda name, result: self.signals.event.emit({'block': name, 'stage': result.status, 'detail': result.stderr, 'evidence': str(result.evidence_path or '')}))
|
||||
report = write_batch_report(requests, results, self.data_root/'reports')
|
||||
return results, report
|
||||
self._start(action, self._batch_done)
|
||||
|
||||
def _progress(self, event):
|
||||
line = f"{event.get('block', '')} | {event.get('stage', '')}"
|
||||
for key in ('detail', 'error', 'action', 'statuses', 'evidence'):
|
||||
if event.get(key): line += f' | {event[key]}'
|
||||
self.output.append(line)
|
||||
block = event.get('block'); stage = event.get('stage')
|
||||
if block and stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED'}:
|
||||
row = self._row_by_name.get(block)
|
||||
if row is not None:
|
||||
if stage == 'PASS':
|
||||
self.cbb_table.item(row, 2).setText('绿色 / Ready')
|
||||
self.cbb_table.item(row, 3).setText('PASS')
|
||||
self.ready_names.add(block)
|
||||
self._mark_row_ready(row)
|
||||
else:
|
||||
detail = str(event.get('detail') or event.get('error') or '').strip()
|
||||
label = str(stage) if not detail else f'{stage}: {detail[:96]}'
|
||||
self.cbb_table.item(row, 3).setText(label)
|
||||
if detail:
|
||||
self.cbb_table.item(row, 3).setToolTip(detail)
|
||||
if self.logging_context: self.logging_context.logger.info('cbb_progress %s', line)
|
||||
|
||||
def _mark_row_ready(self, row):
|
||||
"""Make a verified row visibly complete and remove it from the queue."""
|
||||
name_item = self.cbb_table.item(row, 0)
|
||||
if name_item is None:
|
||||
return
|
||||
name_item.setCheckState(Qt.Unchecked)
|
||||
name_item.setFlags(name_item.flags() & ~Qt.ItemIsUserCheckable)
|
||||
for column in range(self.cbb_table.columnCount()):
|
||||
cell = self.cbb_table.item(row, column)
|
||||
if cell is not None:
|
||||
cell.setBackground(QColor('#E8F5E9'))
|
||||
|
||||
def _batch_done(self, outcome):
|
||||
results, report = outcome
|
||||
for result in results:
|
||||
if not result.safe_to_continue and result.evidence_path:
|
||||
self.recovery_path = result.evidence_path.parent
|
||||
self.recovery_button.setEnabled(self.recovery_path.is_dir())
|
||||
passed = sum(r.status == 'PASS' for r in results)
|
||||
skipped = sum(r.status == 'SKIPPED' for r in results)
|
||||
failed = len(results)-passed-skipped
|
||||
text = (f'已结束:成功 {passed},失败 {failed},预检跳过 {len(self.skipped_names)},'
|
||||
f'队列未执行 {skipped}。\n完整日志:{report}\n仅失败日志:{failure_report_path(report)}')
|
||||
self.status_label.setText(text); self.output.append(text)
|
||||
self.summary = QMessageBox(self)
|
||||
self.summary.setWindowTitle('CBB 校验结果'); self.summary.setText(text)
|
||||
self.summary.setIcon(QMessageBox.Warning if failed else QMessageBox.Information)
|
||||
# Modeless notification: do not force activation or steal keyboard focus.
|
||||
from PySide6.QtCore import Qt
|
||||
self.summary.setAttribute(Qt.WA_ShowWithoutActivating)
|
||||
self.summary.show()
|
||||
|
||||
def request_stop(self):
|
||||
self.stop.set(); self.status_label.setText('已请求停止;当前 CBB 完成或超时后停止队列。'); self._update()
|
||||
|
||||
def _failed(self, error):
|
||||
self.status_label.setText(str(error)); self.output.append(str(error))
|
||||
if self.logging_context: self.logging_context.logger.error('cbb_worker_failed %s', error)
|
||||
|
||||
def _finished(self):
|
||||
self.busy = False; self._update()
|
||||
|
||||
def open_logs(self):
|
||||
self.data_root.mkdir(parents=True, exist_ok=True); os.startfile(str(self.data_root))
|
||||
|
||||
def recover(self):
|
||||
if not self.recovery_path: return
|
||||
try: os.startfile(str(self.recovery_path))
|
||||
except Exception as error: self._failed(error)
|
||||
|
||||
def closeEvent(self, event):
|
||||
if self.busy:
|
||||
self.request_stop(); event.ignore()
|
||||
else:
|
||||
self._release_library_lease()
|
||||
event.accept()
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Small local fallback for the replacement tool's reusable Qt worker."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QObject, QRunnable, Signal, Slot
|
||||
|
||||
|
||||
class WorkerSignals(QObject):
|
||||
succeeded = Signal(object)
|
||||
failed = Signal(object)
|
||||
finished = Signal()
|
||||
|
||||
|
||||
class ServiceWorker(QRunnable):
|
||||
"""Run one callable on a QThreadPool when the shared worker is unavailable."""
|
||||
|
||||
def __init__(self, action: Callable[[], Any]) -> None:
|
||||
super().__init__()
|
||||
self.action = action
|
||||
self.signals = WorkerSignals()
|
||||
|
||||
@Slot()
|
||||
def run(self) -> None:
|
||||
try:
|
||||
self.signals.succeeded.emit(self.action())
|
||||
except Exception as error:
|
||||
self.signals.failed.emit(error)
|
||||
finally:
|
||||
self.signals.finished.emit()
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Bounded, diagnostic-only snapshots for a native Mentor Verify failure.
|
||||
|
||||
Only known paths are inspected. No database/lock repair, recursive traversal,
|
||||
or sustained file handles are allowed here. The parent repeats log collection
|
||||
once after cleanup if the worker was killed while a native file was open.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import tempfile
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
NATIVE_LOG_MAX_BYTES = 128 * 1024
|
||||
|
||||
|
||||
def _write_record(path, record):
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
except OSError as error:
|
||||
record['evidence_error'] = str(error)
|
||||
return record
|
||||
|
||||
|
||||
def _path_metadata(path, *, directory=False):
|
||||
item = {'path': str(path), 'exists': None}
|
||||
try:
|
||||
info = path.stat()
|
||||
item.update(exists=True, size_bytes=info.st_size, mtime_ns=info.st_mtime_ns)
|
||||
if directory:
|
||||
item['is_directory'] = stat.S_ISDIR(info.st_mode)
|
||||
else:
|
||||
item['readable'] = False
|
||||
if not stat.S_ISREG(info.st_mode):
|
||||
item['error'] = 'expected a regular file'
|
||||
else:
|
||||
with path.open('rb') as stream:
|
||||
stream.read(1)
|
||||
item['readable'] = True
|
||||
except FileNotFoundError:
|
||||
item['exists'] = False
|
||||
except OSError as error:
|
||||
item['error'] = str(error)
|
||||
return item
|
||||
|
||||
|
||||
def collect_preflight_diagnostics(pcb_path, evidence_root):
|
||||
"""One-shot metadata/readability and unique scratch-file writability probe.
|
||||
|
||||
Layout_Temp is generated by Mentor. Its absence is never a preflight gate.
|
||||
This runs in the supervised worker BEFORE Mentor starts, never in polling.
|
||||
"""
|
||||
directory = Path(pcb_path).parent
|
||||
paths = [_path_metadata(directory, directory=True)]
|
||||
paths.extend(_path_metadata(directory/relative) for relative in (
|
||||
'Layout/JobPrefsDB.jpf', 'Layout_Temp/JobPrefsDB.jpf',
|
||||
'Work/Layout_Temp/JobPrefsDB.jpf'))
|
||||
warnings = [f"{item['path']}: {item.get('error') or 'absent (may be generated by Mentor)'}"
|
||||
for item in paths if item['exists'] is not True or item.get('error')]
|
||||
record = {'non_blocking': True, 'paths': paths, 'warnings': warnings,
|
||||
'directory_writable': False,
|
||||
'note': 'Missing temporary JobPrefs paths are diagnostic only; no files repaired.'}
|
||||
# tempfile uses exclusive creation and delete-on-close for this new file;
|
||||
# never construct a deletion path or touch an existing library-side file.
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(mode='wb', prefix='.cbb-verify-write-probe-',
|
||||
suffix='.tmp', dir=directory):
|
||||
pass
|
||||
record['directory_writable'] = True
|
||||
except OSError as error:
|
||||
record['directory_write_error'] = str(error)
|
||||
warnings.append(f'{directory}: create/close write probe failed: {error}')
|
||||
return _write_record(Path(evidence_root)/'diagnostics/preflight.json', record)
|
||||
|
||||
|
||||
def collect_native_failure_logs(pcb_path, evidence_root, *, max_bytes=NATIVE_LOG_MAX_BYTES):
|
||||
"""Copy the last bounded bytes of known logs, preserving native multi-line text.
|
||||
|
||||
Evidence is binary so native ANSI/UTF-16 encodings are not damaged. Each
|
||||
original path/size/truncation/error is recorded in a UTF-8 JSON manifest.
|
||||
Native sources are opened read-only and promptly closed, never modified.
|
||||
"""
|
||||
pcb_directory = Path(pcb_path).parent
|
||||
destination = Path(evidence_root)/'diagnostics/native-logs'
|
||||
record = {'non_blocking': True, 'collected_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'max_bytes_per_file': max(1, min(int(max_bytes), 256 * 1024)), 'files': []}
|
||||
try:
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as error:
|
||||
record['evidence_error'] = str(error)
|
||||
return record
|
||||
sources = [('pcb-logfiles', pcb_directory/'LogFiles'/name)
|
||||
for name in ('PCBLogFile.txt', 'ForwardAnnotation.txt', 'PartPkg.log',
|
||||
'MsgBoxResponse.log', 'ReusableBlock.txt')]
|
||||
sources.extend((('pcb-root', pcb_directory/'PCBLogFile.txt'),
|
||||
('pcb-root', pcb_directory/'ReusableBlock.txt'),
|
||||
('work-root', pcb_directory.parent/'ReusableBlock.txt')))
|
||||
for label, source in sources:
|
||||
item = {'source': str(source), 'exists': None}
|
||||
record['files'].append(item)
|
||||
try:
|
||||
with source.open('rb') as stream:
|
||||
stream.seek(0, os.SEEK_END)
|
||||
size = stream.tell()
|
||||
item['mtime_ns'] = os.fstat(stream.fileno()).st_mtime_ns
|
||||
stream.seek(max(0, size-record['max_bytes_per_file']))
|
||||
data = stream.read(record['max_bytes_per_file'])
|
||||
item.update(exists=True, original_size_bytes=size,
|
||||
truncated=size > record['max_bytes_per_file'])
|
||||
target = destination/(label+'-'+source.name)
|
||||
target.write_bytes(data)
|
||||
item.update(evidence=str(target), copied_bytes=len(data))
|
||||
except FileNotFoundError:
|
||||
item['exists'] = False
|
||||
except OSError as error:
|
||||
item['error'] = str(error)
|
||||
return _write_record(destination.parent/'native-logs.json', record)
|
||||
|
||||
|
||||
|
||||
def failure_logs_main(request_path):
|
||||
job = json.loads(Path(request_path).read_text(encoding='utf-8'))
|
||||
collect_native_failure_logs(job['pcb'], job['root'])
|
||||
return 0
|
||||
|
||||
|
||||
def capture_failure_logs_with_timeout(request_path, *, timeout_seconds=8):
|
||||
"""Post-cleanup retry in a killable helper, not a potentially stuck SMB thread."""
|
||||
request_path = Path(request_path)
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||
[sys.executable, '-m', 'cbb_refresh_verify'])
|
||||
command += ['--collect-failure-logs', str(request_path)]
|
||||
record = {'status': 'ERROR', 'timeout_seconds': timeout_seconds}
|
||||
try:
|
||||
outcome = subprocess.run(command, capture_output=True, timeout=timeout_seconds,
|
||||
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
record.update(status='COMPLETE' if outcome.returncode == 0 else 'ERROR',
|
||||
exit_code=outcome.returncode)
|
||||
if outcome.stderr:
|
||||
record['error'] = outcome.stderr[-4096:].decode('utf-8', errors='replace')
|
||||
except subprocess.TimeoutExpired:
|
||||
# subprocess.run kills and reaps this child; it never launches children.
|
||||
record.update(status='TIMEOUT', error='Native log collection budget exceeded; original Verify result unchanged.')
|
||||
except OSError as error:
|
||||
record['error'] = str(error)
|
||||
return _write_record(request_path.parent/'diagnostics/native-log-capture.json', record)
|
||||
@@ -0,0 +1,156 @@
|
||||
"""Read-only probe for Mentor's private CBB Verify exports.
|
||||
|
||||
The probe deliberately stops at export discovery. It never calls
|
||||
``VerifyReuseBlock`` or ``UnVerifyReuseBlock`` because those functions use a
|
||||
private 32-bit MFC ``CFilename`` ABI that has not been reconstructed safely.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import Any, Mapping
|
||||
|
||||
|
||||
KNOWN_EXPORTS = (
|
||||
"IsVerifiedReuseBlock",
|
||||
"GetStatusRBInContextOfCL",
|
||||
"VerifyReuseBlock",
|
||||
"UnVerifyReuseBlock",
|
||||
"GetReusableCircuitVerificationStatus",
|
||||
)
|
||||
|
||||
|
||||
class ProbeResponseError(ValueError):
|
||||
"""The helper returned a response outside the probe contract."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExportInfo:
|
||||
name: str
|
||||
found: bool
|
||||
address: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExportProbeResult:
|
||||
dll_path: str
|
||||
architecture: str
|
||||
exports: tuple[ExportInfo, ...]
|
||||
write_enabled: bool
|
||||
write_reason: str
|
||||
response: Mapping[str, Any]
|
||||
|
||||
def export(self, name: str) -> ExportInfo:
|
||||
for item in self.exports:
|
||||
if item.name == name:
|
||||
return item
|
||||
raise KeyError(name)
|
||||
|
||||
|
||||
def _require_mapping(value: Any, label: str) -> Mapping[str, Any]:
|
||||
if not isinstance(value, Mapping):
|
||||
raise ProbeResponseError(f"探测响应字段 {label} 不是对象")
|
||||
return value
|
||||
|
||||
|
||||
def parse_export_probe(raw: str) -> ExportProbeResult:
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
except json.JSONDecodeError as error:
|
||||
raise ProbeResponseError(f"探测响应不是 JSON: {error}") from error
|
||||
payload = _require_mapping(payload, "root")
|
||||
if payload.get("ok") is not True or payload.get("probe") != "exports":
|
||||
raise ProbeResponseError(str(payload.get("error") or "导出探测失败"))
|
||||
architecture = str(payload.get("architecture") or "").lower()
|
||||
if architecture != "x86":
|
||||
raise ProbeResponseError(f"导出探测桥架构异常: {architecture or 'empty'}")
|
||||
dll_path = str(payload.get("dll_path") or "").strip()
|
||||
if not dll_path:
|
||||
raise ProbeResponseError("导出探测未返回 DLL 路径")
|
||||
|
||||
write_call = _require_mapping(payload.get("write_call"), "write_call")
|
||||
enabled = write_call.get("enabled")
|
||||
if enabled is not False:
|
||||
raise ProbeResponseError("写接口探测桥不能启用写调用")
|
||||
reason = str(write_call.get("reason") or "").strip()
|
||||
if not reason:
|
||||
raise ProbeResponseError("写接口探测必须说明未启用原因")
|
||||
|
||||
raw_exports = _require_mapping(payload.get("exports"), "exports")
|
||||
exports: list[ExportInfo] = []
|
||||
for name in KNOWN_EXPORTS:
|
||||
item = _require_mapping(raw_exports.get(name), f"exports.{name}")
|
||||
found = item.get("found")
|
||||
if not isinstance(found, bool):
|
||||
raise ProbeResponseError(f"导出 {name} 的 found 字段非法")
|
||||
address = str(item.get("address") or "")
|
||||
if found and not address:
|
||||
raise ProbeResponseError(f"导出 {name} 已找到但没有地址")
|
||||
exports.append(ExportInfo(name=name, found=found, address=address))
|
||||
|
||||
return ExportProbeResult(
|
||||
dll_path=dll_path,
|
||||
architecture=architecture,
|
||||
exports=tuple(exports),
|
||||
write_enabled=False,
|
||||
write_reason=reason,
|
||||
response=dict(payload),
|
||||
)
|
||||
|
||||
|
||||
def default_probe_path() -> Path:
|
||||
configured = os.environ.get("CBB_VERIFY_PROBE", "").strip()
|
||||
if configured:
|
||||
return Path(configured).expanduser()
|
||||
package_root = Path(__file__).resolve().parent
|
||||
frozen_root = Path(getattr(sys, "_MEIPASS", package_root))
|
||||
candidates = (
|
||||
package_root / "verify_probe32.exe",
|
||||
package_root / "bridge" / "VerifyProbe32.exe",
|
||||
Path(sys.executable).resolve().parent / "tools" / "status_bridge" / "bin" / "VerifyProbe32.exe",
|
||||
frozen_root / "tools" / "status_bridge" / "bin" / "VerifyProbe32.exe",
|
||||
package_root.parent.parent / "tools" / "status_bridge" / "bin" / "VerifyProbe32.exe",
|
||||
)
|
||||
for candidate in candidates:
|
||||
if candidate.is_file():
|
||||
return candidate
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def probe_exports(
|
||||
executable: Path | None = None,
|
||||
*,
|
||||
env: Mapping[str, str] | None = None,
|
||||
timeout_seconds: float = 10,
|
||||
) -> ExportProbeResult:
|
||||
helper = Path(executable) if executable is not None else default_probe_path()
|
||||
if not helper.is_file():
|
||||
raise FileNotFoundError(f"找不到 Verify 导出探测桥: {helper}")
|
||||
child_env = os.environ.copy()
|
||||
child_env.update(dict(env or {}))
|
||||
try:
|
||||
process = subprocess.run(
|
||||
[str(helper), "--probe-exports"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
timeout=max(0.1, float(timeout_seconds)),
|
||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||
env=child_env,
|
||||
check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired as error:
|
||||
raise ProbeResponseError("导出探测桥响应超时") from error
|
||||
lines = [line.strip() for line in process.stdout.splitlines() if line.strip()]
|
||||
if process.returncode != 0:
|
||||
detail = (process.stderr or process.stdout).strip() or f"退出码 {process.returncode}"
|
||||
raise ProbeResponseError(f"导出探测桥失败: {detail}")
|
||||
if not lines:
|
||||
raise ProbeResponseError("导出探测桥没有返回 JSON")
|
||||
return parse_export_probe(lines[0])
|
||||
@@ -0,0 +1,970 @@
|
||||
"""Serial Verify supervisor.
|
||||
|
||||
Each CBB gets one isolated, bounded automation worker on a private Windows
|
||||
desktop. The worker reproduces the observed refresh flow: invoke the CBB's
|
||||
native Library Manager Verify action, bind the resulting ReusableCircuit PCB,
|
||||
verify the document identity, run Project Integration, save the Reusable Block
|
||||
cell and close. Optionally the official
|
||||
``ReuseBlockImporter.exe -chkContents`` check runs first when a LibSpec and a
|
||||
DMS login configuration are supplied.
|
||||
|
||||
Nothing here injects mouse or keyboard input or edits the central library. The
|
||||
native menu invocation happens on the worker's private desktop.
|
||||
"""
|
||||
from dataclasses import asdict, dataclass, field, replace
|
||||
from pathlib import Path
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from .network_path import absolute_preserving_drive
|
||||
from .runtime_timing import RunTimings
|
||||
from .defaults import DEFAULT_TIMEOUT_SECONDS
|
||||
|
||||
SUCCESS_TEXT = re.compile(r'content checking completed successfully', re.IGNORECASE)
|
||||
ERROR_TEXT = re.compile(r'failed|error|cannot connect|bad data', re.IGNORECASE)
|
||||
INVALID_NAME_CHARS = '\\/:*?"<>|'
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VerifyRequest:
|
||||
lmc_file: Path
|
||||
block_name: str
|
||||
evidence_dir: Path
|
||||
libspec: str = ''
|
||||
dms_login_config: str = ''
|
||||
mentor_bin: str = ''
|
||||
# PCB startup on EE7.9 includes iCDB recovery and COM registration. The
|
||||
# previous 30-second UI default was shorter than the observed startup
|
||||
# window on this machine and caused a false timeout before document attach.
|
||||
timeout_seconds: int = DEFAULT_TIMEOUT_SECONDS
|
||||
logging_context: object | None = None
|
||||
# The production default stays on an isolated desktop. The explicit
|
||||
# interactive mode is reserved for a real-input compatibility test on
|
||||
# machines where EE7.9 cannot dispatch the tree menu on a private desktop.
|
||||
interactive_input: bool = False
|
||||
# The native Library Manager menu route is opt-in until a machine's menu
|
||||
# dispatch has been proven. The flag is serialized to the worker so a
|
||||
# Win10 compatibility run can select it explicitly.
|
||||
native_lm_verify: bool = False
|
||||
# A reserved iCDB range is a host-wide prerequisite failure. Do not
|
||||
# launch a PCB that is guaranteed to time out; batch orchestration will
|
||||
# record this item and continue with the next one.
|
||||
strict_port_check: bool = True
|
||||
# A mapped drive can be invisible to an elevated/private worker on Win10.
|
||||
# Preserve the parent session's mapping identity so the worker can restore
|
||||
# it before launching Library Manager/PCB.
|
||||
mapped_drive: str = ''
|
||||
mapped_remote_root: str = ''
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VerifyResult:
|
||||
status: str
|
||||
stderr: str = ''
|
||||
stdout: str = ''
|
||||
evidence_path: Path | None = None
|
||||
safe_to_continue: bool = True
|
||||
library_flag: str = 'UNKNOWN'
|
||||
library_flag_detail: str = ''
|
||||
report_path: Path | None = None
|
||||
content_check_exit_code: int | None = None
|
||||
error_category: str = ""
|
||||
error_stage: str = ""
|
||||
bridge_attempts: tuple[dict, ...] = ()
|
||||
timings_seconds: dict[str, float] = field(default_factory=dict)
|
||||
incomplete_timing_phases: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def resolve_importer(mentor_bin: str | None = None) -> Path:
|
||||
"""Configured bin first, then the EE7.9.5 environment defaults."""
|
||||
candidates = []
|
||||
if mentor_bin:
|
||||
configured = Path(mentor_bin)
|
||||
if configured.is_file() and configured.name.casefold() == 'reuseblockimporter.exe':
|
||||
candidates.append(configured.parent)
|
||||
else:
|
||||
candidates.append(configured)
|
||||
if configured.name.casefold() == 'sdd_home':
|
||||
candidates.append(configured / 'lm' / 'win32' / 'bin')
|
||||
from .mentor_paths import discover_sdd_home
|
||||
discovered = discover_sdd_home(mentor_bin)
|
||||
if discovered is not None:
|
||||
candidates.append(discovered / 'lm' / 'win32' / 'bin')
|
||||
for variable in ('SDD_LM_BIN', 'SDD_HOME'):
|
||||
value = os.environ.get(variable)
|
||||
if not value:
|
||||
continue
|
||||
root = Path(value)
|
||||
candidates.append(root if root.name.lower() == 'bin' else root/'lm'/'win32'/'bin')
|
||||
candidates.append(Path(r'D:\Mentor\7.9.5EE\SDD_HOME\lm\win32\bin'))
|
||||
for candidate in candidates:
|
||||
executable = candidate/'ReuseBlockImporter.exe'
|
||||
if executable.is_file():
|
||||
return executable
|
||||
raise ValueError('ReuseBlockImporter.exe 未找到;请设置 SDD_LM_BIN')
|
||||
|
||||
|
||||
def build_content_check_command(request, executable) -> tuple[str, ...]:
|
||||
"""The documented Logical-Physical contents check invocation."""
|
||||
return (str(executable), '-lmcFile', str(request.lmc_file), '-blockName', request.block_name,
|
||||
'-logicalType', 'LP', '-chkContents', '-libSpec', str(request.libspec),
|
||||
'-dmsLoginConfig', str(request.dms_login_config))
|
||||
|
||||
|
||||
def contents_report_path(lmc_file, block_name) -> Path:
|
||||
safe_name = re.sub(f'[{re.escape(INVALID_NAME_CHARS)}]', '_', str(block_name))
|
||||
return Path(lmc_file).parent/'LogFiles'/f'restorerb_RULP_{safe_name}_contents.log'
|
||||
|
||||
|
||||
def classify_output(exit_code: int | None, output: str, *, timed_out: bool = False) -> str:
|
||||
"""Never invent success: PASS needs the success text and no error marker."""
|
||||
if timed_out:
|
||||
return 'TIMEOUT'
|
||||
if SUCCESS_TEXT.search(output) and not ERROR_TEXT.search(output):
|
||||
return 'PASS'
|
||||
if ERROR_TEXT.search(output):
|
||||
return 'FAIL'
|
||||
if exit_code not in (None, 0):
|
||||
return 'FAIL'
|
||||
return 'UNKNOWN'
|
||||
|
||||
|
||||
def preflight(request):
|
||||
"""Validate the library entry and its ReusableCircuit sources before launch."""
|
||||
library = absolute_preserving_drive(request.lmc_file)
|
||||
name = request.block_name
|
||||
if not name or name in ('.', '..') or any(character in name for character in INVALID_NAME_CHARS):
|
||||
raise ValueError('CBB 名称非法')
|
||||
if not library.is_file():
|
||||
raise ValueError(f'中心库不存在: {library}')
|
||||
work = library.parent/'ReusableBlocksLP'/name/'Work'
|
||||
projects = list(work.glob('*.prj'))
|
||||
if len(projects) != 1:
|
||||
raise ValueError(f'{name}: 缺少或无法唯一确定 Work 下的工程 PRJ')
|
||||
project = absolute_preserving_drive(projects[0])
|
||||
content = project.read_text(encoding='utf-8', errors='replace')
|
||||
refs = re.findall(r'^KEY PCBDesignPath "([^"]+)"', content, re.M)
|
||||
if not refs:
|
||||
raise ValueError(f'{name}: 工程没有 PCBDesignPath')
|
||||
pcb = absolute_preserving_drive(project.parent/refs[0])
|
||||
if not pcb.is_relative_to(absolute_preserving_drive(work)):
|
||||
raise ValueError(f'{name}: PCB 引用越出当前 CBB,停止操作: {pcb}')
|
||||
if not pcb.is_file() or not (pcb.parent/'Layout'/'LayoutDB.lyt').is_file():
|
||||
raise ValueError(f'{name}: 缺少 PCB 或布局数据库: {pcb}')
|
||||
return project, pcb
|
||||
|
||||
|
||||
def preflight_skip_reason(lmc_file, block_name):
|
||||
"""Return a user-facing skip reason for an import-incomplete CBB.
|
||||
|
||||
This is intentionally narrower than ``preflight``: only local source
|
||||
structure problems are excluded before a batch starts. Runtime failures
|
||||
such as ports, DMS, COM, or Project Integration remain normal per-item
|
||||
failures and are still attempted when the user queues them.
|
||||
"""
|
||||
library = absolute_preserving_drive(lmc_file)
|
||||
if not library.is_file():
|
||||
return ''
|
||||
work = library.parent / 'ReusableBlocksLP' / str(block_name) / 'Work'
|
||||
if not work.is_dir():
|
||||
return ''
|
||||
request = VerifyRequest(library, str(block_name), library.parent / '.cbb-preflight-evidence')
|
||||
try:
|
||||
preflight(request)
|
||||
except Exception as error:
|
||||
detail = str(error)
|
||||
if any(marker in detail for marker in ('缺少或无法唯一确定 Work 下的工程 PRJ',
|
||||
'工程没有 PCBDesignPath',
|
||||
'缺少 PCB 或布局数据库')):
|
||||
return detail
|
||||
return ''
|
||||
|
||||
|
||||
def _run_process(command, timeout_seconds, cwd):
|
||||
"""Run the importer, draining both pipes while it works (no pipe deadlock)."""
|
||||
process = subprocess.Popen(command, cwd=str(cwd), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
try:
|
||||
stdout, stderr = process.communicate(timeout=timeout_seconds)
|
||||
return process.returncode, stdout.decode('utf-8', errors='replace'), stderr.decode('utf-8', errors='replace'), False
|
||||
except subprocess.TimeoutExpired:
|
||||
# A timed-out importer may have spawned a child that still owns the
|
||||
# pipes. Bound both tree termination and the final drain so a hung
|
||||
# helper cannot turn a 30-second item timeout into an unbounded wait.
|
||||
try:
|
||||
subprocess.run(['taskkill', '/PID', str(process.pid), '/T', '/F'],
|
||||
capture_output=True, timeout=5,
|
||||
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
try:
|
||||
process.kill()
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
stdout, stderr = process.communicate(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
stdout, stderr = b'', b''
|
||||
return None, stdout.decode('utf-8', errors='replace'), stderr.decode('utf-8', errors='replace'), True
|
||||
|
||||
|
||||
def _stop_worker(process, *, timeout=5):
|
||||
"""Best-effort worker tree termination that never masks the item result."""
|
||||
try:
|
||||
process.kill()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
process.wait(timeout=timeout)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _normalize_bridge_result(probe):
|
||||
from .status_bridge import BridgeResult
|
||||
if not isinstance(probe, BridgeResult):
|
||||
detail = str(probe[1]) if isinstance(probe, tuple) and len(probe) > 1 else str(probe)
|
||||
return BridgeResult('MALFORMED', '', None,
|
||||
'BRIDGE_RESULT_INVALID: 非权威桥接器结果;' + detail)
|
||||
if probe.status in {'READY', 'PENDING'} and (
|
||||
probe.source != 'IsVerifiedReuseBlock'
|
||||
or probe.raw_status != (1 if probe.status == 'READY' else 0)):
|
||||
return BridgeResult('MALFORMED', probe.source, probe.raw_status,
|
||||
'BRIDGE_RESULT_INVALID: status/source/raw_status 不一致')
|
||||
return probe
|
||||
|
||||
|
||||
def read_library_flag_with_retry(reader, library, block_name, *, attempts=3,
|
||||
delays=(0.0, 3.0, 5.0), sleep=None, on_attempt=None):
|
||||
"""Bounded read-only bridge retries; never repeat Verify or promote PENDING."""
|
||||
from .status_bridge import BridgeResult
|
||||
sleep = sleep or time.sleep
|
||||
last = BridgeResult('UNAVAILABLE', '', None, '状态桥没有返回结果')
|
||||
for index in range(max(1, int(attempts))):
|
||||
if index > 0:
|
||||
delay = delays[min(index, len(delays)-1)] if delays else 0
|
||||
sleep(max(0.0, float(delay)))
|
||||
started = time.monotonic()
|
||||
try:
|
||||
last = _normalize_bridge_result(reader(library, block_name))
|
||||
except Exception as error:
|
||||
last = BridgeResult('UNAVAILABLE', '', None, 'BRIDGE_UNAVAILABLE: ' + str(error))
|
||||
if on_attempt:
|
||||
on_attempt({'attempt': index + 1, 'status': last.status,
|
||||
'source': last.source, 'raw_status': last.raw_status,
|
||||
'detail': last.detail,
|
||||
'query_seconds': round(time.monotonic()-started, 6)})
|
||||
if last.status in {'READY', 'MALFORMED'}:
|
||||
return last
|
||||
return last
|
||||
|
||||
|
||||
def classify_failure_category(detail):
|
||||
text = str(detail or '')
|
||||
lower = text.casefold()
|
||||
if 'tf_floatinglangbar_wndtitle' in lower or 'cicerouiwndframe' in lower:
|
||||
return 'TOOL_FALSE_DIALOG'
|
||||
if 'could not load job preferences db' in lower or 'unable to create local cell library' in lower:
|
||||
return 'MENTOR_LOCAL_CELL_LIBRARY'
|
||||
if ('database_load_failed' in lower
|
||||
or 'problem encountered while opening one of the database files' in lower
|
||||
or 'database load is being terminated' in lower):
|
||||
return 'MENTOR_DATABASE_LOAD_FAILED'
|
||||
if 'project integration error' in lower or 'project_integration_failed' in lower:
|
||||
return 'MENTOR_PROJECT_INTEGRATION'
|
||||
if 'save_reusable_block_failed' in lower or 'error saving the reusable block' in lower:
|
||||
return 'MENTOR_SAVE_FAILED'
|
||||
if 'design_server_failed' in lower or 'could not run server' in lower or 'could not bring it alive' in lower:
|
||||
return 'ENVIRONMENT_DESIGN_SERVER'
|
||||
if 'bridge_unavailable' in lower or '权威状态读取失败' in text:
|
||||
return 'BRIDGE_UNAVAILABLE'
|
||||
if 'bridge_result_invalid' in lower:
|
||||
return 'BRIDGE_RESULT_INVALID'
|
||||
if 'pending' in lower and 'isverifiedreuseblock' in lower:
|
||||
return 'MENTOR_VERIFY_NOT_COMMITTED'
|
||||
if 'cert' in lower and ('incomplete' in lower or '成果' in text):
|
||||
return 'TOOL_CERT_DIAGNOSTIC'
|
||||
if 'unknown_dialog' in lower or 'dialog' in lower:
|
||||
return 'TOOL_DIALOG_SUPERVISOR'
|
||||
if 'timeout' in lower or '超时' in text:
|
||||
return 'TOOL_TIMEOUT'
|
||||
return 'UNCLASSIFIED'
|
||||
|
||||
|
||||
def read_library_flag_if_available(library, block_name):
|
||||
"""Read the authoritative Mentor Verify state through the x86 bridge.
|
||||
|
||||
Unit tests replace this external boundary; production never accepts Cert
|
||||
files or legacy tree readers as a substitute for this gold standard.
|
||||
"""
|
||||
from .status_bridge import StatusBridgeClient
|
||||
return StatusBridgeClient(
|
||||
env={'CBB_STATUS_BRIDGE_ALLOW_PRIVATE': '1'}
|
||||
).query(Path(library), block_name)
|
||||
|
||||
|
||||
def apply_post_verify_status(result, bridge_result):
|
||||
"""Only the authoritative bridge can confirm READY, never a Cert/tuple/icon."""
|
||||
if result.status != 'PASS':
|
||||
return result # a pre-existing READY cannot erase a real execution error
|
||||
bridge_result = _normalize_bridge_result(bridge_result)
|
||||
if bridge_result.status == 'READY':
|
||||
return replace(result, library_flag='GREEN', library_flag_detail=(
|
||||
f'READY ({bridge_result.source}, raw={bridge_result.raw_status})'))
|
||||
detail = bridge_result.detail or (
|
||||
f'执行已完成,但权威状态仍为 {bridge_result.status} '
|
||||
f'({bridge_result.source}, raw={bridge_result.raw_status})')
|
||||
pending = bridge_result.status == 'PENDING'
|
||||
return replace(result, status='FAIL',
|
||||
stderr='\n'.join(part for part in (result.stderr, detail) if part),
|
||||
library_flag='NOT_GREEN' if pending else 'UNKNOWN', library_flag_detail=detail,
|
||||
error_category=('MENTOR_VERIFY_NOT_COMMITTED' if pending else
|
||||
'BRIDGE_RESULT_INVALID' if bridge_result.status == 'MALFORMED' else 'BRIDGE_UNAVAILABLE'),
|
||||
error_stage='library_flag', safe_to_continue=True)
|
||||
|
||||
|
||||
def worker_command(request_path):
|
||||
if getattr(sys, 'frozen', False):
|
||||
return [sys.executable, '--verify-worker', str(request_path)]
|
||||
return [sys.executable, '-m', 'cbb_refresh_verify', '--verify-worker', str(request_path)]
|
||||
|
||||
|
||||
def phase_for_event(event, current=None):
|
||||
from .dialog_models import DialogPhase
|
||||
|
||||
stage = str(event.get('stage', ''))
|
||||
mapping = {
|
||||
'lm_launch': DialogPhase.PCB_STARTING,
|
||||
'lm_started': DialogPhase.PCB_STARTING,
|
||||
'lm_ready': DialogPhase.PCB_STARTING,
|
||||
'lm_session_ready': DialogPhase.PCB_STARTING,
|
||||
'verify_invoke': DialogPhase.PCB_STARTING,
|
||||
'verify_invoke_returned': DialogPhase.PCB_STARTING,
|
||||
'pcb_launch': DialogPhase.PCB_STARTING,
|
||||
'pcb_started': DialogPhase.PCB_STARTING,
|
||||
'com_wait': DialogPhase.DOCUMENT_ATTACH,
|
||||
'identity_wait': DialogPhase.DOCUMENT_ATTACH,
|
||||
'identity_verified': DialogPhase.IDENTITY_CHECK,
|
||||
'license_key_requested': DialogPhase.LICENSE_ACQUISITION,
|
||||
'license_token_received': DialogPhase.LICENSE_ACQUISITION,
|
||||
'document_validated': DialogPhase.VALIDATE,
|
||||
'integration_status': DialogPhase.PROJECT_INTEGRATION,
|
||||
'integration_action': DialogPhase.PROJECT_INTEGRATION,
|
||||
'integration_error': DialogPhase.PROJECT_INTEGRATION,
|
||||
'save_start': DialogPhase.SAVE,
|
||||
'save_helper': DialogPhase.SAVE,
|
||||
'save_progress': DialogPhase.SAVE,
|
||||
'save_quit_recovered': DialogPhase.CLOSE,
|
||||
'saved_and_closed': DialogPhase.CLOSE,
|
||||
'pcb_exit_recovered': DialogPhase.CLOSE,
|
||||
'complete': DialogPhase.CLOSE,
|
||||
}
|
||||
return mapping.get(stage, current or DialogPhase.PCB_STARTING)
|
||||
|
||||
|
||||
def classify_verify_dispatch(*, verify_invoked, invoke_returned, target_pid, observation):
|
||||
"""Classify a returned Verify command that never started its PCB.
|
||||
|
||||
UI Automation can report a successful ``InvokePattern`` call even when
|
||||
Library Manager only closed the popup and did not dispatch its native MFC
|
||||
command. A returned menu call is therefore not a success signal. Keep
|
||||
this predicate small and evidence based so the supervisor can distinguish
|
||||
a dispatch failure from a generic inactivity timeout without changing the
|
||||
underlying automation route.
|
||||
"""
|
||||
if not (verify_invoked and invoke_returned) or target_pid is not None:
|
||||
return None
|
||||
return (
|
||||
'FAIL',
|
||||
'VERIFY_DISPATCH_FAILED: LMC Verify 菜单调用已返回,但未启动目标 ReusableCircuit PCB',
|
||||
)
|
||||
|
||||
|
||||
def _write_failure_windows(root, snapshots):
|
||||
if not snapshots:
|
||||
return
|
||||
records = [dict(time=time.strftime('%Y-%m-%d %H:%M:%S'), **snapshot.to_record())
|
||||
for snapshot in snapshots]
|
||||
(root/'window_snapshots.jsonl').write_text(
|
||||
''.join(json.dumps(record, ensure_ascii=False) + '\n' for record in records), encoding='utf-8')
|
||||
|
||||
|
||||
def _write_process_tree(root, process, target_pid):
|
||||
record = {
|
||||
'time': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'worker_pid': getattr(process, 'pid', None),
|
||||
'companion_pids': list(getattr(process, 'companion_pids', ())),
|
||||
'pcb_pid': target_pid,
|
||||
}
|
||||
temporary = root/'process_tree.json.tmp'
|
||||
temporary.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
temporary.replace(root/'process_tree.json')
|
||||
|
||||
|
||||
def runtime_fingerprint(mentor_bin=''):
|
||||
"""Return host/runtime facts needed to compare Win10 and Win11 runs."""
|
||||
result = {
|
||||
'platform': platform.platform(),
|
||||
'system': platform.system(),
|
||||
'release': platform.release(),
|
||||
'version': platform.version(),
|
||||
'machine': platform.machine(),
|
||||
'python_version': platform.python_version(),
|
||||
'python_bitness': struct.calcsize('P') * 8,
|
||||
'mentor_bin': str(mentor_bin or ''),
|
||||
'uia_backend': 'pywinauto.win32',
|
||||
}
|
||||
if os.name == 'nt':
|
||||
try:
|
||||
import winreg
|
||||
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
|
||||
r'SOFTWARE\Microsoft\Windows NT\CurrentVersion') as key:
|
||||
for name, output_name in (
|
||||
('ProductName', 'windows_product_name'),
|
||||
('CurrentBuild', 'windows_current_build'),
|
||||
('UBR', 'windows_ubr'),
|
||||
):
|
||||
try:
|
||||
result[output_name] = winreg.QueryValueEx(key, name)[0]
|
||||
except OSError:
|
||||
pass
|
||||
except (ImportError, OSError):
|
||||
pass
|
||||
result['windows_build_family'] = windows_build_family(
|
||||
result.get('windows_current_build'))
|
||||
from .mentor_paths import describe_installation, discover_sdd_home
|
||||
result['mentor_installation'] = describe_installation(
|
||||
discover_sdd_home(mentor_bin))
|
||||
return result
|
||||
|
||||
|
||||
def windows_build_family(build):
|
||||
"""Classify Windows from the build number, not ProductName.
|
||||
|
||||
Windows 11 commonly keeps ``ProductName=Windows 10 Pro`` for
|
||||
compatibility. The first public Windows 11 build is 22000, so the build
|
||||
number is the stable discriminator for compatibility reports.
|
||||
"""
|
||||
try:
|
||||
number = int(str(build or '').split('.', 1)[0])
|
||||
except (TypeError, ValueError):
|
||||
return 'unknown'
|
||||
if number >= 22000:
|
||||
return 'Windows 11'
|
||||
if number >= 10240:
|
||||
return 'Windows 10'
|
||||
return 'unknown'
|
||||
|
||||
|
||||
def native_lm_verify_enabled():
|
||||
"""Read the explicit compatibility switch for the native LM route."""
|
||||
return os.environ.get('CBB_NATIVE_LM_VERIFY', '').strip().casefold() in {
|
||||
'1', 'true', 'yes', 'on',
|
||||
}
|
||||
|
||||
|
||||
def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline,
|
||||
progress=None):
|
||||
"""Reap Mentor processes after the worker can no longer run its ``finally``.
|
||||
|
||||
The outer supervisor owns the worker lifetime. A timeout or an unknown
|
||||
dialog may therefore terminate the worker while its child LMC/PCB processes
|
||||
remain alive. Delegate the same target-filtered cleanup used by the worker
|
||||
and persist its events before the batch advances.
|
||||
"""
|
||||
from .mentor_adapter import cleanup_verify_processes
|
||||
|
||||
event_path = Path(root) / 'events.jsonl'
|
||||
|
||||
def emit(**event):
|
||||
event = {
|
||||
'time': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'source': 'supervisor_cleanup',
|
||||
**event,
|
||||
}
|
||||
try:
|
||||
with event_path.open('a', encoding='utf-8') as stream:
|
||||
stream.write(json.dumps(event, ensure_ascii=False) + '\n')
|
||||
except OSError:
|
||||
pass
|
||||
if progress:
|
||||
progress(event)
|
||||
|
||||
cleanup_verify_processes(
|
||||
lm_pid,
|
||||
target_pid,
|
||||
None,
|
||||
expected_pcb=pcb,
|
||||
baseline_pids=pcb_baseline,
|
||||
emit=emit,
|
||||
)
|
||||
|
||||
|
||||
def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None,
|
||||
dialog_supervisor_factory=None):
|
||||
timing = RunTimings()
|
||||
result = _run_verify(request, timing=timing, progress=progress, flag_reader=flag_reader,
|
||||
process_runner=process_runner, port_check=port_check,
|
||||
dialog_supervisor_factory=dialog_supervisor_factory)
|
||||
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'} and result.evidence_path:
|
||||
job_path = result.evidence_path.with_name('request.json')
|
||||
if job_path.is_file():
|
||||
timing.begin('failure_diagnostics')
|
||||
try:
|
||||
from .verify_diagnostics import capture_failure_logs_with_timeout
|
||||
capture_failure_logs_with_timeout(job_path)
|
||||
except Exception:
|
||||
# Never replace the underlying Mentor/bridge/timeout failure.
|
||||
pass
|
||||
finally:
|
||||
timing.end('failure_diagnostics')
|
||||
durations, unfinished = timing.snapshot()
|
||||
result = replace(result, timings_seconds=durations, incomplete_timing_phases=unfinished,
|
||||
error_category=(result.error_category or classify_failure_category(result.stderr)
|
||||
if result.status not in {"PASS", "SKIPPED"} else ""),
|
||||
error_stage=(result.error_stage or (unfinished[-1] if unfinished else 'execution')
|
||||
if result.status not in {"PASS", "SKIPPED"} else ""))
|
||||
if result.evidence_path:
|
||||
result.evidence_path.write_text(json.dumps(
|
||||
{'block_name': request.block_name, **asdict(result)},
|
||||
ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
result.evidence_path.with_name('performance.json').write_text(json.dumps({
|
||||
'block_name': request.block_name, 'status': result.status,
|
||||
'unit': 'seconds', 'timings_seconds': durations,
|
||||
'incomplete_timing_phases': unfinished,
|
||||
'clock': 'monotonic; save helper subphases: VBScript Timer (midnight adjusted)',
|
||||
'notes': 'phase totals overlap action/call subphases; skipped phases are absent',
|
||||
}, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
if progress:
|
||||
progress({'stage': 'performance', 'block': request.block_name,
|
||||
'timings_seconds': durations, 'incomplete_timing_phases': unfinished,
|
||||
'detail': ' '.join(f'{key}={value:.3f}s' for key, value in durations.items())})
|
||||
if request.logging_context:
|
||||
request.logging_context.logger.info('operation=cbb_verify block=%s status=%s flag=%s evidence=%s error=%s timings_seconds=%s',
|
||||
request.block_name, result.status, result.library_flag, result.evidence_path, result.stderr, durations)
|
||||
return result
|
||||
|
||||
|
||||
def _run_verify(request, *, timing, progress=None, flag_reader=None, process_runner=None, port_check=None,
|
||||
dialog_supervisor_factory=None):
|
||||
"""Refresh one CBB and record its evidence.
|
||||
|
||||
``flag_reader`` is a read-only probe returning an authoritative ``BridgeResult``.
|
||||
After successful execution, only IsVerifiedReuseBlock READY/raw=1 confirms
|
||||
PASS/GREEN; Cert or icon observations never substitute for it. ``port_check`` is injectable so tests do
|
||||
not depend on the host's port reservations.
|
||||
"""
|
||||
root = Path(request.evidence_dir).resolve()/('verify-' + uuid4().hex[:12])
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
fingerprint = runtime_fingerprint(request.mentor_bin)
|
||||
(root/'runtime.json').write_text(
|
||||
json.dumps(fingerprint, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
if progress:
|
||||
progress({'stage': 'runtime_fingerprint', 'block': request.block_name,
|
||||
**fingerprint})
|
||||
result_path = root/'result.json'
|
||||
runner = process_runner or _run_process
|
||||
|
||||
def finish(result):
|
||||
# Backups are transient protection for the active worker. Keep the
|
||||
# small, actionable evidence files but reclaim the copied CBB tree so
|
||||
# large libraries do not accumulate tens of megabytes per item.
|
||||
try:
|
||||
from .mentor_adapter import cleanup_evidence_backup
|
||||
cleanup_evidence_backup(root)
|
||||
except Exception:
|
||||
# Cleanup must never hide or change the verification result.
|
||||
pass
|
||||
return replace(result, evidence_path=result_path)
|
||||
|
||||
timing.begin('preflight')
|
||||
try:
|
||||
project, pcb = preflight(request)
|
||||
except Exception as error:
|
||||
return finish(VerifyResult('BLOCKED', stderr=str(error)))
|
||||
finally:
|
||||
timing.end('preflight')
|
||||
|
||||
content_check_enabled = bool(str(request.libspec).strip() and str(request.dms_login_config).strip())
|
||||
if content_check_enabled:
|
||||
try:
|
||||
executable = resolve_importer(request.mentor_bin)
|
||||
except Exception as error:
|
||||
return finish(VerifyResult('BLOCKED', stderr=str(error)))
|
||||
command = build_content_check_command(request, executable)
|
||||
if progress:
|
||||
progress({'stage': 'content_check_start', 'block': request.block_name,
|
||||
'detail': ' '.join(command)})
|
||||
timing.begin('content_check')
|
||||
try:
|
||||
exit_code, stdout, stderr, timed_out = runner(command, request.timeout_seconds, Path(request.lmc_file).parent)
|
||||
finally:
|
||||
timing.end('content_check')
|
||||
combined = '\n'.join(part for part in (stdout, stderr) if part)
|
||||
report = contents_report_path(request.lmc_file, request.block_name)
|
||||
try:
|
||||
report.parent.mkdir(parents=True, exist_ok=True)
|
||||
report.write_text(combined, encoding='utf-8')
|
||||
except Exception as error:
|
||||
stderr = f'{stderr}\n无法写入内容检查报告 {report}: {error}'
|
||||
status = classify_output(exit_code, combined, timed_out=timed_out)
|
||||
if status != 'PASS':
|
||||
# A contents failure or an unusable DMS must block before touching the PCB.
|
||||
return finish(VerifyResult(status if status in ('FAIL', 'TIMEOUT') else 'BLOCKED',
|
||||
stderr=combined.strip() or f'内容检查结果未知(退出码 {exit_code})',
|
||||
stdout=stdout, report_path=report, content_check_exit_code=exit_code))
|
||||
if progress:
|
||||
progress({'stage': 'content_check_done', 'block': request.block_name, 'status': 'PASS'})
|
||||
|
||||
# The design server needs a port in 10000-10100; a system reservation there
|
||||
# blocks every item, so fail fast with the fix instead of timing out.
|
||||
from .mentor_adapter import icdb_ports_bindable
|
||||
check_ports = port_check or icdb_ports_bindable
|
||||
ports_ok, ports_detail = check_ports()
|
||||
if not ports_ok:
|
||||
if progress:
|
||||
progress({'stage': 'port_warning', 'block': request.block_name, 'detail': ports_detail})
|
||||
if request.strict_port_check:
|
||||
return finish(VerifyResult('BLOCKED', stderr=ports_detail))
|
||||
|
||||
job = {'lmc_file': str(absolute_preserving_drive(request.lmc_file)), 'block_name': request.block_name,
|
||||
'project': str(project), 'pcb': str(pcb), 'root': str(root), 'timeout': request.timeout_seconds,
|
||||
'mentor_bin': str(request.mentor_bin or ''),
|
||||
'mapped_drive': str(request.mapped_drive or ''),
|
||||
'mapped_remote_root': str(request.mapped_remote_root or ''),
|
||||
'interactive_input': bool(request.interactive_input),
|
||||
'native_lm_verify': bool(request.native_lm_verify),
|
||||
'desktop': 'CbbVerify_' + uuid4().hex[:12],
|
||||
'start_gate': str(root/'start-worker.signal')}
|
||||
job_path = root/'request.json'
|
||||
job_path.write_text(json.dumps(job, ensure_ascii=False), encoding='utf-8')
|
||||
events = root/'events.jsonl'
|
||||
offset = 0
|
||||
target_pid = None
|
||||
lm_pid = None
|
||||
verify_invoked = False
|
||||
invoke_returned = False
|
||||
pcb_baseline = set()
|
||||
last_observation = 0.0
|
||||
last_post_verify_observation = {}
|
||||
from .mentor_adapter import ActivityDeadline, pcb_startup_timeout_seconds
|
||||
from .desktop_worker import DesktopWorker
|
||||
from .dialog_supervisor import AgentDialogBackend, DialogSupervisor, Win32DialogBackend
|
||||
from .dialog_models import DialogPhase
|
||||
import win32event, win32con
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
lock_status = win32event.WaitForSingleObject(mutex, 0)
|
||||
if lock_status not in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED):
|
||||
mutex.Close()
|
||||
return finish(VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行,请等待结束。', safe_to_continue=False))
|
||||
try:
|
||||
timing.begin('worker_setup')
|
||||
with (root/'worker.log').open('w', encoding='utf-8') as log:
|
||||
if request.interactive_input:
|
||||
process = DesktopWorker(
|
||||
worker_command(job_path), None, interactive_input=True)
|
||||
else:
|
||||
process = DesktopWorker(worker_command(job_path), job['desktop'])
|
||||
deadline = ActivityDeadline(request.timeout_seconds)
|
||||
last_activity_key = None
|
||||
phase = DialogPhase.PCB_STARTING
|
||||
dialog_agent = None
|
||||
latest_snapshots = ()
|
||||
if dialog_supervisor_factory is None:
|
||||
if hasattr(process, 'start_companion'):
|
||||
from .dialog_agent import DialogAgentClient
|
||||
from .dialog_rules import default_rules_path, load_rules
|
||||
dialog_agent = DialogAgentClient.start(process, root/'dialog-agent')
|
||||
dialog_supervisor = DialogSupervisor(
|
||||
AgentDialogBackend(dialog_agent),
|
||||
rules=load_rules(default_rules_path()),
|
||||
)
|
||||
else:
|
||||
dialog_supervisor = DialogSupervisor(Win32DialogBackend(
|
||||
lambda: ({value for value in (target_pid, lm_pid) if value is not None}),
|
||||
desktop=process.desktop,
|
||||
))
|
||||
else:
|
||||
dialog_supervisor = dialog_supervisor_factory(
|
||||
desktop=process.desktop,
|
||||
pids=lambda: ({value for value in (target_pid, lm_pid) if value is not None}),
|
||||
)
|
||||
Path(job['start_gate']).touch()
|
||||
while process.poll() is None:
|
||||
if events.exists():
|
||||
with events.open(encoding='utf-8') as stream:
|
||||
stream.seek(offset)
|
||||
while line := stream.readline():
|
||||
try:
|
||||
event = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
break
|
||||
timing.record(event)
|
||||
if event.get('pcb_pid'): target_pid = event['pcb_pid']
|
||||
if event.get('lm_pid'): lm_pid = event['lm_pid']
|
||||
stage = event.get('stage')
|
||||
if stage == 'verify_invoke': verify_invoked = True
|
||||
if stage == 'verify_invoke_returned': invoke_returned = True
|
||||
if stage == 'pcb_baseline': pcb_baseline = set(event.get('pids', ()))
|
||||
phase = phase_for_event(event, phase)
|
||||
activity_key = (stage, json.dumps(event.get('statuses'), sort_keys=True),
|
||||
json.dumps(event.get('markers'), sort_keys=True),
|
||||
event.get('action'), event.get('detail'))
|
||||
# Repeated integration_status snapshots are normal
|
||||
# polling, not progress. Only a changed state or
|
||||
# a new stage/marker extends the inactivity window.
|
||||
if activity_key != last_activity_key:
|
||||
if stage in ('lm_started', 'lm_ready', 'verify_invoke',
|
||||
'verify_invoke_returned', 'lm_session_ready',
|
||||
'pcb_started', 'pcb_worker_started'):
|
||||
deadline.timeout_seconds = pcb_startup_timeout_seconds(
|
||||
request.timeout_seconds)
|
||||
elif stage == 'identity_verified':
|
||||
deadline.timeout_seconds = max(
|
||||
0.1, float(request.timeout_seconds))
|
||||
deadline.touch()
|
||||
last_activity_key = activity_key
|
||||
if progress: progress(event)
|
||||
offset = stream.tell()
|
||||
if verify_invoked and target_pid is None and time.monotonic() - last_observation >= .5:
|
||||
from .post_verify_diagnostics import observe_post_verify
|
||||
last_observation = time.monotonic()
|
||||
try:
|
||||
observation = observe_post_verify(process.desktop, pcb, pcb_baseline, lm_pid)
|
||||
except Exception as error:
|
||||
observation = {'error': str(error)}
|
||||
last_post_verify_observation = observation
|
||||
if dialog_agent is not None and target_pid is None:
|
||||
# The Library Manager Verify route starts its own window
|
||||
# before it launches Expedition PCB. Do not feed that
|
||||
# large MFC main window to the PCB dialog probe; it can
|
||||
# exhaust the UIA observation deadline before Verify has
|
||||
# even produced a target process.
|
||||
from .dialog_supervisor import DialogPollResult
|
||||
dialog_result = DialogPollResult(activity=False)
|
||||
elif dialog_agent is not None:
|
||||
dialog_result = dialog_supervisor.poll(phase)
|
||||
elif dialog_supervisor_factory is not None:
|
||||
try:
|
||||
dialog_result = dialog_supervisor.poll(phase)
|
||||
except TypeError:
|
||||
# Compatibility for injected legacy test supervisors only.
|
||||
dialog_result = dialog_supervisor.poll()
|
||||
else:
|
||||
dialog_result = dialog_supervisor.poll()
|
||||
# Normal progress stays in memory. Only actions/errors and the
|
||||
# last failure snapshots are persisted, not every elapsed tick.
|
||||
latest_snapshots = dialog_result.observed_snapshots
|
||||
if dialog_result.snapshot is not None and (
|
||||
dialog_result.action_sent or dialog_result.error_code):
|
||||
snapshot_record = (dialog_result.snapshot.to_record()
|
||||
if hasattr(dialog_result.snapshot, 'to_record')
|
||||
else dialog_result.snapshot.as_log_record())
|
||||
record = {
|
||||
'time': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
**snapshot_record,
|
||||
'action': dialog_result.action,
|
||||
'rule_id': dialog_result.rule_id,
|
||||
'channel': dialog_result.channel,
|
||||
'accepted_control': list(dialog_result.accepted_controls),
|
||||
'error_code': dialog_result.error_code,
|
||||
'detail': dialog_result.detail,
|
||||
}
|
||||
with (root/'dialogs.jsonl').open('a', encoding='utf-8') as stream:
|
||||
stream.write(json.dumps(record, ensure_ascii=False) + '\n')
|
||||
if dialog_result.activity:
|
||||
deadline.touch()
|
||||
if dialog_result.error_code:
|
||||
_write_failure_windows(root, latest_snapshots)
|
||||
_write_process_tree(root, process, target_pid)
|
||||
_stop_worker(process)
|
||||
return finish(VerifyResult(
|
||||
'FAIL',
|
||||
stderr=f'{dialog_result.error_code}: {dialog_result.detail}',
|
||||
error_stage=phase.value,
|
||||
safe_to_continue=True,
|
||||
))
|
||||
if deadline.expired():
|
||||
_write_failure_windows(root, latest_snapshots)
|
||||
# Kills the worker's whole job: worker, PCB and cscript helper.
|
||||
_write_process_tree(root, process, target_pid)
|
||||
if last_post_verify_observation:
|
||||
(root/'post_verify_observations.jsonl').write_text(json.dumps({
|
||||
'time': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'invoke_returned': invoke_returned,
|
||||
**last_post_verify_observation,
|
||||
}, ensure_ascii=False) + '\n', encoding='utf-8')
|
||||
dispatch_failure = classify_verify_dispatch(
|
||||
verify_invoked=verify_invoked,
|
||||
invoke_returned=invoke_returned,
|
||||
target_pid=target_pid,
|
||||
observation=last_post_verify_observation,
|
||||
)
|
||||
_stop_worker(process)
|
||||
if dispatch_failure is not None:
|
||||
status, detail = dispatch_failure
|
||||
if progress:
|
||||
progress({
|
||||
'stage': 'verify_dispatch_failed',
|
||||
'block': request.block_name,
|
||||
'detail': detail,
|
||||
'observation': last_post_verify_observation,
|
||||
})
|
||||
return finish(VerifyResult(status, stderr=detail, safe_to_continue=True))
|
||||
return finish(VerifyResult('TIMEOUT', stderr='操作超时;已记录现场,跳过当前 CBB。', error_stage=phase.value, safe_to_continue=True))
|
||||
time.sleep(.2)
|
||||
worker_result = root/'outcome.json'
|
||||
if not worker_result.exists():
|
||||
return finish(VerifyResult('FAIL', stderr=f'执行器异常退出 ({process.returncode}),见 worker.log', safe_to_continue=False))
|
||||
outcome = json.loads(worker_result.read_text(encoding='utf-8'))
|
||||
if outcome.get('status') == 'PASS' and process.returncode != 0:
|
||||
return finish(VerifyResult('FAIL', stderr='执行器异常退出,不能确认成功', safe_to_continue=False))
|
||||
result = VerifyResult(**outcome)
|
||||
except Exception as error:
|
||||
if 'process' in locals() and process.poll() is None:
|
||||
_stop_worker(process)
|
||||
return finish(VerifyResult('FAIL', stderr=str(error), safe_to_continue=False))
|
||||
finally:
|
||||
if 'dialog_agent' in locals() and dialog_agent is not None:
|
||||
dialog_agent.close()
|
||||
if 'process' in locals(): process.close()
|
||||
if 'process' in locals():
|
||||
try:
|
||||
_cleanup_session_processes(
|
||||
root,
|
||||
lm_pid=lm_pid,
|
||||
target_pid=target_pid,
|
||||
pcb=pcb,
|
||||
pcb_baseline=pcb_baseline,
|
||||
progress=progress,
|
||||
)
|
||||
except Exception:
|
||||
# Cleanup is best effort; the original Verify result remains
|
||||
# authoritative and the evidence directory records everything
|
||||
# that was successfully reaped.
|
||||
pass
|
||||
# Drain the timing tail even when the worker exited before a poll.
|
||||
# This is optional telemetry: an unreadable log must not mask failure
|
||||
# or prevent releasing the serial-operation mutex.
|
||||
try:
|
||||
if events.is_file():
|
||||
with events.open(encoding='utf-8') as stream:
|
||||
stream.seek(offset)
|
||||
for line in stream:
|
||||
try:
|
||||
timing.record(json.loads(line))
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
continue
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
|
||||
if result.status == 'PASS':
|
||||
timing.begin('library_flag')
|
||||
bridge_records = []
|
||||
def record_attempt(record):
|
||||
bridge_records.append(record)
|
||||
if progress:
|
||||
progress({'stage': 'library_flag_probe', 'block': request.block_name, **record})
|
||||
try:
|
||||
probe = read_library_flag_with_retry(
|
||||
flag_reader or read_library_flag_if_available, Path(request.lmc_file),
|
||||
request.block_name, on_attempt=record_attempt)
|
||||
result = apply_post_verify_status(result, probe)
|
||||
result = replace(result, bridge_attempts=tuple(bridge_records))
|
||||
(root/'bridge-status.json').write_text(json.dumps(bridge_records, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
if progress:
|
||||
progress({'stage': 'library_flag', 'block': request.block_name,
|
||||
'library_flag': result.library_flag, 'detail': result.library_flag_detail})
|
||||
finally:
|
||||
timing.end('library_flag')
|
||||
return finish(result)
|
||||
|
||||
|
||||
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None):
|
||||
"""Run CBBs serially; one item's failure never aborts the queue."""
|
||||
if max_workers != 1:
|
||||
raise ValueError('Only serial Verify is supported for the shared Library Manager session')
|
||||
if verifier is None:
|
||||
verifier = lambda request: run_verify(request, flag_reader=read_library_flag_if_available) # noqa: E731
|
||||
results = []
|
||||
queue_stop = False
|
||||
for request in requests:
|
||||
if queue_stop or (stop is not None and stop.is_set()):
|
||||
result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
|
||||
else:
|
||||
try:
|
||||
result = verifier(request)
|
||||
except Exception as error:
|
||||
# An unexpected worker exception is a failed item, not a batch abort.
|
||||
result = VerifyResult('FAIL', stderr=str(error), safe_to_continue=False)
|
||||
results.append(result)
|
||||
# Failure status and safe_to_continue describe this item, not the batch;
|
||||
# the queue is skipped only after an explicit stop signal.
|
||||
queue_stop = queue_stop or result.status == 'QUEUE_STOP'
|
||||
if result.status == 'QUEUE_STOP' and stop is not None:
|
||||
stop.set()
|
||||
if progress: progress(request.block_name, result)
|
||||
return results
|
||||
|
||||
|
||||
def failure_report_path(batch_report):
|
||||
batch_report = Path(batch_report)
|
||||
return batch_report.with_name(batch_report.name.replace('batch-', 'failures-', 1))
|
||||
|
||||
|
||||
def _report_field(value):
|
||||
# One CBB per row; full native multi-line text remains in evidence files.
|
||||
return str(value).replace('\r', r'\r').replace('\n', r'\n').replace('\t', r'\t')
|
||||
|
||||
|
||||
def write_failure_report(requests, results, root, *, path=None):
|
||||
requests, results = tuple(requests), tuple(results)
|
||||
if len(requests) != len(results):
|
||||
raise ValueError('requests/results 长度不一致,不能生成遗漏条目的报告')
|
||||
root = Path(root); root.mkdir(parents=True, exist_ok=True)
|
||||
path = Path(path) if path else root/('failures-' + time.strftime('%Y%m%d-%H%M%S') + '-' + uuid4().hex[:6] + '.log')
|
||||
failed = [(req, result) for req, result in zip(requests, results)
|
||||
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'}]
|
||||
passed = sum(result.status == 'PASS' for result in results)
|
||||
skipped = len(results)-passed-len(failed)
|
||||
lines = ['CBB Verify 失败清单', f'总数: {len(results)} 成功: {passed} 失败: {len(failed)} 未执行: {skipped}',
|
||||
'CBB\t状态\t错误分类\t失败阶段\t桥状态\t原始错误\t证据\t实际耗时(秒)']
|
||||
for req, result in failed:
|
||||
timings = ' '.join(f'{key}={value:.3f}s' +
|
||||
('(unfinished)' if key in result.incomplete_timing_phases else '')
|
||||
for key, value in result.timings_seconds.items())
|
||||
lines.append(f'{req.block_name}\t{result.status}\t{result.error_category or classify_failure_category(result.stderr)}\t'
|
||||
f'{result.error_stage or "unknown"}\t{result.library_flag}\t{_report_field(result.stderr or result.stdout.strip()[:200])}\t{result.evidence_path or ""}\t{timings}')
|
||||
if not failed:
|
||||
lines.append('本批次没有失败项。')
|
||||
path.write_text('\n'.join(lines) + '\n', encoding='utf-8-sig')
|
||||
return path
|
||||
|
||||
|
||||
def write_batch_report(requests, results, root):
|
||||
requests, results = tuple(requests), tuple(results)
|
||||
if len(requests) != len(results):
|
||||
raise ValueError('requests/results 长度不一致,不能生成遗漏条目的报告')
|
||||
root = Path(root); root.mkdir(parents=True, exist_ok=True)
|
||||
path = root/('batch-' + time.strftime('%Y%m%d-%H%M%S') + '-' + uuid4().hex[:6] + '.log')
|
||||
lines = ['CBB Verify 批量结果',
|
||||
'流程: LMC 原生 Verify / ReusableCircuit PCB -> Project Integration -> Save/Close -> IsVerifiedReuseBlock READY(金标准)']
|
||||
for req, result in zip(requests, results):
|
||||
detail = _report_field(result.stderr or result.stdout.strip()[:200])
|
||||
seconds = ' '.join(f'{key}={value:.3f}s' +
|
||||
('(unfinished)' if key in result.incomplete_timing_phases else '')
|
||||
for key, value in result.timings_seconds.items())
|
||||
lines.append(f'{req.block_name}\t{result.status}\t{result.library_flag}\t{detail}\t{result.evidence_path or ""}\t{seconds}')
|
||||
path.write_text('\n'.join(lines) + '\n', encoding='utf-8-sig')
|
||||
write_failure_report(requests, results, root, path=failure_report_path(path))
|
||||
return path
|
||||
Reference in new issue
Block a user