"""Verify live selection on an explicitly opened independent DxDesigner copy.""" from __future__ import annotations import argparse import json import os from pathlib import Path import shlex import subprocess import sys import time import win32gui import win32process from pywinauto import Application from dx_productivity.bridge.startup_assets import generate_startup_assets, vbscript_string 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('--evidence', required=True, type=Path) options = parser.parse_args() exe, project, base = options.executable.resolve(), options.project.resolve(), options.evidence.resolve() base.mkdir(parents=True, exist_ok=True) helper = Path(__file__).with_name('run_dx_script.py') assets = generate_startup_assets(exe.parent, base / 'private-menu') def run(script): return subprocess.run([sys.executable, str(helper), '--project', str(project), str(script)], check=True, timeout=20, capture_output=True) run(assets.menu_script) invoke = base / 'open-selection-menu.vbs' invoke.write_text(f''' Dim liveBar,liveItem,liveIndex If LCase(Application.GetProjectData().GetProjectFilePath()) <> LCase({vbscript_string(str(project))}) Then Err.Raise 513, "Acceptance", "Wrong project" Set liveBar=CommandBars("Sheet Menu Bar") For liveIndex=1 To liveBar.Controls.Count Set liveItem=liveBar.Controls.Item(liveIndex) If liveItem.Caption="Dx " & ChrW(&H6548) & ChrW(&H7387) & ChrW(&H5DE5) & ChrW(&H5177) Then Application.ExecuteCommand liveItem.Controls.Item(1).OnAction Exit For End If Next ''', encoding='ascii') before = {p.pid for p in tools_running()} log = (base / 'native-menu-call.log').open('wb') native_call = subprocess.Popen([sys.executable, str(helper), '--project', str(project), str(invoke)], stdout=log, stderr=log) tool = wait_for(lambda: next((p for p in tools_running() if p.pid not in before and Path(p.executable).resolve() == exe and '--request' in p.command_line and '--smoke-test-ms' not in p.command_line), None), 30) args = shlex.split(tool.command_line, posix=False) request = Path(args[args.index('--request') + 1].strip('"')) initial = json.loads(request.read_text(encoding='utf-8-sig')) selection = request.with_name('selection.json') live_ui = ToolbarUI(tool.pid) ui = live_ui.app window = live_ui.panel window.wait('visible', timeout=15) main_handle = window.handle refs = {'uid:' + c['stable_uid'].casefold(): c['refdes'] for c in initial['components'] if c['stable_uid']} evidence = [] def actual_refs(): try: payload = json.loads(selection.read_text(encoding='utf-8-sig')) if payload.get('state') != 'ready': return None return sorted(refs[key] for key in payload['selected_keys']) except (OSError, ValueError, KeyError): return None def displayed(expected): texts = live_ui.texts(window) + live_ui.texts(live_ui.toolbar) matches = [text for text in texts if text.startswith(f'已选 {len(expected)} 个')] return matches[0] if matches and all(ref in matches[0] for ref in expected[:4]) else None def select(refdes, name): script = base / f'{name}.vbs' literals = ','.join(vbscript_string(ref) for ref in refdes) targets = f'Array({literals})' if refdes else 'Array()' script.write_text(f''' Dim liveComp,liveRef,liveTargets,liveTarget If LCase(Application.GetProjectData().GetProjectFilePath()) <> LCase({vbscript_string(str(project))}) Then Err.Raise 513, "Acceptance", "Wrong project" ActiveView.Block.DeSelectAll liveTargets={targets} For Each liveComp In ActiveView.Query(VDM_COMP,VD_ALL) liveRef=CStr(liveComp.Refdes) For Each liveTarget In liveTargets If liveRef=liveTarget Then liveComp.Selected=True Next Next ActiveView.Refresh ''', encoding='ascii') began = time.monotonic() run(script) wait_for(lambda: actual_refs() == sorted(refdes), 10) label = wait_for(lambda: displayed(refdes), 10) elapsed = time.monotonic() - began assert elapsed < 2.5, elapsed assert json.loads(request.read_text(encoding='utf-8-sig'))['snapshot_id'] == initial['snapshot_id'] evidence.append({'case': name, 'selected': refdes, 'label': label, 'elapsed_seconds': round(elapsed, 3), 'without_manual_refresh': True}) print(f'PASS LIVE SELECTION {name} {label} {elapsed:.3f}s', flush=True) try: select(['CE17'], 'single-capacitor') select(['LE03'], 'single-inductor') select(['CE17', 'LE03'], 'multiple') live_ui.feature('属性批改') rows = [x.window_text() for x in window.descendants(control_type='Text')] assert any(text.startswith('已选 2 个') and 'CE17' in text and 'LE03' in text for text in rows) select([], 'deselected') live_ui.feature('自动位号') live_ui.collapse() wait_for(lambda: not win32gui.IsWindowVisible(main_handle)) script = base / 'collapsed-select.vbs' native_name = next(component['stable_uid'] for component in initial['components'] if component['refdes'] == 'CE17') script.write_text(f'If LCase(Application.GetProjectData().GetProjectFilePath()) <> LCase({vbscript_string(str(project))}) Then Err.Raise 513\nActiveView.SelectByName {vbscript_string(native_name)}\nActiveView.Refresh\n', encoding='ascii') run(script) wait_for(lambda: actual_refs() == ['CE17'], 10) handles = [] def inspect(handle, _): if (win32process.GetWindowThreadProcessId(handle)[1] == tool.pid and win32gui.GetWindowText(handle) == '一叶知秋悬浮工具栏' and win32gui.IsWindowVisible(handle)): handles.append(handle) win32gui.EnumWindows(inspect, None) assert len(handles) == 1 toolbar_label = wait_for(lambda: next((text for text in live_ui.texts(live_ui.toolbar) if 'CE17' in text), None), 10) live_ui.expand() window.wait('visible', timeout=15) wait_for(lambda: displayed(['CE17']), 10) evidence.append({'case': 'collapsed-selection', 'selected': ['CE17'], 'toolbar_label': toolbar_label, 'restored_selection_current': True}) finally: live_ui.exit() assert native_call.wait(timeout=15) == 0 log.close() report = {'executable': str(exe), 'project': str(project), 'pid': tool.pid, 'request': str(request), 'cases': evidence, 'design_values_written': False} (base / 'live-selection-acceptance.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8') print('PASS NATIVE LIVE SELECTION', json.dumps(report, ensure_ascii=False), flush=True) if __name__ == '__main__': main()