From 7a471fec24750f37a1fd73c7869ec6f61267a652 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Sat, 10 Oct 2026 22:51:29 +0800 Subject: [PATCH] fix: register DxDesigner menus from Start and keep the bridge alive --- docs/testing/dxdesigner-795-live.md | 25 ++- docs/testing/native-acceptance.md | 2 +- docs/user/一叶知秋_重构版_更新说明.md | 6 + integration/dxdesigner795/BridgeCommon.vbs | 15 ++ integration/dxdesigner795/LoadMenu.vbs | 23 +++ integration/dxdesigner795/MenuAdd.vbs | 18 +- integration/dxdesigner795/PdfSaveListener.vbs | 4 +- integration/dxdesigner795/core/Mailbox.vbs | 11 +- integration/dxdesigner795/core/Snapshot.vbs | 7 +- packaging/DxDesignerTools.spec | 2 + packaging/build_release.ps1 | 3 + src/dx_productivity/bridge/launcher.py | 4 + src/dx_productivity/bridge/startup.py | 172 +++++++++++++++++ src/dx_productivity/bridge/startup_assets.py | 146 ++++++++++++-- src/dx_productivity/ui/app.py | 18 +- src/dx_productivity/ui/main_window.py | 12 ++ src/dx_productivity/ui/startup_controller.py | 51 +++++ tests/bridge/test_startup.py | 182 +++++++++++++++--- tests/integration/test_menu_script.py | 3 +- tests/packaging/test_built_release.py | 4 +- tests/ui/test_main_window.py | 29 +++ tests/vbs/test_menu_add.vbs | 19 +- 22 files changed, 683 insertions(+), 73 deletions(-) create mode 100644 integration/dxdesigner795/LoadMenu.vbs create mode 100644 src/dx_productivity/bridge/startup.py create mode 100644 src/dx_productivity/ui/startup_controller.py diff --git a/docs/testing/dxdesigner-795-live.md b/docs/testing/dxdesigner-795-live.md index ead8b12..074cc9a 100644 --- a/docs/testing/dxdesigner-795-live.md +++ b/docs/testing/dxdesigner-795-live.md @@ -1,6 +1,6 @@ # DxDesigner 7.9.5 现场验收记录 -> 发布状态:离线构建已验证;真实 DxDesigner 7.9.5 验收待完成。所有关键项目通过前,不得把模拟测试结果表述为实机兼容结论。 +> 发布状态:Start 注册菜单、菜单启动工具及工程快照刷新已在 DxDesigner 7.9.5 实机核对;写回、PDF 出图及保存事件验收待完成。 ## 1. 测试信息 @@ -9,7 +9,7 @@ | Windows 版本 / Build | | | DxDesigner / Expedition Enterprise 完整版本与 Build | | | 工具 ZIP SHA-256 | | -| 解压根目录 | | +| 解压根目录 | `release\一叶知秋_重构版_Start修复版` | | `script_path_source` | | | 解析到的脚本完整路径 | | | 菜单回调路径 | | @@ -17,17 +17,24 @@ | `compatibility.json` 路径 | | | 测试工程 / 副本说明 | | | 测试器 | | -| 日期 | | +| 日期 | 2026-10-10 | ## 2. 发布包与启动脚本 - [ ] ZIP 在离线 Win11 x64 目标机完整解压,无需安装 Python、联网、管理员权限或环境变量。 -- [ ] 解压路径包含中文和空格时,`DxDesignerTools.exe` 可启动。 -- [ ] 仅通过 `Settings -> Run at Startup -> Scripts` 导入根目录 `MenuAdd.vbs`。 -- [ ] 首次重启后只出现一个“Dx 效率工具”菜单。 -- [ ] 连续重启两次后仍只有一个同名菜单,没有重复按钮。 -- [ ] 菜单包含“自动位号”“兼容性检测”“使用说明”,三个动作均能打开对应功能。 -- [ ] 移动完整工具目录后,旧路径失效提示明确;删除旧项并重新导入后恢复正常。 +- [x] 目录包含中文和空格时,`DxDesignerTools.exe` 可启动。 +- [x] 点击工具的 Start,自动生成用户目录中的启动配置并加载菜单。 +- [ ] 未打开 DxDesigner 时,Start 会带菜单配置启动宿主。 +- [x] 已打开的 DxDesigner 7.9.5 可即时加载菜单;2026-10-10 收到宿主回执。 +- [x] 连续注册两次,Main Menu Bar 与 Sheet Menu Bar 各只有一个菜单,每个含八个动作。 +- [ ] 菜单各功能在副本工程中均能完成操作。 +- [ ] 移动完整工具目录后重新打开 exe 并点击 Start,入口更新到新位置。 + +本次菜单实机检查记录:`%LOCALAPPDATA%\DxProductivity\startup-refactored\installed-menu.txt`。该记录只验证菜单与入口,工程写回、PDF 出图及保存事件仍需按后续条目验收。 + +2026-10-10 补充:通过真实 Sheet Menu Bar 的 PDF 菜单命令打开工具,读取 `1GPHY_RTL8211F.prj` 的完整路径与 114 个器件;同一连接连续刷新两次,快照序号从 1 增至 3,心跳继续更新。运行目录为 `%LOCALAPPDATA%\DxProductivity\runs\20261010T224256-4E6E617F`,宿主日志为 `%LOCALAPPDATA%\DxProductivity\bridge-diagnostics.log`。本次操作未执行应用或 PDF 出图。当前工程的命名图页返回非数字页名,`current_sheet_number` 尚为空,网络读取及所有写回功能仍未验收。 + +最终包补充:从 `release\一叶知秋_重构版_Start修复版\DxDesignerTools.exe` 启动 GUI 并调用 Start,返回“菜单已加入当前 DxDesigner”;触发 Sheet Menu Bar 的自动位号菜单命令后,实际启动同一目录下的 exe,显示当前工程及“桥接已连接”。运行目录为 `%LOCALAPPDATA%\DxProductivity\runs\20261010T225035-5245617F`。exe SHA-256 为 `978AF94FBB4646E80D6678B3E937A486D73E09A2EDB9D3F580B2DFFAD6FBB639`。本包采用隔离 PATH 的构建环境,避免混入其他软件的运行库。 ## 3. 兼容性检测 diff --git a/docs/testing/native-acceptance.md b/docs/testing/native-acceptance.md index 22ea6ab..c98894c 100644 --- a/docs/testing/native-acceptance.md +++ b/docs/testing/native-acceptance.md @@ -4,7 +4,7 @@ ## 通用前置条件 -- 使用便携包根目录的 `MenuAdd.vbs`,通过 DxDesigner 7.9.5 的启动脚本设置导入;Expedition 侧导入 `expedition\ExpeditionBridge.vbs`。 +- 从完整便携包打开 `DxDesignerTools.exe`,点击 Start 自动注册并加载 DxDesigner 菜单;Expedition 侧导入 `expedition\ExpeditionBridge.vbs`。 - 准备可恢复的样例工程,先复制工程目录和原理图文件。 - 运行“兼容性检测”,保存诊断输出和宿主版本信息。 diff --git a/docs/user/一叶知秋_重构版_更新说明.md b/docs/user/一叶知秋_重构版_更新说明.md index 0cbf111..bca5c4f 100644 --- a/docs/user/一叶知秋_重构版_更新说明.md +++ b/docs/user/一叶知秋_重构版_更新说明.md @@ -2,6 +2,12 @@ ## 本版变更(原生迁移版) +- 打开完整工具包中的 `DxDesignerTools.exe`,点击顶部 **Start**,即可自动加入 DxDesigner 菜单。已打开的 DxDesigner 会加载菜单;未打开时工具会带菜单配置启动它。 +- 菜单包含自动位号、属性批改、属性显示、设计检查、BOM、PDF 导出、兼容性检测及使用说明。Start 使用用户目录中的独立启动配置,保留公司原有启动脚本;生成入口明确绑定当前工具目录,支持中文及空格路径。 +- 移动完整工具包后重新打开其中的 exe 并点击 Start,入口会更新到新位置。工具目录不完整或宿主未加载成功时,界面会显示原因。DxDesigner 若正在等待报错对话框,先关闭该对话框,再点击 Start。 +- 修复菜单动作与 DxDesigner 内置常量重名、桥接心跳函数名错误,以及刷新快照时重复对象编号的问题。工程路径改用 7.9.5 的 `GetProjectData().GetProjectFilePath()`,PDF 保存监听也使用同一接口。 +- 菜单点击、快照生成与工具启动阶段写入 `%LOCALAPPDATA%\DxProductivity\bridge-diagnostics.log`,桥接异常会显示具体错误。 + - 原“一叶知秋”七大功能全部**原生迁移**进新工具,不再桥接旧 EFM/VBS:Value/Value1/Part Number 批量修改、PartName/PartLabel 批量隐藏(新增“显示”方向)、孤立网络/网络列表/跨页互动、Value/Value1 遗漏查找、BOM 导出(含创维料号校验)与 Expedition PCB 装配位号整理。 - 全部功能共用统一事务通道:预检(摘要与状态一致性校验)→ 逐项写回并读回验证 → 失败自动回滚 → 全设计终检。 - 桥接协议升级到 v2:快照包含属性全集、可见性、网络分布与真实锁定状态;调度表按“操作类型 + 属性名”泛化,同一事务核心承载所有功能。 diff --git a/integration/dxdesigner795/BridgeCommon.vbs b/integration/dxdesigner795/BridgeCommon.vbs index c91383a..8753f2c 100644 --- a/integration/dxdesigner795/BridgeCommon.vbs +++ b/integration/dxdesigner795/BridgeCommon.vbs @@ -1,5 +1,20 @@ ' Shared DxDesigner 7.9.5 bridge helpers. Keep this file ASCII-only. +Sub DxToolsAppendDiagnostic(stage, detail) + Dim fso, root, stream + On Error Resume Next + Set fso = CreateObject("Scripting.FileSystemObject") + root = CreateObject("WScript.Shell").ExpandEnvironmentStrings( _ + "%LOCALAPPDATA%\DxProductivity") + If Not fso.FolderExists(root) Then fso.CreateFolder root + Set stream = fso.OpenTextFile( _ + fso.BuildPath(root, "bridge-diagnostics.log"), 8, True, -1) + stream.WriteLine CStr(Now) & " " & CStr(stage) & " " & CStr(detail) + stream.Close + Err.Clear + On Error GoTo 0 +End Sub + Function DxToolsQuote(value) Dim text Dim expression diff --git a/integration/dxdesigner795/LoadMenu.vbs b/integration/dxdesigner795/LoadMenu.vbs new file mode 100644 index 0000000..1d5dfd0 --- /dev/null +++ b/integration/dxdesigner795/LoadMenu.vbs @@ -0,0 +1,23 @@ +' Request the current DxDesigner host to execute the generated menu script. +' This external adapter only forwards a command; design APIs run in the host. +Option Explicit +Dim app, path, errorText +If WScript.Arguments.Count <> 1 Then WScript.Quit 2 +path = WScript.Arguments(0) +If Not CreateObject("Scripting.FileSystemObject").FileExists(path) Then WScript.Quit 2 +On Error Resume Next +Set app = GetObject(, "ViewDraw.Application") +If Err.Number <> 0 Or app Is Nothing Then + Err.Clear + WScript.Quit 3 +End If +Err.Clear +app.ExecuteCommand "run " & Chr(34) & path & Chr(34) +If Err.Number <> 0 Then + errorText = Err.Description + Err.Clear + WScript.Echo errorText + WScript.Quit 1 +End If +On Error GoTo 0 +WScript.Quit 0 diff --git a/integration/dxdesigner795/MenuAdd.vbs b/integration/dxdesigner795/MenuAdd.vbs index a487a8e..552dc05 100644 --- a/integration/dxdesigner795/MenuAdd.vbs +++ b/integration/dxdesigner795/MenuAdd.vbs @@ -20,6 +20,15 @@ Else End If Sub DxToolsInstallMenu() + Call DxToolsInstallMenuBar("Main Menu Bar") + Call DxToolsInstallMenuBar("Sheet Menu Bar") + On Error Resume Next + Call DxToolsMaybeStartPdfListener() + Err.Clear + On Error GoTo 0 +End Sub + +Sub DxToolsInstallMenuBar(barName) Dim menuBar Dim existing Dim button @@ -27,7 +36,7 @@ Sub DxToolsInstallMenu() Dim caption caption = DxToolsSuiteCaption() - Set menuBar = CommandBars("Sheet Menu Bar") + Set menuBar = CommandBars(CStr(barName)) For i = menuBar.Controls.Count To 1 Step -1 Set existing = menuBar.Controls.Item(i) If existing.Caption = caption Then @@ -38,7 +47,8 @@ Sub DxToolsInstallMenu() End If Next - Set DxToolsMenu = menuBar.Controls.Add(cmdControlPopup) + ' CommandBarSvr70/75 defines cmdControlPopup as 1; Run does not inject it. + Set DxToolsMenu = menuBar.Controls.Add(1) DxToolsMenu.Caption = caption Set button = DxToolsMenu.Controls.Add @@ -72,10 +82,6 @@ Sub DxToolsInstallMenu() Set button = DxToolsMenu.Controls.Add button.Caption = DxToolsGuideCaption() button.OnAction = "DxToolsOpenGuide" - On Error Resume Next - Call DxToolsMaybeStartPdfListener() - Err.Clear - On Error GoTo 0 End Sub Sub DxToolsOpenRefDes() diff --git a/integration/dxdesigner795/PdfSaveListener.vbs b/integration/dxdesigner795/PdfSaveListener.vbs index 295c34e..69ff863 100644 --- a/integration/dxdesigner795/PdfSaveListener.vbs +++ b/integration/dxdesigner795/PdfSaveListener.vbs @@ -80,7 +80,7 @@ Sub DxPdf_AfterDocumentSave(Doc) projectPath = "" blockName = "" On Error Resume Next - projectPath = CStr(app.ProjectPath) + projectPath = CStr(app.GetProjectData().GetProjectFilePath()) blockName = CStr(app.ActiveView.Block.GetName(1)) If Err.Number <> 0 Then Call DxPdfLog("Could not read saved project or active Block: " & Err.Description) @@ -216,7 +216,7 @@ Function DxPdfHostAvailable() Dim projectPath DxPdfHostAvailable = False On Error Resume Next - projectPath = CStr(app.ProjectPath) + projectPath = CStr(app.GetProjectData().GetProjectFilePath()) DxPdfHostAvailable = (Err.Number = 0) Err.Clear On Error GoTo 0 diff --git a/integration/dxdesigner795/core/Mailbox.vbs b/integration/dxdesigner795/core/Mailbox.vbs index 297667a..98e2786 100644 --- a/integration/dxdesigner795/core/Mailbox.vbs +++ b/integration/dxdesigner795/core/Mailbox.vbs @@ -63,6 +63,7 @@ Function DxLaunchUi(runRoot, featureKey) Exit Function End If Set DxLaunchUi = process + Call DxToolsAppendDiagnostic("ui.started", "pid=" & CStr(process.ProcessID) & " " & runRoot) End Function Function DxBridgeUiCommand(runRoot, featureKey) @@ -93,7 +94,7 @@ Function DxBridgeMailboxLoop(process, runRoot, runId, snapshotId, _ Call DxBridgePumpRefresh(runRoot, runId, objectMap, originalMap, _ snapshotId) Call DxBridgePumpBomExport(runRoot) - Call DxBridgeWriteProgress(runRoot, "waiting") + Call DxWriteProgress(runRoot, "waiting") If fso.FileExists(resultPath) Then If DxBridgeClaimFile(fso, resultPath, claimPath) Then Call DxWriteProgress(runRoot, "processing") @@ -133,14 +134,20 @@ Sub DxBridgePumpRefresh(runRoot, runId, objectMap, originalMap, _ Dim fso Dim refreshPath Dim claimPath + Dim refreshedObjects + Dim refreshedOriginals Set fso = CreateObject("Scripting.FileSystemObject") refreshPath = fso.BuildPath(runRoot, "refresh.request") If Not fso.FileExists(refreshPath) Then Exit Sub claimPath = fso.BuildPath(runRoot, "refresh.processing") If Not DxBridgeClaimFile(fso, refreshPath, claimPath) Then Exit Sub Call DxWriteProgress(runRoot, "processing") - If DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _ + Set refreshedObjects = CreateObject("Scripting.Dictionary") + Set refreshedOriginals = CreateObject("Scripting.Dictionary") + If DxRefreshSnapshot(runRoot, runId, refreshedObjects, refreshedOriginals, _ snapshotId) Then + Set objectMap = refreshedObjects + Set originalMap = refreshedOriginals Call DxWriteProgress(runRoot, "waiting") End If On Error Resume Next diff --git a/integration/dxdesigner795/core/Snapshot.vbs b/integration/dxdesigner795/core/Snapshot.vbs index cdfff85..8fdb215 100644 --- a/integration/dxdesigner795/core/Snapshot.vbs +++ b/integration/dxdesigner795/core/Snapshot.vbs @@ -13,6 +13,7 @@ Function DxExportSnapshot(objectMap, originalMap, ByRef runRoot, _ "%LOCALAPPDATA%\DxProductivity\runs") runRoot = fsoBuildPath(runsRoot, CStr(runId)) Call DxBridgeEnsureFolder(runRoot) + Call DxToolsAppendDiagnostic("snapshot.begin", runRoot) DxExportSnapshot = DxRefreshSnapshot(runRoot, runId, objectMap, _ originalMap, snapshotId) End Function @@ -69,9 +70,11 @@ Function DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _ Exit Function End If On Error GoTo 0 + Call DxToolsAppendDiagnostic("snapshot.project", "project data available") Set designs = projectData.GetiCDBDesigns() designId = CStr(designs.GetItem(1)) topBlock = projectData.GetiCDBDesignRootBlock(designId) + Call DxToolsAppendDiagnostic("snapshot.design", "id=" & designId & " root=" & CStr(topBlock)) designPath = DxBridgeDesignPath() activeBlockName = DxBridgeCurrentBlockName() currentSheetNumberJson = DxBridgeCurrentSheetNumberJson() @@ -154,6 +157,7 @@ Function DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _ " ]" & vbCrLf & "}" & vbCrLf Call DxToolsWriteUtf8Atomic(fsoBuildPath(runRoot, "request.json"), _ requestText) + Call DxToolsAppendDiagnostic("snapshot.ready", runRoot & " components=" & CStr(componentCount)) DxRefreshSnapshot = True End Function @@ -289,6 +293,7 @@ Function DxBridgeNextSnapshotSequence(runRoot) End Function Sub DxBridgeExportFailed(message) + Call DxToolsAppendDiagnostic("snapshot.error", message) MsgBox DxBridgeExportFailedPrefix() & vbCrLf & message, vbExclamation End Sub @@ -475,7 +480,7 @@ End Function Function DxBridgeDesignPath() DxBridgeDesignPath = "" On Error Resume Next - DxBridgeDesignPath = CStr(Application.ProjectPath) + DxBridgeDesignPath = CStr(Application.GetProjectData().GetProjectFilePath()) Err.Clear On Error GoTo 0 End Function diff --git a/packaging/DxDesignerTools.spec b/packaging/DxDesignerTools.spec index d9fd155..a78654c 100644 --- a/packaging/DxDesignerTools.spec +++ b/packaging/DxDesignerTools.spec @@ -1,11 +1,13 @@ # -*- mode: python ; coding: utf-8 -*- from pathlib import Path +import sys from PyInstaller.utils.hooks import collect_data_files, collect_submodules ROOT = Path(SPEC).resolve().parent.parent +sys.path.insert(0, str(ROOT / "src")) hiddenimports = ( collect_submodules("dx_productivity") + collect_submodules("qtawesome") diff --git a/packaging/build_release.ps1 b/packaging/build_release.ps1 index 51853bf..7aa2e1a 100644 --- a/packaging/build_release.ps1 +++ b/packaging/build_release.ps1 @@ -83,6 +83,7 @@ Copy-Item -LiteralPath (Join-Path $repoRoot "integration\dxdesigner795\MenuAdd.v Copy-Item -LiteralPath (Join-Path $repoRoot "integration\dxdesigner795\DesignBridge.vbs") -Destination (Join-Path $releaseRoot "DesignBridge.vbs") Copy-Item -LiteralPath (Join-Path $repoRoot "integration\dxdesigner795\CompatibilityProbe.vbs") -Destination (Join-Path $releaseRoot "CompatibilityProbe.vbs") Copy-Item -LiteralPath (Join-Path $repoRoot "integration\dxdesigner795\PdfSaveListener.vbs") -Destination (Join-Path $releaseRoot "PdfSaveListener.vbs") +Copy-Item -LiteralPath (Join-Path $repoRoot "integration\dxdesigner795\LoadMenu.vbs") -Destination (Join-Path $releaseRoot "LoadMenu.vbs") $runtimeVbs = Join-Path $releaseRoot "_runtime\vbs" New-Item -ItemType Directory -Path $runtimeVbs -Force | Out-Null @@ -106,6 +107,7 @@ $guideDestination = Join-Path $docsRoot "DxDesigner_7.9.5_自动位号工具使 Copy-Item -LiteralPath $guideSource -Destination $guideDestination $pdfGuideDestination = Join-Path $docsRoot "PDF导出.md" Copy-Item -LiteralPath (Join-Path $repoRoot "docs\user\PDF_export.md") -Destination $pdfGuideDestination +Copy-Item -LiteralPath (Join-Path $repoRoot "docs\user\一叶知秋_重构版_更新说明.md") -Destination (Join-Path $docsRoot "更新说明.md") $env:PYTHONPATH = Join-Path $repoRoot "src" $productVersion = (& $pythonExe -c "import dx_productivity; print(dx_productivity.__version__)").Trim() @@ -139,6 +141,7 @@ $expected = @( (Join-Path $releaseRoot "DesignBridge.vbs"), (Join-Path $releaseRoot "CompatibilityProbe.vbs"), (Join-Path $releaseRoot "PdfSaveListener.vbs"), + (Join-Path $releaseRoot "LoadMenu.vbs"), (Join-Path $releaseRoot "_runtime\vbs\BridgeCommon.vbs"), (Join-Path $releaseRoot "_runtime\vbs\Snapshot.vbs"), (Join-Path $releaseRoot "_runtime\vbs\Transaction.vbs"), diff --git a/src/dx_productivity/bridge/launcher.py b/src/dx_productivity/bridge/launcher.py index 293267b..7106d33 100644 --- a/src/dx_productivity/bridge/launcher.py +++ b/src/dx_productivity/bridge/launcher.py @@ -8,6 +8,10 @@ from collections.abc import Sequence def main(argv: Sequence[str] | None = None) -> int: arguments = list(sys.argv[1:] if argv is None else argv) + if arguments and arguments[0] in ("startup", "start"): + from dx_productivity.bridge.startup import main as startup_main + + return startup_main(arguments[1:]) if arguments and arguments[0] == "probe": from dx_productivity.bridge.probe_host import main as probe_main diff --git a/src/dx_productivity/bridge/startup.py b/src/dx_productivity/bridge/startup.py new file mode 100644 index 0000000..c794a17 --- /dev/null +++ b/src/dx_productivity/bridge/startup.py @@ -0,0 +1,172 @@ +"""Install the tool menu and start or reuse DxDesigner without UI automation.""" +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import time + +from dx_productivity.bridge.startup_assets import REQUIRED_FILES, StartupAssets, generate_startup_assets, write_atomic + + +class StartupError(RuntimeError): + pass + + +@dataclass(frozen=True) +class StartupConfiguration: + assets: StartupAssets + scripts_ini: Path + viewdraw: Path + launch_environment: dict[str, str] + + +def discover_viewdraw(environment: dict[str, str]) -> Path: + candidates = [] + explicit = environment.get("VIEWDRAW_EXE") + if explicit: + candidates.append(Path(explicit.strip('"'))) + sdd_home = environment.get("SDD_HOME") + if sdd_home: + candidates.append(Path(sdd_home) / "wv/win32/bin/viewdraw.exe") + on_path = shutil.which("viewdraw.exe", path=environment.get("PATH", "")) + if on_path: + candidates.append(Path(on_path)) + for drive in "CDEFG": + root = Path(f"{drive}:/Mentor") + if root.is_dir(): + candidates.extend(root.glob("7.9.5*/SDD_HOME/wv/win32/bin/viewdraw.exe")) + for candidate in candidates: + if candidate.is_file() and candidate.name.lower() == "viewdraw.exe": + return candidate.resolve() + raise StartupError("未找到 DxDesigner 7.9.5,请确认已安装该版本,或设置 VIEWDRAW_EXE 指定可执行文件。") + + +def _read_ini(path: Path) -> tuple[str, str]: + if not path.exists(): + return "", "gbk" + data = path.read_bytes() + if data.startswith(b"\xef\xbb\xbf"): + return data.decode("utf-8-sig"), "utf-8-sig" + if data.startswith((b"\xff\xfe", b"\xfe\xff")): + return data.decode("utf-16"), "utf-16" + for encoding in ("gbk", "utf-8"): + try: + return data.decode(encoding), encoding + except UnicodeError: + continue + raise StartupError(f"无法读取启动配置编码:{path}") + + +def _register_menu(text: str, menu: Path) -> str: + lines = text.splitlines() + start = next((i for i, line in enumerate(lines) if line.strip().lower() == "[viewdraw]"), None) + if start is None: + lines += ["[ViewDraw]"] + start = len(lines) - 1 + end = next((i for i in range(start + 1, len(lines)) if lines[i].strip().startswith("[")), len(lines)) + entry = str(menu) + used = set() + for line in lines[start + 1:end]: + match = re.match(r"\s*(?:Script|脚本)#(\d+)\s*=\s*(.*)", line, re.I) + if match: + used.add(int(match[1])) + if os.path.normcase(match[2].strip('"')) == os.path.normcase(entry): + return text + index = next(i for i in range(len(used) + 1) if i not in used) + lines[end:end] = ["; DxProductivity Start managed entry", f"Script#{index}={entry}"] + return "\r\n".join(lines) + "\r\n" + + +def prepare_startup(tool_root: Path, viewdraw: Path, environment: dict[str, str]) -> StartupConfiguration: + tool_root = tool_root.resolve() + missing = [name for name in REQUIRED_FILES if not (tool_root / name).is_file()] + if missing: + raise StartupError("工具目录不完整,缺少:" + ", ".join(missing)) + if not viewdraw.is_file(): + raise StartupError(f"DxDesigner 可执行文件不存在:{viewdraw}") + profile = environment.get("LOCALAPPDATA", "") + if not profile: + raise StartupError("无法读取用户配置目录 LOCALAPPDATA") + startup_root = Path(profile) / "DxProductivity" / "startup-refactored" + # No system or user environment variable is modified: WDIR belongs to the + # child process. Preserve peer scripts by copying the existing configuration. + wdir = [] + for entry in environment.get("WDIR", "").split(";"): + if entry.strip(): + path = Path(os.path.expandvars(entry.strip().strip('"'))) + if path.resolve() != startup_root.resolve(): + wdir.append(path) + standard = viewdraw.resolve().parents[3] / "standard" + if standard not in wdir: + wdir.append(standard) + vendor_ini = next((path / "scripts.ini" for path in wdir if (path / "scripts.ini").is_file()), None) + text, encoding = _read_ini(vendor_ini) if vendor_ini else ("", "gbk") + catalog = next((path / "vllib.vmb" for path in wdir if (path / "vllib.vmb").is_file()), None) + if catalog is None: + raise StartupError("DxDesigner 安装不完整,未找到消息目录 vllib.vmb") + assets = generate_startup_assets(tool_root, startup_root) + ini = startup_root / "scripts.ini" + content = _register_menu(text, assets.menu_script).encode(encoding) + if ini.exists() and ini.read_bytes() != content: + backups = Path(profile) / "DxProductivity" / "backups" + backups.mkdir(parents=True, exist_ok=True) + shutil.copy2(ini, backups / f"startup-scripts.{datetime.now():%Y%m%d-%H%M%S-%f}.bak") + if not ini.exists() or ini.read_bytes() != content: + write_atomic(ini, content) + shutil.copy2(catalog, startup_root / "vllib.vmb") + child_environment = dict(environment) + child_environment["WDIR"] = ";".join(str(path) for path in (startup_root, *wdir)) + # Keep tool subprocesses on the package that Start actually registered. + child_environment["DXTOOLS_HOME"] = str(tool_root) + state = {"format_version": 3, "viewdraw": str(viewdraw.resolve()), "tool_root": str(tool_root), "scripts_ini": str(ini), "menu_script": str(assets.menu_script)} + write_atomic(startup_root / "startup.json", json.dumps(state, ensure_ascii=False, indent=2).encode("utf-8")) + return StartupConfiguration(assets, ini, viewdraw.resolve(), child_environment) + + +def start_dxdesigner(tool_root: Path, *, viewdraw: Path | None = None, environment: dict[str, str] | None = None, timeout: float = 20) -> str: + environment = dict(os.environ if environment is None else environment) + configuration = prepare_startup(tool_root, viewdraw or discover_viewdraw(environment), environment) + host = Path(environment.get("WINDIR", "C:/Windows")) / "SysWOW64/cscript.exe" + if not host.is_file(): + host = host.parent.parent / "System32/cscript.exe" + command = [str(host), "//B", "//NoLogo", str(tool_root / "LoadMenu.vbs"), str(configuration.assets.menu_script)] + try: + loaded = subprocess.run(command, capture_output=True, timeout=timeout, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) + except subprocess.TimeoutExpired as error: + raise StartupError("DxDesigner 正在等待对话框或忙于操作,请关闭报错对话框后再次点击 Start。") from error + reused = loaded.returncode == 0 + if loaded.returncode == 3: + subprocess.Popen([str(configuration.viewdraw)], cwd=configuration.viewdraw.parent, env=configuration.launch_environment) + elif loaded.returncode != 0: + detail = (loaded.stdout + loaded.stderr).decode("mbcs", errors="replace").strip() + raise StartupError("无法让当前 DxDesigner 加载菜单:" + (detail or str(loaded.returncode))) + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + if configuration.assets.ready_file.read_text(encoding="utf-16").strip() == configuration.assets.token: + return "菜单已加入当前 DxDesigner" if reused else "DxDesigner 已启动,工具菜单已加载" + except (OSError, UnicodeError): + pass + time.sleep(0.1) + raise StartupError("未收到 DxDesigner 的菜单加载回执,请查看宿主报错;启动配置已准备,可再次点击 Start。") + + +def main(argv=None) -> int: + import argparse + import sys + parser = argparse.ArgumentParser(description="Register the tool menu and start DxDesigner") + parser.add_argument("--tool-root", type=Path, default=Path(sys.executable).resolve().parent) + parser.add_argument("--viewdraw", type=Path) + options = parser.parse_args(argv) + try: + print(start_dxdesigner(options.tool_root, viewdraw=options.viewdraw)) + except (StartupError, OSError, ValueError) as error: + print(str(error), file=sys.stderr) + return 1 + return 0 diff --git a/src/dx_productivity/bridge/startup_assets.py b/src/dx_productivity/bridge/startup_assets.py index 9569853..7f04be7 100644 --- a/src/dx_productivity/bridge/startup_assets.py +++ b/src/dx_productivity/bridge/startup_assets.py @@ -1,31 +1,141 @@ -"""Describe startup menu actions included in a portable release.""" +"""Generate self-contained scripts for the DxDesigner 7.9.5 Run host.""" from __future__ import annotations from dataclasses import dataclass from pathlib import Path +import re +import uuid + + +FEATURE_ACTIONS = { + "refdes": ("DxToolsOpenRefDes", "DxRefDesAction.vbs"), + "property-change": ("DxToolsOpenPropertyChange", "DxPropertyChangeAction.vbs"), + "property-visibility": ("DxToolsOpenPropertyVisibility", "DxPropertyVisibilityAction.vbs"), + "inspection": ("DxToolsOpenInspection", "DxInspectionAction.vbs"), + "bom": ("DxToolsOpenBom", "DxBomAction.vbs"), + "pdf-export": ("DxToolsOpenPdfExport", "DxPdfExportAction.vbs"), + "compatibility": ("DxToolsOpenCompatibility", "DxCompatibilityAction.vbs"), + "guide": ("DxToolsOpenGuide", "DxGuideAction.vbs"), +} +CORE_FILES = ("Snapshot.vbs", "Transaction.vbs", "Mailbox.vbs", "BomExport.vbs") +REQUIRED_FILES = ( + "DxDesignerTools.exe", "MenuAdd.vbs", "DesignBridge.vbs", + "CompatibilityProbe.vbs", "LoadMenu.vbs", "_runtime/vbs/BridgeCommon.vbs", + *(f"_runtime/vbs/{name}" for name in CORE_FILES), +) @dataclass(frozen=True, slots=True) class StartupAssets: - tool_root: Path - action_scripts: dict[str, str] + menu_script: Path + action_scripts: dict[str, Path] + ready_file: Path + token: str -def generate_startup_assets(tool_root: Path) -> StartupAssets: - """Return stable named actions for the startup-imported menu. +def generate_startup_assets(tool_root: Path, startup_root: Path) -> StartupAssets: + """Bind the package location explicitly; host path metadata is unreliable.""" + tool_root = tool_root.resolve() + startup_root = startup_root.resolve() + startup_root.mkdir(parents=True, exist_ok=True) + menu_script = startup_root / "MenuAdd.vbs" + ready_file = startup_root / "menu-ready.txt" + token = uuid.uuid4().hex + actions = {key: startup_root / value[1] for key, value in FEATURE_ACTIONS.items()} + menu = (tool_root / "MenuAdd.vbs").read_text(encoding="ascii") + assignment = "\n".join(( + f"DxToolsHome = {vbscript_string(str(tool_root))}", + 'DxToolsScriptPathSource = "Start generated configuration"', + f"DxToolsScriptFullName = {vbscript_string(str(menu_script))}", + )) + root_entry = r"(?m)^DxToolsHome = DxToolsResolveRoot\(\)$" + if len(re.findall(root_entry, menu)) != 1: + raise ValueError("MenuAdd.vbs does not contain the expected startup entry") + menu = re.sub(root_entry, lambda _match: assignment, menu) + for key, (procedure, _) in FEATURE_ACTIONS.items(): + old = f'button.OnAction = "{procedure}"' + if menu.count(old) != 1: + raise ValueError(f"MenuAdd.vbs is missing action: {key}") + command = 'run "' + str(actions[key]) + '"' + menu = menu.replace(old, f"button.OnAction = {vbscript_string(command)}") + menu = menu.replace( + " Call DxToolsInstallMenu()", + " Call DxToolsInstallMenu()\n Call DxToolsWriteMenuReady()", 1, + ) + menu += "\n" + "\n".join(( + "Sub DxToolsWriteMenuReady()", " Dim stream", + " Set stream = CreateObject(\"Scripting.FileSystemObject\").CreateTextFile( _", + f" {vbscript_string(str(ready_file))}, True, True)", + f" stream.WriteLine {vbscript_string(token)}", " stream.Close", "End Sub", "", + )) + common = (tool_root / "_runtime/vbs/BridgeCommon.vbs").read_text(encoding="ascii") + design = "\n".join( + (tool_root / "_runtime/vbs" / name).read_text(encoding="ascii") + for name in CORE_FILES + ) + "\n" + (tool_root / "DesignBridge.vbs").read_text(encoding="ascii") + for key, action_path in actions.items(): + context = "\n".join(( + "' Generated by the Start button. Do not edit.", + "' ViewDraw supplies its VDM/VD enums to Run actions. Do not redeclare them.", + "Dim DxToolsHome, DxToolsScriptPathSource, DxToolsScriptFullName", + f"DxToolsHome = {vbscript_string(str(tool_root))}", + 'DxToolsScriptPathSource = "generated Run action"', + f"DxToolsScriptFullName = {vbscript_string(str(action_path))}", + )) + if key == "compatibility": + content = context + "\n" + common + "\n" + (tool_root / "CompatibilityProbe.vbs").read_text(encoding="ascii") + entry = 'Call DxToolsProbeExecute("run")' + elif key == "guide": + guide = tool_root / "docs" / "DxDesigner_7.9.5_自动位号工具使用说明.docx" + content = context + entry = 'CreateObject("WScript.Shell").Run ' + vbscript_string('"' + str(guide) + '"') + ", 1, False" + else: + content = context + "\nDim DxToolsDesignBridgeCoreLoaded\nDxToolsDesignBridgeCoreLoaded = True\n" + common + "\n" + design + entry = "\n".join(( + f'Call DxToolsAppendDiagnostic("menu.click", "{key} root=" & DxToolsHome)', + "Dim DxToolsActionError", + "On Error Resume Next", + f'Call DxToolsRunDesignBridge("{key}")', + 'DxToolsActionError = ""', + "If Err.Number <> 0 Then DxToolsActionError = CStr(Err.Number) & \": \" & Err.Description", + "Err.Clear", + "On Error GoTo 0", + 'If DxToolsActionError <> "" Then', + ' Call DxToolsAppendDiagnostic("bridge.error", DxToolsActionError)', + ' MsgBox DxToolsActionError, vbExclamation, "Dx tools bridge"', + "End If", + )) + write_atomic(action_path, (content + "\n' DXTOOLS_ENTRY\n" + entry + "\n").encode("ascii")) + write_atomic(menu_script, menu.replace("\r\n", "\n").replace("\n", "\r\n").encode("ascii")) + return StartupAssets(menu_script, actions, ready_file, token) - The values are action routes, not filesystem paths. This deliberately keeps - the menu relocatable and prevents feature actions from entering RefDes state. - """ - actions = { - "refdes": "DxToolsOpenRefDes", - "property-change": "DxToolsOpenPropertyChange", - "property-visibility": "DxToolsOpenPropertyVisibility", - "inspection": "DxToolsOpenInspection", - "bom": "DxToolsOpenBom", - "compatibility": "DxToolsOpenCompatibility", - "guide": "DxToolsOpenGuide", - } - return StartupAssets(tool_root=Path(tool_root), action_scripts=actions) +def vbscript_string(value: str) -> str: + """Represent Unicode paths in ASCII VBS, including UTF-16 surrogate pairs.""" + parts = [] + buffer = [] + def flush(): + if buffer: + parts.append('"' + "".join(buffer).replace('"', '""') + '"') + buffer.clear() + for char in value: + if ord(char) < 128: + buffer.append(char) + else: + flush() + encoded = char.encode("utf-16-le") + for index in range(0, len(encoded), 2): + parts.append(f"ChrW(&H{int.from_bytes(encoded[index:index + 2], 'little'):04X})") + flush() + return " & ".join(parts) if parts else '""' + + +def write_atomic(path: Path, data: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp") + try: + temporary.write_bytes(data) + temporary.replace(path) + finally: + temporary.unlink(missing_ok=True) diff --git a/src/dx_productivity/ui/app.py b/src/dx_productivity/ui/app.py index 475f04a..3b61fe6 100644 --- a/src/dx_productivity/ui/app.py +++ b/src/dx_productivity/ui/app.py @@ -23,6 +23,7 @@ from dx_productivity.domain.models import RunPaths from dx_productivity.ui.bom_controller import BomController from dx_productivity.ui.bom_page import BomPage from dx_productivity.ui.main_window import MainWindow +from dx_productivity.ui.startup_controller import StartupController from dx_productivity.ui.property_change_controller import PropertyChangeController from dx_productivity.ui.property_change_page import PropertyChangePage from dx_productivity.ui.property_visibility_controller import ( @@ -294,6 +295,17 @@ def create_main_window(request_path: Path | None = None) -> MainWindow: window.navigation.setCurrentRow(0) window.pages.setCurrentIndex(0) window.page_title.setText("自动位号") + startup_controller = StartupController(_tool_root(), window) + window.startup_controller = startup_controller + window.start_requested.connect(startup_controller.start) + startup_controller.started.connect(lambda: window.start_button.setEnabled(False)) + startup_controller.started.connect(lambda: window.operation_status.setText("正在自动加入 DxDesigner 菜单…")) + def startup_finished(success: bool, message: str) -> None: + window.start_button.setEnabled(True) + window.operation_status.setText(message) + if not success: + QMessageBox.warning(window, "Start 未完成", message) + startup_controller.completed.connect(startup_finished) return window @@ -380,11 +392,13 @@ def _install_excepthook() -> None: def _tool_root() -> Path: + # A copied portable executable must never use a cached root from another + # release inherited through DXTOOLS_HOME. + if getattr(sys, "frozen", False): + return Path(sys.executable).resolve().parent configured = os.environ.get("DXTOOLS_HOME") if configured: return Path(configured) - if getattr(sys, "frozen", False): - return Path(sys.executable).resolve().parent return Path(__file__).resolve().parents[3] / "integration" / "dxdesigner795" diff --git a/src/dx_productivity/ui/main_window.py b/src/dx_productivity/ui/main_window.py index e219e50..7bcbcdf 100644 --- a/src/dx_productivity/ui/main_window.py +++ b/src/dx_productivity/ui/main_window.py @@ -36,6 +36,7 @@ NAVIGATION = ( class MainWindow(QMainWindow): + start_requested = Signal() refresh_requested = Signal() preview_requested = Signal() apply_requested = Signal() @@ -71,6 +72,11 @@ class MainWindow(QMainWindow): self.page_title.setText(NAVIGATION[index][0]) def closeEvent(self, event) -> None: + startup = getattr(self, "startup_controller", None) + if startup is not None and startup.is_running(): + self.operation_status.setText("正在完成菜单注册,请稍候再关闭") + event.ignore() + return for controller in ( getattr(self, "settings_controller", None), getattr(self, "refdes_controller", None), @@ -117,6 +123,11 @@ class MainWindow(QMainWindow): layout.addWidget(self.project_label) layout.addStretch(1) + self.start_button = QPushButton("Start") + self.start_button.setToolTip("自动加入工具菜单并打开 DxDesigner") + self.start_button.setAccessibleName("Start:加入菜单并打开 DxDesigner") + self.start_button.clicked.connect(self.start_requested) + layout.addWidget(self.start_button) self.theme_button = self._tool_button("切换明暗主题") self.theme_button.clicked.connect(self._toggle_theme) layout.addWidget(self.theme_button) @@ -224,6 +235,7 @@ class MainWindow(QMainWindow): def _refresh_icons(self) -> None: tokens = theme_tokens(self.theme) + self.start_button.setIcon(themed_icon("fa6s.play", self.theme)) self.theme_button.setIcon( themed_icon( "fa6s.sun" if self.theme is Theme.DARK else "fa6s.moon", diff --git a/src/dx_productivity/ui/startup_controller.py b/src/dx_productivity/ui/startup_controller.py new file mode 100644 index 0000000..13a30a1 --- /dev/null +++ b/src/dx_productivity/ui/startup_controller.py @@ -0,0 +1,51 @@ +"""Keep menu installation and host startup off the Qt UI thread.""" +from pathlib import Path + +from PySide6.QtCore import QObject, QThread, Signal, Slot + +from dx_productivity.bridge.startup import start_dxdesigner + + +class _StartupWorker(QThread): + def __init__(self, tool_root, service, parent): + super().__init__(parent) + self.tool_root = tool_root + self.service = service + self.result = (False, "启动未完成") + + def run(self): + try: + self.result = (True, self.service(self.tool_root)) + except Exception as error: + self.result = (False, str(error)) + + +class StartupController(QObject): + started = Signal() + completed = Signal(bool, str) + + def __init__(self, tool_root: Path, parent=None, *, service=start_dxdesigner): + super().__init__(parent) + self.tool_root = tool_root + self.service = service + self._worker = None + + def is_running(self): + return self._worker is not None and self._worker.isRunning() + + @Slot() + def start(self): + if self.is_running(): + return + self.started.emit() + self._worker = _StartupWorker(self.tool_root, self.service, self) + self._worker.finished.connect(self._finish) + self._worker.finished.connect(self._worker.deleteLater) + self._worker.start() + + @Slot() + def _finish(self): + worker = self._worker + self._worker = None + if worker is not None: + self.completed.emit(*worker.result) diff --git a/tests/bridge/test_startup.py b/tests/bridge/test_startup.py index cf05b1e..ea1687b 100644 --- a/tests/bridge/test_startup.py +++ b/tests/bridge/test_startup.py @@ -1,31 +1,165 @@ from pathlib import Path +import shutil +import subprocess + +import pytest + +from dx_productivity.bridge.startup_assets import generate_startup_assets -def test_generate_startup_assets_lists_all_feature_actions() -> None: - from dx_productivity.bridge.startup_assets import generate_startup_assets +@pytest.fixture +def portable_root(tmp_path): + root = tmp_path / "一叶知秋 工具" + integration = Path(__file__).parents[2] / "integration" / "dxdesigner795" + root.mkdir() + (root / "DxDesignerTools.exe").write_bytes(b"fixture") + for name in ("MenuAdd.vbs", "DesignBridge.vbs", "CompatibilityProbe.vbs", "LoadMenu.vbs"): + source = integration / name + if source.exists(): + shutil.copy2(source, root / name) + runtime = root / "_runtime" / "vbs" + runtime.mkdir(parents=True) + shutil.copy2(integration / "BridgeCommon.vbs", runtime) + for source in (integration / "core").glob("*.vbs"): + shutil.copy2(source, runtime) + return root - assets = generate_startup_assets(Path("C:/portable/DxDesignerTools")) +def test_generated_menu_loads_without_host_script_path_metadata(portable_root, tmp_path): + assets = generate_startup_assets(portable_root, tmp_path / "用户 profile") + # Run the real VBS without DxDesigner script-path globals: the reported bug. + fixture = Path(__file__).parents[1] / "vbs" / "test_menu_add.vbs" + fake_host = fixture.read_text(encoding="ascii").split('Set Fso = CreateObject')[0] + fake_host = fake_host.replace("Const cmdControlPopup = 1", "") + collection = fake_host.split("Class FakeControlsCollection", 1)[1].split("End Class", 1)[0] + popup_collection = "Class FakePopupControlsCollection" + collection.replace( + "Public Function Add()", + 'Public Function Add(controlType)\n If CStr(controlType) <> "1" Then WScript.Quit 5', + ) + "End Class\n" + harness = tmp_path / "host.vbs" + harness.write_text( + fake_host + popup_collection + + '\nSet Fso = CreateObject("Scripting.FileSystemObject")\n' + + 'Set FakeMenuBar = New FakeControl\n' + + 'Set FakeMenuBar.Controls = New FakePopupControlsCollection\n' + + 'Set FakeMainMenuBar = New FakeControl\n' + + 'Set FakeMainMenuBar.Controls = New FakePopupControlsCollection\n' + + 'MenuText = Fso.OpenTextFile(WScript.Arguments(0), 1).ReadAll\n' + + 'ExecuteGlobal MenuText\n' + + 'If FakeMenuBar.Controls.Count <> 1 Then WScript.Quit 1\n' + + 'If FakeMainMenuBar.Controls.Count <> 1 Then WScript.Quit 6\n' + + 'If FakeMenuBar.Controls.Item(1).Controls.Count <> 8 Then WScript.Quit 2\n' + + 'For Each SourceMenu In Array(1, 2, 3, 4, 5, 6, 7, 8)\n' + + ' If Left(FakeMenuBar.Controls.Item(1).Controls.Item(SourceMenu).OnAction, 5) <> "run """ Then WScript.Quit 3\n' + + 'Next\n' + + 'Call DxToolsInstallMenu()\n' + + 'If FakeMenuBar.Controls.Count <> 1 Then WScript.Quit 4\n', + encoding="ascii", + ) + result = subprocess.run( + ["cscript", "//nologo", str(harness), str(assets.menu_script)], + capture_output=True, timeout=10, + ) + assert result.returncode == 0, result.stderr.decode(errors="replace") + assert assets.ready_file.read_text(encoding="utf-16").strip() == assets.token assert set(assets.action_scripts) == { - "refdes", - "property-change", - "property-visibility", - "inspection", - "bom", - "compatibility", - "guide", + "refdes", "property-change", "property-visibility", "inspection", + "bom", "pdf-export", "compatibility", "guide", } - assert assets.action_scripts["refdes"] == "DxToolsOpenRefDes" - assert ( - assets.action_scripts["property-change"] - == "DxToolsOpenPropertyChange" - ) - assert assets.action_scripts["bom"] == "DxToolsOpenBom" - assert assets.action_scripts["compatibility"] == "DxToolsOpenCompatibility" - assert assets.action_scripts["guide"] == "DxToolsOpenGuide" - assert all( - "D:\\NET_CHECK" not in value for value in assets.action_scripts.values() - ) - assert not any( - value.startswith("run ") for value in assets.action_scripts.values() - ) + for script in assets.action_scripts.values(): + assert script.read_bytes().isascii() + compiler = tmp_path / "compile-action.vbs" + compiler.write_text( + 'Dim text\ntext = CreateObject("Scripting.FileSystemObject").OpenTextFile(WScript.Arguments(0), 1).ReadAll\n' + 'ExecuteGlobal Split(text, "\' DXTOOLS_ENTRY")(0)\n', + encoding="ascii", + ) + result = subprocess.run(["cscript", "//nologo", str(compiler), str(script)], capture_output=True, timeout=10) + assert result.returncode == 0, result.stderr.decode(errors="replace") + + +def test_private_startup_preserves_vendor_scripts_and_existing_actions(portable_root, tmp_path): + from dx_productivity.bridge.startup import prepare_startup + + install = tmp_path / "Mentor" / "7.9.5EE" / "SDD_HOME" + viewdraw = install / "wv" / "win32" / "bin" / "viewdraw.exe" + viewdraw.parent.mkdir(parents=True) + viewdraw.write_bytes(b"fixture") + standard = install / "standard" + standard.mkdir() + vendor = standard / "scripts.ini" + original = b"[LibraryStudio]\r\nScript#0=library.vbs\r\n[ViewDraw]\r\nScript#0=company.vbs\r\n" + vendor.write_bytes(original) + (standard / "vllib.vmb").write_bytes(b"vendor message catalog") + environment = {"LOCALAPPDATA": str(tmp_path / "profile"), "WDIR": str(standard)} + configuration = prepare_startup(portable_root, viewdraw, environment) + configuration_again = prepare_startup(portable_root, viewdraw, environment) + + assert vendor.read_bytes() == original + private = configuration.scripts_ini.read_text(encoding="gbk") + assert "Script#0=company.vbs" in private + assert private.count("MenuAdd.vbs") == 1 + assert configuration_again.scripts_ini == configuration.scripts_ini + assert configuration.launch_environment["WDIR"].split(";") == [str(configuration.scripts_ini.parent), str(standard)] + assert (configuration.scripts_ini.parent / "vllib.vmb").read_bytes() == b"vendor message catalog" + + +def test_incomplete_tool_package_is_rejected_before_registering_any_script(portable_root, tmp_path): + from dx_productivity.bridge.startup import StartupError, prepare_startup + + (portable_root / "_runtime" / "vbs" / "Snapshot.vbs").unlink() + profile = tmp_path / "untouched" + with pytest.raises(StartupError, match="Snapshot.vbs"): + prepare_startup(portable_root, tmp_path / "viewdraw.exe", {"LOCALAPPDATA": str(profile)}) + assert not profile.exists() + + +def test_start_never_reports_success_from_a_stale_host_receipt(portable_root, tmp_path, monkeypatch): + from dx_productivity.bridge.startup import StartupError, start_dxdesigner + + install = tmp_path / "SDD_HOME" + viewdraw = install / "wv/win32/bin/viewdraw.exe" + viewdraw.parent.mkdir(parents=True) + viewdraw.write_bytes(b"fixture") + standard = install / "standard" + standard.mkdir() + (standard / "vllib.vmb").write_bytes(b"catalog") + profile = tmp_path / "profile" + ready = profile / "DxProductivity/startup-refactored/menu-ready.txt" + ready.parent.mkdir(parents=True) + ready.write_text("old-token", encoding="utf-16") + monkeypatch.setattr(subprocess, "run", lambda *args, **kwargs: subprocess.CompletedProcess(args[0], 0, b"", b"")) + with pytest.raises(StartupError, match="菜单加载回执"): + start_dxdesigner(portable_root, viewdraw=viewdraw, environment={"LOCALAPPDATA": str(profile), "WDIR": str(standard)}, timeout=0.01) + + +def test_start_launches_absent_host_with_private_configuration(portable_root, tmp_path, monkeypatch): + import re + from dx_productivity.bridge.startup import start_dxdesigner + + install = tmp_path / "SDD_HOME" + viewdraw = install / "wv/win32/bin/viewdraw.exe" + viewdraw.parent.mkdir(parents=True) + viewdraw.write_bytes(b"fixture") + standard = install / "standard" + standard.mkdir() + (standard / "vllib.vmb").write_bytes(b"catalog") + profile = tmp_path / "profile" + environment = {"LOCALAPPDATA": str(profile), "WDIR": str(standard)} + launched = [] + monkeypatch.setattr(subprocess, "run", lambda *args, **kwargs: subprocess.CompletedProcess(args[0], 3, b"", b"")) + def launch(command, *, cwd, env): + launched.append((command, cwd, env)) + private = profile / "DxProductivity/startup-refactored" + token = re.search(r'stream.WriteLine "([0-9a-f]+)"', (private / "MenuAdd.vbs").read_text(encoding="ascii"))[1] + (private / "menu-ready.txt").write_text(token, encoding="utf-16") + monkeypatch.setattr(subprocess, "Popen", launch) + + assert "已启动" in start_dxdesigner(portable_root, viewdraw=viewdraw, environment=environment, timeout=0.1) + assert len(launched) == 1 + command, cwd, child = launched[0] + assert command == [str(viewdraw.resolve())] + assert cwd == viewdraw.parent.resolve() + assert child["WDIR"].split(";")[0] == str(profile / "DxProductivity/startup-refactored") + assert child["DXTOOLS_HOME"] == str(portable_root.resolve()) + assert environment == {"LOCALAPPDATA": str(profile), "WDIR": str(standard)} diff --git a/tests/integration/test_menu_script.py b/tests/integration/test_menu_script.py index 6fa208f..9061952 100644 --- a/tests/integration/test_menu_script.py +++ b/tests/integration/test_menu_script.py @@ -8,7 +8,8 @@ INTEGRATION_ROOT = Path("integration/dxdesigner795") def test_menu_is_ascii_portable_and_uses_795_menu_bar() -> None: text = (INTEGRATION_ROOT / "MenuAdd.vbs").read_text(encoding="ascii") - assert 'CommandBars("Sheet Menu Bar")' in text + assert 'DxToolsInstallMenuBar("Sheet Menu Bar")' in text + assert 'DxToolsInstallMenuBar("Main Menu Bar")' in text assert "DxToolsResolveRoot" in text assert "WScript.ScriptFullName" in text assert "Scripting.CurrentScriptFullName" in text diff --git a/tests/packaging/test_built_release.py b/tests/packaging/test_built_release.py index 91e7384..a28020f 100644 --- a/tests/packaging/test_built_release.py +++ b/tests/packaging/test_built_release.py @@ -7,7 +7,7 @@ import subprocess REPO_ROOT = Path(__file__).resolve().parents[2] -RELEASE_ROOT = REPO_ROOT / "release" / "DxDesigner效率工具" +RELEASE_ROOT = Path(os.environ.get("DXTOOLS_RELEASE_ROOT", str(REPO_ROOT / "release" / "DxDesigner效率工具"))) def _sanitized_environment() -> dict[str, str]: @@ -35,6 +35,8 @@ def test_release_contains_portable_runtime_and_root_scripts() -> None: "MenuAdd.vbs", "DesignBridge.vbs", "CompatibilityProbe.vbs", + "PdfSaveListener.vbs", + "LoadMenu.vbs", "templates/BOM模板.xls", "expedition/ExpeditionBridge.vbs", "docs/DxDesigner_7.9.5_自动位号工具使用说明.docx", diff --git a/tests/ui/test_main_window.py b/tests/ui/test_main_window.py index 50ff834..5d57cce 100644 --- a/tests/ui/test_main_window.py +++ b/tests/ui/test_main_window.py @@ -115,3 +115,32 @@ def test_main_window_wires_settings_page(qtbot): assert isinstance(window.pages.widget(7), SettingsPage) assert window.settings_page.version_label.text().startswith("当前版本 0.1.0") + + +def test_start_button_requests_dxdesigner_menu_installation(qtbot): + window = MainWindow() + qtbot.addWidget(window) + with qtbot.waitSignal(window.start_requested): + qtbot.mouseClick(window.start_button, Qt.MouseButton.LeftButton) + + +def test_start_button_runs_registration_and_shows_its_result(qtbot): + window = create_main_window() + qtbot.addWidget(window) + window.startup_controller.service = lambda _root: "菜单已加入当前 DxDesigner" + with qtbot.waitSignal(window.startup_controller.completed): + qtbot.mouseClick(window.start_button, Qt.MouseButton.LeftButton) + assert not window.start_button.isEnabled() + assert window.start_button.isEnabled() + assert window.operation_status.text() == "菜单已加入当前 DxDesigner" + + +def test_portable_executable_uses_its_own_folder_over_stale_environment(monkeypatch, tmp_path): + import sys + from dx_productivity.ui.app import _tool_root + + current = tmp_path / "current" / "DxDesignerTools.exe" + monkeypatch.setattr(sys, "frozen", True, raising=False) + monkeypatch.setattr(sys, "executable", str(current)) + monkeypatch.setenv("DXTOOLS_HOME", str(tmp_path / "old-release")) + assert _tool_root() == current.parent.resolve() diff --git a/tests/vbs/test_menu_add.vbs b/tests/vbs/test_menu_add.vbs index 5153954..c7a80c2 100644 --- a/tests/vbs/test_menu_add.vbs +++ b/tests/vbs/test_menu_add.vbs @@ -1,6 +1,6 @@ Option Explicit -Const cmdControlPopup = 10 +Const cmdControlPopup = 1 Dim Fso Dim SourceRoot @@ -11,6 +11,7 @@ Dim MenuText Dim Stream Dim Scripting Dim FakeMenuBar +Dim FakeMainMenuBar Dim DxToolsCommonLoads Dim DxToolsProbeRuns Dim RuntimeRoot @@ -81,8 +82,13 @@ Class FakeControlsCollection End Class Function CommandBars(name) - If name <> "Sheet Menu Bar" Then Call Fail("unexpected menu bar") - Set CommandBars = FakeMenuBar + If name = "Main Menu Bar" Then + Set CommandBars = FakeMainMenuBar + ElseIf name = "Sheet Menu Bar" Then + Set CommandBars = FakeMenuBar + Else + Call Fail("unexpected menu bar") + End If End Function Set Fso = CreateObject("Scripting.FileSystemObject") @@ -116,19 +122,21 @@ Set Scripting = New FakeScriptingHost Scripting.CurrentScriptFullName = TargetMenu Scripting.ScriptFullName = "" Set FakeMenuBar = New FakeControl +Set FakeMainMenuBar = New FakeControl Set Stream = Fso.OpenTextFile(TargetMenu, 1, False, 0) MenuText = Stream.ReadAll Stream.Close -MenuText = Replace(MenuText, ".Controls.Add(cmdControlPopup)", _ +MenuText = Replace(MenuText, ".Controls.Add(1)", _ ".Controls.Add") +DxToolsCommonLoads = 0 ExecuteGlobal MenuText Call AssertEqual(DxToolsHome, TempRoot, "portable root") Call AssertEqual(DxToolsScriptPathSource, _ "Scripting.CurrentScriptFullName", "path source") Call AssertEqual(FakeMenuBar.Controls.Count, 1, "top menu count") -Call AssertEqual(FakeMenuBar.Controls.Item(1).Controls.Count, 7, _ +Call AssertEqual(FakeMenuBar.Controls.Item(1).Controls.Count, 8, _ "command count") Call AssertEqual(FakeMenuBar.Controls.Item(1).Controls.Item(1).OnAction, _ "DxToolsOpenRefDes", "refdes action") @@ -140,7 +148,6 @@ Call AssertEqual(FakeMenuBar.Controls.Item(1).Controls.Item(5).OnAction, _ Call DxToolsInstallMenu() Call AssertEqual(FakeMenuBar.Controls.Count, 1, "idempotent menu count") -DxToolsCommonLoads = 0 DxToolsProbeRuns = 0 Call DxToolsOpenCompatibility() Call DxToolsOpenCompatibility()