"""Exercise generated menu actions on the dedicated native feature copy.""" from __future__ import annotations import argparse import json import os from pathlib import Path import subprocess import sys import time from types import SimpleNamespace import win32gui import win32process from pywinauto import Application import win32com.client BASE = Path(os.environ["LOCALAPPDATA"]) / "DxProductivity/acceptance/native-20261010" PROJECT = BASE / "1GPHY_RTL8211F/1GPHY_RTL8211F.prj" HOST_PID = 81576 def wait_for(predicate, seconds=30): deadline = time.monotonic() + seconds while time.monotonic() < deadline: result = predicate() if result: return result time.sleep(0.2) raise TimeoutError("Menu action did not produce the expected native result") def owned_dialogs(): result = [] def callback(handle, _): if win32process.GetWindowThreadProcessId(handle)[1] == HOST_PID and win32gui.GetClassName(handle) == "#32770" and win32gui.IsWindowVisible(handle): texts = [] win32gui.EnumChildWindows(handle, lambda child, _: texts.append(win32gui.GetWindowText(child)), None) result.append((handle, texts)) win32gui.EnumWindows(callback, None) return result def close_completion_dialog(handle): buttons = [] win32gui.EnumChildWindows(handle, lambda child, _: buttons.append(child) if win32gui.GetClassName(child) == "Button" and win32gui.GetWindowText(child) in {"确定", "OK"} else None, None) assert len(buttons) == 1, "Expected one confirmation button on owned completion dialog" # DxDesigner uses control ID 2 for its localized confirmation button. win32gui.PostMessage(handle, 0x111, win32gui.GetDlgCtrlID(buttons[0]), buttons[0]) def tools_running(): service = win32com.client.GetObject("winmgmts:") return [SimpleNamespace(pid=int(p.ProcessId), executable=str(p.ExecutablePath), command_line=str(p.CommandLine)) for p in service.ExecQuery("SELECT ProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='DxDesignerTools.exe'")] def main(): parser = argparse.ArgumentParser() parser.add_argument("executable", type=Path) parser.add_argument("--features") parser.add_argument("--project", type=Path) parser.add_argument("--host-pid", type=int) parser.add_argument("--evidence", type=Path) parser.add_argument("--menu-script", type=Path) options = parser.parse_args() global PROJECT, HOST_PID, BASE if options.project: PROJECT = options.project.resolve() if options.host_pid: HOST_PID = options.host_pid if options.evidence: BASE = options.evidence.resolve() BASE.mkdir(parents=True, exist_ok=True) root = options.executable.resolve().parent helper = Path(__file__).with_name("run_dx_script.py") install = options.menu_script or Path(os.environ["LOCALAPPDATA"]) / "DxProductivity/startup-refactored/MenuAdd.vbs" subprocess.run([sys.executable, str(helper), "--project", str(PROJECT), str(install)], timeout=30, check=True) cases = [(1, "refdes", "自动位号"), (2, "property-change", "属性批改"), (3, "property-visibility", "属性显示"), (4, "inspection", "设计检查"), (5, "bom", "BOM 工具"), (6, "pdf-export", "PDF 导出"), (7, "compatibility", ""), (8, "guide", "")] if options.features: cases = [case for case in cases if case[1] in options.features.split(",")] results = [] for index, feature, expected in cases: script = BASE / f"packaged-menu-{feature}.vbs" marker = BASE / f"packaged-menu-{feature}.txt" marker.unlink(missing_ok=True) script.write_text(f''' Dim mBar, mItem, mAction, mIndex, mStream If LCase(Application.GetProjectData().GetProjectFilePath()) <> LCase("{PROJECT}") Then Err.Raise 513, "Acceptance", "Wrong test project" Set mBar = CommandBars("Sheet Menu Bar") For mIndex = 1 To mBar.Controls.Count Set mItem = mBar.Controls.Item(mIndex) If mItem.Caption = "Dx " & ChrW(&H6548) & ChrW(&H7387) & ChrW(&H5DE5) & ChrW(&H5177) Then mAction = mItem.Controls.Item({index}).OnAction Set mStream = CreateObject("Scripting.FileSystemObject").CreateTextFile("{marker}", True, True) mStream.WriteLine mAction mStream.Close Application.ExecuteCommand mAction Set mStream = CreateObject("Scripting.FileSystemObject").OpenTextFile("{marker}", 8, False, -1) mStream.WriteLine "DONE" mStream.Close Exit For End If Next ''', encoding="ascii") before = {p.pid for p in tools_running()} if feature == "compatibility": for handle, texts in owned_dialogs(): if any("compatibility.json" in text for text in texts): close_completion_dialog(handle) time.sleep(0.3) started_at = time.time() child = subprocess.Popen([sys.executable, str(helper), "--project", str(PROJECT), str(script)]) if expected: def new_tool(): for p in tools_running(): if p.pid not in before and "--request" in p.command_line and Path(p.executable).resolve() == options.executable.resolve(): return p tool = wait_for(new_tool) from toolbar_ui import ToolbarUI toolbar_ui = ToolbarUI(tool.pid) window = toolbar_ui.panel window.wait("visible", timeout=15) def connected_page(): if toolbar_ui.toolbar.child_window(title='展开面板', control_type='Button').exists(timeout=.2): toolbar_ui.expand() try: texts = toolbar_ui.texts(window) except Exception: return None return texts if expected in texts and '桥接已连接' in texts and PROJECT.name in texts else None texts = wait_for(connected_page, 15) results.append({"feature": feature, "pid": tool.pid, "selected_page": expected, "bridge": "connected", "project": PROJECT.name, "executable": tool.executable}) # Route acceptance ends each launch through explicit toolbar close; # the More-menu exit itself is covered by the controls acceptance. win32gui.PostMessage(toolbar_ui.toolbar.handle, 0x10, 0, 0) toolbar_ui.toolbar.wait_not('exists', timeout=15) elif feature == "compatibility": def close_completion(): probe = Path(os.environ["LOCALAPPDATA"]) / "DxProductivity/compatibility.json" if not probe.exists() or probe.stat().st_mtime < started_at: return None try: payload = json.loads(probe.read_text(encoding="utf-8")) except (OSError, ValueError): return None if "retained_reference" not in payload or not payload.get("yield_method"): return None for handle, texts in owned_dialogs(): if any("compatibility.json" in text for text in texts): close_completion_dialog(handle) return texts if any("VBScript" in text or "Microsoft" in text for text in texts): raise RuntimeError(f"Native compatibility dialog: {texts}") texts = wait_for(close_completion) probe = Path(os.environ["LOCALAPPDATA"]) / "DxProductivity/compatibility.json" assert probe.stat().st_mtime >= started_at data = json.loads(probe.read_text(encoding="utf-8")) for key in ("portable_root_valid", "full_design_enumeration", "refdes_readable", "uid_readable", "attributes_readable", "sheet_number_readable", "retained_reference"): assert data[key] is True, (key, data) assert data["full_design_count"] == 114 and data["position_method"] and data["yield_method"] results.append({"feature": feature, "probe": data}) else: guide = root / "docs/DxDesigner_7.9.5_自动位号工具使用说明.docx" def open_guide(): try: word = win32com.client.GetActiveObject("Word.Application") for doc in word.Documents: if Path(doc.FullName).resolve() == guide.resolve(): return doc except Exception: return None doc = wait_for(open_guide) results.append({"feature": feature, "document": str(guide), "pages": doc.ComputeStatistics(2)}) doc.Close(SaveChanges=0) assert child.wait(timeout=15) == 0 assert "DONE" in marker.read_text(encoding="utf-16") print(f"PASS MENU {feature}", flush=True) (BASE / "packaged-menu-acceptance.json").write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8") (BASE / "packaged-menu-acceptance.json").write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8") if __name__ == "__main__": main()