128 lines
5.6 KiB
Python
128 lines
5.6 KiB
Python
"""Enable automatic PDF export through the GUI and exercise native saves."""
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shlex
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
|
|
from pypdf import PdfReader
|
|
from dx_productivity.bridge.startup_assets import 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()
|
|
assert 'acceptance' in project.parts
|
|
assert not base.exists(), 'Retain existing evidence; use a fresh directory'
|
|
base.mkdir(parents=True)
|
|
tool = wait_for(lambda: next((p for p in tools_running() if Path(p.executable).resolve() == exe
|
|
and '--request' in p.command_line), None))
|
|
args = shlex.split(tool.command_line, posix=False)
|
|
request = Path(args[args.index('--request') + 1].strip('"'))
|
|
data = json.loads(request.read_text(encoding='utf-8-sig'))
|
|
assert Path(data['design_path']).resolve() == project
|
|
comp = next(c for c in data['components'] if c['refdes'] == 'CE17')
|
|
old = next(a['value'] for a in comp['attributes'] if a['name'] == 'Value')
|
|
marker = '_TOOLBAR_AUTO'
|
|
ui = ToolbarUI(tool.pid)
|
|
if ui.panel.exists(timeout=.2) and ui.panel.is_visible():
|
|
ui.collapse()
|
|
ui.feature('PDF 导出')
|
|
ui.select_combo(ui.panel.child_window(title='导出范围', control_type='ComboBox'), 0, '整工程')
|
|
output = base / 'output'
|
|
edits = [e for e in ui.panel.descendants(control_type='Edit')
|
|
if e.is_visible() and not e.iface_value.CurrentIsReadOnly]
|
|
assert len(edits) == 1, edits
|
|
edits[0].set_edit_text(str(output))
|
|
enabled = ui.panel.child_window(title='保存工程后自动导出', control_type='CheckBox')
|
|
assert enabled.is_enabled()
|
|
enabled.click_input()
|
|
config = Path(os.environ['LOCALAPPDATA']) / 'DxProductivity/pdf-export-settings.json'
|
|
state_path = config.with_name(config.name + '.listener-state.json')
|
|
log_path = config.with_name(config.name + '.listener.log')
|
|
|
|
def events():
|
|
return [json.loads(line) for line in log_path.read_text(encoding='utf-8').splitlines() if line] if log_path.exists() else []
|
|
|
|
def listening():
|
|
if not state_path.exists():
|
|
return None
|
|
state = json.loads(state_path.read_text(encoding='utf-8'))
|
|
return state if state.get('state') == 'listening' else None
|
|
|
|
def run(value, name):
|
|
script = base / f'{name}.vbs'
|
|
script.write_text(f'''
|
|
Dim autoComp,autoAttr,autoFound
|
|
If LCase(Application.GetProjectData().GetProjectFilePath()) <> LCase({vbscript_string(str(project))}) Then Err.Raise 513, "Acceptance", "Wrong project"
|
|
autoFound=False
|
|
For Each autoComp In ActiveView.Query(VDM_COMP,VD_ALL)
|
|
If CStr(autoComp.Refdes)="CE17" Then
|
|
Set autoAttr=autoComp.FindAttribute("Value")
|
|
autoAttr.Value={vbscript_string(value)}
|
|
autoFound=True
|
|
Exit For
|
|
End If
|
|
Next
|
|
If Not autoFound Then Err.Raise 513, "Acceptance", "CE17 not found"
|
|
Call Application.Documents.SaveAll()
|
|
ActiveView.Refresh
|
|
''', encoding='ascii')
|
|
subprocess.run([sys.executable, str(Path(__file__).with_name('run_dx_script.py')),
|
|
'--project', str(project), str(script)], check=True, timeout=30)
|
|
|
|
def exported(expected_count):
|
|
entries = [e for e in events() if e.get('event') == 'export-completed']
|
|
if len(entries) < expected_count:
|
|
return None
|
|
assert entries[-1]['returncode'] == 0, entries[-1]
|
|
return entries[-1]
|
|
|
|
changed = False
|
|
try:
|
|
binding = wait_for(listening, 30)
|
|
assert str(project).casefold() == str(binding.get('project', '')).casefold(), binding
|
|
count = len([e for e in events() if e.get('event') == 'export-completed'])
|
|
ui.collapse()
|
|
run(old + marker, 'change-and-save')
|
|
changed = True
|
|
changed_event = wait_for(lambda: exported(count + 1), 60)
|
|
pdfs = tuple(output.glob('*.pdf'))
|
|
assert len(pdfs) == 1, pdfs
|
|
pdf = PdfReader(pdfs[0])
|
|
assert len(pdf.pages) == 1 and old + marker in pdf.pages[0].extract_text()
|
|
shutil.copy2(pdfs[0], base / 'changed-value.pdf')
|
|
print('PASS AUTO PDF WHILE COLLAPSED', flush=True)
|
|
run(old, 'restore-and-save')
|
|
changed = False
|
|
restored_event = wait_for(lambda: exported(count + 2), 60)
|
|
assert marker not in PdfReader(pdfs[0]).pages[0].extract_text()
|
|
report = {'executable': str(exe), 'project': str(project), 'pid': tool.pid,
|
|
'native_binding': binding, 'changed_event': changed_event, 'restored_event': restored_event,
|
|
'pdf': str(pdfs[0]), 'native_saves': 2, 'value_restored': True, 'completed_while_collapsed': True}
|
|
finally:
|
|
if changed:
|
|
run(old, 'restore-after-failure')
|
|
if not (ui.panel.exists(timeout=.2) and ui.panel.is_visible()):
|
|
ui.expand()
|
|
if enabled.get_toggle_state():
|
|
enabled.click_input()
|
|
wait_for(lambda: json.loads(config.read_text(encoding='utf-8')).get('auto_export') is False, 10)
|
|
ui.collapse()
|
|
report['auto_export_disabled_after_test'] = True
|
|
(base / 'toolbar-auto-pdf.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
|
|
print('PASS TOOLBAR NATIVE SAVE AUTO PDF', flush=True)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|