"""Verify persistent menus after a normal restart of an acceptance host.""" import argparse import json import os from pathlib import Path import shlex import subprocess import sys import win32com.client import pythoncom import win32gui import win32process from dx_productivity.bridge.startup_assets import vbscript_string import packaged_menu from packaged_menu import tools_running, wait_for from toolbar_ui import ToolbarUI def main(): parser = argparse.ArgumentParser() parser.add_argument('executable', type=Path) parser.add_argument('--project', required=True, type=Path) parser.add_argument('--host-pid', required=True, type=int) parser.add_argument('--evidence', required=True, type=Path) parser.add_argument('--block', default='1GPHY_RTL8211F') parser.add_argument('--sheet', default='GE_PHY_8211') options = parser.parse_args() exe, project, base = options.executable.resolve(), options.project.resolve(), options.evidence.resolve() assert 'acceptance' in project.parts and options.host_pid != 44008 base.mkdir(parents=True, exist_ok=True) for tool in tools_running(): if Path(tool.executable).resolve() != exe or '--request' not in tool.command_line: continue args = shlex.split(tool.command_line, posix=False) request = Path(args[args.index('--request') + 1].strip('"')) if Path(json.loads(request.read_text(encoding='utf-8-sig'))['design_path']).resolve() == project: ToolbarUI(tool.pid).exit() packaged_menu.HOST_PID = options.host_pid for handle, texts in packaged_menu.owned_dialogs(): assert any('应用完成' in text for text in texts), texts packaged_menu.close_completion_dialog(handle) hosts = [] win32gui.EnumWindows(lambda h, _: hosts.append(h) if win32process.GetWindowThreadProcessId(h)[1] == options.host_pid and win32gui.GetWindowText(h).startswith('DxDesigner -') else None, None) assert len(hosts) == 1, hosts win32gui.PostMessage(hosts[0], 0x10, 0, 0) service = win32com.client.GetObject('winmgmts:') wait_for(lambda: not list(service.ExecQuery(f'SELECT ProcessId FROM Win32_Process WHERE ProcessId={options.host_pid}')), 30) state = json.loads((Path(os.environ['LOCALAPPDATA']) / 'DxProductivity/startup-refactored/startup.json').read_text(encoding='utf-8')) assert Path(state['tool_root']).resolve() == exe.parent process = subprocess.Popen([state['viewdraw'], str(project)], cwd=Path(state['viewdraw']).parent) # A normal project launch opens Start Page. Open the native sheet before # asking for Sheet Menu Bar; its scripting surface waits for an active view. def open_sheet(): context = pythoncom.CreateBindCtx(0) rot = pythoncom.GetRunningObjectTable() entries = rot.EnumRunning() while batch := entries.Next(1): moniker = batch[0] if not moniker.GetDisplayName(context, None).startswith('!Viewdraw.Application'): continue app = win32com.client.Dispatch(rot.GetObject(moniker).QueryInterface(pythoncom.IID_IDispatch)) try: path = app.GetProjectData().GetProjectFilePath path = path() if callable(path) else path if Path(path).resolve() == project: app.PushPath(options.block, '', options.sheet) handle = int(app.ActiveViewHandle) return handle and win32process.GetWindowThreadProcessId(handle)[1] == process.pid except Exception: continue return False wait_for(open_sheet, 30) helper = Path(__file__).with_name('run_dx_script.py') report_path = base / 'native-menu-readback.txt' script = base / 'read-persistent-menu.vbs' script.write_text(f''' Dim restartBarName,restartBar,restartItem,restartIndex,restartCount,restartRows,restartOut,restartAction If LCase(Application.GetProjectData().GetProjectFilePath()) <> LCase({vbscript_string(str(project))}) Then Err.Raise 513, "Acceptance", "Wrong project" restartRows="" For Each restartBarName In Array("Main Menu Bar","Sheet Menu Bar") Set restartBar=CommandBars(restartBarName) restartCount=0 For restartIndex=1 To restartBar.Controls.Count Set restartItem=restartBar.Controls.Item(restartIndex) If restartItem.Caption="Dx " & ChrW(&H6548) & ChrW(&H7387) & ChrW(&H5DE5) & ChrW(&H5177) Then restartCount=restartCount+1 restartRows=restartRows & "BAR" & vbTab & restartBarName & vbTab & CStr(restartItem.Controls.Count) & vbCrLf For Each restartAction In restartItem.Controls restartRows=restartRows & "ACTION" & vbTab & restartAction.Caption & vbTab & restartAction.OnAction & vbCrLf Next End If Next If restartCount<>1 Then Err.Raise 513,"Acceptance","Persistent menu count=" & CStr(restartCount) Next Set restartOut=CreateObject("Scripting.FileSystemObject").CreateTextFile({vbscript_string(str(report_path))},True,True) restartOut.Write restartRows restartOut.Close ''', encoding='ascii') def probe(): result = subprocess.run([sys.executable, str(helper), '--pid', str(process.pid), str(script)], capture_output=True, timeout=10) return report_path if result.returncode == 0 and report_path.exists() else None wait_for(probe, 30) rows = [line.split('\t') for line in report_path.read_text(encoding='utf-16').splitlines()] bars = [row for row in rows if row[0] == 'BAR'] assert len(bars) == 2 and all(row[2] == '8' for row in bars), bars assert all('startup-refactored' in row[2] for row in rows if row[0] == 'ACTION') (base / 'persistent-menu.json').write_text(json.dumps({'project': str(project), 'executable': str(exe), 'old_host_pid': options.host_pid, 'new_host_pid': process.pid, 'normal_launch': True, 'menu_loaded_without_manual_install': True, 'menus': bars}, ensure_ascii=False, indent=2), encoding='utf-8') print('PASS NORMAL DX RESTART PERSISTENT MENUS', process.pid, flush=True) if __name__ == '__main__': main()