Files
cbb-refresh-verify-795/src/cbb_refresh_verify/dialog_probe.py
T

311 lines
12 KiB
Python

"""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 matches_identity(self, snapshot):
try:
return (self.win32gui.IsWindowVisible(snapshot.hwnd)
and self.win32process.GetWindowThreadProcessId(snapshot.hwnd)[1] == snapshot.pid
and self.win32gui.GetClassName(snapshot.hwnd) == snapshot.window_class)
except Exception:
return False
def capture(self, phase: DialogPhase, *, pids=None) -> tuple[WindowSnapshot, ...]:
snapshots = []
for hwnd in self._handles():
if pids is not None:
try:
if self.win32process.GetWindowThreadProcessId(hwnd)[1] not in pids:
continue
except Exception:
continue
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)