fix: persist native menus and validate every tool workflow
This commit is contained in:
1 parent
7a471fec24
commit
cd88a9950a
76 files changed
+4249
-264
No files matched your search
@@ -0,0 +1,30 @@
|
||||
# 菜单持久化与逐项实机验证
|
||||
|
||||
> For agentic workers: execute independent validation domains with dispatching-parallel-agents; keep all live DxDesigner operations on the root agent.
|
||||
|
||||
**Goal:** Start 注册后,普通启动、切换工程及重启仍保留菜单;每个工具功能都有明确验证结果和证据。
|
||||
|
||||
**Architecture:** 在实际 WDIR 的 scripts.ini 中备份后幂等注册用户目录下的生成菜单,保留其他脚本。宿主事件负责工程切换后的菜单刷新。工程数据操作与 PDF 出图仅在复制的验收工程上执行;源工程保持原状。
|
||||
|
||||
**Tech stack:** Python 3.12、PySide6、32 位 WSH、DxDesigner/Expedition 7.9.5、Excel COM。
|
||||
|
||||
**Spec:** 用户 2026-10-10 明确要求“Start 持久化,一直都在菜单,每个功能都测试”;范围见 docs/testing/native-acceptance.md。
|
||||
|
||||
## Constraints
|
||||
|
||||
- 不操作用户原工程的图纸或关闭未保存文档;使用独立实例和验收副本。
|
||||
- 不改用户/系统环境变量;修改实际启动配置时先备份,保留公司条目及原编码。
|
||||
- 只有实际 native 输出和读回证据支持实机通过;自动化模拟结果单独记录。
|
||||
- 单个 DxDesigner 实例由 root 协调,PDF 独立副本及 Excel/PCB 测试分别执行。
|
||||
|
||||
## Tasks
|
||||
|
||||
- [x] 复现 scripts.ini 缺少工具条目;新增测试要求普通 WDIR 配置持久含一个入口、重复 Start 幂等且保留原脚本。
|
||||
- [x] 修改 src/dx_productivity/bridge/startup.py:备份并写入实际配置,记录注册位置;修改 integration/dxdesigner795/MenuAdd.vbs:订阅 ProjectChanged/AfterDocumentOpened 并幂等恢复菜单。
|
||||
- [x] 用普通环境启动独立 Dx 实例,确认 Start Page 与工程页菜单存在;关闭验收实例后重新启动、切换副本工程,重新读取菜单计数。
|
||||
- [x] 修复实机快照中命名页号、坐标、网络等 API 差异;tests/integration 回归覆盖实际 VBS 方法签名。
|
||||
- [x] 在验收副本完成自动位号预览/应用/第二次应用/历史恢复、属性修改/隐藏/显示/恢复、设计检查与定位,读回原生对象验证结果。
|
||||
- [x] PDF 三种范围和保存事件在独立副本验证;BOM Excel 模板及 PCB 装配整理逐项记录。
|
||||
- [ ] 推送当前分支(构建、395 项源码测试、16 项便携包测试和最终菜单/冻结监听器/更新安装已完成)。
|
||||
|
||||
结果与边界:`docs/testing/native-acceptance-20261010.md`。额外修复发布 ZIP 目录兼容、Windows 更新程序自锁、持续重启与计划文件竞争,实际便携包更新及回滚通过。
|
||||
@@ -1,6 +1,6 @@
|
||||
# DxDesigner 7.9.5 现场验收记录
|
||||
|
||||
> 发布状态:Start 注册菜单、菜单启动工具及工程快照刷新已在 DxDesigner 7.9.5 实机核对;写回、PDF 出图及保存事件验收待完成。
|
||||
> 当前验收:2026-10-10 至 2026-10-11 已完成持久菜单、原生写回与恢复、定位、BOM、PCB、PDF 范围及自动导出的副本测试,详见 [逐项验收报告](native-acceptance-20261010.md)。下文保留早期记录与扩展验收模板,不代表本轮仍未验证。
|
||||
|
||||
## 1. 测试信息
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# 持久菜单与全工具验收(2026-10-10—11)
|
||||
|
||||
本轮针对 Start 不持久、菜单无法打开、工程未桥接和“每个功能都测试”的反馈完成修复与验收。设计写回、PDF 和 PCB 测试均在独立工程副本上执行,用户原 DxDesigner 实例未关闭、未写回。
|
||||
|
||||
## 环境与证据
|
||||
|
||||
- Windows 11 x64,Python 3.12,DxDesigner / Expedition Enterprise 7.9.5。
|
||||
- 位号与属性副本:`%LOCALAPPDATA%\DxProductivity\acceptance\native-20261010\1GPHY_RTL8211F`,114 个器件、56 个命名网络,活动页 `GE_PHY_8211`。
|
||||
- 菜单与自动 PDF 副本:同目录下 `switch-audio\Audio_D2128_SURGE_ESD.prj`。
|
||||
- PDF 多页工程副本:`%LOCALAPPDATA%\DxProductivity\acceptance\pdf-scopes-20261010`。
|
||||
- BOM / PCB 原生证据:`%TEMP%\dx-native-bom-pcb-20261010`。
|
||||
- 源码全套:`395 passed`,便携包测试:`16 passed`;JUnit 位于 `build/test-evidence/full-source.xml` 和 `packaged.xml`。
|
||||
|
||||
## 逐项结果
|
||||
|
||||
| 功能 | 实际验证 | 结果与边界 |
|
||||
|---|---|---|
|
||||
| Start 持久注册 | 写入平时 WDIR 的启动配置;普通启动、打开工程、关闭验收实例后重新普通启动;重复注册读取两栏菜单 | Main / Sheet Menu Bar 各一个菜单、每菜单八个动作。中文宿主需 `脚本#n`,兼容英文 `Script#n`;保留原条目并备份 |
|
||||
| 工程桥接与刷新 | 宿主快照枚举、真实路径、命名图页、坐标、属性与网络;多次刷新 | 114 个器件与 56 个网络;桥接标识及活动页正确 |
|
||||
| 自动位号 | CE17 / LE03 改为 C7000 / L7000,再次应用 8000;CE17 / CE18 交换;分别恢复 | 原生读回一致,循环位号无临时值残留;114 个器件身份、位置和未涉及属性核对 |
|
||||
| 属性批改 | Value、Value1、Part Number 写回,空值清理、缺失属性跳过及历史恢复 | 原生读回及备份值一致。Value1 夹具仅在副本新增 |
|
||||
| 属性显示 | PartName / PartLabel 显示、隐藏及对应恢复,共八次事务 | 原生可见性读回一致,恢复不依赖旧位号 |
|
||||
| 设计检查 / 网络工具 | 空 Value / Value1 查找,56 个真实网络列表、孤立与跨页计算;清除目标选择后执行器件和 GND 定位 | 器件独占选择 CE17,GND 被真实选中;多页网络计算由离线夹具覆盖,原生定位工程为单页 |
|
||||
| 历史 / 预检 / 回滚 | 位号、属性与可见性恢复;旧快照、错误工程、篡改摘要、实际外部修改;第二步赋值失败 | 不一致事务均在写入前拒绝;实际失败回滚状态 `rolled-back`、`failing_sequence=2`、`rollback_state=verified` |
|
||||
| BOM | 真实 Dx 114 器件生成 15 行 BOM;独立 Excel 输出 XLSX/XLS、重新打开逐格与颜色核对 | 合并、NC 和 MARK 等过滤、重复红色及创维料号橙色标记通过;Excel 格式分别为 51(XLSX)与 56(XLS),重复色号 3、料号色号 44 |
|
||||
| Expedition PCB | 真实许可证、原生文字导出、104 项计划写回、参数读回和 Edit → Undo;对照旧脚本真实运行结果 | 88 项位置移动、5 项仅格式修改、11 项删除;79 项未计划文字不变;一次撤销 172 → 183 恢复完整,锁计数 0;93 个位号的几何/格式对照一致,数值舍入差小于 0.00005 |
|
||||
| PCB 菜单 | 独立导入脚本、从 Start 记录解析实际工具根目录、重复安装 | 修复宿主无脚本路径元数据和菜单接口;菜单幂等,回调验收见原生报告 |
|
||||
| PDF 整工程 | PON 多页工程原生 sch2pdf 输出 | 24 页 |
|
||||
| PDF 当前页 | PON / `03_FLASH` 精确书签筛页,与整工程第 10 页比较 | 1 页,文本与渲染像素一致;书签不存在或重复时拒绝发布,不覆盖旧 PDF |
|
||||
| PDF 指定 Block | PON 与 DCDC_T56220_C 两个范围 | 分别 17 页(含层次子页)和 1 页 |
|
||||
| 自动 PDF | 按工程路径绑定独立实例;原生属性变更,稳定后导出;恢复再导出;关闭后再次变更 | 开启时 PDF 正文含 `IC/D2128_PDF_NATIVE_ON`;恢复后标记消失;关闭后次数保持 2、PDF 哈希不变。EE iCDB 使用原生变更事件,保留传统保存完成事件 |
|
||||
| 设置 / 更新 | 版本检查、持久设置、每日检查、签名/摘要/协议保护;发布 ZIP 目录、外部更新运行目录与实际跨进程互斥 | 最终 exe 在中文临时目录完成等待旧窗口退出、安装、持续重启窗口和启动探针失败后的回滚;真实发布包及备份内容核对 |
|
||||
| 兼容性 / 说明 | 最终菜单调用原生 API 检测及 Word 打开说明 | 114 个器件、属性、页、坐标、路径与保留对象均成功读取;消息让出方式 `ActiveView.Refresh`;说明打开后关闭测试文档 |
|
||||
|
||||
## 具体证据文件
|
||||
|
||||
- 菜单:`native-20261010\persistent-menu-check.txt`、`persistent-after-switch.txt`,明确 `DONE` 回执。
|
||||
- 位号等事务:`native-20261010\native-feature-tests\<用例>\verified.json`、`apply-status.json`、`host-trace.txt`。`inspection-final\after.json` 对照初始 `refdes\before.json`,114 个器件的位号、位置、属性值和可见性恢复。
|
||||
- BOM:`bom-actual-native-verified.json`、`bom-native-final-verified.json`、`BOM-actual-DxDesigner.xlsx`、`bom-final.xlsx`、`bom-final.xls`。
|
||||
- PCB:`pcb-native-report.json`、`pcb-texts-before.txt`、`pcb-texts-after.txt`、`pcb-texts-undo.txt`。
|
||||
- PDF 范围:`pdf-scopes-20261010\verification.json`、`pon-scope-results.json` 和输出 PDF。
|
||||
- PDF 自动:`native-20261010\pdf-native-acceptance.json`、`pdf-native-enabled-result.json`、`pdf-native-restored-result.json`、`pdf-native-disabled-result.json`、监听器原生日志。
|
||||
|
||||
## 适用边界
|
||||
|
||||
实际 API 行为通过上述样例工程验证;多单元、锁定、排序规则和跨页计算还有离线回归,未声称穷举所有公司工程。原始 Surge 267 文件与 PON 133 个相关文件比较无增加、删除或修改。
|
||||
|
||||
PCB 整理保留 79 个未匹配到已知器件的文字;旧脚本会额外删除它们。本版验证了这些文字不变,以及非装配层正交位号只调整格式、保留位置。安装目录为 7.9.5EE,本机 Expedition Automation 返回版本 `7.9.4.543380`。
|
||||
|
||||
原生 sch2pdf 在本机有缺失字体造成的中文乱码或裁切,范围筛页没有引入额外变化。活动工程的数据库可能被宿主共享锁锁住,此时导出记录明确列出未能核验内容的原生数据库文件;可读设计文件及工程配置仍严格比较,普通权限错误继续阻止导出。
|
||||
|
||||
## 最终便携包复验
|
||||
|
||||
交付目录:`release\一叶知秋_重构版_持久菜单与全功能修复版`。ZIP 名称在目录名后增加 `_Win11_x64.zip`,校验记录为同名 `_SHA256SUMS.txt`。
|
||||
|
||||
- ZIP SHA-256:`efa435acf568c92fe467be33d8eec782a4c4311cf27095466bd1d22599fcf26d`。
|
||||
- exe SHA-256:`d592d941543057622d2bc0867d2bd2e5c82aff07ed95424bf3c7f19ce948802e`。
|
||||
- 隔离构建 PATH,避免混入其他软件 DLL;最终 VBS 文件逐个比较,与本轮源码一致。
|
||||
- 最终 GUI 的 Start 已实际调用并收到“菜单已持久注册并加入当前 DxDesigner”。随后普通启动新的 DxDesigner,未点击 Start,两栏各一个菜单、八个动作;证据 `persistent-final-startup.json`。
|
||||
- 八个菜单回调均执行:六个设计功能打开最终 exe 的正确页面并连接副本工程,兼容性检测生成原生结果,使用说明通过 Word 打开;证据 `packaged-menu-acceptance.json`。
|
||||
- 最终包的 Expedition 脚本直接导入原生宿主,解析到最终交付目录,菜单 13 → 14,实际注册 Target 的回调调用通过;证据 `%TEMP%\dx-native-bom-pcb-20261010\pcb-native-menu-verified.json`。
|
||||
- 最终 exe 的九个页面、兼容性 CLI、PCB 计算 CLI、关闭的保存监听入口及中文空格目录运行,在 PATH 不含 Python 时通过便携包测试。
|
||||
- 最终冻结监听器按准确 ROT 实例生成含新值的一页 PDF,恢复原值后再次输出,关闭后退出码 0;证据 `pdf-frozen-final-acceptance.json`。保留本机 Mentor 原生引擎运行库路径,PATH 不含 Python。
|
||||
- 最终 exe 使用真实交付 ZIP 在临时副本完成安装、持续重启和失败回滚;证据 `build/test-evidence/packaged-update.json`。测试没有替换交付目录。
|
||||
|
||||
35 个设计实机用例:26 个应用、4 个预检拒绝、1 个读回验证的回滚、4 个检查/定位/无写入用例。验收结束后已关闭本轮独立 Dx 副本,用户原实例继续运行。
|
||||
|
||||
最终工具窗口已打开并连接用户当前 `Audio_D2128_ESD.prj`,保持可见;只读取工程快照。记录为 `final-open-tool.json`。
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
本清单用于在真实 DxDesigner 7.9.5 / Expedition PCB 环境中验收原生迁移后的功能。各功能的计算逻辑已由自动化测试覆盖;本清单关注 COM 宿主行为(属性写回、读回验证、定位、Excel 输出)与端到端体验。没有真实宿主运行记录时,不得写成“已验证”。
|
||||
|
||||
2026-10-10 至 2026-10-11 的逐项实际结果见 [本轮验收报告](native-acceptance-20261010.md),包括持久菜单、PDF 三种范围、自动导出关闭检查及失败回滚。以下为后续工程复测清单。
|
||||
|
||||
## 通用前置条件
|
||||
|
||||
- 从完整便携包打开 `DxDesignerTools.exe`,点击 Start 自动注册并加载 DxDesigner 菜单;Expedition 侧导入 `expedition\ExpeditionBridge.vbs`。
|
||||
|
||||
@@ -5,11 +5,13 @@
|
||||
范围有三种:
|
||||
|
||||
- **整工程**:导出当前工程中的全部原理图页。
|
||||
- **当前页**:导出打开工具时 DxDesigner 活动视图对应的 Block。
|
||||
- **当前页**:导出活动视图对应的命名图页,多页 Block 只保留该页。
|
||||
- **指定原理图或 Block**:输入本机 DxDesigner 工程中的实际 Block 名称。
|
||||
|
||||
默认输出到 `%LOCALAPPDATA%\DxProductivity\pdf-output` 下按工程区分的目录。可在页面选择其他输出目录,但不能选择源工程目录或其子目录。覆盖现有 PDF 前,手动导出会先询问;自动导出只在新 PDF 验证成功后替换原文件。
|
||||
|
||||
“保存工程后自动导出”默认关闭。开启后,DxDesigner 7.9.5 的保存完成事件会触发后台导出;关闭后监听器会自行退出。导出状态显示在 DxDesigner 状态栏,详细记录位于 `%LOCALAPPDATA%\DxProductivity\pdf-runs`。
|
||||
“保存工程后自动导出”默认关闭。EE iCDB 工程会即时保存设计变更,工具收到原生变更事件、等待变更稳定后导出当前数据库;传统文件工程在保存完成后导出。重复通知会合并,已有导出进程结束后才执行下一次导出。监听器按配置中的工程路径绑定实例,关闭开关后自行退出。导出状态显示在 DxDesigner 状态栏,详细记录位于 `%LOCALAPPDATA%\DxProductivity\pdf-runs`。
|
||||
|
||||
PDF 使用本机 `sch2pdf.exe`、DxDesigner 配置和许可。原生出图可能更新工程数据库或运行记录;发布 PDF 前工具会检查工程文件变化,未确认的变化会阻止发布。
|
||||
|
||||
工程打开时数据库可能被锁定,工具会明确记录无法核验数据库内容;工程配置和其他可读设计文件继续进行变化检查。
|
||||
@@ -3,9 +3,9 @@
|
||||
## 本版变更(原生迁移版)
|
||||
|
||||
- 打开完整工具包中的 `DxDesignerTools.exe`,点击顶部 **Start**,即可自动加入 DxDesigner 菜单。已打开的 DxDesigner 会加载菜单;未打开时工具会带菜单配置启动它。
|
||||
- 菜单包含自动位号、属性批改、属性显示、设计检查、BOM、PDF 导出、兼容性检测及使用说明。Start 使用用户目录中的独立启动配置,保留公司原有启动脚本;生成入口明确绑定当前工具目录,支持中文及空格路径。
|
||||
- 菜单包含自动位号、属性批改、属性显示、设计检查、BOM、PDF 导出、兼容性检测及使用说明。Start 会先备份,再向 DxDesigner 平时使用的 `scripts.ini` 注册入口,保留公司原有启动脚本;关闭工具、普通重启 DxDesigner、切换工程后菜单继续存在。生成的动作保存在用户目录,绑定当前工具包,支持中文及空格路径。
|
||||
- 移动完整工具包后重新打开其中的 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 装配位号整理。
|
||||
@@ -13,6 +13,9 @@
|
||||
- 桥接协议升级到 v2:快照包含属性全集、可见性、网络分布与真实锁定状态;调度表按“操作类型 + 属性名”泛化,同一事务核心承载所有功能。
|
||||
- 宿主侧信箱支持多次应用、真实休眠(不再空转占用 CPU)、心跳检测与旧运行目录自动清理;界面增加“刷新设计快照”的真实重新导出。
|
||||
- 更新通道安全强化:stable 频道强制 Ed25519 签名验证(公钥内置于程序),下载地址仅允许 https 与 file 协议,阻止跨协议重定向;更新器加单实例互斥并等待主程序退出后再切换版本。
|
||||
- PDF 支持整工程、当前页、指定原理图或 Block。当前页通过原生 PDF 的准确书签保留一页;书签缺失或歧义时保留旧输出并报错。自动导出默认关闭,开启后监听原生事件;EE 数据库即时保存后等待变更稳定再导出。
|
||||
- 修复 BOM 只输出表头、合并行内重复位号检测及 Excel 失败后的资源清理;修复 Expedition 的工具目录解析、菜单接口和脚本入口。
|
||||
- 修复更新器对发布 ZIP 外层目录的处理,并将更新程序复制到缓存后运行,避免 Windows 上自身锁住待替换 exe。
|
||||
|
||||
## 设置页
|
||||
|
||||
@@ -20,4 +23,4 @@
|
||||
|
||||
## 实机验收
|
||||
|
||||
DxDesigner 7.9.5 与 Expedition PCB 的宿主行为(COM 属性写回、网络定位、Excel 输出)仍需按 `docs/testing/native-acceptance.md` 在真实环境验收;逻辑正确性已由自动化测试覆盖。
|
||||
本轮已在 DxDesigner / Expedition 7.9.5 的独立工程副本上验证位号、属性、可见性、历史恢复、器件与网络定位、BOM、PCB 整理和 PDF 导出。逐项结果和适用边界见 `docs/testing/native-acceptance-20261010.md`。原生 PDF 字体缺失造成的中文乱码或裁切仍依赖本机字体和出图配置。
|
||||
@@ -169,7 +169,7 @@ Function DxToolsProbePathMethod(comp)
|
||||
If comp Is Nothing Then Exit Function
|
||||
|
||||
On Error Resume Next
|
||||
ignored = CStr(comp.Parent) & "\" & CStr(comp.GetName(SHORT_NAME))
|
||||
ignored = CStr(comp.Parent.GetName(SHORT_NAME)) & "\" & CStr(comp.GetName(SHORT_NAME))
|
||||
If Err.Number = 0 Then DxToolsProbePathMethod = "Parent+GetName(SHORT_NAME)"
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
@@ -181,6 +181,14 @@ Function DxToolsProbePositionMethod(comp)
|
||||
DxToolsProbePositionMethod = ""
|
||||
If comp Is Nothing Then Exit Function
|
||||
|
||||
On Error Resume Next
|
||||
x = comp.GetLocation().X
|
||||
y = comp.GetLocation().Y
|
||||
If Err.Number = 0 Then DxToolsProbePositionMethod = "GetLocation().X/Y"
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
If DxToolsProbePositionMethod <> "" Then Exit Function
|
||||
|
||||
On Error Resume Next
|
||||
x = comp.X
|
||||
y = comp.Y
|
||||
|
||||
@@ -17,8 +17,56 @@ If DxToolsHome = "" Then
|
||||
MsgBox DxToolsPathErrorMessage(), vbExclamation
|
||||
Else
|
||||
Call DxToolsInstallMenu()
|
||||
Call DxToolsAttachMenuEvents()
|
||||
End If
|
||||
|
||||
Sub DxToolsAttachMenuEvents()
|
||||
' Native startup scripts must remain alive to receive project/view events.
|
||||
On Error Resume Next
|
||||
Scripting.AttachEvents Application, "DxToolsHost"
|
||||
Scripting.DontExit = True
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
End Sub
|
||||
|
||||
Sub DxToolsHost_ProjectChanged(projectData)
|
||||
Call DxToolsRestoreMenus()
|
||||
End Sub
|
||||
|
||||
Sub DxToolsHost_AfterDocumentOpened(dataType, name, path)
|
||||
Call DxToolsRestoreMenus()
|
||||
End Sub
|
||||
|
||||
Sub DxToolsHost_ActivateView()
|
||||
Call DxToolsRestoreMenus()
|
||||
End Sub
|
||||
|
||||
Sub DxToolsHost_ProjectClosed()
|
||||
Call DxToolsRestoreMenus()
|
||||
End Sub
|
||||
|
||||
Sub DxToolsRestoreMenus()
|
||||
Call DxToolsRestoreMenuBar("Main Menu Bar")
|
||||
Call DxToolsRestoreMenuBar("Sheet Menu Bar")
|
||||
End Sub
|
||||
|
||||
Sub DxToolsRestoreMenuBar(barName)
|
||||
Dim menuBar, item, index
|
||||
On Error Resume Next
|
||||
Set menuBar = CommandBars(CStr(barName))
|
||||
If Err.Number <> 0 Then
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
Exit Sub
|
||||
End If
|
||||
On Error GoTo 0
|
||||
For index = 1 To menuBar.Controls.Count
|
||||
Set item = menuBar.Controls.Item(index)
|
||||
If item.Caption = DxToolsSuiteCaption() Then Exit Sub
|
||||
Next
|
||||
Call DxToolsInstallMenuBar(barName)
|
||||
End Sub
|
||||
|
||||
Sub DxToolsInstallMenu()
|
||||
Call DxToolsInstallMenuBar("Main Menu Bar")
|
||||
Call DxToolsInstallMenuBar("Sheet Menu Bar")
|
||||
@@ -190,16 +238,10 @@ Sub DxToolsMaybeStartPdfListener()
|
||||
expression.Global = False
|
||||
If Not expression.Test(settingsText) Then Exit Sub
|
||||
|
||||
listenerPath = fso.BuildPath(DxToolsHome, "PdfSaveListener.vbs")
|
||||
executablePath = fso.BuildPath(DxToolsHome, "DxDesignerTools.exe")
|
||||
hostPath = shell.ExpandEnvironmentStrings( _
|
||||
"%WINDIR%\SysWOW64\wscript.exe")
|
||||
If Not fso.FileExists(listenerPath) Then Exit Sub
|
||||
If Not fso.FileExists(executablePath) Then Exit Sub
|
||||
If Not fso.FileExists(hostPath) Then Exit Sub
|
||||
commandLine = DxToolsQuote(hostPath) & " //B //NoLogo " & _
|
||||
DxToolsQuote(listenerPath) & " " & DxToolsQuote(settingsPath) & " " & _
|
||||
DxToolsQuote(executablePath) & " exe " & DxToolsQuote(DxToolsHome)
|
||||
commandLine = DxToolsQuote(executablePath) & " pdf-export-listen --settings " & _
|
||||
DxToolsQuote(settingsPath)
|
||||
shell.Run commandLine, 0, False
|
||||
End Sub
|
||||
|
||||
|
||||
@@ -30,13 +30,35 @@ Sub DxBridgeRenderBom(runRoot, claimedPath)
|
||||
End Sub
|
||||
|
||||
Sub DxBomRenderPayload(text, ByRef statusState, ByRef statusError)
|
||||
Dim excel
|
||||
Dim workbook
|
||||
Set excel = Nothing
|
||||
Set workbook = Nothing
|
||||
On Error Resume Next
|
||||
Set excel = CreateObject("Excel.Application")
|
||||
If Err.Number = 0 Then
|
||||
Call DxBomPopulateWorkbook(excel, workbook, text)
|
||||
End If
|
||||
If Err.Number <> 0 Then
|
||||
statusState = "failed"
|
||||
statusError = Err.Description
|
||||
Err.Clear
|
||||
If Not workbook Is Nothing Then workbook.Close False
|
||||
If Not excel Is Nothing Then excel.Quit
|
||||
Err.Clear
|
||||
Else
|
||||
statusState = "ok"
|
||||
statusError = ""
|
||||
End If
|
||||
On Error GoTo 0
|
||||
End Sub
|
||||
|
||||
Sub DxBomPopulateWorkbook(excel, ByRef workbook, text)
|
||||
Dim templatePath
|
||||
Dim outputPath
|
||||
Dim designName
|
||||
Dim descriptionHeader
|
||||
Dim excel
|
||||
Dim workbooks
|
||||
Dim workbook
|
||||
Dim sheet
|
||||
Dim saveFormat
|
||||
|
||||
@@ -45,7 +67,6 @@ Sub DxBomRenderPayload(text, ByRef statusState, ByRef statusError)
|
||||
Call DxBomField(text, "design_name", designName)
|
||||
Call DxBomField(text, "description_header", descriptionHeader)
|
||||
|
||||
Set excel = CreateObject("Excel.Application")
|
||||
excel.Visible = False
|
||||
excel.DisplayAlerts = False
|
||||
Set workbooks = excel.Workbooks
|
||||
@@ -68,20 +89,20 @@ Sub DxBomRenderPayload(text, ByRef statusState, ByRef statusError)
|
||||
Call workbook.SaveAs(CStr(outputPath), saveFormat)
|
||||
excel.Visible = True
|
||||
excel.DisplayAlerts = True
|
||||
statusState = "ok"
|
||||
statusError = ""
|
||||
End Sub
|
||||
|
||||
Sub DxBomWriteSections(excel, sheet, text)
|
||||
' Sections and rows are embedded as line-oriented records to keep the VBS
|
||||
' JSON reading trivial: S|<page> / R|<qty>|<refdes>|<pn>|<desc>|<flags>
|
||||
Dim lines
|
||||
Dim records
|
||||
Dim line
|
||||
Dim parts
|
||||
Dim rowIndex
|
||||
Dim flagParts
|
||||
rowIndex = 2
|
||||
lines = Split(Replace(CStr(text), vbCr, ""), vbLf)
|
||||
Call DxBomField(text, "records", records)
|
||||
lines = Split(Replace(CStr(records), vbCr, ""), vbLf)
|
||||
For Each line In lines
|
||||
If Left(line, 2) = "S|" Then
|
||||
sheet.Cells(rowIndex, 1).Value = Mid(line, 3)
|
||||
|
||||
@@ -10,6 +10,7 @@ Sub DxToolsDesignBridgeStart(featureKey)
|
||||
Dim snapshotId
|
||||
Dim process
|
||||
Dim state
|
||||
Dim messageStyle
|
||||
|
||||
Set objectMap = CreateObject("Scripting.Dictionary")
|
||||
Set originalMap = CreateObject("Scripting.Dictionary")
|
||||
@@ -22,8 +23,9 @@ Sub DxToolsDesignBridgeStart(featureKey)
|
||||
state = DxBridgeMailboxLoop(process, runRoot, runId, snapshotId, _
|
||||
objectMap, originalMap)
|
||||
If state <> "" Then
|
||||
MsgBox DxBridgeStateMessage(state), _
|
||||
IIf(state = "applied", vbInformation, vbExclamation)
|
||||
messageStyle = vbExclamation
|
||||
If state = "applied" Then messageStyle = vbInformation
|
||||
MsgBox DxBridgeStateMessage(state), messageStyle
|
||||
End If
|
||||
End Sub
|
||||
|
||||
@@ -184,7 +186,7 @@ Sub DxBridgeConsumeLocate(runRoot, objectMap)
|
||||
If Not fso.FileExists(locatePath) Then Exit Sub
|
||||
If Not DxBridgeClaimFile(fso, locatePath, processingPath) Then Exit Sub
|
||||
On Error Resume Next
|
||||
bridgeId = Trim(DxToolsReadUtf8(processingPath))
|
||||
bridgeId = Trim(Replace(Replace(DxToolsReadUtf8(processingPath), vbCr, ""), vbLf, ""))
|
||||
If Err.Number <> 0 Then
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
@@ -211,6 +213,7 @@ Sub DxBridgeLocateNet(netName, pageNumber)
|
||||
Dim topBlock
|
||||
Dim net
|
||||
Dim found
|
||||
Dim page, pageIndex, sheetName
|
||||
On Error Resume Next
|
||||
Set projectData = Application.GetProjectData()
|
||||
If Err.Number <> 0 Then
|
||||
@@ -222,13 +225,22 @@ Sub DxBridgeLocateNet(netName, pageNumber)
|
||||
designId = CStr(designs.GetItem(1))
|
||||
topBlock = projectData.GetiCDBDesignRootBlock(designId)
|
||||
Err.Clear
|
||||
ActiveView.UnselectAll
|
||||
ActiveView.Block.DeSelectAll
|
||||
Err.Clear
|
||||
Application.PushPath topBlock, "", CLng(pageNumber)
|
||||
pageIndex = 0
|
||||
sheetName = CStr(pageNumber)
|
||||
For Each page In Application.QueryPages(topBlock)
|
||||
pageIndex = pageIndex + 1
|
||||
If pageIndex = CLng(pageNumber) Then
|
||||
sheetName = CStr(page.SheetNum)
|
||||
Exit For
|
||||
End If
|
||||
Next
|
||||
Application.PushPath topBlock, "", sheetName
|
||||
Err.Clear
|
||||
found = False
|
||||
For Each net In ActiveView.Query(VDM_NET, VD_ALL)
|
||||
If CStr(net.Name) = CStr(netName) Then
|
||||
If StrComp(DxBridgeNetName(net), CStr(netName), vbTextCompare) = 0 Then
|
||||
net.Selected = True
|
||||
If Err.Number <> 0 Then Err.Clear
|
||||
ActiveView.ZoomSelect
|
||||
@@ -254,15 +266,13 @@ End Function
|
||||
|
||||
Sub DxBridgeLocateComponent(component)
|
||||
On Error Resume Next
|
||||
ActiveView.UnselectAll
|
||||
Application.PushPath component.Parent.GetName(SHORT_NAME), "", CStr(component.Parent.SheetNum)
|
||||
Err.Clear
|
||||
ActiveView.Select component
|
||||
If Err.Number <> 0 Then
|
||||
Err.Clear
|
||||
ActiveView.SelectObject component
|
||||
End If
|
||||
ActiveView.Block.DeSelectAll
|
||||
Err.Clear
|
||||
ActiveView.ZoomTo component
|
||||
ActiveView.SelectByName component.GetName(SHORT_NAME)
|
||||
Err.Clear
|
||||
ActiveView.ZoomSelect
|
||||
Err.Clear
|
||||
ActiveView.Refresh
|
||||
Err.Clear
|
||||
|
||||
@@ -99,10 +99,11 @@ Function DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _
|
||||
refdes = DxBridgeRefdes(component)
|
||||
symbolDefault = DxBridgeSymbolDefault(component, refdes)
|
||||
sheetNumber = DxBridgeSheetNumber(component)
|
||||
sheetName = CStr(sheetNumber)
|
||||
sheetName = CStr(component.Parent.SheetNum)
|
||||
identityKey = DxBridgeIdentityKey(stableUid, fullPath)
|
||||
selectedValue = selectedKeys.Exists(identityKey)
|
||||
currentSheetValue = (sheetNumber = DxBridgeCurrentSheetNumber())
|
||||
currentSheetValue = (LCase(DxBridgeBlockName(component.Parent)) = LCase(activeBlockName) _
|
||||
And LCase(sheetName) = LCase(DxBridgeCurrentSheetName()))
|
||||
attributesText = DxBridgeExportAttributes(component)
|
||||
|
||||
objectMap.Add bridgeId, component
|
||||
@@ -151,6 +152,7 @@ Function DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _
|
||||
" ""active_block_name"": """ & _
|
||||
DxToolsJson(activeBlockName) & """," & vbCrLf & _
|
||||
" ""current_sheet_number"": " & currentSheetNumberJson & "," & vbCrLf & _
|
||||
" ""current_sheet_name"": """ & DxToolsJson(DxBridgeCurrentSheetName()) & """," & vbCrLf & _
|
||||
" ""nets"": " & netsText & "," & vbCrLf & _
|
||||
" ""selected_nets"": " & selectedNetsText & "," & vbCrLf & _
|
||||
" ""components"": [" & vbCrLf & componentText & vbCrLf & _
|
||||
@@ -215,12 +217,12 @@ Function DxBridgeExportNets(topBlock)
|
||||
For Each net In nets
|
||||
name = ""
|
||||
page = -1
|
||||
name = CStr(net.Name)
|
||||
name = DxBridgeNetName(net)
|
||||
If Err.Number <> 0 Then
|
||||
Err.Clear
|
||||
name = ""
|
||||
End If
|
||||
page = CLng(net.SheetNum)
|
||||
page = DxBridgeBlockSheetNumber(net.Parent)
|
||||
If Err.Number <> 0 Then
|
||||
Err.Clear
|
||||
page = DxBridgeCurrentSheetNumber()
|
||||
@@ -230,7 +232,7 @@ Function DxBridgeExportNets(topBlock)
|
||||
If Not names.Exists(nameText) Then
|
||||
names.Add nameText, name
|
||||
pages.Add nameText, CStr(page)
|
||||
ElseIf InStr(pages(nameText), CStr(page)) = 0 Then
|
||||
ElseIf InStr("," & Replace(pages(nameText), " ", "") & ",", "," & CStr(page) & ",") = 0 Then
|
||||
pages(nameText) = pages(nameText) & ", " & CStr(page)
|
||||
End If
|
||||
End If
|
||||
@@ -256,7 +258,7 @@ Function DxBridgeExportSelectedNets()
|
||||
text = ""
|
||||
On Error Resume Next
|
||||
For Each net In ActiveView.Query(VDM_NET, VD_SELECTED)
|
||||
name = CStr(net.Name)
|
||||
name = DxBridgeNetName(net)
|
||||
If Err.Number <> 0 Then
|
||||
Err.Clear
|
||||
ElseIf name <> "" Then
|
||||
@@ -328,7 +330,7 @@ Function DxBridgeFullPath(component)
|
||||
parentName = ""
|
||||
componentName = ""
|
||||
On Error Resume Next
|
||||
parentName = CStr(component.Parent.Name)
|
||||
parentName = CStr(component.Parent.GetName(SHORT_NAME))
|
||||
componentName = CStr(component.GetName(SHORT_NAME))
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
@@ -369,28 +371,83 @@ Function DxBridgeRefdes(component)
|
||||
End Function
|
||||
|
||||
Function DxBridgeSymbolDefault(component, refdes)
|
||||
Dim symbolAttribute
|
||||
DxBridgeSymbolDefault = ""
|
||||
On Error Resume Next
|
||||
DxBridgeSymbolDefault = CStr(component.SymbolRefdesDefault)
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
If DxBridgeSymbolDefault = "" Then
|
||||
On Error Resume Next
|
||||
Set symbolAttribute = component.SymbolBlock.FindAttribute("Ref Designator")
|
||||
If Not symbolAttribute Is Nothing Then
|
||||
DxBridgeSymbolDefault = CStr(symbolAttribute.Value)
|
||||
End If
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
End If
|
||||
If DxBridgeSymbolDefault = "" And InStr(CStr(refdes), "?") > 0 Then
|
||||
DxBridgeSymbolDefault = CStr(refdes)
|
||||
End If
|
||||
End Function
|
||||
|
||||
Function DxBridgeSheetNumber(component)
|
||||
DxBridgeSheetNumber = DxBridgeCurrentSheetNumber()
|
||||
On Error Resume Next
|
||||
DxBridgeSheetNumber = CLng(component.Parent.SheetNum)
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
DxBridgeSheetNumber = DxBridgeBlockSheetNumber(component.Parent)
|
||||
End Function
|
||||
|
||||
Function DxBridgeCurrentSheetNumber()
|
||||
DxBridgeCurrentSheetNumber = 0
|
||||
On Error Resume Next
|
||||
DxBridgeCurrentSheetNumber = CLng(ActiveView.Block.SheetNum)
|
||||
DxBridgeCurrentSheetNumber = DxBridgeBlockSheetNumber(ActiveView.Block)
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
End Function
|
||||
|
||||
Function DxBridgeBlockSheetNumber(block)
|
||||
Dim rawName, page, index
|
||||
DxBridgeBlockSheetNumber = 0
|
||||
On Error Resume Next
|
||||
rawName = CStr(block.SheetNum)
|
||||
If IsNumeric(rawName) Then
|
||||
DxBridgeBlockSheetNumber = CLng(rawName)
|
||||
Else
|
||||
index = 0
|
||||
For Each page In Application.QueryPages(DxBridgeBlockName(block))
|
||||
index = index + 1
|
||||
If StrComp(CStr(page.SheetNum), rawName, vbTextCompare) = 0 Then
|
||||
DxBridgeBlockSheetNumber = index
|
||||
Exit For
|
||||
End If
|
||||
Next
|
||||
End If
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
End Function
|
||||
|
||||
Function DxBridgeBlockName(block)
|
||||
DxBridgeBlockName = ""
|
||||
On Error Resume Next
|
||||
DxBridgeBlockName = CStr(block.GetName(SHORT_NAME))
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
End Function
|
||||
|
||||
Function DxBridgeCurrentSheetName()
|
||||
DxBridgeCurrentSheetName = ""
|
||||
On Error Resume Next
|
||||
DxBridgeCurrentSheetName = CStr(ActiveView.Block.SheetNum)
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
End Function
|
||||
|
||||
Function DxBridgeNetName(net)
|
||||
DxBridgeNetName = ""
|
||||
On Error Resume Next
|
||||
DxBridgeNetName = CStr(net.LogicalNetName)
|
||||
If Err.Number <> 0 Then
|
||||
Err.Clear
|
||||
DxBridgeNetName = CStr(net.Name)
|
||||
End If
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
End Function
|
||||
@@ -404,14 +461,13 @@ Function DxBridgeCurrentBlockName()
|
||||
End Function
|
||||
|
||||
Function DxBridgeCurrentSheetNumberJson()
|
||||
DxBridgeCurrentSheetNumberJson = "null"
|
||||
On Error Resume Next
|
||||
DxBridgeCurrentSheetNumberJson = CStr(CLng(ActiveView.Block.SheetNum))
|
||||
If Err.Number <> 0 Then
|
||||
Dim number
|
||||
number = DxBridgeCurrentSheetNumber()
|
||||
If number > 0 Then
|
||||
DxBridgeCurrentSheetNumberJson = CStr(number)
|
||||
Else
|
||||
DxBridgeCurrentSheetNumberJson = "null"
|
||||
Err.Clear
|
||||
End If
|
||||
On Error GoTo 0
|
||||
End Function
|
||||
|
||||
Function DxBridgeCoordinate(component, readX)
|
||||
@@ -419,16 +475,16 @@ Function DxBridgeCoordinate(component, readX)
|
||||
value = 0
|
||||
On Error Resume Next
|
||||
If CBool(readX) Then
|
||||
value = component.X
|
||||
value = component.GetLocation().X
|
||||
Else
|
||||
value = component.Y
|
||||
value = component.GetLocation().Y
|
||||
End If
|
||||
If Err.Number <> 0 Then
|
||||
Err.Clear
|
||||
If CBool(readX) Then
|
||||
value = component.PositionX
|
||||
value = component.X
|
||||
Else
|
||||
value = component.PositionY
|
||||
value = component.Y
|
||||
End If
|
||||
End If
|
||||
Err.Clear
|
||||
@@ -461,7 +517,7 @@ End Function
|
||||
Function DxBridgeAttribute(component, name)
|
||||
DxBridgeAttribute = ""
|
||||
On Error Resume Next
|
||||
DxBridgeAttribute = CStr(component.Attributes.Item(CStr(name)).Value)
|
||||
DxBridgeAttribute = CStr(component.FindAttribute(CStr(name)).Value)
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
End Function
|
||||
@@ -472,8 +528,9 @@ Function DxBridgeLocked(component)
|
||||
DxBridgeLocked = CBool(component.Locked)
|
||||
If Err.Number <> 0 Then
|
||||
Err.Clear
|
||||
DxBridgeLocked = False
|
||||
DxBridgeLocked = CBool(component.Parent.IsReadOnly)
|
||||
End If
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
End Function
|
||||
|
||||
|
||||
@@ -49,18 +49,38 @@ Function DxPreflightApply(runRoot, runId, snapshotId, objectMap, _
|
||||
Dim projected
|
||||
Dim key
|
||||
Dim component
|
||||
Dim snapshotPath, snapshotText, snapshotDesignPath, currentProjectPath
|
||||
|
||||
DxPreflightApply = False
|
||||
errorText = ""
|
||||
backupPath = ""
|
||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||
requestPath = fso.BuildPath(runRoot, "apply-request.json")
|
||||
resultPath = fso.BuildPath(runRoot, "result.tsv")
|
||||
resultPath = fso.BuildPath(runRoot, "result.processing")
|
||||
If Not fso.FileExists(resultPath) Then resultPath = fso.BuildPath(runRoot, "result.tsv")
|
||||
If Not fso.FileExists(requestPath) Or Not fso.FileExists(resultPath) Then
|
||||
errorText = "Apply request is incomplete"
|
||||
Exit Function
|
||||
End If
|
||||
|
||||
snapshotPath = fso.BuildPath(runRoot, "request.json")
|
||||
If fso.FileExists(snapshotPath) Then
|
||||
snapshotText = DxToolsReadUtf8(snapshotPath)
|
||||
If Not DxToolsJsonString(snapshotText, "design_path", snapshotDesignPath) Then
|
||||
errorText = "Design snapshot project path is invalid"
|
||||
Exit Function
|
||||
End If
|
||||
currentProjectPath = ""
|
||||
On Error Resume Next
|
||||
currentProjectPath = CStr(Application.GetProjectData().GetProjectFilePath())
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
If currentProjectPath = "" Or StrComp(currentProjectPath, snapshotDesignPath, vbTextCompare) <> 0 Then
|
||||
errorText = "Design snapshot belongs to a different current project"
|
||||
Exit Function
|
||||
End If
|
||||
End If
|
||||
|
||||
requestText = DxToolsReadUtf8(requestPath)
|
||||
If InStr(requestText, """format_version"": 2,") = 0 Then
|
||||
errorText = "Unsupported apply request version"
|
||||
@@ -215,7 +235,7 @@ Function DxApplySchedule(resultText, objectMap, _
|
||||
touched, rollbackState, errorText)
|
||||
Exit Function
|
||||
End If
|
||||
finals.Add key, Array(CStr(op), CStr(propertyName), _
|
||||
finals(key) = Array(CStr(op), CStr(propertyName), _
|
||||
CStr(bridgeId), CStr(finalValue))
|
||||
End If
|
||||
Next
|
||||
@@ -331,7 +351,7 @@ Function DxBridgeReadOpValue(component, op, propertyName)
|
||||
DxBridgeReadOpValue = ""
|
||||
On Error Resume Next
|
||||
DxBridgeReadOpValue = CStr( _
|
||||
component.Attributes.Item(CStr(propertyName)).Value)
|
||||
component.FindAttribute(CStr(propertyName)).Value)
|
||||
If Err.Number <> 0 Then
|
||||
Err.Clear
|
||||
DxBridgeReadOpValue = ""
|
||||
@@ -341,7 +361,7 @@ Function DxBridgeReadOpValue(component, op, propertyName)
|
||||
DxBridgeReadOpValue = ""
|
||||
On Error Resume Next
|
||||
DxBridgeReadOpValue = DxBridgeNormalizeVisible( _
|
||||
component.Attributes.Item(CStr(propertyName)).Visible)
|
||||
component.FindAttribute(CStr(propertyName)).Visible)
|
||||
If Err.Number <> 0 Then
|
||||
Err.Clear
|
||||
DxBridgeReadOpValue = ""
|
||||
@@ -361,9 +381,9 @@ Function DxBridgeWriteOpValue(component, op, propertyName, value, _
|
||||
Case "refdes"
|
||||
component.Refdes = CStr(value)
|
||||
Case "property"
|
||||
component.Attributes.Item(CStr(propertyName)).Value = CStr(value)
|
||||
component.FindAttribute(CStr(propertyName)).Value = CStr(value)
|
||||
Case "visibility"
|
||||
component.Attributes.Item(CStr(propertyName)).Visible = _
|
||||
component.FindAttribute(CStr(propertyName)).Visible = _
|
||||
CBool(CStr(value))
|
||||
Case Else
|
||||
Err.Raise vbObjectError + 801, "DxBridgeWriteOpValue", _
|
||||
|
||||
@@ -4,6 +4,25 @@
|
||||
' host applies it inside one undoable transaction.
|
||||
|
||||
Dim DxToolsHome
|
||||
Dim DxExpeditionMenu
|
||||
|
||||
Call DxEpInitialize()
|
||||
|
||||
Sub DxEpInitialize()
|
||||
Dim host
|
||||
Set host = Nothing
|
||||
On Error Resume Next
|
||||
Set host = Application
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
If host Is Nothing Then Exit Sub
|
||||
Call DxToolsInstallExpeditionMenu()
|
||||
If DxToolsHome = "" Then Exit Sub
|
||||
On Error Resume Next
|
||||
Scripting.DontExit = True
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
End Sub
|
||||
|
||||
Sub DxToolsInstallExpeditionMenu()
|
||||
Dim menuBar
|
||||
@@ -14,13 +33,13 @@ Sub DxToolsInstallExpeditionMenu()
|
||||
|
||||
DxToolsHome = DxEpResolveRoot()
|
||||
If DxToolsHome = "" Then
|
||||
MsgBox "DxDesignerTools.exe not found next to this script.", _
|
||||
MsgBox "Run Start in DxDesignerTools.exe before importing this script.", _
|
||||
vbExclamation
|
||||
Exit Sub
|
||||
End If
|
||||
|
||||
caption = "Dx " & ChrW(&H6548) & ChrW(&H7387) & ChrW(&H5DE5) & ChrW(&H5177)
|
||||
Set menuBar = CommandBars("Document Menu Bar")
|
||||
Set menuBar = Application.Gui.CommandBars("Document Menu Bar")
|
||||
For i = menuBar.Controls.Count To 1 Step -1
|
||||
Set existing = menuBar.Controls.Item(i)
|
||||
If existing.Caption = caption Then
|
||||
@@ -31,14 +50,19 @@ Sub DxToolsInstallExpeditionMenu()
|
||||
End If
|
||||
Next
|
||||
|
||||
Set DxExpeditionMenu = menuBar.Controls.Add(10) ' cmdControlPopup
|
||||
Set DxExpeditionMenu = menuBar.Controls.Add(1) ' cmdControlPopup
|
||||
DxExpeditionMenu.Caption = caption
|
||||
|
||||
Set button = DxExpeditionMenu.Controls.Add
|
||||
button.Caption = ChrW(&H81EA) & ChrW(&H52A8) & ChrW(&H8C03) & _
|
||||
ChrW(&H6574) & ChrW(&H88C5) & ChrW(&H914D) & ChrW(&H5C42) & _
|
||||
ChrW(&H4F4D) & ChrW(&H53F7)
|
||||
button.OnAction = "DxExpeditionRunAssemblyRefdes"
|
||||
button.Target = ScriptEngine
|
||||
button.ExecuteMethod = "DxEpAssemblyMenuCommand"
|
||||
End Sub
|
||||
|
||||
Sub DxEpAssemblyMenuCommand(nID)
|
||||
Call DxExpeditionRunAssemblyRefdes()
|
||||
End Sub
|
||||
|
||||
Sub DxExpeditionRunAssemblyRefdes()
|
||||
@@ -66,9 +90,9 @@ Sub DxExpeditionRunAssemblyRefdes()
|
||||
|
||||
Dim exec
|
||||
Dim commandLine
|
||||
commandLine = DxToolsQuote(DxToolsHome & "\DxDesignerTools.exe") & _
|
||||
" compute assembly-refdes --request " & DxToolsQuote(requestPath) & _
|
||||
" --output " & DxToolsQuote(planPath)
|
||||
commandLine = DxEpQuote(DxToolsHome & "\DxDesignerTools.exe") & _
|
||||
" compute assembly-refdes --request " & DxEpQuote(requestPath) & _
|
||||
" --output " & DxEpQuote(planPath)
|
||||
On Error Resume Next
|
||||
Set exec = shell.Exec(commandLine)
|
||||
If Err.Number <> 0 Then
|
||||
@@ -109,6 +133,7 @@ Function DxEpExportRequest(docObj)
|
||||
Dim componentKey
|
||||
Dim orientation
|
||||
Dim hasComponent
|
||||
Dim assemblyFlag
|
||||
|
||||
Set spans = CreateObject("Scripting.Dictionary")
|
||||
lines = ""
|
||||
@@ -191,10 +216,12 @@ Function DxEpExportRequest(docObj)
|
||||
On Error GoTo 0
|
||||
|
||||
If lines <> "" Then lines = lines & vbCrLf
|
||||
assemblyFlag = "0"
|
||||
If fabtxt.Type = epcbFabAssembly Then assemblyFlag = "1"
|
||||
lines = lines & "T|" & textIndex & _
|
||||
"|" & CStr(fabtxt.TextType) & _
|
||||
"|" & CStr(fabtxt.Side) & _
|
||||
"|" & IIf(fabtxt.Type = epcbFabAssembly, "1", "0") & _
|
||||
"|" & assemblyFlag & _
|
||||
"|" & fabtxt.TextString & _
|
||||
"|" & orientation & _
|
||||
"|" & componentKey
|
||||
@@ -254,7 +281,11 @@ Sub DxEpApplyLine(line, fabtxt)
|
||||
fabtxt.Format.Height(epcbUnitMM) = CDbl(parts(5))
|
||||
End If
|
||||
fabtxt.Format.Orientation(epcbAngleUnitDegrees) = CDbl(parts(4))
|
||||
Call fabtxt.Move(CDbl(parts(2)), CDbl(parts(3)))
|
||||
' Blank height represents the legacy nonassembly/cardinal branch:
|
||||
' change text format while retaining the existing text position.
|
||||
If parts(5) <> "" Then
|
||||
Call fabtxt.Move(CDbl(parts(2)), CDbl(parts(3)))
|
||||
End If
|
||||
End If
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
@@ -268,6 +299,17 @@ Sub DxEpWriteAscii(path, text)
|
||||
stream.Close
|
||||
End Sub
|
||||
|
||||
Function DxEpQuote(value)
|
||||
Dim text, expression
|
||||
text = CStr(value)
|
||||
Set expression = CreateObject("VBScript.RegExp")
|
||||
expression.Pattern = "\\+$"
|
||||
expression.Global = False
|
||||
text = expression.Replace(text, "$&$&")
|
||||
DxEpQuote = Chr(34) & Replace(text, Chr(34), _
|
||||
Chr(92) & Chr(34)) & Chr(34)
|
||||
End Function
|
||||
|
||||
Function DxEpReadAscii(path)
|
||||
Dim stream
|
||||
Set stream = CreateObject("Scripting.FileSystemObject"). _
|
||||
@@ -285,28 +327,136 @@ Sub DxEpSleep(milliseconds)
|
||||
End Sub
|
||||
|
||||
Function DxEpResolveRoot()
|
||||
Dim fso
|
||||
Dim candidate
|
||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||
DxEpResolveRoot = ""
|
||||
On Error Resume Next
|
||||
candidate = CStr(WScript.ScriptFullName)
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
DxEpResolveRoot = DxEpRootForScript(candidate)
|
||||
If DxEpResolveRoot <> "" Then Exit Function
|
||||
candidate = ""
|
||||
On Error Resume Next
|
||||
candidate = CStr(Scripting.CurrentScriptFullName)
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
DxEpResolveRoot = DxEpRootForScript(candidate)
|
||||
If DxEpResolveRoot <> "" Then Exit Function
|
||||
candidate = ""
|
||||
On Error Resume Next
|
||||
candidate = CStr(Scripting.ScriptFullName)
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
DxEpResolveRoot = DxEpRootForScript(candidate)
|
||||
If DxEpResolveRoot <> "" Then Exit Function
|
||||
DxEpResolveRoot = DxEpRegisteredRoot()
|
||||
End Function
|
||||
|
||||
Function DxEpRootForScript(path)
|
||||
Dim fso, root
|
||||
DxEpRootForScript = ""
|
||||
If CStr(path) = "" Then Exit Function
|
||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||
' expedition\<script> -> tool root is two levels up.
|
||||
root = fso.GetParentFolderName(fso.GetParentFolderName(CStr(path)))
|
||||
If fso.FileExists(fso.BuildPath(root, "DxDesignerTools.exe")) And _
|
||||
fso.FileExists(root & "\expedition\ExpeditionBridge.vbs") Then
|
||||
DxEpRootForScript = root
|
||||
End If
|
||||
End Function
|
||||
|
||||
Function DxEpRegisteredRoot()
|
||||
Dim path
|
||||
path = CreateObject("WScript.Shell").ExpandEnvironmentStrings( _
|
||||
"%LOCALAPPDATA%\DxProductivity\startup-refactored\startup.json")
|
||||
DxEpRegisteredRoot = DxEpStartupRootFromFile(path)
|
||||
End Function
|
||||
|
||||
Function DxEpStartupRootFromFile(path)
|
||||
Dim fso, stream, text, root
|
||||
DxEpStartupRootFromFile = ""
|
||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||
If Not fso.FileExists(CStr(path)) Then Exit Function
|
||||
Set stream = Nothing
|
||||
On Error Resume Next
|
||||
Set stream = CreateObject("ADODB.Stream")
|
||||
stream.Type = 2
|
||||
stream.Charset = "utf-8"
|
||||
stream.Open
|
||||
stream.LoadFromFile CStr(path)
|
||||
text = stream.ReadText
|
||||
If Err.Number <> 0 Then
|
||||
Err.Clear
|
||||
candidate = CStr(Scripting.ScriptFullName)
|
||||
If Not stream Is Nothing Then stream.Close
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
Exit Function
|
||||
End If
|
||||
stream.Close
|
||||
On Error GoTo 0
|
||||
If candidate <> "" Then
|
||||
' expedition\<script> -> tool root is two levels up
|
||||
DxEpResolveRoot = fso.GetParentFolderName( _
|
||||
fso.GetParentFolderName(candidate))
|
||||
If Not fso.FileExists(fso.BuildPath( _
|
||||
DxEpResolveRoot, "DxDesignerTools.exe")) Then
|
||||
DxEpResolveRoot = ""
|
||||
End If
|
||||
If Not DxEpJsonString(text, "tool_root", root) Then Exit Function
|
||||
If fso.FileExists(fso.BuildPath(root, "DxDesignerTools.exe")) And _
|
||||
fso.FileExists(root & "\expedition\ExpeditionBridge.vbs") Then
|
||||
DxEpStartupRootFromFile = root
|
||||
End If
|
||||
End Function
|
||||
|
||||
Function DxEpJsonString(jsonText, key, ByRef value)
|
||||
Dim marker, markerAt, colonAt, quoteAt, index, character, escaped
|
||||
Dim hexValue, expression
|
||||
DxEpJsonString = False
|
||||
marker = Chr(34) & CStr(key) & Chr(34)
|
||||
markerAt = InStr(1, CStr(jsonText), marker, vbBinaryCompare)
|
||||
If markerAt = 0 Then Exit Function
|
||||
colonAt = InStr(markerAt + Len(marker), CStr(jsonText), ":")
|
||||
If colonAt = 0 Then Exit Function
|
||||
quoteAt = colonAt + 1
|
||||
Do While quoteAt <= Len(CStr(jsonText))
|
||||
character = Mid(CStr(jsonText), quoteAt, 1)
|
||||
If InStr(" " & vbTab & vbCr & vbLf, character) = 0 Then Exit Do
|
||||
quoteAt = quoteAt + 1
|
||||
Loop
|
||||
If Mid(CStr(jsonText), quoteAt, 1) <> Chr(34) Then Exit Function
|
||||
escaped = False
|
||||
value = ""
|
||||
For index = quoteAt + 1 To Len(CStr(jsonText))
|
||||
character = Mid(CStr(jsonText), index, 1)
|
||||
If escaped Then
|
||||
Select Case character
|
||||
Case Chr(34), Chr(92), "/"
|
||||
value = value & character
|
||||
Case "r"
|
||||
value = value & vbCr
|
||||
Case "n"
|
||||
value = value & vbLf
|
||||
Case "t"
|
||||
value = value & vbTab
|
||||
Case "b"
|
||||
value = value & Chr(8)
|
||||
Case "f"
|
||||
value = value & Chr(12)
|
||||
Case "u"
|
||||
hexValue = Mid(CStr(jsonText), index + 1, 4)
|
||||
Set expression = CreateObject("VBScript.RegExp")
|
||||
expression.Pattern = "^[0-9A-Fa-f]{4}$"
|
||||
If Not expression.Test(hexValue) Then Exit Function
|
||||
value = value & ChrW(CLng("&H" & hexValue))
|
||||
index = index + 4
|
||||
Case Else
|
||||
Exit Function
|
||||
End Select
|
||||
escaped = False
|
||||
ElseIf character = Chr(92) Then
|
||||
escaped = True
|
||||
ElseIf character = Chr(34) Then
|
||||
DxEpJsonString = True
|
||||
Exit Function
|
||||
Else
|
||||
value = value & character
|
||||
End If
|
||||
Next
|
||||
End Function
|
||||
|
||||
Function DxEpGetLicensedDoc(app)
|
||||
On Error Resume Next
|
||||
Dim key, licenseServer, licenseToken, docObj
|
||||
|
||||
@@ -13,7 +13,9 @@ hiddenimports = (
|
||||
+ collect_submodules("qtawesome")
|
||||
+ collect_submodules("cryptography")
|
||||
+ collect_submodules("pypdf")
|
||||
+ ["pypdf", "win32job", "win32con", "win32process", "pywintypes"]
|
||||
+ ["pypdf", "win32job", "win32con", "win32process", "pywintypes",
|
||||
"pythoncom", "win32com.client", "win32com.client.gencache",
|
||||
"win32com.client.genpy", "win32com.client.makepy"]
|
||||
)
|
||||
datas = collect_data_files("qtawesome")
|
||||
|
||||
|
||||
@@ -43,6 +43,11 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
|
||||
return pdf_export_main(arguments[1:])
|
||||
|
||||
if arguments and arguments[0] == "pdf-export-listen":
|
||||
from dx_productivity.features.pdf_export.native_listener import main as pdf_listener_main
|
||||
|
||||
return pdf_listener_main(arguments[1:])
|
||||
|
||||
if arguments and arguments[0] == "ui":
|
||||
arguments = arguments[1:]
|
||||
|
||||
|
||||
@@ -55,6 +55,9 @@ def load_request(path: Path) -> DesignSnapshot:
|
||||
current_sheet_number = data.get("current_sheet_number")
|
||||
if current_sheet_number is not None and type(current_sheet_number) is not int:
|
||||
raise ProtocolError("current_sheet_number must be an integer or null")
|
||||
current_sheet_name = data.get("current_sheet_name", "")
|
||||
if not isinstance(current_sheet_name, str):
|
||||
raise ProtocolError("current_sheet_name must be a string")
|
||||
|
||||
return DesignSnapshot(
|
||||
format_version=FORMAT_VERSION,
|
||||
@@ -67,6 +70,7 @@ def load_request(path: Path) -> DesignSnapshot:
|
||||
selected_nets=selected_nets,
|
||||
active_block_name=active_block_name,
|
||||
current_sheet_number=current_sheet_number,
|
||||
current_sheet_name=current_sheet_name,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -66,12 +66,12 @@ class RunStore:
|
||||
) -> Path:
|
||||
if plan.snapshot_id != snapshot.snapshot_id:
|
||||
raise RunStoreError("plan snapshot does not match backup snapshot")
|
||||
targets = {
|
||||
bridge_id: (row.new_refdes or "", row.op, row.property_name)
|
||||
targets = [
|
||||
(bridge_id, row.new_refdes or "", row.op, row.property_name)
|
||||
for row in plan.rows
|
||||
if row.changed and row.new_refdes is not None
|
||||
for bridge_id in row.bridge_ids
|
||||
}
|
||||
]
|
||||
if not targets:
|
||||
raise RunStoreError("backup requires at least one changed component")
|
||||
|
||||
@@ -83,12 +83,10 @@ class RunStore:
|
||||
full_path=by_bridge[bridge_id].full_path,
|
||||
op=op,
|
||||
property_name=property_name,
|
||||
old_value=by_bridge[bridge_id].refdes
|
||||
if op is OpType.REFDES
|
||||
else _attribute_value(by_bridge[bridge_id], property_name),
|
||||
old_value=_operation_value(by_bridge[bridge_id], op, property_name),
|
||||
new_value=new_value,
|
||||
)
|
||||
for bridge_id, (new_value, op, property_name) in targets.items()
|
||||
for bridge_id, new_value, op, property_name in targets
|
||||
]
|
||||
return self.write_operation_backup(snapshot, tuple(changes))
|
||||
|
||||
@@ -251,9 +249,13 @@ def _parse_restore_item(value: object) -> RestoreItem:
|
||||
)
|
||||
|
||||
|
||||
def _attribute_value(component: Any, property_name: str) -> str:
|
||||
def _operation_value(component: Any, op: OpType, property_name: str) -> str:
|
||||
if op is OpType.REFDES:
|
||||
return component.refdes
|
||||
for attribute in component.attributes:
|
||||
if attribute.name.casefold() == property_name.casefold():
|
||||
if op is OpType.PROPERTY_VISIBILITY:
|
||||
return "1" if attribute.visible else "0"
|
||||
return attribute.value
|
||||
return ""
|
||||
|
||||
|
||||
@@ -72,14 +72,24 @@ def _register_menu(text: str, menu: Path) -> str:
|
||||
end = next((i for i in range(start + 1, len(lines)) if lines[i].strip().startswith("[")), len(lines))
|
||||
entry = str(menu)
|
||||
used = set()
|
||||
registered_keys = set()
|
||||
registered_index = None
|
||||
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}"]
|
||||
registered_index = int(match[1])
|
||||
registered_keys.add(line.split("#", 1)[0].strip().lower())
|
||||
if registered_keys == {"script", "脚本"}:
|
||||
return text
|
||||
index = registered_index if registered_index is not None else next(i for i in range(len(used) + 1) if i not in used)
|
||||
# Chinese 7.9.5 reads the localized key. Keep the English alias for other
|
||||
# installations; each host reads its language's entry, and menus are unique.
|
||||
added = [f"{key}#{index}={entry}" for key in ("Script", "脚本") if key.lower() not in registered_keys]
|
||||
if registered_index is None:
|
||||
added.insert(0, "; DxProductivity Start managed entry")
|
||||
lines[end:end] = added
|
||||
return "\r\n".join(lines) + "\r\n"
|
||||
|
||||
|
||||
@@ -94,8 +104,8 @@ def prepare_startup(tool_root: Path, viewdraw: Path, environment: dict[str, str]
|
||||
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.
|
||||
# Register in the same WDIR used by ordinary DxDesigner launches, so the
|
||||
# menu survives closing the tool, opening another project, and restarting.
|
||||
wdir = []
|
||||
for entry in environment.get("WDIR", "").split(";"):
|
||||
if entry.strip():
|
||||
@@ -111,7 +121,7 @@ def prepare_startup(tool_root: Path, viewdraw: Path, environment: dict[str, str]
|
||||
if catalog is None:
|
||||
raise StartupError("DxDesigner 安装不完整,未找到消息目录 vllib.vmb")
|
||||
assets = generate_startup_assets(tool_root, startup_root)
|
||||
ini = startup_root / "scripts.ini"
|
||||
ini = vendor_ini or wdir[0] / "scripts.ini"
|
||||
content = _register_menu(text, assets.menu_script).encode(encoding)
|
||||
if ini.exists() and ini.read_bytes() != content:
|
||||
backups = Path(profile) / "DxProductivity" / "backups"
|
||||
@@ -119,9 +129,8 @@ def prepare_startup(tool_root: Path, viewdraw: Path, environment: dict[str, str]
|
||||
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))
|
||||
child_environment["WDIR"] = ";".join(str(path) for path in 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)}
|
||||
@@ -150,7 +159,7 @@ def start_dxdesigner(tool_root: Path, *, viewdraw: Path | None = None, environme
|
||||
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 已启动,工具菜单已加载"
|
||||
return "菜单已持久注册并加入当前 DxDesigner" if reused else "DxDesigner 已启动,工具菜单已持久注册"
|
||||
except (OSError, UnicodeError):
|
||||
pass
|
||||
time.sleep(0.1)
|
||||
|
||||
@@ -196,6 +196,7 @@ class DesignSnapshot:
|
||||
selected_nets: tuple[str, ...] = ()
|
||||
active_block_name: str = ""
|
||||
current_sheet_number: int | None = None
|
||||
current_sheet_name: str = ""
|
||||
|
||||
@property
|
||||
def component_count(self) -> int:
|
||||
|
||||
@@ -18,6 +18,7 @@ from dx_productivity.domain.models import (
|
||||
from dx_productivity.domain.refdes_rules import (
|
||||
is_claimed_refdes,
|
||||
refdes_prefix,
|
||||
split_refdes,
|
||||
)
|
||||
from dx_productivity.domain.schedule import build_apply_schedule
|
||||
|
||||
@@ -60,9 +61,19 @@ def build_restore_plan(
|
||||
)
|
||||
)
|
||||
continue
|
||||
current = component.refdes.strip().casefold()
|
||||
expected = item.expected_value.strip().casefold()
|
||||
restore = item.restore_value.strip().casefold()
|
||||
value = _operation_value(component, item)
|
||||
if value is None:
|
||||
issues.append(
|
||||
_issue(
|
||||
"restore-property-missing",
|
||||
"备份中的属性已不存在,不能恢复",
|
||||
component.bridge_id,
|
||||
)
|
||||
)
|
||||
continue
|
||||
current = _comparison_value(value, item.op)
|
||||
expected = _comparison_value(item.expected_value, item.op)
|
||||
restore = _comparison_value(item.restore_value, item.op)
|
||||
if current == expected:
|
||||
satisfied = False
|
||||
elif current == restore:
|
||||
@@ -71,7 +82,7 @@ def build_restore_plan(
|
||||
issues.append(
|
||||
_issue(
|
||||
"restore-stale",
|
||||
"器件位号已在备份后发生变化",
|
||||
"器件属性已在备份后发生变化",
|
||||
component.bridge_id,
|
||||
)
|
||||
)
|
||||
@@ -111,8 +122,8 @@ def build_restore_plan(
|
||||
|
||||
for logical_key in sorted(groups, key=str.casefold):
|
||||
values = groups[logical_key]
|
||||
expected_values = {item.expected_value.strip().casefold() for item, _, _ in values}
|
||||
restore_values = {item.restore_value.strip().casefold() for item, _, _ in values}
|
||||
expected_values = {_comparison_value(item.expected_value, item.op) for item, _, _ in values}
|
||||
restore_values = {_comparison_value(item.restore_value, item.op) for item, _, _ in values}
|
||||
if len(expected_values) != 1 or len(restore_values) != 1:
|
||||
issues.append(
|
||||
_issue(
|
||||
@@ -124,9 +135,9 @@ def build_restore_plan(
|
||||
continue
|
||||
|
||||
item, representative, satisfied = values[0]
|
||||
target = item.restore_value.strip()
|
||||
target_folded = target.casefold()
|
||||
is_refdes = item.op is OpType.REFDES
|
||||
target = item.restore_value.strip() if is_refdes else item.restore_value
|
||||
target_folded = _comparison_value(target, item.op)
|
||||
if is_refdes and is_claimed_refdes(target):
|
||||
if target_folded in outside_claimed:
|
||||
issues.append(
|
||||
@@ -160,14 +171,14 @@ def build_restore_plan(
|
||||
),
|
||||
full_path=representative.full_path,
|
||||
prefix=(
|
||||
refdes_prefix(target) or refdes_prefix(item.expected_value)
|
||||
_restore_prefix(target) or _restore_prefix(item.expected_value)
|
||||
)
|
||||
if is_refdes
|
||||
else None,
|
||||
old_refdes=item.expected_value.strip(),
|
||||
old_refdes=item.expected_value.strip() if is_refdes else item.expected_value,
|
||||
new_refdes=target,
|
||||
status="restore",
|
||||
changed=item.expected_value.strip().casefold() != target_folded
|
||||
changed=_comparison_value(item.expected_value, item.op) != target_folded
|
||||
and not satisfied,
|
||||
sheet_name=representative.sheet_name,
|
||||
sheet_number=representative.sheet_number,
|
||||
@@ -206,23 +217,7 @@ def _match_components(
|
||||
item: RestoreItem,
|
||||
) -> tuple[ComponentRecord, ...]:
|
||||
bridge_id = item.bridge_id.strip().casefold()
|
||||
if bridge_id:
|
||||
exact = tuple(
|
||||
component
|
||||
for component in snapshot.components
|
||||
if component.bridge_id.casefold() == bridge_id
|
||||
)
|
||||
if exact:
|
||||
return exact
|
||||
path = item.full_path.strip().casefold()
|
||||
if path:
|
||||
by_path = tuple(
|
||||
component
|
||||
for component in snapshot.components
|
||||
if component.full_path.strip().casefold() == path
|
||||
)
|
||||
if len(by_path) == 1:
|
||||
return by_path
|
||||
uid = (item.stable_uid or "").strip().casefold()
|
||||
if uid:
|
||||
by_uid = tuple(
|
||||
@@ -231,11 +226,56 @@ def _match_components(
|
||||
if component.stable_uid
|
||||
and component.stable_uid.strip().casefold() == uid
|
||||
)
|
||||
if by_uid:
|
||||
if len(by_uid) == 1:
|
||||
return by_uid
|
||||
if by_uid:
|
||||
by_path = tuple(
|
||||
component for component in by_uid
|
||||
if path and component.full_path.strip().casefold() == path
|
||||
)
|
||||
if len(by_path) == 1:
|
||||
return by_path
|
||||
exact = tuple(
|
||||
component for component in by_uid
|
||||
if component.bridge_id.casefold() == bridge_id
|
||||
)
|
||||
if len(exact) == 1:
|
||||
return exact
|
||||
return by_uid
|
||||
return ()
|
||||
if path:
|
||||
return tuple(
|
||||
component for component in snapshot.components
|
||||
if component.full_path.strip().casefold() == path
|
||||
)
|
||||
if bridge_id:
|
||||
return tuple(
|
||||
component for component in snapshot.components
|
||||
if component.bridge_id.casefold() == bridge_id
|
||||
)
|
||||
return ()
|
||||
|
||||
|
||||
def _operation_value(component: ComponentRecord, item: RestoreItem) -> str | None:
|
||||
if item.op is OpType.REFDES:
|
||||
return component.refdes
|
||||
for attribute in component.attributes:
|
||||
if attribute.name.casefold() == item.property_name.casefold():
|
||||
if item.op is OpType.PROPERTY_VISIBILITY:
|
||||
return "1" if attribute.visible else "0"
|
||||
return attribute.value
|
||||
return None
|
||||
|
||||
|
||||
def _comparison_value(value: str, op: OpType) -> str:
|
||||
return value.strip().casefold() if op is OpType.REFDES else value
|
||||
|
||||
|
||||
def _restore_prefix(value: str) -> str | None:
|
||||
formal = split_refdes(value)
|
||||
return formal[0] if formal is not None else refdes_prefix(value)
|
||||
|
||||
|
||||
def _identity_key(component: ComponentRecord) -> str:
|
||||
if component.stable_uid:
|
||||
return f"uid:{component.stable_uid.casefold()}"
|
||||
|
||||
@@ -34,12 +34,12 @@ def _direct_steps(row: PlanRow) -> list[ApplyStep]:
|
||||
if not row.bridge_ids:
|
||||
raise ValueError(f"changed row {row.logical_key!r} has no bridge ID")
|
||||
bridge_id = min(row.bridge_ids, key=str.casefold)
|
||||
target = row.new_refdes.strip()
|
||||
target = row.new_refdes
|
||||
return [
|
||||
ApplyStep(
|
||||
sequence=0,
|
||||
bridge_id=bridge_id,
|
||||
expected_refdes=row.old_refdes.strip(),
|
||||
expected_refdes=row.old_refdes,
|
||||
new_refdes=target,
|
||||
final_refdes=target,
|
||||
op=row.op,
|
||||
|
||||
@@ -106,7 +106,10 @@ def build_bom(
|
||||
refdes=row.refdes,
|
||||
part_number=row.part_number,
|
||||
description=row.description,
|
||||
duplicate_refdes=row.refdes.casefold() in duplicate_refdes,
|
||||
duplicate_refdes=any(
|
||||
refdes.strip().casefold() in duplicate_refdes
|
||||
for refdes in row.refdes.split(",")
|
||||
),
|
||||
part_number_mismatch=mismatch,
|
||||
mismatch_reason=reason,
|
||||
)
|
||||
|
||||
@@ -25,6 +25,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
parser.add_argument("--settings", required=True, type=Path)
|
||||
parser.add_argument("--project", required=True, type=Path)
|
||||
parser.add_argument("--active-block", default="")
|
||||
parser.add_argument("--active-sheet", default="")
|
||||
parser.add_argument("--status-file", required=True, type=Path)
|
||||
options = parser.parse_args(argv)
|
||||
settings = load_settings(options.project, config_path=options.settings)
|
||||
@@ -35,6 +36,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
settings,
|
||||
threading.Event(),
|
||||
active_block_name=options.active_block,
|
||||
active_sheet_name=options.active_sheet,
|
||||
overwrite=True,
|
||||
)
|
||||
_write_status(options.status_file, result.message)
|
||||
|
||||
@@ -13,7 +13,7 @@ import uuid
|
||||
from contextlib import suppress
|
||||
from typing import Callable
|
||||
|
||||
from pypdf import PdfReader
|
||||
from pypdf import PdfReader, PdfWriter
|
||||
|
||||
from .engine import discover_engine, run_engine
|
||||
from .models import ExportScope, PdfExportResult, PdfExportSettings
|
||||
@@ -93,18 +93,71 @@ def _source_files(root: Path):
|
||||
yield from walk(root)
|
||||
|
||||
|
||||
def _fingerprint(root: Path, cancel: threading.Event) -> dict[str, str]:
|
||||
def _locked_native_file(name: str, database_relative: str) -> bool:
|
||||
prefix = tuple(part.casefold() for part in database_relative.strip("/").split("/") if part)
|
||||
parts = tuple(part.casefold() for part in name.split("/"))
|
||||
if not prefix or parts[:len(prefix)] != prefix:
|
||||
return False
|
||||
relative = parts[len(prefix):]
|
||||
return (
|
||||
relative == ("icdb.dat",)
|
||||
or relative in {("cdbsvr", "saddress.adr"), ("cdbsvr", "backup.lck")}
|
||||
or len(relative) > 2 and relative[0] == "cdbsvr"
|
||||
and relative[1] in {"events", "log", "plog", "dbcheck", "dbupgrade"}
|
||||
)
|
||||
|
||||
|
||||
def _sharing_violation(path: Path, error: PermissionError) -> bool:
|
||||
code = getattr(error, "winerror", None)
|
||||
if code is not None:
|
||||
return code in {32, 33}
|
||||
if os.name != "nt":
|
||||
return False
|
||||
# Python file IO can discard the Windows sharing-error code. Probe the
|
||||
# same read with explicit sharing flags before treating it as a DB lock.
|
||||
import pywintypes
|
||||
import win32con
|
||||
import win32file
|
||||
|
||||
try:
|
||||
handle = win32file.CreateFile(
|
||||
str(path), win32con.GENERIC_READ,
|
||||
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
|
||||
None, win32con.OPEN_EXISTING, 0, None,
|
||||
)
|
||||
except pywintypes.error as native_error:
|
||||
return native_error.winerror in {32, 33}
|
||||
handle.Close()
|
||||
return False
|
||||
|
||||
|
||||
def _fingerprint(
|
||||
root: Path,
|
||||
cancel: threading.Event,
|
||||
database_relative: str = "",
|
||||
unverified_native: set[str] | None = None,
|
||||
) -> dict[str, str]:
|
||||
digest_map: dict[str, str] = {}
|
||||
for path in _source_files(root):
|
||||
if cancel.is_set():
|
||||
raise InterruptedError("导出已取消")
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
while chunk := stream.read(1024 * 1024):
|
||||
if cancel.is_set():
|
||||
raise InterruptedError("导出已取消")
|
||||
digest.update(chunk)
|
||||
digest_map[path.relative_to(root).as_posix()] = digest.hexdigest()
|
||||
name = path.relative_to(root).as_posix()
|
||||
try:
|
||||
with path.open("rb") as stream:
|
||||
while chunk := stream.read(1024 * 1024):
|
||||
if cancel.is_set():
|
||||
raise InterruptedError("导出已取消")
|
||||
digest.update(chunk)
|
||||
except PermissionError as error:
|
||||
if not _locked_native_file(name, database_relative) or not _sharing_violation(path, error):
|
||||
raise
|
||||
details = path.stat()
|
||||
digest_map[name] = f"unreadable-native:windows-sharing-lock:{details.st_size}:{details.st_mtime_ns}"
|
||||
if unverified_native is not None:
|
||||
unverified_native.add(name)
|
||||
continue
|
||||
digest_map[name] = digest.hexdigest()
|
||||
return digest_map
|
||||
|
||||
|
||||
@@ -189,7 +242,11 @@ def _safe_name(value: str) -> str:
|
||||
return cleaned[:80] or "block"
|
||||
|
||||
|
||||
def output_path(settings: PdfExportSettings, active_block_name: str = "") -> Path:
|
||||
def output_path(
|
||||
settings: PdfExportSettings,
|
||||
active_block_name: str = "",
|
||||
active_sheet_name: str = "",
|
||||
) -> Path:
|
||||
project = Path(settings.project_path)
|
||||
stem = _safe_name(project.stem)
|
||||
if settings.scope is ExportScope.PROJECT:
|
||||
@@ -198,8 +255,12 @@ def output_path(settings: PdfExportSettings, active_block_name: str = "") -> Pat
|
||||
name = active_block_name.strip()
|
||||
if not name:
|
||||
raise ValueError("无法读取当前活动页的 Block 名称,请刷新设计快照")
|
||||
digest = hashlib.sha256(name.casefold().encode("utf-8")).hexdigest()[:6]
|
||||
suffix = f"current-page-{_safe_name(name)}-{digest}"
|
||||
sheet = active_sheet_name.strip()
|
||||
if not sheet or any(char in sheet for char in "\r\n\x00"):
|
||||
raise ValueError("无法读取当前活动页名称,请刷新设计快照")
|
||||
identity = name.casefold() + "\x00" + sheet.casefold()
|
||||
digest = hashlib.sha256(identity.encode("utf-8")).hexdigest()[:6]
|
||||
suffix = f"current-page-{_safe_name(name + '-' + sheet)}-{digest}"
|
||||
else:
|
||||
name = settings.block_name.strip()
|
||||
if not name:
|
||||
@@ -209,6 +270,39 @@ def output_path(settings: PdfExportSettings, active_block_name: str = "") -> Pat
|
||||
return Path(settings.output_dir) / f"{stem}_{suffix}.pdf"
|
||||
|
||||
|
||||
def _select_current_page(path: Path, block_name: str, sheet_name: str) -> None:
|
||||
"""Select the exact native bookmark destination; sch2pdf only accepts blocks."""
|
||||
expected = f"{block_name.strip()} Sheet {sheet_name.strip()}".casefold()
|
||||
selected = path.with_name(f".{path.stem}.{uuid.uuid4().hex[:8]}.selected.pdf")
|
||||
try:
|
||||
with path.open("rb") as source:
|
||||
reader = PdfReader(source, strict=True)
|
||||
candidates: list[int] = []
|
||||
|
||||
def inspect(items) -> None:
|
||||
for item in items:
|
||||
if isinstance(item, list):
|
||||
inspect(item)
|
||||
elif item.title.casefold() == expected:
|
||||
page = reader.get_destination_page_number(item)
|
||||
if page is not None:
|
||||
candidates.append(page)
|
||||
|
||||
inspect(reader.outline)
|
||||
if len(candidates) != 1:
|
||||
raise ValueError("原生 PDF 无法唯一定位当前活动页,未发布 PDF")
|
||||
writer = PdfWriter()
|
||||
writer.append(reader, pages=[candidates[0]], import_outline=True)
|
||||
with selected.open("xb") as output:
|
||||
writer.write(output)
|
||||
pages, _, _ = _validate_pdf(selected)
|
||||
if pages != 1:
|
||||
raise ValueError("当前活动页 PDF 页数验证失败")
|
||||
os.replace(selected, path)
|
||||
finally:
|
||||
selected.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def build_command(
|
||||
engine: Path,
|
||||
project: Path,
|
||||
@@ -249,6 +343,7 @@ def export_project(
|
||||
on_event: Callable[[str], None] | None = None,
|
||||
*,
|
||||
active_block_name: str = "",
|
||||
active_sheet_name: str = "",
|
||||
overwrite: bool = False,
|
||||
timeout: float = 300,
|
||||
local_app_data: Path | None = None,
|
||||
@@ -271,6 +366,7 @@ def export_project(
|
||||
before: dict[str, str] | None = None
|
||||
source_root: Path | None = None
|
||||
database_relative: str | None = None
|
||||
unverified_native: set[str] = set()
|
||||
|
||||
def emit(value: str) -> None:
|
||||
try:
|
||||
@@ -314,7 +410,7 @@ def export_project(
|
||||
source_root = project.parent
|
||||
database_relative = database.relative_to(source_root).as_posix()
|
||||
output_dir = _validate_output_location(source_root, Path(settings.output_dir))
|
||||
final_path = output_path(settings, active_block_name)
|
||||
final_path = output_path(settings, active_block_name, active_sheet_name)
|
||||
final_path = output_dir / final_path.name
|
||||
if final_path.exists() and not overwrite:
|
||||
state, message = "exists", f"已有同名 PDF:{final_path}"
|
||||
@@ -333,6 +429,8 @@ def export_project(
|
||||
"project": str(project),
|
||||
"scope": settings.scope.value,
|
||||
"block_name": block_name,
|
||||
"sheet_name": active_sheet_name.strip()
|
||||
if settings.scope is ExportScope.CURRENT_PAGE else "",
|
||||
"output": str(final_path),
|
||||
"engine": str(engine),
|
||||
"command": command,
|
||||
@@ -340,7 +438,7 @@ def export_project(
|
||||
)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
emit("核验当前工程和输出目录")
|
||||
before = _fingerprint(source_root, cancel)
|
||||
before = _fingerprint(source_root, cancel, database_relative, unverified_native)
|
||||
_write_json(run_dir / "source-before.json", before)
|
||||
emit("直接调用本机 sch2pdf.exe;读取当前工程配置")
|
||||
return_code = run_engine(command, source_root, run_dir, cancel, timeout, emit)
|
||||
@@ -348,25 +446,30 @@ def export_project(
|
||||
raise RuntimeError(f"原生引擎退出码 {return_code};请检查工程、许可和运行日志")
|
||||
if cancel.is_set():
|
||||
raise InterruptedError("导出已取消")
|
||||
if settings.scope is ExportScope.CURRENT_PAGE:
|
||||
emit(f"从原生 PDF 定位当前活动页:{active_sheet_name.strip()}")
|
||||
_select_current_page(stage, block_name, active_sheet_name)
|
||||
pages, size, sha256 = _validate_pdf(stage)
|
||||
_write_json(
|
||||
run_dir / "pdf-check.json",
|
||||
{"pages": pages, "size": size, "sha256": sha256},
|
||||
)
|
||||
after = _fingerprint(source_root, cancel)
|
||||
after = _fingerprint(source_root, cancel, database_relative, unverified_native)
|
||||
_write_json(run_dir / "source-after.json", after)
|
||||
differences = _changes(before, after)
|
||||
accepted, blocked = _classify_changes(
|
||||
differences, database.relative_to(source_root).as_posix()
|
||||
)
|
||||
if any(blocked.values()):
|
||||
_write_json(run_dir / "source-assessment.json", {"accepted": accepted, "blocked": blocked})
|
||||
_write_json(run_dir / "source-assessment.json", {"accepted": accepted, "blocked": blocked, "unverified_native_files": sorted(unverified_native)})
|
||||
state = "uncertain"
|
||||
message = "导出期间工程文件发生变化,未发布 PDF;请检查运行记录中的 source-assessment.json"
|
||||
return PdfExportResult(project, state, message, final_path, pages, run_dir)
|
||||
if any(accepted.values()):
|
||||
warnings.append("原生数据库或运行记录发生变化;这不代表源工程只读")
|
||||
_write_json(run_dir / "source-assessment.json", {"accepted": accepted, "blocked": blocked})
|
||||
if unverified_native:
|
||||
warnings.append("工程打开期间原生数据库被锁定,无法核验其内容;工程配置和可读设计文件已核验")
|
||||
_write_json(run_dir / "source-assessment.json", {"accepted": accepted, "blocked": blocked, "unverified_native_files": sorted(unverified_native)})
|
||||
if cancel.is_set():
|
||||
raise InterruptedError("导出已取消")
|
||||
if overwrite:
|
||||
@@ -380,7 +483,7 @@ def export_project(
|
||||
state = "success"
|
||||
message = f"PDF 已导出,共 {pages} 页:{final_path}"
|
||||
if warnings:
|
||||
message += "。" + warnings[0]
|
||||
message += "。" + "。".join(warnings)
|
||||
except InterruptedError as error:
|
||||
state, message = "cancelled", str(error)
|
||||
except TimeoutError as error:
|
||||
@@ -396,11 +499,11 @@ def export_project(
|
||||
and state not in {"success", "uncertain"}
|
||||
):
|
||||
try:
|
||||
after = _fingerprint(source_root, threading.Event())
|
||||
after = _fingerprint(source_root, threading.Event(), database_relative, unverified_native)
|
||||
_write_json(run_dir / "source-after.json", after)
|
||||
changes = _changes(before, after)
|
||||
accepted, blocked = _classify_changes(changes, database_relative)
|
||||
_write_json(run_dir / "source-assessment.json", {"accepted": accepted, "blocked": blocked})
|
||||
_write_json(run_dir / "source-assessment.json", {"accepted": accepted, "blocked": blocked, "unverified_native_files": sorted(unverified_native)})
|
||||
if any(blocked.values()):
|
||||
state = "uncertain"
|
||||
message += ";失败期间源工程也发生变化,请核对 source-assessment.json"
|
||||
|
||||
@@ -6,38 +6,28 @@ import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def ensure_listener(config_path: Path, tool_root: Path) -> str | None:
|
||||
windows_root = Path(os.environ.get("WINDIR", r"C:\Windows"))
|
||||
script_path = Path(tool_root) / "PdfSaveListener.vbs"
|
||||
host = windows_root / "SysWOW64" / "wscript.exe"
|
||||
if not host.is_file():
|
||||
if os.environ.get("PROCESSOR_ARCHITEW6432"):
|
||||
return "未找到 32 位 Windows Script Host,自动导出监听未启动"
|
||||
host = windows_root / "System32" / "wscript.exe"
|
||||
if not host.is_file() or not script_path.is_file():
|
||||
return "找不到 DxDesigner 保存事件监听脚本,自动导出监听未启动"
|
||||
def tool_command(arguments: list[str]) -> tuple[list[str], Path, dict[str, str]]:
|
||||
executable = Path(sys.executable)
|
||||
environment = os.environ.copy()
|
||||
if getattr(sys, "frozen", False):
|
||||
executable = Path(sys.executable)
|
||||
mode = "exe"
|
||||
working_root = executable.parent
|
||||
else:
|
||||
executable = Path(sys.executable)
|
||||
mode = "module"
|
||||
working_root = Path(__file__).resolve().parents[4]
|
||||
command = [
|
||||
str(host),
|
||||
"//B",
|
||||
"//NoLogo",
|
||||
str(script_path),
|
||||
str(Path(config_path).resolve()),
|
||||
str(executable),
|
||||
mode,
|
||||
str(working_root),
|
||||
]
|
||||
return [str(executable), *arguments], executable.parent, environment
|
||||
root = Path(__file__).resolve().parents[4]
|
||||
source = str(root / "src")
|
||||
environment["PYTHONPATH"] = source + (
|
||||
os.pathsep + environment["PYTHONPATH"] if environment.get("PYTHONPATH") else ""
|
||||
)
|
||||
return [str(executable), "-m", "dx_productivity.bridge.launcher", *arguments], root, environment
|
||||
|
||||
|
||||
def ensure_listener(config_path: Path, tool_root: Path) -> str | None:
|
||||
command, working_root, environment = tool_command(
|
||||
["pdf-export-listen", "--settings", str(Path(config_path).resolve())]
|
||||
)
|
||||
try:
|
||||
subprocess.Popen(
|
||||
command,
|
||||
cwd=working_root,
|
||||
env=environment,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
from typing import Callable
|
||||
|
||||
from .exporter import _write_json
|
||||
from .listener import tool_command
|
||||
from .settings import normalized_project_path
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SaveEvent:
|
||||
project_path: Path
|
||||
block_name: str
|
||||
sheet_name: str
|
||||
|
||||
|
||||
class SaveQueue:
|
||||
def __init__(self, start: Callable[[SaveEvent], object], *, debounce_seconds: float = 0.5, on_complete: Callable[[int], None] | None = None) -> None:
|
||||
self.start = start
|
||||
self.debounce_seconds = debounce_seconds
|
||||
self.on_complete = on_complete or (lambda _code: None)
|
||||
self.pending: SaveEvent | None = None
|
||||
self.due_at = 0.0
|
||||
self.process = None
|
||||
|
||||
def add(self, event: SaveEvent, now: float) -> None:
|
||||
self.pending = event
|
||||
self.due_at = now + self.debounce_seconds
|
||||
|
||||
def tick(self, now: float, *, enabled: bool = True) -> None:
|
||||
if not enabled:
|
||||
self.pending = None
|
||||
if self.process is not None:
|
||||
code = self.process.poll()
|
||||
if code is None:
|
||||
return
|
||||
self.process = None
|
||||
self.on_complete(code)
|
||||
if enabled and self.pending is not None and now >= self.due_at:
|
||||
event, self.pending = self.pending, None
|
||||
self.process = self.start(event)
|
||||
|
||||
|
||||
def _project_path(app) -> str:
|
||||
value = app.GetProjectData().GetProjectFilePath
|
||||
return str(value() if callable(value) else value)
|
||||
|
||||
|
||||
def select_application(candidates, project: Path):
|
||||
matches = []
|
||||
expected = normalized_project_path(project)
|
||||
for name, app in candidates:
|
||||
try:
|
||||
if normalized_project_path(_project_path(app)) == expected:
|
||||
matches.append((name, app))
|
||||
except Exception:
|
||||
continue
|
||||
if len(matches) > 1:
|
||||
raise ValueError("多个 DxDesigner 实例打开同一工程,无法唯一绑定保存监听")
|
||||
return matches[0] if matches else None
|
||||
|
||||
|
||||
def _applications():
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
|
||||
context = pythoncom.CreateBindCtx(0)
|
||||
table = pythoncom.GetRunningObjectTable()
|
||||
for moniker in table.EnumRunning():
|
||||
try:
|
||||
name = moniker.GetDisplayName(context, None)
|
||||
if name.casefold().startswith("!viewdraw.application"):
|
||||
app = win32com.client.Dispatch(table.GetObject(moniker).QueryInterface(pythoncom.IID_IDispatch))
|
||||
yield name, app
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
|
||||
def _enabled_project(config: Path) -> Path | None:
|
||||
try:
|
||||
data = json.loads(config.read_text(encoding="utf-8"))
|
||||
if isinstance(data, dict) and data.get("auto_export") is True:
|
||||
path = data.get("project_path")
|
||||
if isinstance(path, str) and path.strip():
|
||||
return Path(path).resolve()
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
class _Events:
|
||||
def OnAfterDocumentSave(self, Doc) -> None:
|
||||
self.owner.changed("native-after-document-save", quiet_seconds=0.1)
|
||||
|
||||
def OnShutdown(self) -> None:
|
||||
self.owner.shutdown = True
|
||||
|
||||
def OnDocumentSave(self) -> None:
|
||||
self.owner.record("native-document-save")
|
||||
|
||||
def OnSourceDocumentSave(self, filename) -> None:
|
||||
self.owner.record("native-source-document-save", filename=str(filename))
|
||||
|
||||
def OnBeforeSaveAndCheck(self, data) -> None:
|
||||
self.owner.record("native-before-save-and-check")
|
||||
|
||||
def OnAfterSaveAndCheck(self) -> None:
|
||||
self.owner.changed("native-after-save-and-check", quiet_seconds=0.1)
|
||||
|
||||
def OnDocumentModified(self) -> None:
|
||||
self.owner.changed("native-document-modified")
|
||||
|
||||
def OnBlockModified(self, block) -> None:
|
||||
self.owner.changed("native-block-modified")
|
||||
|
||||
|
||||
class NativeListener:
|
||||
def __init__(self, config: Path) -> None:
|
||||
self.config = config
|
||||
self.status_path = config.with_name(config.name + ".last-status")
|
||||
self.log_path = config.with_name(config.name + ".listener.log")
|
||||
self.state_path = config.with_name(config.name + ".listener-state.json")
|
||||
self.app = None
|
||||
self.shutdown = False
|
||||
self.change_due_at: float | None = None
|
||||
self.native_event = ""
|
||||
self.queue = SaveQueue(self.start, on_complete=self.completed)
|
||||
|
||||
def record(self, event: str, **details) -> None:
|
||||
try:
|
||||
with self.log_path.open("a", encoding="utf-8") as stream:
|
||||
stream.write(json.dumps({"time": datetime.now().isoformat(), "event": event, **details}, ensure_ascii=False) + "\n")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def status(self, message: str) -> None:
|
||||
self.record("status", message=message)
|
||||
if self.app is not None:
|
||||
try:
|
||||
self.app.StatusBarText = message[:240]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def changed(self, event: str, *, quiet_seconds: float = 1.0) -> None:
|
||||
self.record(event)
|
||||
self.native_event = event
|
||||
self.change_due_at = time.monotonic() + quiet_seconds
|
||||
|
||||
def flush_changes(self, now: float) -> None:
|
||||
if self.change_due_at is not None and now >= self.change_due_at:
|
||||
self.change_due_at = None
|
||||
self.saved()
|
||||
|
||||
def saved(self) -> None:
|
||||
try:
|
||||
configured = _enabled_project(self.config)
|
||||
if configured is None or normalized_project_path(_project_path(self.app)) != normalized_project_path(configured):
|
||||
return
|
||||
block = self.app.ActiveView.Block
|
||||
event = SaveEvent(configured, str(block.GetName(1)), str(block.SheetNum))
|
||||
self.record("save-event", project=str(event.project_path), block=event.block_name, sheet=event.sheet_name, native_event=self.native_event)
|
||||
self.queue.add(event, time.monotonic() - self.queue.debounce_seconds)
|
||||
except Exception as error:
|
||||
self.record("save-event-error", error=str(error))
|
||||
|
||||
def start(self, event: SaveEvent):
|
||||
configured = _enabled_project(self.config)
|
||||
if configured is None or normalized_project_path(configured) != normalized_project_path(event.project_path):
|
||||
return None
|
||||
try:
|
||||
self.status_path.unlink(missing_ok=True)
|
||||
command, root, environment = tool_command([
|
||||
"pdf-export-event", "--settings", str(self.config),
|
||||
"--project", str(event.project_path), "--active-block", event.block_name,
|
||||
"--active-sheet", event.sheet_name, "--status-file", str(self.status_path),
|
||||
])
|
||||
process = subprocess.Popen(command, cwd=root, env=environment, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
self.record("export-started", pid=process.pid, project=str(event.project_path), sheet=event.sheet_name)
|
||||
self.status("保存完成,正在自动导出 PDF")
|
||||
return process
|
||||
except Exception as error:
|
||||
self.status(f"PDF 自动导出无法启动:{error}")
|
||||
return None
|
||||
|
||||
def completed(self, code: int) -> None:
|
||||
try:
|
||||
message = self.status_path.read_text(encoding="utf-8").strip()
|
||||
except OSError:
|
||||
message = f"PDF 自动导出进程已退出,退出码 {code};请检查本地运行记录"
|
||||
self.record("export-completed", returncode=code)
|
||||
self.status(message)
|
||||
|
||||
|
||||
def listen(config: Path, *, connect_timeout: float = 30) -> int:
|
||||
import msvcrt
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
|
||||
config = config.resolve()
|
||||
config.parent.mkdir(parents=True, exist_ok=True)
|
||||
if _enabled_project(config) is None:
|
||||
return 0
|
||||
lock = config.with_name(config.name + ".listener-lock").open("a+b")
|
||||
lock.seek(0, os.SEEK_END)
|
||||
if lock.tell() == 0:
|
||||
lock.write(b"0")
|
||||
lock.flush()
|
||||
lock.seek(0)
|
||||
try:
|
||||
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
|
||||
except OSError:
|
||||
lock.close()
|
||||
return 0
|
||||
sink = None
|
||||
listener = NativeListener(config)
|
||||
configured_path = None
|
||||
began = time.monotonic()
|
||||
pythoncom.CoInitialize()
|
||||
try:
|
||||
while not listener.shutdown:
|
||||
configured = _enabled_project(config)
|
||||
if configured is None:
|
||||
listener.queue.tick(time.monotonic(), enabled=False)
|
||||
listener.record("disabled")
|
||||
break
|
||||
if configured_path != configured:
|
||||
if sink is not None:
|
||||
sink.close()
|
||||
sink = None
|
||||
listener.app = None
|
||||
listener.queue.pending = None
|
||||
listener.change_due_at = None
|
||||
configured_path = configured
|
||||
began = time.monotonic()
|
||||
if listener.app is None:
|
||||
match = select_application(_applications(), configured)
|
||||
if match is None:
|
||||
if time.monotonic() - began > connect_timeout:
|
||||
listener.record("host-not-found", project=str(configured))
|
||||
return 1
|
||||
else:
|
||||
moniker, listener.app = match
|
||||
win32com.client.gencache.is_readonly = False
|
||||
sink = win32com.client.WithEvents(listener.app, _Events)
|
||||
sink.owner = listener
|
||||
_write_json(listener.state_path, {"state": "listening", "project": str(configured), "moniker": moniker, "pid": os.getpid()})
|
||||
listener.record("listening", project=str(configured), moniker=moniker)
|
||||
else:
|
||||
try:
|
||||
if normalized_project_path(_project_path(listener.app)) != normalized_project_path(configured):
|
||||
listener.record("host-project-changed")
|
||||
break
|
||||
except Exception:
|
||||
listener.record("host-disconnected")
|
||||
break
|
||||
pythoncom.PumpWaitingMessages()
|
||||
listener.flush_changes(time.monotonic())
|
||||
listener.queue.tick(time.monotonic())
|
||||
time.sleep(0.05)
|
||||
return 0
|
||||
except Exception as error:
|
||||
listener.record("listener-error", error=str(error))
|
||||
return 1
|
||||
finally:
|
||||
if sink is not None:
|
||||
try:
|
||||
sink.close()
|
||||
except Exception:
|
||||
pass
|
||||
pythoncom.CoUninitialize()
|
||||
_write_json(listener.state_path, {"state": "stopped", "pid": os.getpid()})
|
||||
lock.seek(0)
|
||||
msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
|
||||
lock.close()
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="DxDesignerTools pdf-export-listen")
|
||||
parser.add_argument("--settings", required=True, type=Path)
|
||||
options = parser.parse_args(argv)
|
||||
return listen(options.settings)
|
||||
@@ -76,6 +76,7 @@ FEATURE_PAGE_INDEX = {
|
||||
"property-change": 1,
|
||||
"property-visibility": 2,
|
||||
"inspection": 3,
|
||||
"network": 4,
|
||||
"bom": 5,
|
||||
"history": 6,
|
||||
"settings": 7,
|
||||
@@ -192,6 +193,11 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
|
||||
inspection_controller.status_changed.connect(window.operation_status.setText)
|
||||
window.set_page(3, inspection_page, "设计检查")
|
||||
window.inspection_controller = inspection_controller
|
||||
network_page = InspectionPage(network_only=True)
|
||||
network_controller = InspectionController(network_page, run_paths=run_paths)
|
||||
network_controller.status_changed.connect(window.operation_status.setText)
|
||||
window.set_page(4, network_page, "网络工具")
|
||||
window.network_controller = network_controller
|
||||
bom_page = BomPage()
|
||||
bom_controller = BomController(
|
||||
bom_page,
|
||||
@@ -279,6 +285,8 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
|
||||
window.property_visibility_controller.load_snapshot(snapshot)
|
||||
if window.inspection_controller is not None:
|
||||
window.inspection_controller.load_snapshot(snapshot)
|
||||
if window.network_controller is not None:
|
||||
window.network_controller.load_snapshot(snapshot)
|
||||
if window.bom_controller is not None:
|
||||
window.bom_controller.load_snapshot(snapshot)
|
||||
if history_controller is not None:
|
||||
@@ -358,8 +366,20 @@ class _SnapshotWatcher(QObject):
|
||||
self._window, "设计快照刷新失败", str(error)
|
||||
)
|
||||
return
|
||||
if self._window.refdes_controller is not None:
|
||||
self._window.refdes_controller.load_snapshot(snapshot)
|
||||
for controller in (
|
||||
self._window.refdes_controller,
|
||||
self._window.property_change_controller,
|
||||
self._window.property_visibility_controller,
|
||||
self._window.inspection_controller,
|
||||
self._window.network_controller,
|
||||
self._window.bom_controller,
|
||||
self._window.history_controller,
|
||||
):
|
||||
if controller is not None:
|
||||
controller.load_snapshot(snapshot)
|
||||
self._window.project_label.setText(
|
||||
Path(snapshot.design_path).name or snapshot.design_id
|
||||
)
|
||||
self.snapshot_reloaded.emit(snapshot)
|
||||
self._window.operation_status.setText("设计快照已刷新")
|
||||
|
||||
@@ -411,27 +431,29 @@ def _launch_update(window: MainWindow, controller: SettingsController, manifest:
|
||||
if not getattr(sys, "frozen", False):
|
||||
window.operation_status.setText("开发运行环境已完成校验,便携式包中可执行安装")
|
||||
return
|
||||
from dx_productivity.update.installer import InstallPlan
|
||||
from dx_productivity.update.installer import InstallPlan, prepare_updater
|
||||
|
||||
current_root = Path(sys.executable).resolve().parent
|
||||
update_root = Path(os.environ.get("LOCALAPPDATA", current_root)) / "DxProductivity" / "updates"
|
||||
update_root.mkdir(parents=True, exist_ok=True)
|
||||
plan_path = update_root / "install-plan.json"
|
||||
plan_path = update_root / f"install-plan-{uuid.uuid4().hex}.json"
|
||||
executable = current_root / "DxDesignerTools.exe"
|
||||
plan = InstallPlan(
|
||||
current_root=current_root,
|
||||
staged_zip=staged_zip,
|
||||
backup_root=update_root / "backups",
|
||||
restart_command=(str(executable), "ui", "--smoke-test-ms", "1000"),
|
||||
launch_command=(str(executable), "ui"),
|
||||
sha256=str(getattr(manifest, "sha256", "") or "") or None,
|
||||
)
|
||||
temporary = plan_path.with_suffix(f".{uuid.uuid4().hex[:8]}.tmp")
|
||||
temporary.write_text(json.dumps(plan.to_mapping(), ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
temporary.replace(plan_path)
|
||||
try:
|
||||
updater_executable = prepare_updater(current_root, update_root)
|
||||
subprocess.Popen(
|
||||
[str(executable), "update", "--plan", str(plan_path)],
|
||||
cwd=str(current_root),
|
||||
[str(updater_executable), "update", "--plan", str(plan_path)],
|
||||
cwd=str(updater_executable.parent),
|
||||
close_fds=True,
|
||||
)
|
||||
except OSError as error:
|
||||
|
||||
@@ -37,6 +37,7 @@ class BomController(QObject):
|
||||
self._result: BOMResult | None = None
|
||||
self._export_in_flight = False
|
||||
self._export_started_at = 0.0
|
||||
self._requested_output_path = ""
|
||||
self._status_timer = QTimer(self)
|
||||
self._status_timer.setInterval(300)
|
||||
self._status_timer.timeout.connect(self._poll_export_status)
|
||||
@@ -45,6 +46,7 @@ class BomController(QObject):
|
||||
|
||||
def load_snapshot(self, snapshot: DesignSnapshot) -> None:
|
||||
self.snapshot = snapshot
|
||||
self.design_name = Path(snapshot.design_path).name or snapshot.design_id
|
||||
self.refresh_preview()
|
||||
|
||||
def refresh_preview(self) -> None:
|
||||
@@ -53,11 +55,12 @@ class BomController(QObject):
|
||||
try:
|
||||
self._result = build_bom(self.snapshot, self.page.settings())
|
||||
except ValueError as error:
|
||||
self._result = None
|
||||
self.page.set_summary(str(error))
|
||||
self.page.set_can_export(False)
|
||||
return
|
||||
self.page.set_result(self._result)
|
||||
self.page.set_can_export(bool(self._result.rows))
|
||||
self.page.set_can_export(bool(self._result.rows) and not self._export_in_flight)
|
||||
|
||||
def export_to(self, output_path: str) -> None:
|
||||
if self._export_in_flight:
|
||||
@@ -68,13 +71,16 @@ class BomController(QObject):
|
||||
raise RuntimeError("BOM preview is empty")
|
||||
if self.template_path is None or not self.template_path.is_file():
|
||||
raise RuntimeError(f"BOM 模板不存在:{self.template_path}")
|
||||
self._export_in_flight = True
|
||||
self._export_started_at = time.monotonic()
|
||||
payload = self._build_payload(output_path)
|
||||
(self.run_paths.root / "bom-export-status.json").unlink(missing_ok=True)
|
||||
atomic_write_text(
|
||||
self.run_paths.root / "bom-export.json",
|
||||
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
|
||||
)
|
||||
self._export_in_flight = True
|
||||
self._export_started_at = time.monotonic()
|
||||
self._requested_output_path = output_path
|
||||
self.page.set_can_export(False)
|
||||
self._status_timer.start()
|
||||
|
||||
def _build_payload(self, output_path: str) -> dict[str, object]:
|
||||
@@ -83,16 +89,15 @@ class BomController(QObject):
|
||||
for page, rows in self._result.sections:
|
||||
records.append(f"S|{'' if page is None else page}")
|
||||
for row in rows:
|
||||
flags = f"{'D' if row.duplicate_refdes else ''}{'' }"
|
||||
flags = ("D" if row.duplicate_refdes else "") + (
|
||||
"M" if row.part_number_mismatch else ""
|
||||
)
|
||||
records.append(
|
||||
"R|{qty}|{refdes}|{pn}|{desc}|{flags}".format(
|
||||
qty=row.qty,
|
||||
refdes=row.refdes.replace("|", " "),
|
||||
pn=row.part_number.replace("|", " "),
|
||||
desc=row.description.replace("|", " "),
|
||||
refdes=_record_field(row.refdes),
|
||||
pn=_record_field(row.part_number),
|
||||
desc=_record_field(row.description),
|
||||
flags=flags,
|
||||
)
|
||||
)
|
||||
@@ -118,13 +123,16 @@ class BomController(QObject):
|
||||
return
|
||||
self._status_timer.stop()
|
||||
self._export_in_flight = False
|
||||
self.refresh_preview()
|
||||
try:
|
||||
data = json.loads(status_path.read_text(encoding="utf-8-sig"))
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("BOM 导出状态必须是 JSON 对象")
|
||||
except (OSError, ValueError) as error:
|
||||
self.export_failed.emit(str(error))
|
||||
return
|
||||
if data.get("state") == "ok":
|
||||
self.export_completed.emit(str(data.get("output_path", "")))
|
||||
self.export_completed.emit(str(data.get("output_path") or self._requested_output_path))
|
||||
self.status_changed.emit("BOM 已导出,Excel 已打开")
|
||||
else:
|
||||
self.export_failed.emit(str(data.get("error") or "BOM 导出失败"))
|
||||
@@ -133,3 +141,8 @@ class BomController(QObject):
|
||||
self._status_timer.stop()
|
||||
self._export_in_flight = False
|
||||
self.export_failed.emit(message)
|
||||
self.refresh_preview()
|
||||
|
||||
|
||||
def _record_field(value: str) -> str:
|
||||
return value.replace("|", " ").replace("\r", " ").replace("\n", " ").replace("\t", " ")
|
||||
@@ -69,6 +69,8 @@ class HistoryController(QObject):
|
||||
self.page.set_entries(
|
||||
self.run_store.list_history(self.snapshot.design_id)
|
||||
)
|
||||
if self._restore_in_flight:
|
||||
self.page.restore_button.setEnabled(False)
|
||||
|
||||
def restore_latest(self) -> Path | None:
|
||||
if self._restore_in_flight:
|
||||
@@ -88,8 +90,6 @@ class HistoryController(QObject):
|
||||
if not self.confirm_restore(entry, changed_count):
|
||||
return None
|
||||
|
||||
self._restore_in_flight = True
|
||||
self._restore_started_at = time.monotonic()
|
||||
self.pending_plan = plan
|
||||
self.pending_backup = self.run_store.write_backup(self.snapshot, plan)
|
||||
self._clear_previous_mailbox()
|
||||
@@ -104,6 +104,9 @@ class HistoryController(QObject):
|
||||
),
|
||||
)
|
||||
write_schedule(self.run_paths.result, plan.schedule)
|
||||
self._restore_in_flight = True
|
||||
self._restore_started_at = time.monotonic()
|
||||
self.page.restore_button.setEnabled(False)
|
||||
self._status_recorded = False
|
||||
self._timer.start()
|
||||
return self.run_paths.result
|
||||
@@ -152,13 +155,14 @@ class HistoryController(QObject):
|
||||
self._timer.stop()
|
||||
self._restore_in_flight = False
|
||||
self.restore_failed.emit(message)
|
||||
self.refresh()
|
||||
|
||||
def _confirm_restore(self, entry: HistoryEntry, changed_count: int) -> bool:
|
||||
answer = QMessageBox.question(
|
||||
self.page,
|
||||
"恢复上次位号",
|
||||
"恢复所选操作",
|
||||
(
|
||||
f"将恢复 {changed_count} 个器件的位号。\n"
|
||||
f"将恢复 {changed_count} 项器件属性修改。\n"
|
||||
f"备份时间:{entry.timestamp.astimezone():%Y-%m-%d %H:%M:%S}"
|
||||
),
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.Cancel,
|
||||
|
||||
@@ -38,7 +38,7 @@ class HistoryPage(QWidget):
|
||||
_state_text(entry.state),
|
||||
str(entry.changed_count),
|
||||
entry.design_id,
|
||||
str(entry.backup_path),
|
||||
str(entry.backup_path) if entry.backup_path is not None else "—",
|
||||
)
|
||||
items = [QStandardItem(value) for value in values]
|
||||
for item in items:
|
||||
@@ -70,7 +70,7 @@ class HistoryPage(QWidget):
|
||||
title.setObjectName("pageTitle")
|
||||
toolbar.addWidget(title)
|
||||
toolbar.addStretch(1)
|
||||
self.restore_button = QPushButton("恢复上次位号")
|
||||
self.restore_button = QPushButton("恢复所选操作")
|
||||
self.restore_button.setIcon(
|
||||
themed_icon("fa6s.clock-rotate-left", Theme.LIGHT)
|
||||
)
|
||||
@@ -105,7 +105,8 @@ class HistoryPage(QWidget):
|
||||
layout.addWidget(self.table, 1)
|
||||
|
||||
def _update_restore_state(self, *_args) -> None:
|
||||
self.restore_button.setEnabled(self.selected_entry() is not None)
|
||||
entry = self.selected_entry()
|
||||
self.restore_button.setEnabled(entry is not None and entry.backup_path is not None)
|
||||
|
||||
|
||||
def _state_text(state: str) -> str:
|
||||
|
||||
@@ -30,6 +30,7 @@ class InspectionController(QObject):
|
||||
self.page = page
|
||||
self.run_paths = run_paths
|
||||
self.snapshot: DesignSnapshot | None = None
|
||||
self._active_check: tuple[str, str] | None = None
|
||||
page.solitary_requested.connect(self.show_solitary)
|
||||
page.net_list_requested.connect(self.show_net_list)
|
||||
page.value_miss_requested.connect(self.show_value_miss)
|
||||
@@ -39,6 +40,19 @@ class InspectionController(QObject):
|
||||
|
||||
def load_snapshot(self, snapshot: DesignSnapshot) -> None:
|
||||
self.snapshot = snapshot
|
||||
self.page.set_snapshot_available(True)
|
||||
if self._active_check is not None:
|
||||
kind, argument = self._active_check
|
||||
if kind == "solitary":
|
||||
self.show_solitary()
|
||||
elif kind == "list":
|
||||
self.show_net_list()
|
||||
elif kind == "value":
|
||||
self.show_value_miss(argument)
|
||||
else:
|
||||
self.show_cross_page(argument)
|
||||
elif self.page.network_only:
|
||||
self.show_net_list()
|
||||
|
||||
def _require_snapshot(self) -> DesignSnapshot:
|
||||
if self.snapshot is None:
|
||||
@@ -46,6 +60,7 @@ class InspectionController(QObject):
|
||||
return self.snapshot
|
||||
|
||||
def show_solitary(self) -> None:
|
||||
self._active_check = ("solitary", "")
|
||||
snapshot = self._require_snapshot()
|
||||
if not net_data_available(snapshot):
|
||||
self.page.show_no_net_data()
|
||||
@@ -54,6 +69,7 @@ class InspectionController(QObject):
|
||||
self.page.set_rows(rows, f"孤立网络:{len(rows)} 个")
|
||||
|
||||
def show_net_list(self) -> None:
|
||||
self._active_check = ("list", "")
|
||||
snapshot = self._require_snapshot()
|
||||
if not net_data_available(snapshot):
|
||||
self.page.show_no_net_data()
|
||||
@@ -62,6 +78,7 @@ class InspectionController(QObject):
|
||||
self.page.set_rows(rows, f"网络总数:{len(rows)}")
|
||||
|
||||
def show_value_miss(self, attribute_name: str) -> None:
|
||||
self._active_check = ("value", attribute_name)
|
||||
snapshot = self._require_snapshot()
|
||||
rows = missing_attribute_values(
|
||||
snapshot,
|
||||
@@ -73,6 +90,7 @@ class InspectionController(QObject):
|
||||
)
|
||||
|
||||
def show_cross_page(self, net_name: str) -> None:
|
||||
self._active_check = ("cross", net_name)
|
||||
snapshot = self._require_snapshot()
|
||||
if not net_data_available(snapshot):
|
||||
self.page.show_no_net_data()
|
||||
|
||||
@@ -26,10 +26,12 @@ class InspectionPage(QWidget):
|
||||
locate_net_requested = Signal(str, int)
|
||||
locate_component_requested = Signal(str)
|
||||
|
||||
def __init__(self) -> None:
|
||||
def __init__(self, *, network_only: bool = False) -> None:
|
||||
super().__init__()
|
||||
self.network_only = network_only
|
||||
self._rows: list[InspectionRow] = []
|
||||
self._build_ui()
|
||||
self.set_snapshot_available(False)
|
||||
|
||||
def _build_ui(self) -> None:
|
||||
layout = QVBoxLayout(self)
|
||||
@@ -37,8 +39,9 @@ class InspectionPage(QWidget):
|
||||
layout.setSpacing(10)
|
||||
|
||||
hint = QLabel(
|
||||
"只读设计检查:孤立网络、网络列表、属性遗漏。"
|
||||
"双击结果行可在原理图中定位。"
|
||||
("网络检查:孤立网络、网络列表与跨页查询。"
|
||||
if self.network_only else "只读设计检查:孤立网络、网络列表、属性遗漏。")
|
||||
+ "双击结果行可在原理图中定位。"
|
||||
)
|
||||
hint.setObjectName("secondaryLabel")
|
||||
hint.setWordWrap(True)
|
||||
@@ -49,15 +52,18 @@ class InspectionPage(QWidget):
|
||||
self.net_list_button = QPushButton("全部网络列表")
|
||||
self.value_miss_button = QPushButton("Value 遗漏")
|
||||
self.value1_miss_button = QPushButton("Value1 遗漏")
|
||||
for button in (
|
||||
self.solitary_button,
|
||||
self.net_list_button,
|
||||
self.value_miss_button,
|
||||
self.value1_miss_button,
|
||||
):
|
||||
for button in (self.solitary_button, self.net_list_button):
|
||||
buttons_row.addWidget(button)
|
||||
for button in (self.value_miss_button, self.value1_miss_button):
|
||||
if self.network_only:
|
||||
button.hide()
|
||||
else:
|
||||
buttons_row.addWidget(button)
|
||||
self.include_missing_checkbox = QCheckBox("属性缺失也算遗漏")
|
||||
buttons_row.addWidget(self.include_missing_checkbox)
|
||||
if self.network_only:
|
||||
self.include_missing_checkbox.hide()
|
||||
else:
|
||||
buttons_row.addWidget(self.include_missing_checkbox)
|
||||
buttons_row.addStretch(1)
|
||||
layout.addLayout(buttons_row)
|
||||
|
||||
@@ -98,6 +104,16 @@ class InspectionPage(QWidget):
|
||||
def include_missing(self) -> bool:
|
||||
return self.include_missing_checkbox.isChecked()
|
||||
|
||||
def set_snapshot_available(self, available: bool) -> None:
|
||||
for control in (
|
||||
self.solitary_button, self.net_list_button, self.value_miss_button,
|
||||
self.value1_miss_button, self.cross_page_button, self.net_name_edit,
|
||||
self.include_missing_checkbox,
|
||||
):
|
||||
control.setEnabled(available)
|
||||
if not available:
|
||||
self.set_rows([], "请从 DxDesigner 菜单打开工具并读取设计快照。")
|
||||
|
||||
def _on_double_click(self, index) -> None:
|
||||
row = index.row()
|
||||
if 0 <= row < len(self._rows):
|
||||
|
||||
@@ -29,12 +29,14 @@ class _ExportWorker(QObject):
|
||||
self,
|
||||
settings: PdfExportSettings,
|
||||
active_block_name: str,
|
||||
active_sheet_name: str,
|
||||
overwrite: bool,
|
||||
cancel: threading.Event,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.settings = settings
|
||||
self.active_block_name = active_block_name
|
||||
self.active_sheet_name = active_sheet_name
|
||||
self.overwrite = overwrite
|
||||
self.cancel = cancel
|
||||
|
||||
@@ -45,6 +47,7 @@ class _ExportWorker(QObject):
|
||||
self.cancel,
|
||||
self.progress.emit,
|
||||
active_block_name=self.active_block_name,
|
||||
active_sheet_name=self.active_sheet_name,
|
||||
overwrite=self.overwrite,
|
||||
)
|
||||
self.finished.emit(result)
|
||||
@@ -101,8 +104,8 @@ class PdfExportController(QObject):
|
||||
self.status_changed.emit(result)
|
||||
self.page.set_status(result)
|
||||
else:
|
||||
self.status_changed.emit("保存后自动导出监听已启动")
|
||||
self.page.set_status("保存后自动导出已启用")
|
||||
self.status_changed.emit("正在连接保存事件监听")
|
||||
self.page.set_status("自动导出已启用,正在连接当前工程的保存事件")
|
||||
|
||||
def export(self) -> None:
|
||||
if self.snapshot is None:
|
||||
@@ -120,7 +123,11 @@ class PdfExportController(QObject):
|
||||
self.page.set_status("当前范围没有可用的 Block 名称")
|
||||
return
|
||||
try:
|
||||
target = output_path(settings, self.snapshot.active_block_name)
|
||||
target = output_path(
|
||||
settings,
|
||||
self.snapshot.active_block_name,
|
||||
self.snapshot.current_sheet_name,
|
||||
)
|
||||
except ValueError as error:
|
||||
self.page.set_status(str(error))
|
||||
return
|
||||
@@ -136,6 +143,7 @@ class PdfExportController(QObject):
|
||||
self._worker = _ExportWorker(
|
||||
settings,
|
||||
self.snapshot.active_block_name,
|
||||
self.snapshot.current_sheet_name,
|
||||
overwrite,
|
||||
self._cancel,
|
||||
)
|
||||
|
||||
@@ -84,6 +84,7 @@ class PdfExportPage(QWidget):
|
||||
layout.addLayout(form)
|
||||
|
||||
self.auto_export_checkbox = QCheckBox("保存工程后自动导出")
|
||||
self.auto_export_checkbox.setToolTip("EE 工程使用即时保存:原生设计变更稳定后导出;传统工程在保存完成后导出。")
|
||||
self.auto_export_checkbox.setEnabled(False)
|
||||
layout.addWidget(self.auto_export_checkbox)
|
||||
|
||||
@@ -178,6 +179,8 @@ class PdfExportPage(QWidget):
|
||||
settings.scope is ExportScope.PROJECT
|
||||
or bool(settings.block_name.strip())
|
||||
)
|
||||
if valid_scope and settings.scope is ExportScope.CURRENT_PAGE:
|
||||
valid_scope = bool(self.snapshot and self.snapshot.current_sheet_name.strip())
|
||||
self.export_button.setEnabled(enabled and valid_scope)
|
||||
auto_enabled = enabled and valid_scope
|
||||
self.auto_export_checkbox.setEnabled(auto_enabled)
|
||||
@@ -199,6 +202,8 @@ class PdfExportPage(QWidget):
|
||||
self.block_input.setEnabled(
|
||||
not busy and self.scope_combo.currentData() == ExportScope.BLOCK.value
|
||||
)
|
||||
if not busy:
|
||||
self.set_can_export(self.snapshot is not None)
|
||||
|
||||
def set_status(self, message: str) -> None:
|
||||
self.status_label.setText(message)
|
||||
@@ -216,9 +221,9 @@ class PdfExportPage(QWidget):
|
||||
specified = scope == ExportScope.BLOCK.value
|
||||
self.block_input.setEnabled(specified)
|
||||
self.active_block_label.setText(
|
||||
f"活动页:{self.snapshot.active_block_name}"
|
||||
if current and self.snapshot and self.snapshot.active_block_name
|
||||
else ("活动 Block 不可用" if current else "")
|
||||
f"活动页:{self.snapshot.active_block_name} / {self.snapshot.current_sheet_name}"
|
||||
if current and self.snapshot and self.snapshot.active_block_name and self.snapshot.current_sheet_name
|
||||
else ("活动页名称不可用,请刷新设计快照" if current else "")
|
||||
)
|
||||
self.active_block_label.setVisible(current)
|
||||
if not self._loading:
|
||||
|
||||
@@ -46,6 +46,7 @@ class PropertyChangeController(QObject):
|
||||
self.run_store = run_store
|
||||
self.run_paths = run_paths
|
||||
self.snapshot: DesignSnapshot | None = None
|
||||
self._displayed_property: str | None = None
|
||||
self.can_apply = False
|
||||
self._apply_in_flight = False
|
||||
self._apply_started_at = 0.0
|
||||
@@ -57,6 +58,7 @@ class PropertyChangeController(QObject):
|
||||
|
||||
def load_snapshot(self, snapshot: DesignSnapshot) -> None:
|
||||
self.snapshot = snapshot
|
||||
self._displayed_property = self.page.property_name() or ""
|
||||
self._fill_rows()
|
||||
self.refresh_plan()
|
||||
|
||||
@@ -64,16 +66,26 @@ class PropertyChangeController(QObject):
|
||||
if self.snapshot is None:
|
||||
self.page.set_rows([], editable=False)
|
||||
return
|
||||
rows = [
|
||||
(component.bridge_id, component.refdes or "(无位号)", "")
|
||||
for component in self.snapshot.components
|
||||
if component.selected
|
||||
]
|
||||
property_name = (self.page.property_name() or "").casefold()
|
||||
rows = []
|
||||
for component in self.snapshot.components:
|
||||
if not component.selected:
|
||||
continue
|
||||
current = next(
|
||||
(attribute.value for attribute in component.attributes
|
||||
if attribute.name.casefold() == property_name),
|
||||
"",
|
||||
)
|
||||
rows.append((component.bridge_id, component.refdes or "(无位号)", current))
|
||||
self.page.set_rows(rows, editable=True)
|
||||
|
||||
def refresh_plan(self) -> None:
|
||||
if self._apply_in_flight or self.snapshot is None:
|
||||
return
|
||||
property_name = self.page.property_name() or ""
|
||||
if property_name != self._displayed_property:
|
||||
self._displayed_property = property_name
|
||||
self._fill_rows()
|
||||
settings = self.page.settings()
|
||||
if not settings.property_name:
|
||||
self.page.set_issue_text("请选择或输入属性名")
|
||||
@@ -101,8 +113,6 @@ class PropertyChangeController(QObject):
|
||||
plan = build_property_change_plan(self.snapshot, settings)
|
||||
if not plan.can_apply:
|
||||
raise RuntimeError("property change plan is not applicable")
|
||||
self._apply_in_flight = True
|
||||
self._apply_started_at = time.monotonic()
|
||||
changes = tuple(
|
||||
change
|
||||
for row in plan.rows
|
||||
@@ -127,6 +137,8 @@ class PropertyChangeController(QObject):
|
||||
),
|
||||
)
|
||||
write_schedule(self.run_paths.result, plan.schedule)
|
||||
self._apply_in_flight = True
|
||||
self._apply_started_at = time.monotonic()
|
||||
self._set_can_apply(False)
|
||||
self._status_timer.start()
|
||||
return self.run_paths.result
|
||||
@@ -186,6 +198,7 @@ class PropertyChangeController(QObject):
|
||||
self._status_timer.stop()
|
||||
self._apply_in_flight = False
|
||||
self.apply_failed.emit(message)
|
||||
self.refresh_plan()
|
||||
|
||||
def _set_can_apply(self, enabled: bool) -> None:
|
||||
if enabled != self.can_apply:
|
||||
|
||||
@@ -80,10 +80,10 @@ class PropertyChangePage(QWidget):
|
||||
self._on_property_selected
|
||||
)
|
||||
self.custom_property_edit.textChanged.connect(self.settings_changed)
|
||||
self.model.itemChanged.connect(lambda _item: self.settings_changed())
|
||||
self.model.itemChanged.connect(lambda _item: self.settings_changed.emit())
|
||||
|
||||
def _on_property_selected(self) -> None:
|
||||
custom = self.property_name() is None
|
||||
custom = self.property_combo.currentText() == "自定义…"
|
||||
self.custom_property_edit.setVisible(custom)
|
||||
self.settings_changed.emit()
|
||||
|
||||
|
||||
@@ -104,8 +104,6 @@ class PropertyVisibilityController(QObject):
|
||||
plan = build_property_visibility_plan(self.snapshot, settings)
|
||||
if not plan.can_apply:
|
||||
raise RuntimeError("visibility plan is not applicable")
|
||||
self._apply_in_flight = True
|
||||
self._apply_started_at = time.monotonic()
|
||||
by_bridge = {c.bridge_id: c for c in self.snapshot.components}
|
||||
changes = []
|
||||
for row in plan.rows:
|
||||
@@ -148,6 +146,8 @@ class PropertyVisibilityController(QObject):
|
||||
),
|
||||
)
|
||||
write_schedule(self.run_paths.result, plan.schedule)
|
||||
self._apply_in_flight = True
|
||||
self._apply_started_at = time.monotonic()
|
||||
self._set_can_apply(False)
|
||||
self._status_timer.start()
|
||||
return self.run_paths.result
|
||||
@@ -180,6 +180,7 @@ class PropertyVisibilityController(QObject):
|
||||
self._status_timer.stop()
|
||||
self._apply_in_flight = False
|
||||
self.apply_failed.emit(message)
|
||||
self.refresh_plan()
|
||||
|
||||
def _set_can_apply(self, enabled: bool) -> None:
|
||||
if enabled != self.can_apply:
|
||||
|
||||
@@ -102,7 +102,9 @@ class PropertyVisibilityPage(QWidget):
|
||||
ref_item.setEditable(False)
|
||||
value_item = QStandardItem(value)
|
||||
value_item.setEditable(False)
|
||||
state_item = QStandardItem("显示" if visibility == "1" else "隐藏")
|
||||
state_item = QStandardItem(
|
||||
{"1": "显示", "0": "隐藏"}.get(visibility, "属性缺失")
|
||||
)
|
||||
state_item.setEditable(False)
|
||||
self.model.appendRow((ref_item, value_item, state_item))
|
||||
|
||||
|
||||
@@ -79,8 +79,6 @@ class RefDesController(QObject):
|
||||
raise RuntimeError("annotation plan is not applicable")
|
||||
if self.run_store is None or self.run_paths is None:
|
||||
raise RuntimeError("bridge mailbox is not configured")
|
||||
self._apply_in_flight = True
|
||||
self._apply_started_at = time.monotonic()
|
||||
self.pending_backup = self.run_store.write_backup(self.snapshot, self.plan)
|
||||
for path in (
|
||||
self.run_paths.apply_status,
|
||||
@@ -99,6 +97,8 @@ class RefDesController(QObject):
|
||||
),
|
||||
)
|
||||
write_schedule(self.run_paths.result, self.plan.schedule)
|
||||
self._apply_in_flight = True
|
||||
self._apply_started_at = time.monotonic()
|
||||
self._status_recorded = False
|
||||
self.can_apply = False
|
||||
self.can_apply_changed.emit(False)
|
||||
|
||||
@@ -107,12 +107,19 @@ class SettingsController(QObject):
|
||||
return defaults
|
||||
|
||||
def save_settings(self, source: str, channel: str, auto_check: bool) -> None:
|
||||
previous = self.load_settings()
|
||||
self.settings_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
data = {
|
||||
"source": str(source).strip(),
|
||||
"channel": str(channel).strip().casefold(),
|
||||
"auto_check": bool(auto_check),
|
||||
}
|
||||
if (
|
||||
data["source"] == previous["source"]
|
||||
and data["channel"] == previous["channel"]
|
||||
and previous["last_check_at"]
|
||||
):
|
||||
data["last_check_at"] = previous["last_check_at"]
|
||||
temporary = self.settings_path.with_suffix(".tmp")
|
||||
temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
temporary.replace(self.settings_path)
|
||||
|
||||
@@ -71,6 +71,8 @@ class SettingsPage(QWidget):
|
||||
self.release_notes_view.clear()
|
||||
|
||||
def show_stage_result(self, result: object) -> None:
|
||||
if getattr(result, "manifest", None) != self._manifest:
|
||||
return
|
||||
if getattr(result, "state", "") == "ready" and getattr(result, "staged_zip", None) is not None:
|
||||
self._staged_zip = Path(result.staged_zip)
|
||||
self.install_button.setEnabled(True)
|
||||
|
||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
import contextlib
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
@@ -19,6 +20,24 @@ from dx_productivity.update.verification import sha256_file
|
||||
PARENT_EXIT_TIMEOUT_SECONDS = 60.0
|
||||
|
||||
|
||||
def prepare_updater(current_root: Path, update_root: Path) -> Path:
|
||||
"""Run the updater outside the folder it will replace on Windows."""
|
||||
current_root = current_root.resolve()
|
||||
update_root = update_root.resolve()
|
||||
if update_root.is_relative_to(current_root):
|
||||
raise ValueError("updater cache must be outside the portable folder")
|
||||
runner = update_root / f"updater-{uuid.uuid4().hex}"
|
||||
runner.mkdir(parents=True)
|
||||
try:
|
||||
executable = runner / "DxDesignerTools.exe"
|
||||
shutil.copy2(current_root / executable.name, executable)
|
||||
shutil.copytree(current_root / "_runtime", runner / "_runtime")
|
||||
return executable
|
||||
except Exception:
|
||||
shutil.rmtree(runner, ignore_errors=True)
|
||||
raise
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class InstallPlan:
|
||||
current_root: Path
|
||||
@@ -26,6 +45,7 @@ class InstallPlan:
|
||||
backup_root: Path
|
||||
restart_command: tuple[str, ...]
|
||||
sha256: str | None = None
|
||||
launch_command: tuple[str, ...] = ()
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, data: dict[str, object]) -> "InstallPlan":
|
||||
@@ -36,6 +56,7 @@ class InstallPlan:
|
||||
backup_root=Path(str(data["backup_root"])),
|
||||
restart_command=tuple(str(item) for item in data["restart_command"]),
|
||||
sha256=str(sha256) if sha256 else None,
|
||||
launch_command=tuple(str(item) for item in data.get("launch_command", ())),
|
||||
)
|
||||
|
||||
def to_mapping(self) -> dict[str, object]:
|
||||
@@ -47,6 +68,8 @@ class InstallPlan:
|
||||
}
|
||||
if self.sha256 is not None:
|
||||
payload["sha256"] = self.sha256
|
||||
if self.launch_command:
|
||||
payload["launch_command"] = list(self.launch_command)
|
||||
return payload
|
||||
|
||||
|
||||
@@ -97,6 +120,8 @@ class UpdateInstaller:
|
||||
probe = subprocess.run(plan.restart_command, timeout=30, check=False)
|
||||
if probe.returncode != 0:
|
||||
raise RuntimeError(f"restart probe failed with code {probe.returncode}")
|
||||
if plan.launch_command:
|
||||
subprocess.Popen(plan.launch_command, cwd=current, close_fds=True)
|
||||
shutil.rmtree(old_path, ignore_errors=True)
|
||||
self._prune_backups(backup_root)
|
||||
self._log(backup_root, f"installed {current}")
|
||||
@@ -163,6 +188,16 @@ class UpdateInstaller:
|
||||
if not target.is_relative_to(root):
|
||||
raise ValueError("staged ZIP contains path traversal")
|
||||
archive.extractall(destination)
|
||||
# The release builder archives the portable folder itself. Accept that
|
||||
# single wrapper as well as an archive with files directly at its root.
|
||||
if not (destination / "DxDesignerTools.exe").is_file():
|
||||
children = tuple(destination.iterdir())
|
||||
if len(children) == 1 and children[0].is_dir():
|
||||
wrapper = children[0]
|
||||
if (wrapper / "DxDesignerTools.exe").is_file():
|
||||
for child in tuple(wrapper.iterdir()):
|
||||
child.replace(destination / child.name)
|
||||
wrapper.rmdir()
|
||||
|
||||
@staticmethod
|
||||
def _prune_backups(backup_root: Path) -> None:
|
||||
@@ -184,21 +219,27 @@ class UpdateInstaller:
|
||||
@contextlib.contextmanager
|
||||
def _single_instance_lock(current_root: Path):
|
||||
"""Best-effort named mutex so two updaters cannot race each other."""
|
||||
if os.name != "win32":
|
||||
if os.name != "nt":
|
||||
yield
|
||||
return
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
marker = abs(hash(str(current_root).casefold()))
|
||||
name = f"Local\\DxProductivityUpdate-{marker:08x}"
|
||||
handle = ctypes.windll.kernel32.CreateMutexW(None, False, name)
|
||||
already_running = (
|
||||
ctypes.windll.kernel32.GetLastError() == 183
|
||||
) # ERROR_ALREADY_EXISTS
|
||||
marker = hashlib.sha256(str(current_root.resolve()).casefold().encode("utf-8")).hexdigest()
|
||||
name = f"Local\\DxProductivityUpdate-{marker}"
|
||||
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
kernel.CreateMutexW.argtypes = (ctypes.c_void_p, wintypes.BOOL, wintypes.LPCWSTR)
|
||||
kernel.CreateMutexW.restype = wintypes.HANDLE
|
||||
kernel.CloseHandle.argtypes = (wintypes.HANDLE,)
|
||||
kernel.CloseHandle.restype = wintypes.BOOL
|
||||
handle = kernel.CreateMutexW(None, False, name)
|
||||
if not handle:
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
already_running = ctypes.get_last_error() == 183 # ERROR_ALREADY_EXISTS
|
||||
try:
|
||||
if already_running:
|
||||
raise RuntimeError("another update is already in progress")
|
||||
yield
|
||||
finally:
|
||||
if handle:
|
||||
ctypes.windll.kernel32.CloseHandle(handle)
|
||||
kernel.CloseHandle(handle)
|
||||
@@ -104,3 +104,26 @@ def test_backup_filename_does_not_contain_design_path_separators(
|
||||
|
||||
assert "board_power_logic" in backup.name
|
||||
assert ":" not in backup.name
|
||||
|
||||
|
||||
def test_generic_backup_preserves_multiple_operations_and_visibility_state(
|
||||
tmp_path, component_factory, snapshot_factory
|
||||
):
|
||||
from dx_productivity.domain.models import AnnotationPlan, AttributeRecord, OpType, PlanRow
|
||||
|
||||
component = component_factory(attributes=(AttributeRecord("Value", "RES", False),))
|
||||
snapshot = snapshot_factory(components=(component,))
|
||||
plan = AnnotationPlan(snapshot.snapshot_id, (
|
||||
PlanRow("property", (component.bridge_id,), component.full_path, None,
|
||||
"RES", "NEW", "restore", True, op=OpType.PROPERTY_VALUE, property_name="Value"),
|
||||
PlanRow("visibility", (component.bridge_id,), component.full_path, None,
|
||||
"0", "1", "restore", True, op=OpType.PROPERTY_VISIBILITY, property_name="Value"),
|
||||
), (), ())
|
||||
|
||||
path = RunStore(tmp_path).write_backup(snapshot, plan)
|
||||
|
||||
changes = json.loads(path.read_text(encoding="utf-8"))["changes"]
|
||||
assert [(item["op"], item["old_value"], item["new_value"]) for item in changes] == [
|
||||
("property", "RES", "NEW"),
|
||||
("visibility", "0", "1"),
|
||||
]
|
||||
@@ -53,7 +53,13 @@ def test_generated_menu_loads_without_host_script_path_metadata(portable_root, t
|
||||
+ ' 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',
|
||||
+ 'If FakeMenuBar.Controls.Count <> 1 Then WScript.Quit 4\n'
|
||||
+ 'FakeMenuBar.Controls.Item(1).Delete\n'
|
||||
+ 'FakeMainMenuBar.Controls.Item(1).Delete\n'
|
||||
+ 'Call DxToolsHost_ProjectChanged(Nothing)\n'
|
||||
+ 'If FakeMenuBar.Controls.Count <> 1 Then WScript.Quit 7\n'
|
||||
+ 'If FakeMainMenuBar.Controls.Count <> 1 Then WScript.Quit 8\n'
|
||||
+ 'WScript.Echo "menu events verified"\n',
|
||||
encoding="ascii",
|
||||
)
|
||||
result = subprocess.run(
|
||||
@@ -61,6 +67,7 @@ def test_generated_menu_loads_without_host_script_path_metadata(portable_root, t
|
||||
capture_output=True, timeout=10,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr.decode(errors="replace")
|
||||
assert b"menu events verified" in result.stdout, 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",
|
||||
@@ -78,7 +85,7 @@ def test_generated_menu_loads_without_host_script_path_metadata(portable_root, t
|
||||
assert result.returncode == 0, result.stderr.decode(errors="replace")
|
||||
|
||||
|
||||
def test_private_startup_preserves_vendor_scripts_and_existing_actions(portable_root, tmp_path):
|
||||
def test_startup_persists_in_normal_wdir_and_preserves_existing_actions(portable_root, tmp_path):
|
||||
from dx_productivity.bridge.startup import prepare_startup
|
||||
|
||||
install = tmp_path / "Mentor" / "7.9.5EE" / "SDD_HOME"
|
||||
@@ -95,13 +102,18 @@ def test_private_startup_preserves_vendor_scripts_and_existing_actions(portable_
|
||||
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
|
||||
registered = vendor.read_text(encoding="gbk")
|
||||
assert "Script#0=company.vbs" in registered
|
||||
assert "Script#0=library.vbs" in registered
|
||||
assert registered.count(str(configuration.assets.menu_script)) == 2
|
||||
assert f"Script#1={configuration.assets.menu_script}" in registered
|
||||
assert f"脚本#1={configuration.assets.menu_script}" in registered
|
||||
assert configuration.scripts_ini == vendor
|
||||
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"
|
||||
assert configuration.launch_environment["WDIR"].split(";") == [str(standard)]
|
||||
backups = list((tmp_path / "profile" / "DxProductivity" / "backups").glob("startup-scripts.*.bak"))
|
||||
assert len(backups) == 1
|
||||
assert backups[0].read_bytes() == original
|
||||
|
||||
|
||||
def test_incomplete_tool_package_is_rejected_before_registering_any_script(portable_root, tmp_path):
|
||||
@@ -160,6 +172,6 @@ def test_start_launches_absent_host_with_private_configuration(portable_root, tm
|
||||
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["WDIR"].split(";")[0] == str(standard)
|
||||
assert child["DXTOOLS_HOME"] == str(portable_root.resolve())
|
||||
assert environment == {"LOCALAPPDATA": str(profile), "WDIR": str(standard)}
|
||||
@@ -0,0 +1,123 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.domain.models import AttributeRecord, OpType, RestoreItem, RestoreRequest
|
||||
from dx_productivity.domain.restore import build_restore_plan
|
||||
|
||||
|
||||
def _request(op, expected, target, property_name="Value", **identity):
|
||||
values = {"bridge_id": "c0001", "stable_uid": "uid-c0001", "full_path": "ROOT\\C0001"}
|
||||
values.update(identity)
|
||||
return RestoreRequest("design-test", Path("backup.json"), (
|
||||
RestoreItem(**values, expected_value=expected, restore_value=target, op=op, property_name=property_name),
|
||||
))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("op,expected,target,current,visible", [
|
||||
(OpType.PROPERTY_VALUE, "47K", "10K", "47K", True),
|
||||
(OpType.PROPERTY_VISIBILITY, "0", "1", "RES", False),
|
||||
])
|
||||
def test_restore_checks_the_saved_operation_value_instead_of_refdes(
|
||||
component_factory, snapshot_factory, op, expected, target, current, visible
|
||||
):
|
||||
component = component_factory(refdes="R1", attributes=(AttributeRecord("Value", current, visible),))
|
||||
|
||||
plan = build_restore_plan(snapshot_factory(components=(component,)), _request(op, expected, target))
|
||||
|
||||
assert plan.can_apply
|
||||
assert plan.schedule[0].op is op
|
||||
assert plan.schedule[0].expected_refdes == expected
|
||||
assert plan.schedule[0].new_refdes == target
|
||||
assert plan.schedule[0].property_name == "Value"
|
||||
|
||||
|
||||
def test_property_restore_preserves_case_and_whitespace(component_factory, snapshot_factory):
|
||||
component = component_factory(attributes=(AttributeRecord("Value", " new ", True),))
|
||||
|
||||
plan = build_restore_plan(
|
||||
snapshot_factory(components=(component,)),
|
||||
_request(OpType.PROPERTY_VALUE, " new ", " OLD "),
|
||||
)
|
||||
|
||||
assert plan.can_apply
|
||||
assert plan.schedule[0].expected_refdes == " new "
|
||||
assert plan.schedule[0].new_refdes == " OLD "
|
||||
|
||||
|
||||
def test_case_only_property_restore_is_a_change(component_factory, snapshot_factory):
|
||||
component = component_factory(attributes=(AttributeRecord("Value", "abc", True),))
|
||||
|
||||
plan = build_restore_plan(snapshot_factory(components=(component,)), _request(OpType.PROPERTY_VALUE, "abc", "ABC"))
|
||||
|
||||
assert plan.can_apply
|
||||
assert plan.schedule[0].new_refdes == "ABC"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("attributes,issue", [
|
||||
((), "restore-property-missing"),
|
||||
((AttributeRecord("Value", "22K", True),), "restore-stale"),
|
||||
])
|
||||
def test_property_restore_blocks_missing_or_changed_property(
|
||||
component_factory, snapshot_factory, attributes, issue
|
||||
):
|
||||
component = component_factory(refdes="47K", attributes=attributes)
|
||||
|
||||
plan = build_restore_plan(snapshot_factory(components=(component,)), _request(OpType.PROPERTY_VALUE, "47K", "10K"))
|
||||
|
||||
assert not plan.can_apply
|
||||
assert any(item.code == issue for item in plan.issues)
|
||||
|
||||
|
||||
def test_restore_already_satisfied_property_does_not_rewrite(component_factory, snapshot_factory):
|
||||
component = component_factory(attributes=(AttributeRecord("Value", "10K", True),))
|
||||
|
||||
plan = build_restore_plan(snapshot_factory(components=(component,)), _request(OpType.PROPERTY_VALUE, "47K", "10K"))
|
||||
|
||||
assert not plan.issues
|
||||
assert not plan.can_apply
|
||||
assert not plan.rows[0].changed
|
||||
|
||||
|
||||
def test_restore_follows_stable_path_when_bridge_id_is_reassigned(component_factory, snapshot_factory):
|
||||
unrelated = component_factory(refdes="R1", stable_uid="uid-unrelated", full_path="ROOT\\OTHER")
|
||||
original = component_factory(bridge_id="c0002", refdes="R1")
|
||||
snapshot = snapshot_factory(components=(unrelated, original))
|
||||
|
||||
plan = build_restore_plan(snapshot, _request(OpType.REFDES, "R1", "R?", property_name=""))
|
||||
|
||||
assert plan.can_apply
|
||||
assert plan.rows[0].bridge_ids == ("c0002",)
|
||||
|
||||
|
||||
def test_restore_uid_wins_when_annotation_reuses_another_components_old_path(
|
||||
component_factory, snapshot_factory
|
||||
):
|
||||
unrelated = component_factory(stable_uid="uid-unrelated", refdes="R1")
|
||||
original = component_factory(bridge_id="c0002", full_path="ROOT\\RENAMED", refdes="R1")
|
||||
|
||||
plan = build_restore_plan(
|
||||
snapshot_factory(components=(unrelated, original)),
|
||||
_request(OpType.REFDES, "R1", "R?", property_name=""),
|
||||
)
|
||||
|
||||
assert plan.can_apply
|
||||
assert plan.rows[0].bridge_ids == ("c0002",)
|
||||
|
||||
|
||||
def test_restore_swap_derives_cycle_prefix_from_formal_references(
|
||||
component_factory, snapshot_factory
|
||||
):
|
||||
first = component_factory(refdes="CE17")
|
||||
second = component_factory(bridge_id="c2", stable_uid="uid-c2", full_path="ROOT\\C2",
|
||||
logical_group_key="uid-c2", refdes="CE18")
|
||||
request = RestoreRequest("design-test", Path("backup.json"), (
|
||||
RestoreItem(first.bridge_id, first.stable_uid, first.full_path, "CE17", "CE18"),
|
||||
RestoreItem(second.bridge_id, second.stable_uid, second.full_path, "CE18", "CE17"),
|
||||
))
|
||||
|
||||
plan = build_restore_plan(snapshot_factory(components=(first, second)), request)
|
||||
|
||||
assert plan.can_apply
|
||||
assert len(plan.schedule) == 3
|
||||
assert plan.schedule[0].new_refdes == "CE?"
|
||||
@@ -0,0 +1,28 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_bom_json_records_render_sections_rows_and_warning_colors():
|
||||
"""Escaped JSON records must reach the VBS Excel cell writer."""
|
||||
cscript = shutil.which("cscript")
|
||||
if cscript is None:
|
||||
pytest.skip("Windows VBScript host is not available")
|
||||
script = Path(__file__).parents[1] / "vbs" / "test_bom_export.vbs"
|
||||
|
||||
result = subprocess.run(
|
||||
[cscript, "//nologo", str(script)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
timeout=30,
|
||||
check=False,
|
||||
)
|
||||
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert not result.stderr, result.stderr
|
||||
assert "BOM export payload assertions passed" in result.stdout
|
||||
assert "BOM failure cleanup assertions passed" in result.stdout
|
||||
@@ -8,7 +8,7 @@ def _component(component_factory, bridge_id, refdes, value, pn="P1", **kw):
|
||||
return component_factory(
|
||||
bridge_id=bridge_id,
|
||||
stable_uid=f"uid-{bridge_id}",
|
||||
full_path=f"ROOT\{bridge_id}",
|
||||
full_path=f"ROOT\\{bridge_id}",
|
||||
logical_group_key=f"uid-{bridge_id}",
|
||||
refdes=refdes,
|
||||
symbol_refdes_default=refdes,
|
||||
@@ -89,6 +89,21 @@ def test_duplicate_refdes_flagged(component_factory, snapshot_factory):
|
||||
assert len(flagged) == 2
|
||||
|
||||
|
||||
def test_duplicate_refdes_inside_merged_row_flagged(
|
||||
component_factory, snapshot_factory
|
||||
):
|
||||
components = (
|
||||
_component(component_factory, "c1", "R1", "10K", pn="P1"),
|
||||
_component(component_factory, "c2", "R2", "10K", pn="P1"),
|
||||
_component(component_factory, "c3", "r1", "22K", pn="P2"),
|
||||
)
|
||||
|
||||
result = build_bom(snapshot_factory(components=components), BOMSettings())
|
||||
|
||||
assert [row.refdes for row in result.rows] == ["R1,R2", "r1"]
|
||||
assert all(row.duplicate_refdes for row in result.rows)
|
||||
|
||||
|
||||
def test_selected_scope_only_exports_selection(
|
||||
component_factory, snapshot_factory
|
||||
):
|
||||
@@ -104,6 +119,63 @@ def test_selected_scope_only_exports_selection(
|
||||
assert result.rows[0].refdes == "R1"
|
||||
|
||||
|
||||
def test_current_sheet_scope_filters_other_sheets(
|
||||
component_factory, snapshot_factory
|
||||
):
|
||||
current = _component(component_factory, "c1", "R1", "10K")
|
||||
other = _component(
|
||||
component_factory, "c2", "R2", "10K", sheet_number=2, current_sheet=False
|
||||
)
|
||||
|
||||
result = build_bom(
|
||||
snapshot_factory(components=(current, other)),
|
||||
BOMSettings(scope="current-sheet"),
|
||||
)
|
||||
|
||||
assert [(row.page, row.refdes) for row in result.rows] == [(1, "R1")]
|
||||
|
||||
|
||||
def test_same_part_on_different_pages_keeps_separate_quantities(
|
||||
component_factory, snapshot_factory
|
||||
):
|
||||
components = (
|
||||
_component(component_factory, "c1", "R1", "10K"),
|
||||
_component(component_factory, "c2", "R2", "10K", sheet_number=2),
|
||||
)
|
||||
|
||||
result = build_bom(snapshot_factory(components=components), BOMSettings())
|
||||
|
||||
assert [(row.page, row.qty, row.refdes) for row in result.rows] == [
|
||||
(1, 1, "R1"), (2, 1, "R2")
|
||||
]
|
||||
|
||||
|
||||
def test_repeated_unit_with_same_refdes_and_part_counts_once(
|
||||
component_factory, snapshot_factory
|
||||
):
|
||||
components = (
|
||||
_component(component_factory, "u1", "U1", "DUAL AMP", pn="AMP"),
|
||||
_component(component_factory, "u2", "U1", "DUAL AMP", pn="AMP"),
|
||||
)
|
||||
|
||||
result = build_bom(snapshot_factory(components=components), BOMSettings())
|
||||
|
||||
assert [(row.qty, row.refdes, row.duplicate_refdes) for row in result.rows] == [
|
||||
(1, "U1", False)
|
||||
]
|
||||
|
||||
|
||||
def test_all_marker_part_numbers_are_removed(component_factory, snapshot_factory):
|
||||
components = tuple(
|
||||
_component(component_factory, f"c{i}", f"TP{i}", "MARKER", pn=pn)
|
||||
for i, pn in enumerate(("MARK-1", "TEST_POINT-1", "MOUNTHOL-1"))
|
||||
)
|
||||
|
||||
result = build_bom(snapshot_factory(components=components), BOMSettings())
|
||||
|
||||
assert result.rows == ()
|
||||
|
||||
|
||||
def test_part_label_description_source(component_factory, snapshot_factory):
|
||||
component = component_factory(
|
||||
bridge_id="c1",
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_expedition_vbs_exports_assembly_classification_without_shared_globals():
|
||||
cscript = shutil.which("cscript")
|
||||
if cscript is None:
|
||||
pytest.skip("Windows VBScript host is not available")
|
||||
script = Path(__file__).parents[1] / "vbs" / "test_expedition_bridge.vbs"
|
||||
|
||||
result = subprocess.run(
|
||||
[cscript, "//nologo", str(script)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
timeout=30,
|
||||
check=False,
|
||||
)
|
||||
|
||||
assert not result.stderr, result.stderr
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert "Expedition request assertions passed" in result.stdout
|
||||
assert "Expedition standalone quoting assertions passed" in result.stdout
|
||||
assert "Expedition native root assertions passed" in result.stdout
|
||||
assert "Expedition persisted registration assertions passed" in result.stdout
|
||||
assert "Expedition native menu assertions passed" in result.stdout
|
||||
assert "Expedition legacy position parity assertions passed" in result.stdout
|
||||
@@ -0,0 +1,235 @@
|
||||
from pathlib import Path
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
from pypdf import PdfReader, PdfWriter
|
||||
from pypdf.generic import DecodedStreamObject, DictionaryObject, NameObject
|
||||
|
||||
from dx_productivity.features.pdf_export import exporter
|
||||
from dx_productivity.features.pdf_export.models import ExportScope, PdfExportSettings
|
||||
|
||||
|
||||
def _write_pdf(path: Path, sheets: tuple[tuple[str, str], ...]) -> None:
|
||||
writer = PdfWriter()
|
||||
for title, content in sheets:
|
||||
page = writer.add_blank_page(300, 200)
|
||||
font = DictionaryObject(
|
||||
{
|
||||
NameObject('/Type'): NameObject('/Font'),
|
||||
NameObject('/Subtype'): NameObject('/Type1'),
|
||||
NameObject('/BaseFont'): NameObject('/Helvetica'),
|
||||
}
|
||||
)
|
||||
page[NameObject('/Resources')] = DictionaryObject(
|
||||
{NameObject('/Font'): DictionaryObject({NameObject('/F1'): font})}
|
||||
)
|
||||
stream = DecodedStreamObject()
|
||||
stream.set_data(f'BT /F1 12 Tf 20 100 Td ({content}) Tj ET'.encode('ascii'))
|
||||
page[NameObject('/Contents')] = writer._add_object(stream)
|
||||
if title:
|
||||
writer.add_outline_item(title, len(writer.pages) - 1)
|
||||
with path.open('wb') as output:
|
||||
writer.write(output)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project(tmp_path: Path) -> Path:
|
||||
source = tmp_path / 'source'
|
||||
source.mkdir()
|
||||
(source / 'database').mkdir()
|
||||
path = source / 'Demo.prj'
|
||||
path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir ".\\database"\n')
|
||||
return path
|
||||
|
||||
|
||||
def test_current_page_requires_sheet_identity(tmp_path: Path) -> None:
|
||||
settings = PdfExportSettings(tmp_path / 'Demo.prj', ExportScope.CURRENT_PAGE, 'Main', tmp_path)
|
||||
with pytest.raises(ValueError, match='页'):
|
||||
exporter.output_path(settings, 'Main')
|
||||
|
||||
|
||||
def test_named_sheets_receive_distinct_output_paths(tmp_path: Path) -> None:
|
||||
settings = PdfExportSettings(tmp_path / 'Demo.prj', ExportScope.CURRENT_PAGE, 'Main', tmp_path)
|
||||
analog = exporter.output_path(settings, 'Main', 'Analog')
|
||||
digital = exporter.output_path(settings, 'Main', 'Digital')
|
||||
assert analog != digital
|
||||
assert 'Analog' in analog.name
|
||||
assert 'Digital' in digital.name
|
||||
|
||||
|
||||
def test_current_page_selects_named_sheet_without_other_sheet_content(tmp_path: Path) -> None:
|
||||
path = tmp_path / 'native.pdf'
|
||||
_write_pdf(path, (('Main Sheet Analog', 'ANALOG_ONLY'), ('Main Sheet Digital', 'DIGITAL_ONLY')))
|
||||
exporter._select_current_page(path, 'Main', 'Digital')
|
||||
reader = PdfReader(path, strict=True)
|
||||
assert len(reader.pages) == 1
|
||||
assert reader.pages[0].extract_text() == 'DIGITAL_ONLY'
|
||||
assert reader.get_destination_page_number(reader.outline[0]) == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('titles', [('',), ('Main Sheet Missing',), ('Main Sheet Digital', 'Main Sheet Digital')])
|
||||
def test_missing_or_ambiguous_named_sheet_does_not_replace_pdf(tmp_path: Path, titles: tuple[str, ...]) -> None:
|
||||
path = tmp_path / 'native.pdf'
|
||||
_write_pdf(path, tuple((title, 'CONTENT') for title in titles))
|
||||
before = path.read_bytes()
|
||||
with pytest.raises(ValueError, match='活动页'):
|
||||
exporter._select_current_page(path, 'Main', 'Digital')
|
||||
assert path.read_bytes() == before
|
||||
|
||||
|
||||
def test_current_page_export_publishes_only_selected_sheet(project: Path, tmp_path: Path, monkeypatch) -> None:
|
||||
engine = tmp_path / 'sch2pdf.exe'
|
||||
engine.touch()
|
||||
settings = PdfExportSettings(project, ExportScope.CURRENT_PAGE, 'Main', tmp_path / 'output', engine_path=engine)
|
||||
|
||||
def native_engine(command, *_args):
|
||||
assert command[-2:] == ['-schematic', 'Main']
|
||||
_write_pdf(Path(command[command.index('-a') + 1]), (('Main Sheet Analog', 'ANALOG_ONLY'), ('Main Sheet Digital', 'DIGITAL_ONLY')))
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(exporter, 'run_engine', native_engine)
|
||||
result = exporter.export_project(settings, threading.Event(), active_block_name='Main', active_sheet_name='Digital', local_app_data=tmp_path / 'state')
|
||||
assert result.state == 'success'
|
||||
assert result.pages == 1
|
||||
assert PdfReader(result.output_path).pages[0].extract_text() == 'DIGITAL_ONLY'
|
||||
assert not list(settings.output_dir.glob('*.partial.pdf'))
|
||||
|
||||
|
||||
def test_selection_failure_preserves_previous_export(project: Path, tmp_path: Path, monkeypatch) -> None:
|
||||
engine = tmp_path / 'sch2pdf.exe'
|
||||
engine.touch()
|
||||
output = tmp_path / 'output'
|
||||
output.mkdir()
|
||||
settings = PdfExportSettings(project, ExportScope.CURRENT_PAGE, 'Main', output, engine_path=engine)
|
||||
target = exporter.output_path(settings, 'Main', 'Digital')
|
||||
target.write_bytes(b'old-pdf-preserved')
|
||||
|
||||
def native_engine(command, *_args):
|
||||
_write_pdf(Path(command[command.index('-a') + 1]), (('Main Sheet Analog', 'ANALOG_ONLY'),))
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(exporter, 'run_engine', native_engine)
|
||||
result = exporter.export_project(settings, threading.Event(), active_block_name='Main', active_sheet_name='Digital', overwrite=True, local_app_data=tmp_path / 'state')
|
||||
assert result.state == 'failed'
|
||||
assert target.read_bytes() == b'old-pdf-preserved'
|
||||
assert not list(output.glob('*.partial.pdf'))
|
||||
|
||||
|
||||
def test_output_inside_source_never_invokes_engine(project: Path, tmp_path: Path, monkeypatch) -> None:
|
||||
settings = PdfExportSettings(project, ExportScope.PROJECT, '', project.parent / 'output')
|
||||
|
||||
def forbidden_engine(*_args):
|
||||
pytest.fail('source-directory output must be rejected before native execution')
|
||||
|
||||
monkeypatch.setattr(exporter, 'run_engine', forbidden_engine)
|
||||
result = exporter.export_project(settings, threading.Event(), local_app_data=tmp_path / 'state')
|
||||
assert result.state == 'failed'
|
||||
assert '源工程目录之外' in result.message
|
||||
assert not settings.output_dir.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scope,block,want', [
|
||||
(ExportScope.PROJECT, '', []),
|
||||
(ExportScope.BLOCK, 'Main logic 中文', ['-schematic', 'Main logic 中文']),
|
||||
])
|
||||
def test_native_scope_arguments_preserve_paths_and_block_names(tmp_path: Path, scope, block, want) -> None:
|
||||
engine = tmp_path / 'Engine directory' / 'sch2pdf.exe'
|
||||
project = tmp_path / '中文 工程' / 'Demo.prj'
|
||||
output = tmp_path / 'PDF output' / 'Demo.pdf'
|
||||
command = exporter.build_command(engine, project, output, scope, block)
|
||||
assert command[command.index('-project') + 1] == str(project)
|
||||
assert command[command.index('-a') + 1] == str(output)
|
||||
assert command[0] == str(engine)
|
||||
if want:
|
||||
assert command[-2:] == want
|
||||
else:
|
||||
assert '-schematic' not in command
|
||||
|
||||
|
||||
def test_source_configuration_changes_block_publication(project: Path, tmp_path: Path, monkeypatch) -> None:
|
||||
engine = tmp_path / 'sch2pdf.exe'
|
||||
engine.touch()
|
||||
settings = PdfExportSettings(project, ExportScope.PROJECT, '', tmp_path / 'output', engine_path=engine)
|
||||
|
||||
def native_engine(command, *_args):
|
||||
_write_pdf(Path(command[command.index('-a') + 1]), (('Main Sheet Analog', 'CONTENT'),))
|
||||
project.write_text(project.read_text() + 'KEY Unexpected "change"\n')
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(exporter, 'run_engine', native_engine)
|
||||
result = exporter.export_project(settings, threading.Event(), local_app_data=tmp_path / 'state')
|
||||
assert result.state == 'uncertain'
|
||||
assert not result.output_path.exists()
|
||||
assert not list(settings.output_dir.glob('*.partial.pdf'))
|
||||
|
||||
|
||||
def test_cancelled_request_does_not_launch_native_engine(project: Path, tmp_path: Path, monkeypatch) -> None:
|
||||
engine = tmp_path / 'sch2pdf.exe'
|
||||
engine.touch()
|
||||
settings = PdfExportSettings(project, ExportScope.PROJECT, '', tmp_path / 'output', engine_path=engine)
|
||||
cancel = threading.Event()
|
||||
cancel.set()
|
||||
|
||||
def forbidden_engine(*_args):
|
||||
pytest.fail('cancelled request must not launch the engine')
|
||||
|
||||
monkeypatch.setattr(exporter, 'run_engine', forbidden_engine)
|
||||
result = exporter.export_project(settings, cancel, local_app_data=tmp_path / 'state')
|
||||
assert result.state == 'cancelled'
|
||||
assert not result.output_path.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('native_code,allowed', [(32, True), (33, True), (5, False), (None, False)])
|
||||
def test_native_database_sharing_lock_is_distinguished_from_permission_denial(project: Path, tmp_path: Path, monkeypatch, native_code, allowed) -> None:
|
||||
engine = tmp_path / 'sch2pdf.exe'
|
||||
engine.touch()
|
||||
database = project.parent / 'database' / 'icdb.dat'
|
||||
database.write_bytes(b'native database')
|
||||
settings = PdfExportSettings(project, ExportScope.PROJECT, '', tmp_path / 'output', engine_path=engine)
|
||||
original_open = Path.open
|
||||
|
||||
def locked_open(path, *args, **kwargs):
|
||||
if path == database:
|
||||
error = PermissionError(13, 'native database is locked', str(path))
|
||||
if native_code is not None:
|
||||
error.winerror = native_code
|
||||
raise error
|
||||
return original_open(path, *args, **kwargs)
|
||||
|
||||
def native_engine(command, *_args):
|
||||
_write_pdf(Path(command[command.index('-a') + 1]), (('Main Sheet Analog', 'CONTENT'),))
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(Path, 'open', locked_open)
|
||||
monkeypatch.setattr(exporter, 'run_engine', native_engine)
|
||||
result = exporter.export_project(settings, threading.Event(), local_app_data=tmp_path / 'state')
|
||||
if allowed:
|
||||
assert result.state == 'success'
|
||||
assert result.output_path.is_file()
|
||||
assert '无法核验' in result.message
|
||||
else:
|
||||
assert result.state == 'failed'
|
||||
assert not result.output_path.exists()
|
||||
|
||||
|
||||
def test_unreadable_schematic_still_prevents_native_export(project: Path, tmp_path: Path, monkeypatch) -> None:
|
||||
engine = tmp_path / 'sch2pdf.exe'
|
||||
engine.touch()
|
||||
schematic = project.parent / 'source.sch'
|
||||
schematic.write_bytes(b'schematic')
|
||||
settings = PdfExportSettings(project, ExportScope.PROJECT, '', tmp_path / 'output', engine_path=engine)
|
||||
original_open = Path.open
|
||||
|
||||
def locked_open(path, *args, **kwargs):
|
||||
if path == schematic:
|
||||
raise PermissionError(13, 'schematic is locked', str(path))
|
||||
return original_open(path, *args, **kwargs)
|
||||
|
||||
def forbidden_engine(*_args):
|
||||
pytest.fail('unreadable schematic must prevent native execution')
|
||||
|
||||
monkeypatch.setattr(Path, 'open', locked_open)
|
||||
monkeypatch.setattr(exporter, 'run_engine', forbidden_engine)
|
||||
result = exporter.export_project(settings, threading.Event(), local_app_data=tmp_path / 'state')
|
||||
assert result.state == 'failed'
|
||||
assert not result.output_path.exists()
|
||||
@@ -0,0 +1,54 @@
|
||||
from pathlib import Path
|
||||
|
||||
from dx_productivity.features.pdf_export import cli
|
||||
from dx_productivity.features.pdf_export.models import ExportScope, PdfExportResult, PdfExportSettings
|
||||
from dx_productivity.features.pdf_export.settings import load_settings, save_settings
|
||||
|
||||
|
||||
def test_settings_roundtrip_preserves_automatic_scope_and_output(tmp_path: Path) -> None:
|
||||
settings = PdfExportSettings(tmp_path / '中文项目' / 'Demo.prj', ExportScope.BLOCK, 'Digital signal', tmp_path / 'PDF output', True, tmp_path / 'engine' / 'sch2pdf.exe')
|
||||
config = tmp_path / 'state' / 'config.json'
|
||||
save_settings(settings, config_path=config)
|
||||
assert load_settings(settings.project_path, config_path=config) == settings
|
||||
|
||||
|
||||
def test_other_project_cannot_inherit_automatic_export(tmp_path: Path) -> None:
|
||||
config = tmp_path / 'config.json'
|
||||
save_settings(PdfExportSettings(tmp_path / 'First.prj', ExportScope.PROJECT, '', tmp_path / 'output', True), config_path=config)
|
||||
settings = load_settings(tmp_path / 'Second.prj', config_path=config, local_app_data=tmp_path / 'state')
|
||||
assert not settings.auto_export
|
||||
assert settings.project_path == tmp_path / 'Second.prj'
|
||||
assert not settings.output_dir.is_relative_to(settings.project_path.parent / 'Second')
|
||||
|
||||
|
||||
def test_disabled_save_event_writes_status_without_launching_export(tmp_path: Path, monkeypatch) -> None:
|
||||
project = tmp_path / 'Demo.prj'
|
||||
config = tmp_path / 'config.json'
|
||||
status = tmp_path / 'status' / 'result.txt'
|
||||
save_settings(PdfExportSettings(project, ExportScope.PROJECT, '', tmp_path / 'output'), config_path=config)
|
||||
|
||||
def forbidden_export(*_args, **_kwargs):
|
||||
raise AssertionError('disabled automatic export must not invoke exporter')
|
||||
|
||||
monkeypatch.setattr(cli, 'export_project', forbidden_export)
|
||||
assert cli.main(['--settings', str(config), '--project', str(project), '--status-file', str(status)]) == 0
|
||||
assert '已忽略' in status.read_text(encoding='utf-8')
|
||||
|
||||
|
||||
def test_save_event_forwards_exact_named_sheet_and_reports_success(tmp_path: Path, monkeypatch) -> None:
|
||||
project = tmp_path / 'Demo.prj'
|
||||
config = tmp_path / 'config.json'
|
||||
status = tmp_path / 'result.txt'
|
||||
settings = PdfExportSettings(project, ExportScope.CURRENT_PAGE, 'Main', tmp_path / 'output', True)
|
||||
save_settings(settings, config_path=config)
|
||||
observed = {}
|
||||
|
||||
def export(settings, cancel, **kwargs):
|
||||
observed.update(kwargs)
|
||||
return PdfExportResult(settings.project_path, 'success', 'PDF saved')
|
||||
|
||||
monkeypatch.setattr(cli, 'export_project', export)
|
||||
assert cli.main(['--settings', str(config), '--project', str(project), '--active-block', 'Main', '--active-sheet', 'Digital signal', '--status-file', str(status)]) == 0
|
||||
assert observed['active_sheet_name'] == 'Digital signal'
|
||||
assert observed['overwrite'] is True
|
||||
assert status.read_text(encoding='utf-8') == 'PDF saved\n'
|
||||
@@ -0,0 +1,64 @@
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.features.pdf_export import native_listener
|
||||
|
||||
|
||||
def _app(path: Path):
|
||||
return SimpleNamespace(GetProjectData=lambda: SimpleNamespace(GetProjectFilePath=str(path)))
|
||||
|
||||
|
||||
def test_listener_selects_configured_project_among_multiple_native_instances(tmp_path: Path) -> None:
|
||||
original = _app(tmp_path / 'original.prj')
|
||||
selected = _app(tmp_path / 'acceptance.prj')
|
||||
result = native_listener.select_application(
|
||||
[('original', original), ('selected', selected)], tmp_path / 'acceptance.prj'
|
||||
)
|
||||
assert result == ('selected', selected)
|
||||
|
||||
|
||||
def test_listener_does_not_bind_an_unrelated_native_instance(tmp_path: Path) -> None:
|
||||
assert native_listener.select_application([('original', _app(tmp_path / 'original.prj'))], tmp_path / 'acceptance.prj') is None
|
||||
|
||||
|
||||
def test_duplicate_project_instances_are_rejected(tmp_path: Path) -> None:
|
||||
project = tmp_path / 'acceptance.prj'
|
||||
with pytest.raises(ValueError, match='多个'):
|
||||
native_listener.select_application([('one', _app(project)), ('two', _app(project))], project)
|
||||
|
||||
|
||||
def test_save_queue_coalesces_events_and_waits_for_child_exit(tmp_path: Path) -> None:
|
||||
started = []
|
||||
child = SimpleNamespace(returncode=None)
|
||||
child.poll = lambda: child.returncode
|
||||
|
||||
def start(event):
|
||||
started.append(event)
|
||||
return child
|
||||
|
||||
queue = native_listener.SaveQueue(start, debounce_seconds=0.5)
|
||||
first = native_listener.SaveEvent(tmp_path / 'Demo.prj', 'Main', 'Analog')
|
||||
latest = native_listener.SaveEvent(tmp_path / 'Demo.prj', 'Main', 'Digital')
|
||||
queue.add(first, 0)
|
||||
queue.add(first, 0.1)
|
||||
queue.tick(0.4)
|
||||
assert started == []
|
||||
queue.tick(0.7)
|
||||
assert started == [first]
|
||||
queue.add(latest, 0.8)
|
||||
queue.tick(2)
|
||||
assert started == [first]
|
||||
child.returncode = 0
|
||||
queue.tick(2.1)
|
||||
assert started == [first, latest]
|
||||
|
||||
|
||||
def test_disabling_listener_discards_queued_save(tmp_path: Path) -> None:
|
||||
started = []
|
||||
queue = native_listener.SaveQueue(lambda event: started.append(event), debounce_seconds=0.5)
|
||||
queue.add(native_listener.SaveEvent(tmp_path / 'Demo.prj', 'Main', 'Digital'), 0)
|
||||
queue.tick(1, enabled=False)
|
||||
queue.tick(2)
|
||||
assert started == []
|
||||
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -62,3 +63,18 @@ def test_startup_probe_uses_packaged_executable_and_records_portable_path() -> N
|
||||
assert "py -3.12" not in text
|
||||
assert "D:\\NET_CHECK" not in text
|
||||
assert text.isascii()
|
||||
|
||||
|
||||
def test_probe_reads_native_location_and_parent_methods(tmp_path: Path) -> None:
|
||||
fake = Path("tests/vbs/test_refdes_export.vbs").read_text(encoding="ascii").split('Set Fso = CreateObject')[0]
|
||||
probe = Path("integration/dxdesigner795/CompatibilityProbe.vbs").read_text(encoding="ascii")
|
||||
harness = tmp_path / "probe.vbs"
|
||||
harness.write_text(fake + "\n" + probe + '\nSet Component = New FakeComponent\n'
|
||||
'Set Component.Location = New FakeLocation\nComponent.Location.X = 10\nComponent.Location.Y = 20\n'
|
||||
'Set Component.Parent = New FakeParentBlock\nComponent.ComponentName = "R1"\n'
|
||||
'If DxToolsProbePositionMethod(Component) <> "GetLocation().X/Y" Then WScript.Quit 7\n'
|
||||
'If DxToolsProbePathMethod(Component) = "" Then WScript.Quit 8\n'
|
||||
'WScript.Echo "native getters verified"\n', encoding="ascii")
|
||||
result = subprocess.run(["cscript", "//nologo", str(harness)], capture_output=True)
|
||||
assert result.returncode == 0, result.stderr.decode("mbcs", errors="replace")
|
||||
assert b"native getters verified" in result.stdout
|
||||
@@ -46,7 +46,7 @@ def test_real_vbs_bridge_transaction_harness_passes() -> None:
|
||||
["cscript", "//nologo", "tests/vbs/test_refdes_bridge.vbs"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
encoding="mbcs",
|
||||
check=False,
|
||||
timeout=30,
|
||||
)
|
||||
@@ -60,7 +60,7 @@ def test_real_vbs_snapshot_export_harness_passes() -> None:
|
||||
["cscript", "//nologo", "tests/vbs/test_refdes_export.vbs"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
encoding="mbcs",
|
||||
check=False,
|
||||
timeout=30,
|
||||
)
|
||||
@@ -86,6 +86,6 @@ def test_transaction_supports_property_operations() -> None:
|
||||
encoding="ascii"
|
||||
)
|
||||
|
||||
assert 'Attributes.Item(' in transaction
|
||||
assert 'FindAttribute(' in transaction
|
||||
assert '.Visible =' in transaction
|
||||
assert 'DxBridgeNormalizeVisible' in transaction
|
||||
@@ -5,6 +5,8 @@ from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
RELEASE_ROOT = Path(os.environ.get("DXTOOLS_RELEASE_ROOT", str(REPO_ROOT / "release" / "DxDesigner效率工具")))
|
||||
@@ -79,13 +81,19 @@ def test_packaged_probe_runs_without_python_on_path(tmp_path: Path) -> None:
|
||||
assert json.loads(output.read_text(encoding="utf-8"))["portable"] is True
|
||||
|
||||
|
||||
def test_packaged_ui_loads_request_without_python_on_path() -> None:
|
||||
@pytest.mark.parametrize("feature", (
|
||||
"refdes", "property-change", "property-visibility", "inspection", "network",
|
||||
"bom", "history", "settings", "pdf-export",
|
||||
))
|
||||
def test_packaged_ui_loads_request_without_python_on_path(feature: str) -> None:
|
||||
result = subprocess.run(
|
||||
[
|
||||
str(RELEASE_ROOT / "DxDesignerTools.exe"),
|
||||
"ui",
|
||||
"--request",
|
||||
str(REPO_ROOT / "tests" / "fixtures" / "request-basic.json"),
|
||||
"--feature",
|
||||
feature,
|
||||
"--smoke-test-ms",
|
||||
"250",
|
||||
],
|
||||
@@ -139,9 +147,32 @@ def test_packaged_application_runs_from_chinese_path_with_spaces(
|
||||
|
||||
|
||||
def test_release_archive_matches_sha256_manifest() -> None:
|
||||
archive = REPO_ROOT / "release" / "DxDesigner效率工具_Win11_x64.zip"
|
||||
manifest = REPO_ROOT / "release" / "SHA256SUMS.txt"
|
||||
archive = Path(os.environ.get("DXTOOLS_RELEASE_ARCHIVE", str(REPO_ROOT / "release" / "DxDesigner效率工具_Win11_x64.zip")))
|
||||
manifest = Path(os.environ.get("DXTOOLS_RELEASE_MANIFEST", str(REPO_ROOT / "release" / "SHA256SUMS.txt")))
|
||||
|
||||
digest = hashlib.sha256(archive.read_bytes()).hexdigest()
|
||||
|
||||
assert manifest.read_text(encoding="utf-8").split()[0] == digest
|
||||
|
||||
|
||||
def test_packaged_listener_disabled_exits_without_python_on_path(tmp_path: Path) -> None:
|
||||
config = tmp_path / "pdf-export-settings.json"
|
||||
config.write_text('{"auto_export":false}', encoding="utf-8")
|
||||
result = subprocess.run(
|
||||
[str(RELEASE_ROOT / "DxDesignerTools.exe"), "pdf-export-listen", "--settings", str(config)],
|
||||
env=_sanitized_environment(), timeout=30, check=False,
|
||||
)
|
||||
assert result.returncode == 0
|
||||
|
||||
|
||||
def test_packaged_pcb_compute_without_python_on_path(tmp_path: Path) -> None:
|
||||
request = tmp_path / "request.txt"
|
||||
output = tmp_path / "plan.txt"
|
||||
request.write_text("T|0|1|1|1|C1|0|C1\nT|1|2|1|1|NOTE|0|C1\nC|C1|10|20|0.5|0.3\n", encoding="ascii")
|
||||
result = subprocess.run(
|
||||
[str(RELEASE_ROOT / "DxDesignerTools.exe"), "compute", "assembly-refdes", "--request", str(request), "--output", str(output)],
|
||||
env=_sanitized_environment(), timeout=30, check=False,
|
||||
)
|
||||
assert result.returncode == 0
|
||||
assert "MOVE|0|10.0000|20.0000|0.00|0.3000|Arial\n" in output.read_text(encoding="ascii")
|
||||
assert "DELETE|1\n" in output.read_text(encoding="ascii")
|
||||
@@ -0,0 +1,138 @@
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.domain.models import AttributeRecord, RunPaths
|
||||
from dx_productivity.ui.bom_controller import BomController
|
||||
from dx_productivity.ui.bom_page import BomPage
|
||||
|
||||
|
||||
def _controller(qtbot, tmp_path, snapshot):
|
||||
page = BomPage()
|
||||
qtbot.addWidget(page)
|
||||
paths = RunPaths(snapshot.run_id, tmp_path, tmp_path / "request.json",
|
||||
tmp_path / "result.tsv", tmp_path / "locate.tsv", tmp_path / "apply-status.json")
|
||||
template = tmp_path / "BOM模板.xls"
|
||||
template.write_bytes(b"template marker; offline tests do not invoke Excel")
|
||||
controller = BomController(page, run_paths=paths, template_path=template, design_name="old.prj")
|
||||
controller.load_snapshot(snapshot)
|
||||
return controller, page, paths
|
||||
|
||||
|
||||
def test_bom_preview_controls_recompute_scopes_description_and_nc_filter(
|
||||
qtbot, tmp_path, component_factory, snapshot_factory
|
||||
):
|
||||
first = component_factory(refdes="R1", attributes=(
|
||||
AttributeRecord("Value", "10K", True), AttributeRecord("Part Label", "RES", True),
|
||||
))
|
||||
other = component_factory(bridge_id="c2", stable_uid="uid-c2", full_path="ROOT\\C2",
|
||||
logical_group_key="uid-c2", refdes="R2", selected=False, current_sheet=False,
|
||||
sheet_number=2, attributes=(AttributeRecord("Value", "NC", True),))
|
||||
controller, page, paths = _controller(qtbot, tmp_path, snapshot_factory(components=(first, other)))
|
||||
assert len(controller._result.rows) == 2
|
||||
|
||||
page.selected_button.click()
|
||||
assert [row.refdes for row in controller._result.rows] == ["R1"]
|
||||
page.description_combo.setCurrentIndex(1)
|
||||
assert controller._result.rows[0].description == "RES"
|
||||
page.current_sheet_button.click()
|
||||
assert [row.refdes for row in controller._result.rows] == ["R1"]
|
||||
page.full_button.click()
|
||||
page.description_combo.setCurrentIndex(0)
|
||||
page.nc_checkbox.setChecked(True)
|
||||
assert [row.refdes for row in controller._result.rows] == ["R1"]
|
||||
assert controller._result.excluded_count == 1
|
||||
assert page.export_button.isEnabled()
|
||||
|
||||
|
||||
def test_bom_export_clears_old_status_and_disables_duplicate_requests(
|
||||
qtbot, tmp_path, snapshot_factory
|
||||
):
|
||||
controller, page, paths = _controller(qtbot, tmp_path, snapshot_factory())
|
||||
status = tmp_path / "bom-export-status.json"
|
||||
status.write_text('{"state":"ok","output_path":"old.xls"}', encoding="utf-8")
|
||||
|
||||
controller.export_to(str(tmp_path / "new.xls"))
|
||||
|
||||
assert not status.exists()
|
||||
assert controller._export_in_flight
|
||||
assert not page.export_button.isEnabled()
|
||||
payload = json.loads((tmp_path / "bom-export.json").read_text(encoding="utf-8"))
|
||||
assert payload["output_path"] == str(tmp_path / "new.xls")
|
||||
assert payload["design_name"] == "test.prj"
|
||||
assert payload["records"] == "S|1\nR|1|R?|PART|10K|"
|
||||
controller.refresh_preview()
|
||||
assert not page.export_button.isEnabled()
|
||||
controller.export_to(str(tmp_path / "ignored.xls"))
|
||||
assert json.loads((tmp_path / "bom-export.json").read_text(encoding="utf-8"))["output_path"] == str(tmp_path / "new.xls")
|
||||
controller._status_timer.stop()
|
||||
|
||||
|
||||
def test_bom_mailbox_write_failure_can_be_retried(
|
||||
qtbot, tmp_path, snapshot_factory, monkeypatch
|
||||
):
|
||||
from dx_productivity.ui import bom_controller as module
|
||||
controller, page, paths = _controller(qtbot, tmp_path, snapshot_factory())
|
||||
|
||||
def fail_write(*args):
|
||||
raise OSError("mailbox is read-only")
|
||||
|
||||
monkeypatch.setattr(module, "atomic_write_text", fail_write)
|
||||
with pytest.raises(OSError, match="read-only"):
|
||||
controller.export_to("new.xls")
|
||||
|
||||
assert not controller._export_in_flight
|
||||
assert page.export_button.isEnabled()
|
||||
assert not controller._status_timer.isActive()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", ["{not-json", "[]", '{"state":"failed","error":"Excel unavailable"}'])
|
||||
def test_bom_export_failure_reports_error_and_restores_button(
|
||||
qtbot, tmp_path, snapshot_factory, status
|
||||
):
|
||||
controller, page, paths = _controller(qtbot, tmp_path, snapshot_factory())
|
||||
controller.export_to("new.xls")
|
||||
(tmp_path / "bom-export-status.json").write_text(status, encoding="utf-8")
|
||||
|
||||
with qtbot.waitSignal(controller.export_failed) as signal:
|
||||
controller._poll_export_status()
|
||||
|
||||
assert signal.args[0]
|
||||
assert not controller._export_in_flight
|
||||
assert page.export_button.isEnabled()
|
||||
|
||||
|
||||
def test_bom_success_publishes_host_output(qtbot, tmp_path, snapshot_factory):
|
||||
controller, page, paths = _controller(qtbot, tmp_path, snapshot_factory())
|
||||
controller.export_to("new.xls")
|
||||
(tmp_path / "bom-export-status.json").write_text('{"state":"ok","output_path":"new.xls"}', encoding="utf-8")
|
||||
|
||||
with qtbot.waitSignal(controller.export_completed) as signal:
|
||||
controller._poll_export_status()
|
||||
|
||||
assert signal.args == ["new.xls"]
|
||||
assert not controller._export_in_flight
|
||||
assert page.export_button.isEnabled()
|
||||
|
||||
|
||||
def test_bom_success_without_host_path_uses_requested_output(qtbot, tmp_path, snapshot_factory):
|
||||
controller, page, paths = _controller(qtbot, tmp_path, snapshot_factory())
|
||||
requested = str(tmp_path / "BOM导出.xls")
|
||||
controller.export_to(requested)
|
||||
(tmp_path / "bom-export-status.json").write_text('{"state":"ok"}', encoding="utf-8")
|
||||
|
||||
with qtbot.waitSignal(controller.export_completed) as signal:
|
||||
controller._poll_export_status()
|
||||
|
||||
assert signal.args == [requested]
|
||||
|
||||
|
||||
def test_bom_records_keep_multiline_attributes_in_one_record(
|
||||
qtbot, tmp_path, component_factory, snapshot_factory
|
||||
):
|
||||
component = component_factory(refdes="R1", attributes=(AttributeRecord("Value", "a\nb\r\nc|d", True),))
|
||||
controller, page, paths = _controller(qtbot, tmp_path, snapshot_factory(components=(component,)))
|
||||
|
||||
records = controller._build_payload("new.xls")["records"]
|
||||
|
||||
assert records.splitlines() == ["S|1", "R|1|R1|PART|a b c d|"]
|
||||
@@ -91,3 +91,80 @@ def test_restore_cancel_does_not_publish_transaction(
|
||||
assert controller.restore_latest() is None
|
||||
assert not paths.result.exists()
|
||||
assert not paths.apply_request.exists()
|
||||
|
||||
|
||||
def test_restore_attribute_visibility_creates_reversible_second_backup(
|
||||
qtbot, tmp_path, snapshot_factory, component_factory
|
||||
):
|
||||
from dx_productivity.domain.models import AttributeRecord, OperationChange, OpType
|
||||
from dx_productivity.ui.history_controller import HistoryController
|
||||
from dx_productivity.ui.history_page import HistoryPage
|
||||
|
||||
current = snapshot_factory(components=(component_factory(
|
||||
refdes="R1", attributes=(AttributeRecord("Part Name", "RES", False),)
|
||||
),))
|
||||
component = current.components[0]
|
||||
store = RunStore(tmp_path / "store")
|
||||
original_backup = store.write_operation_backup(current, (
|
||||
OperationChange(component.bridge_id, component.stable_uid, component.full_path,
|
||||
OpType.PROPERTY_VISIBILITY, "Part Name", "1", "0"),
|
||||
))
|
||||
store.record_status(ApplyStatus(2, current.run_id, "applied", 1, original_backup))
|
||||
paths = _run_paths(tmp_path, current.run_id)
|
||||
page = HistoryPage()
|
||||
qtbot.addWidget(page)
|
||||
controller = HistoryController(page, run_store=store, run_paths=paths,
|
||||
confirm_restore=lambda entry, count: True)
|
||||
controller.load_snapshot(current)
|
||||
|
||||
result = controller.restore_latest()
|
||||
|
||||
assert result.read_text(encoding="utf-8") == "1\tvisibility\tc0001\tPart Name\t0\t1\t1\n"
|
||||
request = load_apply_request(paths.apply_request)
|
||||
second_change = json.loads(request.backup_path.read_text(encoding="utf-8"))["changes"][0]
|
||||
assert second_change["old_value"] == "0"
|
||||
assert second_change["new_value"] == "1"
|
||||
assert controller.restore_latest() is None
|
||||
paths.apply_status.write_text(json.dumps({
|
||||
"format_version": 2, "run_id": current.run_id, "state": "applied", "changed_count": 1,
|
||||
"backup_path": str(request.backup_path), "failing_sequence": None, "error": None, "rollback_state": None,
|
||||
}), encoding="utf-8")
|
||||
with qtbot.waitSignal(controller.status_changed) as signal:
|
||||
controller._poll_status()
|
||||
assert signal.args == ["applied"]
|
||||
assert not controller._restore_in_flight
|
||||
assert len(store.list_history(current.design_id)) == 2
|
||||
controller._poll_status()
|
||||
assert len(store.list_history(current.design_id)) == 2
|
||||
controller.stop()
|
||||
|
||||
|
||||
def test_restore_schedule_write_failure_does_not_lock_future_restore(
|
||||
qtbot, tmp_path, snapshot_factory, monkeypatch
|
||||
):
|
||||
import pytest
|
||||
from dx_productivity.ui import history_controller as module
|
||||
from dx_productivity.ui.history_page import HistoryPage
|
||||
original = snapshot_factory(target_ref="R?")
|
||||
applied = snapshot_factory(target_ref="R1")
|
||||
store = RunStore(tmp_path / "store")
|
||||
backup = store.write_backup(original, build_annotation_plan(original, AnnotationSettings()))
|
||||
store.record_status(ApplyStatus(2, original.run_id, "applied", 1, backup))
|
||||
paths = _run_paths(tmp_path, applied.run_id)
|
||||
page = HistoryPage()
|
||||
qtbot.addWidget(page)
|
||||
controller = module.HistoryController(page, run_store=store, run_paths=paths,
|
||||
confirm_restore=lambda entry, count: True)
|
||||
controller.load_snapshot(applied)
|
||||
|
||||
def fail_write(*args):
|
||||
raise OSError("mailbox is read-only")
|
||||
|
||||
monkeypatch.setattr(module, "write_schedule", fail_write)
|
||||
with pytest.raises(OSError, match="read-only"):
|
||||
controller.restore_latest()
|
||||
|
||||
assert not controller._restore_in_flight
|
||||
assert not controller._timer.isActive()
|
||||
assert page.restore_button.isEnabled()
|
||||
assert not paths.result.exists()
|
||||
@@ -41,3 +41,16 @@ def test_history_page_disables_restore_when_empty(qtbot) -> None:
|
||||
page.set_entries(())
|
||||
|
||||
assert not page.restore_button.isEnabled()
|
||||
|
||||
|
||||
def test_history_without_backup_is_visible_but_cannot_be_restored(qtbot):
|
||||
from dx_productivity.ui.history_page import HistoryPage
|
||||
page = HistoryPage()
|
||||
qtbot.addWidget(page)
|
||||
entry = HistoryEntry(datetime.now(timezone.utc), "rejected-run", "design-test", None, "rejected", 0)
|
||||
|
||||
page.set_entries((entry,))
|
||||
|
||||
assert page.model.rowCount() == 1
|
||||
assert page.selected_entry() is entry
|
||||
assert not page.restore_button.isEnabled()
|
||||
@@ -0,0 +1,133 @@
|
||||
import pytest
|
||||
|
||||
from dx_productivity.domain.models import AttributeRecord, NetRecord, RunPaths
|
||||
from dx_productivity.ui.inspection_controller import InspectionController
|
||||
from dx_productivity.ui.inspection_page import InspectionPage
|
||||
|
||||
|
||||
def _controller(qtbot, tmp_path, snapshot):
|
||||
page = InspectionPage()
|
||||
qtbot.addWidget(page)
|
||||
paths = RunPaths(snapshot.run_id, tmp_path, tmp_path / "request.json",
|
||||
tmp_path / "result.tsv", tmp_path / "locate.tsv", tmp_path / "apply-status.json")
|
||||
controller = InspectionController(page, run_paths=paths)
|
||||
controller.load_snapshot(snapshot)
|
||||
return controller, page, paths
|
||||
|
||||
|
||||
def test_network_buttons_and_cross_page_rows_publish_location_without_writes(
|
||||
qtbot, tmp_path, snapshot_factory
|
||||
):
|
||||
snapshot = snapshot_factory(nets=(NetRecord("N1", (1,)), NetRecord("N2", (1, 2))))
|
||||
controller, page, paths = _controller(qtbot, tmp_path, snapshot)
|
||||
|
||||
page.solitary_button.click()
|
||||
assert page.model.rowCount() == 1
|
||||
assert page.model.item(0, 1).text() == "N1"
|
||||
page.table.doubleClicked.emit(page.model.index(0, 1))
|
||||
assert paths.locate.read_text(encoding="utf-8") == "net|N1|1\n"
|
||||
page.net_list_button.click()
|
||||
assert page.model.rowCount() == 2
|
||||
page.net_name_edit.setText(" n2 ")
|
||||
page.cross_page_button.click()
|
||||
assert page.model.rowCount() == 2
|
||||
assert page.model.item(1, 2).text() == "2"
|
||||
page.table.doubleClicked.emit(page.model.index(1, 1))
|
||||
assert paths.locate.read_text(encoding="utf-8") == "net|N2|2\n"
|
||||
assert not paths.result.exists()
|
||||
assert not paths.apply_request.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("button_name,attribute_name", [
|
||||
("value_miss_button", "Value"), ("value1_miss_button", "Value1"),
|
||||
])
|
||||
def test_attribute_omission_buttons_and_include_missing_filter(
|
||||
qtbot, tmp_path, component_factory, snapshot_factory, button_name, attribute_name
|
||||
):
|
||||
empty = component_factory(refdes="R1", attributes=(AttributeRecord(attribute_name, "", True),))
|
||||
absent = component_factory(bridge_id="c0002", stable_uid="uid-c2", full_path="ROOT\\C2", refdes="C1")
|
||||
controller, page, paths = _controller(qtbot, tmp_path, snapshot_factory(components=(empty, absent)))
|
||||
|
||||
getattr(page, button_name).click()
|
||||
assert page.model.rowCount() == 1
|
||||
assert page.model.item(0, 1).text() == f"R1 {attribute_name}"
|
||||
page.include_missing_checkbox.setChecked(True)
|
||||
getattr(page, button_name).click()
|
||||
assert page.model.rowCount() == 2
|
||||
page.table.doubleClicked.emit(page.model.index(1, 1))
|
||||
assert paths.locate.read_text(encoding="utf-8") == "c0002\n"
|
||||
assert not paths.result.exists()
|
||||
|
||||
|
||||
def test_cross_page_empty_and_unknown_query_clear_old_results(qtbot, tmp_path, snapshot_factory):
|
||||
controller, page, paths = _controller(qtbot, tmp_path, snapshot_factory(nets=(NetRecord("N2", (1, 2)),)))
|
||||
page.net_list_button.click()
|
||||
|
||||
page.cross_page_button.click()
|
||||
assert page.model.rowCount() == 0
|
||||
assert "请输入" in page.summary_label.text()
|
||||
page.net_name_edit.setText("missing")
|
||||
page.cross_page_button.click()
|
||||
assert page.model.rowCount() == 0
|
||||
assert "missing" in page.summary_label.text()
|
||||
|
||||
|
||||
def test_missing_network_data_reports_limitation(qtbot, tmp_path, snapshot_factory):
|
||||
controller, page, paths = _controller(qtbot, tmp_path, snapshot_factory())
|
||||
|
||||
page.solitary_button.click()
|
||||
|
||||
assert page.model.rowCount() == 0
|
||||
assert "未包含网络数据" in page.summary_label.text()
|
||||
assert not paths.locate.exists()
|
||||
|
||||
|
||||
def test_inspection_actions_wait_for_a_design_snapshot(qtbot, snapshot_factory):
|
||||
page = InspectionPage()
|
||||
qtbot.addWidget(page)
|
||||
controller = InspectionController(page)
|
||||
|
||||
assert not page.solitary_button.isEnabled()
|
||||
assert not page.value_miss_button.isEnabled()
|
||||
assert not page.cross_page_button.isEnabled()
|
||||
controller.load_snapshot(snapshot_factory())
|
||||
assert page.solitary_button.isEnabled()
|
||||
assert page.value_miss_button.isEnabled()
|
||||
assert page.cross_page_button.isEnabled()
|
||||
|
||||
|
||||
def test_network_navigation_has_live_list_and_locator(qtbot, tmp_path, fixture_path, monkeypatch):
|
||||
import json
|
||||
from dx_productivity.ui.app import create_main_window
|
||||
monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "local"))
|
||||
request = tmp_path / "request.json"
|
||||
data = json.loads((fixture_path / "request-basic.json").read_text(encoding="utf-8"))
|
||||
data["nets"] = [{"name": "N1", "pages": [1]}, {"name": "N2", "pages": [1, 2]}]
|
||||
request.write_text(json.dumps(data), encoding="utf-8")
|
||||
window = create_main_window(request)
|
||||
qtbot.addWidget(window)
|
||||
|
||||
window.navigation.setCurrentRow(4)
|
||||
|
||||
page = window.pages.currentWidget()
|
||||
assert isinstance(page, InspectionPage)
|
||||
assert page.model.rowCount() == 2
|
||||
assert page.value_miss_button.isHidden()
|
||||
page.solitary_button.click()
|
||||
assert page.model.rowCount() == 1
|
||||
page.net_name_edit.setText("N2")
|
||||
page.cross_page_button.click()
|
||||
assert page.model.rowCount() == 2
|
||||
page.table.doubleClicked.emit(page.model.index(1, 1))
|
||||
assert (tmp_path / "locate.tsv").read_text(encoding="utf-8") == "net|N2|2\n"
|
||||
assert window.page_title.text() == "网络工具"
|
||||
|
||||
|
||||
def test_refresh_recomputes_the_visible_inspection(qtbot, tmp_path, snapshot_factory):
|
||||
controller, page, paths = _controller(qtbot, tmp_path, snapshot_factory(nets=(NetRecord("old", (1,)),)))
|
||||
page.net_list_button.click()
|
||||
|
||||
controller.load_snapshot(snapshot_factory(snapshot_id="new", nets=(NetRecord("new", (2,)),)))
|
||||
|
||||
assert page.model.rowCount() == 1
|
||||
assert page.model.item(0, 1).text() == "new"
|
||||
@@ -0,0 +1,44 @@
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
import threading
|
||||
|
||||
from dx_productivity.features.pdf_export.models import ExportScope, PdfExportResult, PdfExportSettings
|
||||
from dx_productivity.ui import pdf_export_controller
|
||||
from dx_productivity.ui.pdf_export_page import PdfExportPage
|
||||
|
||||
|
||||
def _snapshot(sheet_name: str):
|
||||
return SimpleNamespace(design_path='C:/Demo.prj', active_block_name='Main', current_sheet_name=sheet_name)
|
||||
|
||||
|
||||
def test_current_page_with_missing_sheet_disables_manual_and_automatic_export(qtbot, tmp_path: Path) -> None:
|
||||
page = PdfExportPage()
|
||||
qtbot.addWidget(page)
|
||||
settings = PdfExportSettings(Path('C:/Demo.prj'), ExportScope.CURRENT_PAGE, 'Main', tmp_path, auto_export=True)
|
||||
page.bind(_snapshot(''), settings)
|
||||
assert not page.export_button.isEnabled()
|
||||
assert not page.auto_export_checkbox.isEnabled()
|
||||
assert not page.auto_export_checkbox.isChecked()
|
||||
|
||||
|
||||
def test_current_page_displays_named_sheet_and_allows_export(qtbot, tmp_path: Path) -> None:
|
||||
page = PdfExportPage()
|
||||
qtbot.addWidget(page)
|
||||
settings = PdfExportSettings(Path('C:/Demo.prj'), ExportScope.CURRENT_PAGE, 'Main', tmp_path)
|
||||
page.bind(_snapshot('Digital signal'), settings)
|
||||
assert page.export_button.isEnabled()
|
||||
assert 'Digital signal' in page.active_block_label.text()
|
||||
|
||||
|
||||
def test_worker_forwards_named_sheet_to_exporter(monkeypatch, tmp_path: Path) -> None:
|
||||
captured = {}
|
||||
settings = PdfExportSettings(tmp_path / 'Demo.prj', ExportScope.CURRENT_PAGE, 'Main', tmp_path)
|
||||
|
||||
def export(settings, cancel, on_event, **kwargs):
|
||||
captured.update(kwargs)
|
||||
return PdfExportResult(settings.project_path, 'success', 'done')
|
||||
|
||||
monkeypatch.setattr(pdf_export_controller, 'export_project', export)
|
||||
worker = pdf_export_controller._ExportWorker(settings, 'Main', 'Digital signal', False, threading.Event())
|
||||
worker.run()
|
||||
assert captured['active_sheet_name'] == 'Digital signal'
|
||||
@@ -0,0 +1,230 @@
|
||||
import hashlib
|
||||
import importlib
|
||||
import json
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.bridge.protocol import load_apply_request
|
||||
from dx_productivity.bridge.run_store import RunStore
|
||||
from dx_productivity.domain.models import AttributeRecord, RunPaths
|
||||
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 PropertyVisibilityController
|
||||
from dx_productivity.ui.property_visibility_page import PropertyVisibilityPage
|
||||
|
||||
|
||||
def _controller(qtbot, tmp_path, snapshot, kind):
|
||||
paths = RunPaths(
|
||||
snapshot.run_id,
|
||||
tmp_path,
|
||||
tmp_path / "request.json",
|
||||
tmp_path / "result.tsv",
|
||||
tmp_path / "locate.tsv",
|
||||
tmp_path / "apply-status.json",
|
||||
)
|
||||
page = PropertyChangePage() if kind == "change" else PropertyVisibilityPage()
|
||||
qtbot.addWidget(page)
|
||||
controller_type = PropertyChangeController if kind == "change" else PropertyVisibilityController
|
||||
controller = controller_type(page, run_store=RunStore(tmp_path / "store"), run_paths=paths)
|
||||
controller.can_apply_changed.connect(page.set_can_apply)
|
||||
controller.load_snapshot(snapshot)
|
||||
if kind == "change":
|
||||
page.model.item(0, 2).setText("47K")
|
||||
return controller, page, paths
|
||||
|
||||
|
||||
def test_property_change_load_preserves_current_values_until_edited(
|
||||
qtbot, component_factory, snapshot_factory
|
||||
):
|
||||
page = PropertyChangePage()
|
||||
qtbot.addWidget(page)
|
||||
controller = PropertyChangeController(page)
|
||||
controller.can_apply_changed.connect(page.set_can_apply)
|
||||
component = component_factory(attributes=(AttributeRecord("Value", "10K", True),))
|
||||
|
||||
controller.load_snapshot(snapshot_factory(components=(component,)))
|
||||
|
||||
assert page.model.item(0, 1).text() == "10K"
|
||||
assert page.model.item(0, 2).text() == "10K"
|
||||
assert not controller.can_apply
|
||||
assert not page.apply_button.isEnabled()
|
||||
page.model.item(0, 2).setText("")
|
||||
assert controller.can_apply # Clearing requires an explicit edit.
|
||||
|
||||
|
||||
def test_property_switch_loads_new_current_values_without_carrying_old_edits(
|
||||
qtbot, component_factory, snapshot_factory
|
||||
):
|
||||
page = PropertyChangePage()
|
||||
qtbot.addWidget(page)
|
||||
controller = PropertyChangeController(page)
|
||||
component = component_factory(attributes=(
|
||||
AttributeRecord("Value", "10K", True),
|
||||
AttributeRecord("Value1", "5%", False),
|
||||
))
|
||||
controller.load_snapshot(snapshot_factory(components=(component,)))
|
||||
page.model.item(0, 2).setText("47K")
|
||||
|
||||
page.property_combo.setCurrentText("Value1")
|
||||
|
||||
assert page.model.item(0, 1).text() == "5%"
|
||||
assert page.model.item(0, 2).text() == "5%"
|
||||
assert not controller.can_apply
|
||||
page.model.item(0, 2).setText("1%")
|
||||
assert page.settings().overrides == (("c0001", "1%"),)
|
||||
assert controller.can_apply
|
||||
|
||||
|
||||
def test_custom_property_input_stays_available_after_switching_back(qtbot):
|
||||
page = PropertyChangePage()
|
||||
qtbot.addWidget(page)
|
||||
page.property_combo.setCurrentText("自定义…")
|
||||
page.custom_property_edit.setText("Tolerance")
|
||||
page.property_combo.setCurrentText("Value")
|
||||
|
||||
page.property_combo.setCurrentText("自定义…")
|
||||
|
||||
assert not page.custom_property_edit.isHidden()
|
||||
assert page.property_name() == "Tolerance"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind,operation,property_name,old,new", [
|
||||
("change", "property", "Value", "10K", "47K"),
|
||||
("visibility", "visibility", "Part Name", "1", "0"),
|
||||
])
|
||||
def test_property_apply_publishes_backup_metadata_and_expected_value_schedule(
|
||||
qtbot, tmp_path, component_factory, snapshot_factory,
|
||||
kind, operation, property_name, old, new
|
||||
):
|
||||
component = component_factory(attributes=(
|
||||
AttributeRecord("Value", "10K", True),
|
||||
AttributeRecord("Part Name", "RES", True),
|
||||
))
|
||||
controller, page, paths = _controller(
|
||||
qtbot, tmp_path, snapshot_factory(components=(component,)), kind
|
||||
)
|
||||
paths.apply_status.write_text('{"stale": true}', encoding="utf-8")
|
||||
|
||||
result = controller.apply()
|
||||
|
||||
assert result.read_text(encoding="utf-8") == (
|
||||
f"1\t{operation}\tc0001\t{property_name}\t{old}\t{new}\t{new}\n"
|
||||
)
|
||||
request = load_apply_request(paths.apply_request)
|
||||
assert request.schedule_sha256 == hashlib.sha256(result.read_bytes()).hexdigest()
|
||||
changes = json.loads(request.backup_path.read_text(encoding="utf-8"))["changes"]
|
||||
assert len(changes) == 1
|
||||
assert changes[0]["op"] == operation
|
||||
assert changes[0]["property"] == property_name
|
||||
assert changes[0]["old_value"] == old
|
||||
assert changes[0]["new_value"] == new
|
||||
assert not paths.apply_status.exists()
|
||||
assert not page.apply_button.isEnabled()
|
||||
with pytest.raises(RuntimeError, match="already in flight"):
|
||||
controller.apply()
|
||||
controller._status_timer.stop()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["change", "visibility"])
|
||||
def test_failed_property_transaction_can_be_retried(
|
||||
qtbot, tmp_path, component_factory, snapshot_factory, kind
|
||||
):
|
||||
component = component_factory(attributes=(
|
||||
AttributeRecord("Value", "10K", True),
|
||||
AttributeRecord("Part Name", "RES", True),
|
||||
))
|
||||
controller, page, paths = _controller(
|
||||
qtbot, tmp_path, snapshot_factory(components=(component,)), kind
|
||||
)
|
||||
controller.apply()
|
||||
controller._apply_started_at = time.monotonic() - 3600
|
||||
|
||||
with qtbot.waitSignal(controller.apply_failed):
|
||||
controller._poll_apply_status()
|
||||
|
||||
assert not controller._apply_in_flight
|
||||
assert controller.can_apply
|
||||
assert page.apply_button.isEnabled()
|
||||
assert not controller._status_timer.isActive()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["change", "visibility"])
|
||||
def test_property_schedule_write_failure_does_not_lock_future_apply(
|
||||
qtbot, tmp_path, component_factory, snapshot_factory, monkeypatch, kind
|
||||
):
|
||||
component = component_factory(attributes=(
|
||||
AttributeRecord("Value", "10K", True),
|
||||
AttributeRecord("Part Name", "RES", True),
|
||||
))
|
||||
controller, page, paths = _controller(
|
||||
qtbot, tmp_path, snapshot_factory(components=(component,)), kind
|
||||
)
|
||||
module_name = "property_change_controller" if kind == "change" else "property_visibility_controller"
|
||||
module = importlib.import_module(f"dx_productivity.ui.{module_name}")
|
||||
|
||||
def fail_write(*args):
|
||||
raise OSError("mailbox is read-only")
|
||||
|
||||
monkeypatch.setattr(module, "write_schedule", fail_write)
|
||||
with pytest.raises(OSError, match="read-only"):
|
||||
controller.apply()
|
||||
|
||||
assert not controller._apply_in_flight
|
||||
assert controller.can_apply
|
||||
assert page.apply_button.isEnabled()
|
||||
assert not controller._status_timer.isActive()
|
||||
assert not paths.result.exists()
|
||||
|
||||
|
||||
def test_visibility_preview_distinguishes_missing_from_hidden(
|
||||
qtbot, component_factory, snapshot_factory
|
||||
):
|
||||
page = PropertyVisibilityPage()
|
||||
qtbot.addWidget(page)
|
||||
controller = PropertyVisibilityController(page)
|
||||
|
||||
controller.load_snapshot(snapshot_factory(components=(component_factory(attributes=()),)))
|
||||
|
||||
assert page.model.item(0, 2).text() == "属性缺失"
|
||||
assert not controller.can_apply
|
||||
|
||||
|
||||
@pytest.mark.parametrize("property_name", ["Value", "Value1", "Part Number", "Tolerance"])
|
||||
def test_every_property_selector_uses_its_attribute_value_and_schedule(
|
||||
qtbot, tmp_path, component_factory, snapshot_factory, property_name
|
||||
):
|
||||
component = component_factory(attributes=(AttributeRecord(property_name, "original", True),))
|
||||
controller, page, paths = _controller(qtbot, tmp_path, snapshot_factory(components=(component,)), "change")
|
||||
if property_name == "Tolerance":
|
||||
page.property_combo.setCurrentText("自定义…")
|
||||
page.custom_property_edit.setText(property_name)
|
||||
else:
|
||||
page.property_combo.setCurrentText(property_name)
|
||||
assert page.model.item(0, 1).text() == "original"
|
||||
page.model.item(0, 2).setText("new")
|
||||
|
||||
controller.apply()
|
||||
|
||||
assert paths.result.read_text(encoding="utf-8") == (
|
||||
f"1\tproperty\tc0001\t{property_name}\toriginal\tnew\tnew\n"
|
||||
)
|
||||
controller._status_timer.stop()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("property_name", ["Part Name", "Part Label"])
|
||||
def test_each_visibility_property_can_be_shown_again(
|
||||
qtbot, tmp_path, component_factory, snapshot_factory, property_name
|
||||
):
|
||||
component = component_factory(attributes=(AttributeRecord(property_name, "RES", False),))
|
||||
controller, page, paths = _controller(qtbot, tmp_path, snapshot_factory(components=(component,)), "visibility")
|
||||
page.property_combo.setCurrentText(property_name)
|
||||
page.show_button.click()
|
||||
assert controller.can_apply
|
||||
|
||||
controller.apply()
|
||||
|
||||
assert paths.result.read_text(encoding="utf-8") == (
|
||||
f"1\tvisibility\tc0001\t{property_name}\t0\t1\t1\n"
|
||||
)
|
||||
controller._status_timer.stop()
|
||||
@@ -185,3 +185,22 @@ def test_missing_heartbeat_fails_transaction(
|
||||
|
||||
with qtbot.waitSignal(controller.apply_failed, timeout=5000):
|
||||
controller._poll_apply_status()
|
||||
|
||||
|
||||
def test_schedule_write_failure_does_not_lock_future_annotation(
|
||||
qtbot, tmp_path, snapshot_factory, monkeypatch
|
||||
):
|
||||
import pytest
|
||||
controller = _make_controller(qtbot, tmp_path, snapshot_factory())
|
||||
|
||||
def fail_write(*args):
|
||||
raise OSError("mailbox is read-only")
|
||||
|
||||
monkeypatch.setattr(controller_module, "write_schedule", fail_write)
|
||||
with pytest.raises(OSError, match="read-only"):
|
||||
controller.apply()
|
||||
|
||||
assert not controller._apply_in_flight
|
||||
assert controller.can_apply
|
||||
assert not controller._status_timer.isActive()
|
||||
assert not controller.run_paths.result.exists()
|
||||
@@ -95,3 +95,35 @@ def test_settings_controller_stages_update_before_install_request(qtbot, tmp_pat
|
||||
assert result.staged_zip == tmp_path / "updates" / "1.1.0.zip"
|
||||
assert controller._stage_thread is None
|
||||
assert controller.staged_path(manifest) == result.staged_zip
|
||||
|
||||
|
||||
def test_settings_save_preserves_daily_check_timestamp_for_same_source(tmp_path):
|
||||
from dx_productivity.ui.settings_controller import SettingsController
|
||||
controller = SettingsController(settings_path=tmp_path / "settings.json")
|
||||
now = datetime(2026, 10, 10, tzinfo=timezone.utc)
|
||||
controller.save_settings("file:///manifest.json", "development", True)
|
||||
controller.record_check(now=now)
|
||||
|
||||
controller.save_settings(" file:///manifest.json ", "DEVELOPMENT", True)
|
||||
|
||||
assert not controller.auto_check_due(controller.load_settings(), now=now + timedelta(hours=1))
|
||||
controller.save_settings("file:///new-manifest.json", "development", True)
|
||||
assert controller.auto_check_due(controller.load_settings(), now=now + timedelta(hours=1))
|
||||
|
||||
|
||||
def test_real_local_update_check_failure_then_retry_releases_worker(qtbot, tmp_path):
|
||||
from dx_productivity.ui.settings_controller import SettingsController
|
||||
from tests.update.test_service import write_manifest
|
||||
controller = SettingsController(current_version="1.0.0", settings_path=tmp_path / "settings.json")
|
||||
manifest = tmp_path / "manifest.json"
|
||||
manifest.write_text("{broken", encoding="utf-8")
|
||||
|
||||
with qtbot.waitSignal(controller.check_finished, timeout=3000) as failure:
|
||||
controller.check_updates(manifest.as_uri(), "stable")
|
||||
assert failure.args[0].status == "error"
|
||||
assert controller._thread is None
|
||||
write_manifest(manifest, "file:///package.zip")
|
||||
with qtbot.waitSignal(controller.check_finished, timeout=3000) as success:
|
||||
controller.check_updates(manifest.as_uri(), "stable")
|
||||
assert success.args[0].status == "available"
|
||||
assert controller._thread is None
|
||||
@@ -104,3 +104,42 @@ def test_settings_page_disables_unsigned_stable_install(qtbot):
|
||||
|
||||
assert not page.install_button.isEnabled()
|
||||
assert "签名" in page.status_label.text()
|
||||
|
||||
|
||||
def test_settings_page_ignores_download_result_for_an_earlier_update(qtbot):
|
||||
from pathlib import Path
|
||||
from dx_productivity.ui.settings_page import SettingsPage
|
||||
from dx_productivity.ui.settings_controller import UpdateStageResult
|
||||
|
||||
page = SettingsPage(current_version="1.0.0")
|
||||
qtbot.addWidget(page)
|
||||
earlier = make_manifest("1.1.0")
|
||||
page.show_update(earlier)
|
||||
page.show_update(make_manifest("1.2.0"))
|
||||
|
||||
page.show_stage_result(UpdateStageResult("ready", earlier, Path("1.1.0.zip"), "ready"))
|
||||
|
||||
assert page.install_button.text() == "准备安装"
|
||||
assert page._staged_zip is None
|
||||
|
||||
|
||||
def test_settings_page_cancelled_confirmations_emit_no_install(qtbot, monkeypatch):
|
||||
from pathlib import Path
|
||||
from dx_productivity.ui.settings_page import SettingsPage
|
||||
from dx_productivity.ui.settings_controller import UpdateStageResult
|
||||
|
||||
page = SettingsPage(current_version="1.0.0")
|
||||
qtbot.addWidget(page)
|
||||
manifest = make_manifest()
|
||||
page.show_update(manifest)
|
||||
monkeypatch.setattr(QMessageBox, "question", lambda *args, **kwargs: QMessageBox.StandardButton.No)
|
||||
page.install_button.click()
|
||||
assert page.download_requested_emissions == 0
|
||||
assert page.install_requested_emissions == 0
|
||||
monkeypatch.setattr(QMessageBox, "question", lambda *args, **kwargs: QMessageBox.StandardButton.Yes)
|
||||
page.install_button.click()
|
||||
page.show_stage_result(UpdateStageResult("ready", manifest, Path("1.1.0.zip"), "ready"))
|
||||
monkeypatch.setattr(QMessageBox, "question", lambda *args, **kwargs: QMessageBox.StandardButton.No)
|
||||
page.install_button.click()
|
||||
assert page.download_requested_emissions == 1
|
||||
assert page.install_requested_emissions == 0
|
||||
@@ -0,0 +1,40 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
from dx_productivity.ui.app import create_main_window
|
||||
|
||||
|
||||
def test_snapshot_refresh_updates_every_design_feature_and_project_label(
|
||||
qtbot, fixture_path, tmp_path, monkeypatch
|
||||
):
|
||||
monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "local"))
|
||||
request = tmp_path / "request.json"
|
||||
original = json.loads((fixture_path / "request-basic.json").read_text(encoding="utf-8"))
|
||||
request.write_text(json.dumps(original), encoding="utf-8")
|
||||
window = create_main_window(request)
|
||||
qtbot.addWidget(window)
|
||||
watcher = window.findChildren(__import__("dx_productivity.ui.app", fromlist=["_SnapshotWatcher"])._SnapshotWatcher)[0]
|
||||
original_mtime = request.stat().st_mtime
|
||||
original["snapshot_id"] = "snapshot-new"
|
||||
original["design_path"] = "C:\\Projects\\updated.prj"
|
||||
original["components"][0]["refdes"] = "R12"
|
||||
original["components"][0]["attributes"] = [{"name": "Value", "value": "47K", "visible": True}]
|
||||
request.write_text(json.dumps(original), encoding="utf-8")
|
||||
os.utime(request, (original_mtime + 2, original_mtime + 2))
|
||||
|
||||
watcher._check()
|
||||
|
||||
snapshot = window.refdes_controller.snapshot
|
||||
assert snapshot.snapshot_id == "snapshot-new"
|
||||
for controller in (
|
||||
window.property_change_controller,
|
||||
window.property_visibility_controller,
|
||||
window.inspection_controller,
|
||||
window.network_controller,
|
||||
window.bom_controller,
|
||||
window.history_controller,
|
||||
window.pdf_export_controller,
|
||||
):
|
||||
assert controller.snapshot is snapshot
|
||||
assert window.project_label.text() == "updated.prj"
|
||||
assert window.property_change_controller.page.model.item(0, 1).text() == "47K"
|
||||
@@ -0,0 +1,111 @@
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
from dx_productivity.ui import app as app_module
|
||||
from dx_productivity.ui.main_window import MainWindow
|
||||
from dx_productivity.ui.settings_controller import SettingsController
|
||||
from dx_productivity.update.models import UpdateManifest
|
||||
|
||||
|
||||
def _ready_update(tmp_path):
|
||||
package = tmp_path / "release.zip"
|
||||
with zipfile.ZipFile(package, "w") as archive:
|
||||
archive.writestr("DxDesignerTools.exe", b"new-version")
|
||||
archive.writestr("_runtime/marker.dll", b"new-runtime")
|
||||
manifest = UpdateManifest.from_mapping({
|
||||
"product": "yiyezhqiu-refactored", "version": "1.1.0", "channel": "development",
|
||||
"min_supported_version": "1.0.0", "package_url": package.as_uri(),
|
||||
"sha256": hashlib.sha256(package.read_bytes()).hexdigest(),
|
||||
"release_notes": "local regression", "published_at": "2026-10-11",
|
||||
})
|
||||
controller = SettingsController(settings_path=tmp_path / "settings.json")
|
||||
# This fixture starts at the already verified package boundary; staging
|
||||
# itself is covered by real local-file tests in tests/update.
|
||||
controller._staged_paths[str(manifest.version)] = package
|
||||
return controller, manifest
|
||||
|
||||
|
||||
def _portable(tmp_path, name):
|
||||
root = tmp_path / name
|
||||
(root / "_runtime").mkdir(parents=True)
|
||||
(root / "DxDesignerTools.exe").write_bytes(b"old-version")
|
||||
(root / "_runtime/marker.dll").write_bytes(b"old-runtime")
|
||||
return root
|
||||
|
||||
|
||||
def _launch_fixture(qtbot, tmp_path, monkeypatch):
|
||||
window = MainWindow()
|
||||
qtbot.addWidget(window)
|
||||
controller, manifest = _ready_update(tmp_path)
|
||||
monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "local"))
|
||||
monkeypatch.setattr(sys, "frozen", True, raising=False)
|
||||
# Prevent the test's shared QApplication from quitting after handoff.
|
||||
monkeypatch.setattr(app_module.QApplication, "instance", lambda: None)
|
||||
commands = []
|
||||
|
||||
def capture_spawn(command, **kwargs):
|
||||
commands.append((list(command), kwargs))
|
||||
return object()
|
||||
|
||||
monkeypatch.setattr(app_module.subprocess, "Popen", capture_spawn)
|
||||
return window, controller, manifest, commands
|
||||
|
||||
|
||||
def test_two_update_handoffs_keep_independent_install_plans(qtbot, tmp_path, monkeypatch):
|
||||
window, controller, manifest, commands = _launch_fixture(qtbot, tmp_path, monkeypatch)
|
||||
first = _portable(tmp_path, "portable-first")
|
||||
second = _portable(tmp_path, "portable-second")
|
||||
monkeypatch.setattr(sys, "executable", str(first / "DxDesignerTools.exe"))
|
||||
app_module._launch_update(window, controller, manifest)
|
||||
monkeypatch.setattr(sys, "executable", str(second / "DxDesignerTools.exe"))
|
||||
|
||||
app_module._launch_update(window, controller, manifest)
|
||||
|
||||
first_plan = Path(commands[0][0][-1])
|
||||
second_plan = Path(commands[1][0][-1])
|
||||
assert first_plan != second_plan
|
||||
assert json.loads(first_plan.read_text(encoding="utf-8"))["current_root"] == str(first)
|
||||
assert json.loads(second_plan.read_text(encoding="utf-8"))["current_root"] == str(second)
|
||||
assert not Path(commands[0][0][0]).is_relative_to(first)
|
||||
assert not Path(commands[1][0][0]).is_relative_to(second)
|
||||
|
||||
|
||||
def test_ui_update_starts_persistent_application_after_successful_smoke(qtbot, tmp_path, monkeypatch):
|
||||
from dx_productivity.update.installer import InstallPlan, UpdateInstaller
|
||||
|
||||
window, controller, manifest, commands = _launch_fixture(qtbot, tmp_path, monkeypatch)
|
||||
current = _portable(tmp_path, "portable")
|
||||
executable = str(current / "DxDesignerTools.exe")
|
||||
monkeypatch.setattr(sys, "executable", executable)
|
||||
app_module._launch_update(window, controller, manifest)
|
||||
mapping = json.loads(Path(commands[0][0][-1]).read_text(encoding="utf-8"))
|
||||
assert mapping["restart_command"] == [executable, "ui", "--smoke-test-ms", "1000"]
|
||||
assert mapping.get("launch_command") == [executable, "ui"]
|
||||
plan = InstallPlan.from_mapping(mapping)
|
||||
events = []
|
||||
|
||||
def successful_smoke(command, **kwargs):
|
||||
assert (current / "DxDesignerTools.exe").read_bytes() == b"new-version"
|
||||
events.append(("smoke", tuple(command)))
|
||||
return subprocess.CompletedProcess(command, 0)
|
||||
|
||||
def persistent_launch(command, **kwargs):
|
||||
assert events == [("smoke", (executable, "ui", "--smoke-test-ms", "1000"))]
|
||||
assert Path(kwargs["cwd"]) == current
|
||||
events.append(("launch", tuple(command)))
|
||||
return object()
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", successful_smoke)
|
||||
monkeypatch.setattr(subprocess, "Popen", persistent_launch)
|
||||
|
||||
result = UpdateInstaller().install(plan)
|
||||
|
||||
assert result.state == "installed", result.message
|
||||
assert events == [
|
||||
("smoke", (executable, "ui", "--smoke-test-ms", "1000")),
|
||||
("launch", (executable, "ui")),
|
||||
]
|
||||
@@ -1,9 +1,12 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def make_plan(tmp_path: Path, restart_probe_exit_code: int):
|
||||
from dx_productivity.update.installer import InstallPlan
|
||||
@@ -65,3 +68,58 @@ def test_install_plan_rejects_missing_staged_zip(tmp_path: Path):
|
||||
result = UpdateInstaller().install(plan)
|
||||
|
||||
assert result.state == "failed"
|
||||
|
||||
|
||||
def test_installer_accepts_release_zip_with_portable_folder(tmp_path: Path):
|
||||
"""Compress-Archive ships the complete portable folder inside the ZIP."""
|
||||
from dx_productivity.update.installer import UpdateInstaller
|
||||
|
||||
plan = make_plan(tmp_path, restart_probe_exit_code=0)
|
||||
with zipfile.ZipFile(plan.staged_zip, "w") as archive:
|
||||
archive.writestr("一叶知秋_重构版/DxDesignerTools.exe", b"new")
|
||||
archive.writestr("一叶知秋_重构版/_runtime/example.dll", b"runtime")
|
||||
|
||||
result = UpdateInstaller().install(plan)
|
||||
|
||||
assert result.state == "installed", result.message
|
||||
assert (plan.current_root / "DxDesignerTools.exe").read_bytes() == b"new"
|
||||
assert (plan.current_root / "_runtime/example.dll").read_bytes() == b"runtime"
|
||||
|
||||
|
||||
def test_prepare_updater_copies_runtime_outside_running_portable_root(tmp_path: Path):
|
||||
from dx_productivity.update.installer import prepare_updater
|
||||
|
||||
current = tmp_path / "portable"
|
||||
(current / "_runtime").mkdir(parents=True)
|
||||
(current / "DxDesignerTools.exe").write_bytes(b"exe")
|
||||
(current / "_runtime/python312.dll").write_bytes(b"runtime")
|
||||
|
||||
executable = prepare_updater(current, tmp_path / "updates")
|
||||
|
||||
assert not executable.is_relative_to(current)
|
||||
assert executable.read_bytes() == b"exe"
|
||||
assert (executable.parent / "_runtime/python312.dll").read_bytes() == b"runtime"
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != "nt", reason="Windows update mutex")
|
||||
def test_update_mutex_blocks_another_python_process(tmp_path: Path):
|
||||
from dx_productivity.update.installer import _single_instance_lock
|
||||
|
||||
script = "\n".join((
|
||||
"import sys",
|
||||
"from pathlib import Path",
|
||||
"from dx_productivity.update.installer import _single_instance_lock",
|
||||
"try:",
|
||||
" with _single_instance_lock(Path(sys.argv[1])):",
|
||||
" raise SystemExit(2)",
|
||||
"except RuntimeError:",
|
||||
" raise SystemExit(0)",
|
||||
))
|
||||
environment = os.environ.copy()
|
||||
environment["PYTHONPATH"] = str(Path(__file__).resolve().parents[2] / "src")
|
||||
with _single_instance_lock(tmp_path):
|
||||
child = subprocess.run(
|
||||
[sys.executable, "-c", script, str(tmp_path)],
|
||||
env=environment, timeout=10, capture_output=True,
|
||||
)
|
||||
assert child.returncode == 0, child.stderr
|
||||
@@ -0,0 +1,160 @@
|
||||
Option Explicit
|
||||
|
||||
Dim fso, root, stream, sheet, payload, source, fixtureExcel, tempRoot, statusText
|
||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||
root = fso.GetAbsolutePathName(fso.BuildPath( _
|
||||
fso.GetParentFolderName(WScript.ScriptFullName), "..\.."))
|
||||
Set stream = fso.OpenTextFile(root & _
|
||||
"\integration\dxdesigner795\BridgeCommon.vbs", 1, False, 0)
|
||||
ExecuteGlobal stream.ReadAll
|
||||
stream.Close
|
||||
Set stream = fso.OpenTextFile(root & _
|
||||
"\integration\dxdesigner795\core\BomExport.vbs", 1, False, 0)
|
||||
source = stream.ReadAll
|
||||
source = Replace(source, "Set excel = CreateObject(""Excel.Application"")", _
|
||||
"Set excel = fixtureExcel")
|
||||
ExecuteGlobal source
|
||||
stream.Close
|
||||
|
||||
payload = "{""records"":""" & DxToolsJson( _
|
||||
"S|1" & vbLf & _
|
||||
"R|2|R1,R2|410000010300|10K|D" & vbLf & _
|
||||
"R|1|R1|410000010A20|4.7R|DM" & vbLf & _
|
||||
"S|2" & vbLf & _
|
||||
"R|1|C1|430000010400|100N|") & """}"
|
||||
Set sheet = New TestSheet
|
||||
Call DxBomWriteSections(Nothing, sheet, payload)
|
||||
Call AssertEqual(sheet.Cells(2, 1).Value, "1", "first section")
|
||||
Call AssertEqual(sheet.Cells(2, 1).Font.Bold, True, "section bold")
|
||||
Call AssertEqual(sheet.Cells(3, 2).Value, 2, "merged quantity")
|
||||
Call AssertEqual(sheet.Cells(3, 3).Value, "R1,R2", "merged refdes")
|
||||
Call AssertEqual(sheet.Cells(3, 4).Value, "'410000010300", "part number text")
|
||||
Call AssertEqual(sheet.Cells(3, 3).Interior.ColorIndex, 3, "duplicate refdes red")
|
||||
Call AssertEqual(sheet.Cells(4, 4).Interior.ColorIndex, 44, "mismatch orange")
|
||||
Call AssertEqual(sheet.Cells(5, 1).Value, "2", "second section")
|
||||
Call AssertEqual(sheet.Cells(6, 3).Value, "C1", "second section row")
|
||||
WScript.Echo "BOM export payload assertions passed"
|
||||
tempRoot = fso.BuildPath(fso.GetSpecialFolder(2), fso.GetTempName)
|
||||
fso.CreateFolder tempRoot
|
||||
Call DxToolsWriteUtf8Atomic(tempRoot & "\bom-export.json", _
|
||||
"{""template_path"":""missing-template.xls""," & _
|
||||
"""output_path"":""output.xlsx""," & _
|
||||
"""design_name"":""Fixture""," & _
|
||||
"""description_header"":""VALUE""," & _
|
||||
"""records"":""S|1""}")
|
||||
Set fixtureExcel = New TestFailureExcel
|
||||
Call DxBridgeRenderBom(tempRoot, tempRoot & "\bom-export.json")
|
||||
statusText = DxToolsReadUtf8(tempRoot & "\bom-export-status.json")
|
||||
If InStr(statusText, """state"": ""failed""") = 0 Then
|
||||
WScript.Echo "FAIL missing-template failure status: " & statusText
|
||||
WScript.Quit 1
|
||||
End If
|
||||
Call AssertEqual(fixtureExcel.QuitCount, 1, "owned Excel quit after failure")
|
||||
Set fixtureExcel = New TestFailureExcel
|
||||
fixtureExcel.Workbooks.FailOpen = False
|
||||
Call DxBridgeRenderBom(tempRoot, tempRoot & "\bom-export.json")
|
||||
statusText = DxToolsReadUtf8(tempRoot & "\bom-export-status.json")
|
||||
If InStr(statusText, "fixture save failed") = 0 Then
|
||||
WScript.Echo "FAIL save failure status: " & statusText
|
||||
WScript.Quit 1
|
||||
End If
|
||||
Call AssertEqual(fixtureExcel.Workbooks.Book.CloseCount, 1, _
|
||||
"only owned workbook closed after save failure")
|
||||
Call AssertEqual(fixtureExcel.Workbooks.Book.SavedOnClose, False, _
|
||||
"failed workbook discarded")
|
||||
Call AssertEqual(fixtureExcel.QuitCount, 1, "owned Excel quit after save failure")
|
||||
fso.DeleteFile tempRoot & "\bom-export.json"
|
||||
fso.DeleteFile tempRoot & "\bom-export-status.json"
|
||||
fso.DeleteFolder tempRoot
|
||||
WScript.Echo "BOM failure cleanup assertions passed"
|
||||
|
||||
Sub AssertEqual(actualValue, expectedValue, label)
|
||||
If CStr(actualValue) <> CStr(expectedValue) Then
|
||||
WScript.Echo "FAIL " & label & ": expected [" & _
|
||||
CStr(expectedValue) & "] got [" & CStr(actualValue) & "]"
|
||||
WScript.Quit 1
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Class TestFormat
|
||||
Public ColorIndex
|
||||
Public Bold
|
||||
End Class
|
||||
|
||||
Class TestFailureWorkbooks
|
||||
Public FailOpen
|
||||
Public Book
|
||||
Private Sub Class_Initialize()
|
||||
FailOpen = True
|
||||
Set Book = New TestFailureWorkbook
|
||||
End Sub
|
||||
Public Function Open(path, links, readOnly)
|
||||
If FailOpen Then
|
||||
Err.Raise vbObjectError + 842, "Fixture", "fixture template missing"
|
||||
Else
|
||||
Set Open = Book
|
||||
End If
|
||||
End Function
|
||||
End Class
|
||||
|
||||
Class TestFailureWorkbook
|
||||
Public Sheet
|
||||
Public CloseCount
|
||||
Public SavedOnClose
|
||||
Private Sub Class_Initialize()
|
||||
Set Sheet = New TestSheet
|
||||
CloseCount = 0
|
||||
SavedOnClose = True
|
||||
End Sub
|
||||
Public Property Get Sheets(name)
|
||||
Set Sheets = Sheet
|
||||
End Property
|
||||
Public Sub SaveAs(path, saveFormat)
|
||||
Err.Raise vbObjectError + 845, "Fixture", "fixture save failed"
|
||||
End Sub
|
||||
Public Sub Close(saveChanges)
|
||||
CloseCount = CloseCount + 1
|
||||
SavedOnClose = saveChanges
|
||||
End Sub
|
||||
End Class
|
||||
|
||||
Class TestFailureExcel
|
||||
Public Visible
|
||||
Public DisplayAlerts
|
||||
Public Workbooks
|
||||
Public QuitCount
|
||||
Private Sub Class_Initialize()
|
||||
Set Workbooks = New TestFailureWorkbooks
|
||||
QuitCount = 0
|
||||
End Sub
|
||||
Public Sub Quit()
|
||||
QuitCount = QuitCount + 1
|
||||
End Sub
|
||||
End Class
|
||||
|
||||
Class TestCell
|
||||
Public Value
|
||||
Public Interior
|
||||
Public Font
|
||||
Private Sub Class_Initialize()
|
||||
Value = ""
|
||||
Set Interior = New TestFormat
|
||||
Set Font = New TestFormat
|
||||
End Sub
|
||||
End Class
|
||||
|
||||
Class TestSheet
|
||||
Private cellMap
|
||||
Private Sub Class_Initialize()
|
||||
Set cellMap = CreateObject("Scripting.Dictionary")
|
||||
End Sub
|
||||
Public Property Get Cells(row, column)
|
||||
Dim key, cell
|
||||
key = CStr(row) & ":" & CStr(column)
|
||||
If Not cellMap.Exists(key) Then
|
||||
Set cell = New TestCell
|
||||
cellMap.Add key, cell
|
||||
End If
|
||||
Set Cells = cellMap(key)
|
||||
End Property
|
||||
End Class
|
||||
@@ -0,0 +1,244 @@
|
||||
Option Explicit
|
||||
|
||||
Const epcbFabAll = 0
|
||||
Const epcbSelectAll = 0
|
||||
Const epcbSideTopOrBottom = 2
|
||||
Const epcbFabAssembly = 4
|
||||
Const epcbJustifyVCenter = 1
|
||||
Const epcbJustifyHCenter = 1
|
||||
Const epcbUnitMM = 2
|
||||
Const epcbAngleUnitDegrees = 1
|
||||
Dim fso, root, stream, docObj, fabtxt, request, Scripting, tempRoot, fixturePath, parsed, Application, ScriptEngine, targetText
|
||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||
root = fso.GetAbsolutePathName(fso.BuildPath( _
|
||||
fso.GetParentFolderName(WScript.ScriptFullName), "..\.."))
|
||||
Set stream = fso.OpenTextFile(root & _
|
||||
"\integration\dxdesigner795\expedition\ExpeditionBridge.vbs", 1, False, 0)
|
||||
ExecuteGlobal stream.ReadAll
|
||||
stream.Close
|
||||
|
||||
Set docObj = New TestDocument
|
||||
Set fabtxt = New TestFabText
|
||||
Set fabtxt.Component = Nothing
|
||||
fabtxt.TextType = 1
|
||||
fabtxt.Side = 1
|
||||
fabtxt.FabType = epcbFabAssembly
|
||||
fabtxt.TextString = "BOARD NOTE"
|
||||
docObj.Texts.Add fabtxt
|
||||
request = DxEpExportRequest(docObj)
|
||||
If request <> "T|0|1|1|1|BOARD NOTE||" & vbCrLf & vbCrLf Then
|
||||
WScript.Echo "FAIL exported assembly classification: " & request
|
||||
WScript.Quit 1
|
||||
End If
|
||||
WScript.Echo "Expedition request assertions passed"
|
||||
If DxEpQuote("C:\PCB Tool\tools.exe") <> Chr(34) & _
|
||||
"C:\PCB Tool\tools.exe" & Chr(34) Then
|
||||
WScript.Echo "FAIL standalone command quoting"
|
||||
WScript.Quit 1
|
||||
End If
|
||||
If DxEpQuote("C:\PCB Tool\") <> Chr(34) & _
|
||||
"C:\PCB Tool\\" & Chr(34) Then
|
||||
WScript.Echo "FAIL trailing command backslash quoting"
|
||||
WScript.Quit 1
|
||||
End If
|
||||
WScript.Echo "Expedition standalone quoting assertions passed"
|
||||
Set targetText = New TestMoveText
|
||||
Call DxEpApplyLine("MOVE|0|10|20|90||Arial", targetText)
|
||||
If targetText.MoveCount <> 0 Then
|
||||
WScript.Echo "FAIL nonassembly cardinal text position must be preserved"
|
||||
WScript.Quit 1
|
||||
End If
|
||||
If targetText.Format.Rotation <> 90 Or targetText.Format.Font <> "Arial" Then
|
||||
WScript.Echo "FAIL format-only refdes update"
|
||||
WScript.Quit 1
|
||||
End If
|
||||
Call DxEpApplyLine("MOVE|0|10|20|90|0.4|Arial", targetText)
|
||||
If targetText.MoveCount <> 1 Or targetText.X <> 10 Or targetText.Y <> 20 Then
|
||||
WScript.Echo "FAIL assembly refdes movement"
|
||||
WScript.Quit 1
|
||||
End If
|
||||
WScript.Echo "Expedition legacy position parity assertions passed"
|
||||
tempRoot = fso.BuildPath(fso.GetSpecialFolder(2), fso.GetTempName)
|
||||
fso.CreateFolder tempRoot
|
||||
fso.CreateFolder tempRoot & "\expedition"
|
||||
Set stream = fso.CreateTextFile(tempRoot & "\DxDesignerTools.exe", True)
|
||||
stream.Close
|
||||
Set stream = fso.CreateTextFile(tempRoot & "\expedition\ExpeditionBridge.vbs", True)
|
||||
stream.Close
|
||||
Set Scripting = New TestScripting
|
||||
Scripting.CurrentScriptFullName = tempRoot & "\expedition\ExpeditionBridge.vbs"
|
||||
If DxEpResolveRoot() <> tempRoot Then
|
||||
WScript.Echo "FAIL native CurrentScriptFullName root fallback"
|
||||
WScript.Quit 1
|
||||
End If
|
||||
fixturePath = tempRoot & "\startup.json"
|
||||
Set stream = fso.CreateTextFile(fixturePath, True)
|
||||
stream.Write "{""tool_root"":""" & Replace(tempRoot, Chr(92), _
|
||||
Chr(92) & Chr(92)) & """}"
|
||||
stream.Close
|
||||
If DxEpStartupRootFromFile(fixturePath) <> tempRoot Then
|
||||
WScript.Echo "FAIL persisted Start registration root"
|
||||
WScript.Quit 1
|
||||
End If
|
||||
If Not DxEpJsonString("{""tool_root"":""C:\\" & _
|
||||
"\u5DE5\u5177\\a\""b""}", "tool_root", parsed) Then
|
||||
WScript.Echo "FAIL escaped registration JSON"
|
||||
WScript.Quit 1
|
||||
End If
|
||||
If parsed <> "C:\" & ChrW(&H5DE5) & ChrW(&H5177) & "\a" & Chr(34) & "b" Then
|
||||
WScript.Echo "FAIL escaped registration value"
|
||||
WScript.Quit 1
|
||||
End If
|
||||
Set Application = New TestApplication
|
||||
ScriptEngine = "fixture-script-engine"
|
||||
Call DxEpInitialize()
|
||||
If Application.Gui.Bar.Controls.Count <> 1 Then
|
||||
WScript.Echo "FAIL native menu installation"
|
||||
WScript.Quit 1
|
||||
End If
|
||||
If Scripting.DontExit <> True Then
|
||||
WScript.Echo "FAIL native callback script lifetime"
|
||||
WScript.Quit 1
|
||||
End If
|
||||
If Application.Gui.Bar.Controls.Item(1).Controls.Button.ExecuteMethod <> _
|
||||
"DxEpAssemblyMenuCommand" Then
|
||||
WScript.Echo "FAIL assembly callback registration"
|
||||
WScript.Quit 1
|
||||
End If
|
||||
If Application.Gui.Bar.Controls.Item(1).Controls.Button.Target <> ScriptEngine Then
|
||||
WScript.Echo "FAIL callback target must be the native script engine"
|
||||
WScript.Quit 1
|
||||
End If
|
||||
fso.DeleteFile tempRoot & "\expedition\ExpeditionBridge.vbs"
|
||||
If DxEpStartupRootFromFile(fixturePath) <> "" Then
|
||||
WScript.Echo "FAIL stale registration without Expedition script"
|
||||
WScript.Quit 1
|
||||
End If
|
||||
fso.DeleteFile fixturePath
|
||||
fso.DeleteFile tempRoot & "\DxDesignerTools.exe"
|
||||
fso.DeleteFolder tempRoot & "\expedition"
|
||||
fso.DeleteFolder tempRoot
|
||||
WScript.Echo "Expedition native root assertions passed"
|
||||
WScript.Echo "Expedition persisted registration assertions passed"
|
||||
WScript.Echo "Expedition native menu assertions passed"
|
||||
|
||||
Class TestFabText
|
||||
Public Component
|
||||
Public TextType
|
||||
Public Side
|
||||
Public FabType
|
||||
Public Property Get [Type]()
|
||||
[Type] = FabType
|
||||
End Property
|
||||
Public TextString
|
||||
End Class
|
||||
|
||||
Class TestDocument
|
||||
Public Texts
|
||||
Private Sub Class_Initialize()
|
||||
Set Texts = CreateObject("System.Collections.ArrayList")
|
||||
End Sub
|
||||
Public Function FabricationLayerTexts(fabType, selection, side, selected)
|
||||
Set FabricationLayerTexts = Texts
|
||||
End Function
|
||||
End Class
|
||||
|
||||
Class TestScripting
|
||||
Public CurrentScriptFullName
|
||||
Public DontExit
|
||||
End Class
|
||||
|
||||
Class TestApplication
|
||||
Public Gui
|
||||
Private Sub Class_Initialize()
|
||||
Set Gui = New TestGui
|
||||
End Sub
|
||||
End Class
|
||||
|
||||
Class TestGui
|
||||
Public Bar
|
||||
Private Sub Class_Initialize()
|
||||
Set Bar = New TestMenuBar
|
||||
End Sub
|
||||
Public Property Get CommandBars(name)
|
||||
If name <> "Document Menu Bar" Then Err.Raise 5
|
||||
Set CommandBars = Bar
|
||||
End Property
|
||||
End Class
|
||||
|
||||
Class TestMenuBar
|
||||
Public Controls
|
||||
Private Sub Class_Initialize()
|
||||
Set Controls = New TestPopupControls
|
||||
End Sub
|
||||
End Class
|
||||
|
||||
Class TestPopupControls
|
||||
Public Count
|
||||
Private Popup
|
||||
Private Sub Class_Initialize()
|
||||
Count = 0
|
||||
End Sub
|
||||
Public Function Add(kind)
|
||||
If kind <> 1 Then Err.Raise 5, "Fixture", "cmdControlPopup must be 1"
|
||||
Set Popup = New TestPopup
|
||||
Count = Count + 1
|
||||
Set Add = Popup
|
||||
End Function
|
||||
Public Property Get Item(index)
|
||||
Set Item = Popup
|
||||
End Property
|
||||
End Class
|
||||
|
||||
Class TestPopup
|
||||
Public Caption
|
||||
Public Controls
|
||||
Private Sub Class_Initialize()
|
||||
Set Controls = New TestButtonControls
|
||||
End Sub
|
||||
End Class
|
||||
|
||||
Class TestButtonControls
|
||||
Public Button
|
||||
Public Function Add()
|
||||
Set Button = New TestButton
|
||||
Set Add = Button
|
||||
End Function
|
||||
End Class
|
||||
|
||||
Class TestButton
|
||||
Public Caption
|
||||
Public OnAction
|
||||
Public Target
|
||||
Public ExecuteMethod
|
||||
End Class
|
||||
|
||||
Class TestMoveText
|
||||
Public Format
|
||||
Public MoveCount
|
||||
Public X
|
||||
Public Y
|
||||
Private Sub Class_Initialize()
|
||||
Set Format = New TestTextFormat
|
||||
MoveCount = 0
|
||||
End Sub
|
||||
Public Sub Move(newX, newY)
|
||||
MoveCount = MoveCount + 1
|
||||
X = newX
|
||||
Y = newY
|
||||
End Sub
|
||||
End Class
|
||||
|
||||
Class TestTextFormat
|
||||
Public VerticalJust
|
||||
Public HorizontalJust
|
||||
Public Font
|
||||
Public Rotation
|
||||
Public Size
|
||||
Public Property Let Orientation(unit, value)
|
||||
Rotation = value
|
||||
End Property
|
||||
Public Property Let Height(unit, value)
|
||||
Size = value
|
||||
End Property
|
||||
End Class
|
||||
@@ -72,6 +72,9 @@ Class FakeComponent
|
||||
Private CurrentRefdes
|
||||
Public FailTarget
|
||||
Public Attributes
|
||||
Public Function FindAttribute(name)
|
||||
Set FindAttribute = Attributes.Item(name)
|
||||
End Function
|
||||
|
||||
Public Property Get Refdes()
|
||||
Refdes = CurrentRefdes
|
||||
@@ -120,10 +123,12 @@ Component.Initialize "R?"
|
||||
ObjectMap.Add "c000001", Component
|
||||
|
||||
Call WriteTransaction(TempRoot, "refdes", "", "R?", "R1")
|
||||
Fso.MoveFile Fso.BuildPath(TempRoot, "result.tsv"), Fso.BuildPath(TempRoot, "result.processing")
|
||||
State = DxProcessApply(TempRoot, "run-vbs", "snapshot-vbs", _
|
||||
ObjectMap, OriginalsMap)
|
||||
Call AssertEqual(State, "applied", "successful state")
|
||||
Call AssertEqual(Component.Refdes, "R1", "successful refdes")
|
||||
Fso.DeleteFile Fso.BuildPath(TempRoot, "result.processing"), True
|
||||
Call AssertContains(DxToolsReadUtf8(Fso.BuildPath( _
|
||||
TempRoot, "apply-status.json")), """state"": ""applied""", _
|
||||
"successful status")
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
Option Explicit
|
||||
|
||||
Const VDM_COMP = 1
|
||||
Const VD_SELECTED = 2
|
||||
Const VDM_COMP = 128
|
||||
Const VDM_NET = 32
|
||||
Const VD_SELECTED = 1
|
||||
Const SHORT_NAME = 3
|
||||
|
||||
Dim Fso
|
||||
@@ -22,14 +23,21 @@ Dim RequestText
|
||||
Class FakeParentBlock
|
||||
Public Name
|
||||
Public SheetNum
|
||||
Public Function GetName(kind)
|
||||
GetName = "ROOT"
|
||||
End Function
|
||||
End Class
|
||||
|
||||
Class FakeLocation
|
||||
Public X
|
||||
Public Y
|
||||
End Class
|
||||
|
||||
Class FakeComponent
|
||||
Public Refdes
|
||||
Public UID
|
||||
Public Parent
|
||||
Public X
|
||||
Public Y
|
||||
Public Location
|
||||
Public PartNumber
|
||||
Public Value
|
||||
Public ComponentName
|
||||
@@ -37,6 +45,9 @@ Class FakeComponent
|
||||
Public Function GetName(kind)
|
||||
GetName = ComponentName
|
||||
End Function
|
||||
Public Function GetLocation()
|
||||
Set GetLocation = Location
|
||||
End Function
|
||||
End Class
|
||||
|
||||
Class FakeDesignNames
|
||||
@@ -46,6 +57,9 @@ Class FakeDesignNames
|
||||
End Class
|
||||
|
||||
Class FakeProjectData
|
||||
Public Function GetProjectFilePath()
|
||||
GetProjectFilePath = "C:\Projects\board.prj"
|
||||
End Function
|
||||
Public Function GetiCDBDesigns()
|
||||
Set GetiCDBDesigns = New FakeDesignNames
|
||||
End Function
|
||||
@@ -68,10 +82,18 @@ Class FakeApplicationHost
|
||||
Set values(0) = TheComponent
|
||||
DesignComponents = values
|
||||
End Function
|
||||
Public Function QueryPages(name)
|
||||
Dim values(0)
|
||||
Set values(0) = TheComponent.Parent
|
||||
QueryPages = values
|
||||
End Function
|
||||
End Class
|
||||
|
||||
Class FakeBlock
|
||||
Public SheetNum
|
||||
Public Function GetName(kind)
|
||||
GetName = "ROOT"
|
||||
End Function
|
||||
End Class
|
||||
|
||||
Class FakeActiveView
|
||||
@@ -79,6 +101,10 @@ Class FakeActiveView
|
||||
Public Block
|
||||
|
||||
Public Function Query(a, b)
|
||||
If a = VDM_NET Then
|
||||
Query = Array()
|
||||
Exit Function
|
||||
End If
|
||||
Dim values(0)
|
||||
Set values(0) = TheComponent
|
||||
Query = values
|
||||
@@ -100,13 +126,14 @@ Shell.Environment("PROCESS")("LOCALAPPDATA") = TempRoot
|
||||
|
||||
Set ParentBlock = New FakeParentBlock
|
||||
ParentBlock.Name = "ROOT"
|
||||
ParentBlock.SheetNum = 3
|
||||
ParentBlock.SheetNum = "Named main"
|
||||
Set Component = New FakeComponent
|
||||
Component.Refdes = "R?"
|
||||
Component.UID = "uid-1"
|
||||
Set Component.Parent = ParentBlock
|
||||
Component.X = 12.5
|
||||
Component.Y = 42.25
|
||||
Set Component.Location = New FakeLocation
|
||||
Component.Location.X = 12.5
|
||||
Component.Location.Y = 42.25
|
||||
Component.PartNumber = "PN-1"
|
||||
Component.Value = "10K"
|
||||
Component.ComponentName = "R1"
|
||||
@@ -117,7 +144,7 @@ Application.ProjectPath = "C:\Projects\board.prj"
|
||||
Set ActiveView = New FakeActiveView
|
||||
Set ActiveView.TheComponent = Component
|
||||
Set ActiveView.Block = New FakeBlock
|
||||
ActiveView.Block.SheetNum = 3
|
||||
ActiveView.Block.SheetNum = "Named main"
|
||||
|
||||
Set ObjectMap = CreateObject("Scripting.Dictionary")
|
||||
Set OriginalMap = CreateObject("Scripting.Dictionary")
|
||||
@@ -130,7 +157,9 @@ Call AssertEqual(ObjectMap.Count, 1, "object count")
|
||||
RequestText = DxToolsReadUtf8(Fso.BuildPath(RunRoot, "request.json"))
|
||||
Call AssertContains(RequestText, """bridge_id"": ""c000001""", "bridge id")
|
||||
Call AssertContains(RequestText, """stable_uid"": ""uid-1""", "stable uid")
|
||||
Call AssertContains(RequestText, """sheet_number"": 3", "sheet number")
|
||||
Call AssertContains(RequestText, """sheet_number"": 1", "sheet number")
|
||||
Call AssertContains(RequestText, """sheet_name"": ""Named main""", "raw named sheet")
|
||||
Call AssertContains(RequestText, """current_sheet_name"": ""Named main""", "active named sheet")
|
||||
Call AssertContains(RequestText, """selected"": true", "selected")
|
||||
Call AssertContains(RequestText, """current_sheet"": true", "current sheet")
|
||||
Call AssertContains(RequestText, """x"": ""12.5""", "x coordinate")
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Verify the packaged native listener against the restored PDF test copy."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from pypdf import PdfReader
|
||||
|
||||
|
||||
def wait_for(predicate, seconds=60):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
result = predicate()
|
||||
if result:
|
||||
return result
|
||||
time.sleep(0.25)
|
||||
raise TimeoutError("Packaged listener did not produce the expected evidence")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("executable", type=Path)
|
||||
parser.add_argument("--name", default="pdf-frozen")
|
||||
options = parser.parse_args()
|
||||
base = Path(os.environ["LOCALAPPDATA"]) / "DxProductivity/acceptance/native-20261010"
|
||||
settings = base / f"{options.name}-settings.json"
|
||||
if settings.exists():
|
||||
raise SystemExit("Frozen acceptance already exists; retain previous evidence")
|
||||
data = json.loads((base / "pdf-native-auto.json").read_text(encoding="utf-8"))
|
||||
data.update(auto_export=True, output_dir=str(base / f"{options.name}-output"))
|
||||
settings.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
environment = os.environ.copy()
|
||||
# The portable Python runtime is self-contained; sch2pdf still needs the
|
||||
# DLL folders belonging to the installed Mentor engine.
|
||||
native_paths = [part for part in os.environ.get("PATH", "").split(";") if "mentor" in part.casefold()]
|
||||
environment["PATH"] = ";".join([*native_paths, r"C:\Windows\System32", r"C:\Windows"])
|
||||
environment.pop("PYTHONPATH", None)
|
||||
environment.pop("PYTHONHOME", None)
|
||||
command = [str(options.executable.resolve()), "pdf-export-listen", "--settings", str(settings)]
|
||||
process = subprocess.Popen(command, env=environment, cwd=options.executable.parent)
|
||||
state = settings.with_name(settings.name + ".listener-state.json")
|
||||
log = settings.with_name(settings.name + ".listener.log")
|
||||
|
||||
def events():
|
||||
if not log.exists():
|
||||
return []
|
||||
return [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines() if line]
|
||||
|
||||
def listening():
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError(f"Listener exited {process.returncode}: {events()}")
|
||||
if state.exists():
|
||||
return json.loads(state.read_text(encoding="utf-8")).get("state") == "listening"
|
||||
|
||||
def completed(count):
|
||||
records = [item for item in events() if item["event"] == "export-completed"]
|
||||
if len(records) >= count:
|
||||
if records[-1]["returncode"] != 0:
|
||||
raise RuntimeError(f"Frozen export failed: {events()}")
|
||||
return records
|
||||
return False
|
||||
|
||||
helper = Path(__file__).with_name("run_dx_script.py")
|
||||
|
||||
def run(script):
|
||||
subprocess.run([sys.executable, str(helper), "--project", data["project_path"], str(script)], check=True, timeout=30)
|
||||
|
||||
changed = False
|
||||
try:
|
||||
wait_for(listening, 30)
|
||||
print(f"FROZEN_LISTENING pid={process.pid}", flush=True)
|
||||
change = base / "pdf-frozen-change-value.vbs"
|
||||
restore = base / "pdf-frozen-restore-value.vbs"
|
||||
for source, target in (("pdf-native-change-value.vbs", change), ("pdf-native-restore-value.vbs", restore)):
|
||||
text = (base / source).read_text(encoding="ascii")
|
||||
text = text.replace("pdf-native-old-value.txt", "pdf-frozen-old-value.txt").replace("_PDF_NATIVE_ON", "_PDF_FROZEN_ON")
|
||||
target.write_text(text, encoding="ascii")
|
||||
run(change)
|
||||
changed = True
|
||||
wait_for(lambda: completed(1))
|
||||
pdfs = tuple(Path(data["output_dir"]).glob("*.pdf"))
|
||||
assert len(pdfs) == 1, pdfs
|
||||
pdf = PdfReader(pdfs[0])
|
||||
assert len(pdf.pages) == 1
|
||||
assert "IC/D2128_PDF_FROZEN_ON" in pdf.pages[0].extract_text()
|
||||
shutil.copy2(pdfs[0], base / "pdf-frozen-enabled-value.pdf")
|
||||
print("FROZEN_PDF_CHANGED_VALUE_CONFIRMED", flush=True)
|
||||
run(restore)
|
||||
changed = False
|
||||
wait_for(lambda: completed(2))
|
||||
assert "_PDF_FROZEN_ON" not in PdfReader(pdfs[0]).pages[0].extract_text()
|
||||
result = {"executable": str(options.executable.resolve()), "listener_pid": process.pid,
|
||||
"state": "passed", "native_binding": json.loads(state.read_text(encoding="utf-8")),
|
||||
"pages": 1, "changed_value_in_pdf": True, "restored_value_confirmed": True,
|
||||
"completed": completed(2), "python_on_path": False}
|
||||
finally:
|
||||
if changed:
|
||||
run(restore)
|
||||
data["auto_export"] = False
|
||||
settings.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
process.wait(timeout=15)
|
||||
result["listener_exit_code"] = process.returncode
|
||||
assert process.returncode == 0
|
||||
(base / f"{options.name}-acceptance.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print("PASS FROZEN PDF NATIVE ACCEPTANCE", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,443 @@
|
||||
"""Plan and verify real DxDesigner acceptance operations; never attaches to COM.
|
||||
|
||||
Only run rendered scripts through run_dx_script.py --pid 81576. The VBS
|
||||
checks the acceptance project before selecting or changing native objects.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from dataclasses import asdict, replace
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(REPO / "src"))
|
||||
|
||||
from dx_productivity.bridge.protocol import atomic_write_text, load_apply_status, load_request, schedule_sha256, write_apply_request, write_schedule
|
||||
from dx_productivity.bridge.run_store import RunStore
|
||||
from dx_productivity.domain.models import AnnotationPlan, AnnotationSettings, ApplyRequest, HistoryEntry, OpType, PlanRow, ProcessingMode, Scope
|
||||
from dx_productivity.domain.planner import build_annotation_plan
|
||||
from dx_productivity.domain.restore import build_restore_plan
|
||||
from dx_productivity.domain.schedule import build_apply_schedule
|
||||
from dx_productivity.features.property_change import PropertyChangeSettings, build_property_change_plan
|
||||
from dx_productivity.features.property_visibility import PropertyVisibilitySettings, build_property_visibility_plan
|
||||
from dx_productivity.features.inspection import missing_attribute_values, net_list, solitary_nets, net_cross_page
|
||||
|
||||
BASE = Path(r"C:\Users\ABS_Windows\AppData\Local\DxProductivity\acceptance\native-20261010\native-feature-tests")
|
||||
MAILBOX = BASE / "mailbox"
|
||||
CAP = "$5I2744"
|
||||
INDUCTOR = "$5I2942"
|
||||
GRAPHIC = "$5I2738"
|
||||
OTHER_CAP = "$5I2745"
|
||||
|
||||
|
||||
def dump(path, data):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(data, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
|
||||
|
||||
|
||||
def vbs(value):
|
||||
chunks, current = [], ""
|
||||
for char in str(value):
|
||||
if ord(char) < 128:
|
||||
current += char
|
||||
else:
|
||||
if current:
|
||||
chunks.append('"' + current.replace('"', '""') + '"')
|
||||
current = ""
|
||||
code = ord(char) if ord(char) < 32768 else ord(char) - 65536
|
||||
chunks.append(f"ChrW({code})")
|
||||
if current or not chunks:
|
||||
chunks.append('"' + current.replace('"', '""') + '"')
|
||||
return " & ".join(chunks)
|
||||
|
||||
|
||||
def render(case):
|
||||
case_dir = BASE / case
|
||||
case_dir.mkdir(parents=True, exist_ok=True)
|
||||
MAILBOX.mkdir(parents=True, exist_ok=True)
|
||||
for name in ("host-trace.txt", "apply-status.json", "claimed-schedule.tsv", "verified.json", "verify-error.txt", "stage-error.txt", "after.json"):
|
||||
(case_dir / name).unlink(missing_ok=True)
|
||||
core = REPO / "integration" / "dxdesigner795"
|
||||
source = '\n'.join((core / path).read_text(encoding="utf-8") for path in (
|
||||
"BridgeCommon.vbs", "core/Snapshot.vbs", "core/Transaction.vbs", "core/Mailbox.vbs",
|
||||
))
|
||||
if case == "locate":
|
||||
source = source.replace('If InStr(bridgeId, "net|") = 1 Then',
|
||||
'nTrace = nTrace & "LOCATE_REQUEST=" & bridgeId & " map=" & CStr(objectMap.Exists(bridgeId)) & vbLf\n If InStr(bridgeId, "net|") = 1 Then')
|
||||
source = source.replace('Sub DxBridgeLocateComponent(component)\n',
|
||||
'Sub DxBridgeLocateComponent(component)\n nTrace = nTrace & "LOCATOR_ARG_TYPE=" & TypeName(component) & vbLf\n')
|
||||
source = source.replace('targetUid = CStr(component.UID)',
|
||||
'targetUid = CStr(component.UID)\n nTrace = nTrace & "LOCATOR_UID=" & targetUid & " err=" & CStr(Err.Number) & " " & Err.Description & vbLf')
|
||||
source = source.replace('visibleComponent.Selected = True',
|
||||
'visibleComponent.Selected = True\n nTrace = nTrace & "SET_VISIBLE_COMPONENT=" & CStr(visibleComponent.UID) & " err=" & CStr(Err.Number) & " " & Err.Description & vbLf')
|
||||
command = f'"{sys.executable}" "{Path(__file__).resolve()}" stage {case}'
|
||||
check = f'"{sys.executable}" "{Path(__file__).resolve()}" verify {case}'
|
||||
if case == "cycle" or case == "restore-cycle":
|
||||
selected = (CAP, OTHER_CAP)
|
||||
elif case.startswith("refdes") or case.startswith("restore-refdes"):
|
||||
selected = (CAP, INDUCTOR)
|
||||
else:
|
||||
selected = (CAP, INDUCTOR, GRAPHIC)
|
||||
matches = " Or ".join(f"CStr(nComp.UID) = {vbs(uid)}" for uid in selected)
|
||||
terminal = f'''
|
||||
Dim nTrace, nError, nDescription
|
||||
nTrace = ""
|
||||
On Error Resume Next
|
||||
Call NativeAcceptanceMain()
|
||||
nError = Err.Number
|
||||
nDescription = Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
Call DxToolsWriteUtf8Atomic({vbs(case_dir / 'host-trace.txt')}, nTrace & "ERROR=" & CStr(nError) & " " & nDescription & vbLf)
|
||||
Sub NativeAcceptanceMain()
|
||||
Dim nProject, nFso, nShell, nObjects, nOriginals, nAfterObjects, nAfterOriginals
|
||||
Dim nRoot, nRunId, nSnapshotId, nComp, nResult, nState, nClaim, nNumber, nMessage, nNet
|
||||
Dim nLocated, nFixtureValue, nFixtureComponent
|
||||
nProject = Application.GetProjectData().GetProjectFilePath()
|
||||
If InStr(1, nProject, "\\acceptance\\native-20261010\\", vbTextCompare) = 0 Then Err.Raise 999, "Acceptance", "Wrong host"
|
||||
nTrace = "PROJECT=" & nProject & vbLf
|
||||
Application.PushPath "1GPHY_RTL8211F", "", "GE_PHY_8211"
|
||||
ActiveView.Block.DeSelectAll
|
||||
For Each nComp In ActiveView.Query(VDM_COMP, VD_ALL)
|
||||
If {matches} Then nComp.Selected = True
|
||||
Next
|
||||
Set nFso = CreateObject("Scripting.FileSystemObject")
|
||||
Set nShell = CreateObject("WScript.Shell")
|
||||
Set nObjects = CreateObject("Scripting.Dictionary")
|
||||
Set nOriginals = CreateObject("Scripting.Dictionary")
|
||||
nRoot = {vbs(MAILBOX)}
|
||||
nRunId = "native-81576"
|
||||
If Not DxRefreshSnapshot(nRoot, nRunId, nObjects, nOriginals, nSnapshotId) Then Err.Raise 998, "Acceptance", "Snapshot failed"
|
||||
nFso.CopyFile nRoot & "\\request.json", {vbs(case_dir / 'before.json')}, True
|
||||
nTrace = nTrace & "BEFORE=" & nSnapshotId & " objects=" & CStr(nObjects.Count) & vbLf
|
||||
nResult = nShell.Run({vbs(command)}, 0, True)
|
||||
nTrace = nTrace & "PYTHON_STAGE=" & CStr(nResult) & vbLf
|
||||
If nResult <> 0 Then Exit Sub
|
||||
If {vbs(case)} = "value-stale" Then
|
||||
For Each nComp In nObjects.Items
|
||||
If CStr(nComp.UID) = "$5I2744" Then
|
||||
Set nFixtureComponent = nComp
|
||||
nFixtureValue = CStr(nComp.FindAttribute("Value").Value)
|
||||
nComp.FindAttribute("Value").Value = "native-external-edit"
|
||||
End If
|
||||
Next
|
||||
nTrace = nTrace & "INJECTED_REAL_EXTERNAL_EDIT=native-external-edit" & vbLf
|
||||
End If
|
||||
If {vbs(case)} = "locate" Then
|
||||
For Each nComp In ActiveView.Query(VDM_COMP, VD_ALL)
|
||||
nComp.Selected = False
|
||||
If CStr(nComp.UID) = "$5I2942" Then nComp.Selected = True
|
||||
Next
|
||||
For Each nNet In ActiveView.Query(VDM_NET, VD_ALL)
|
||||
nNet.Selected = False
|
||||
Next
|
||||
nNumber = 0
|
||||
For Each nComp In ActiveView.Query(VDM_COMP, VD_SELECTED)
|
||||
nTrace = nTrace & "BEFORE_LOCATE_COMPONENT=" & CStr(nComp.UID) & vbLf
|
||||
nNumber = nNumber + 1
|
||||
Next
|
||||
If nNumber <> 1 Then Err.Raise 994, "Acceptance", "Locator fixture selection failed"
|
||||
Call DxBridgeConsumeLocate(nRoot, nObjects)
|
||||
nLocated = False
|
||||
nNumber = 0
|
||||
For Each nComp In ActiveView.Query(VDM_COMP, VD_SELECTED)
|
||||
nTrace = nTrace & "LOCATED_COMPONENT=" & CStr(nComp.UID) & " " & CStr(nComp.Refdes) & vbLf
|
||||
If CStr(nComp.UID) = "$5I2744" Then nLocated = True
|
||||
nNumber = nNumber + 1
|
||||
Next
|
||||
If Not nLocated Or nNumber <> 1 Then Err.Raise 995, "Acceptance", "Component locator did not exclusively select the expected component"
|
||||
Call DxToolsWriteUtf8Atomic(nRoot & "\\locate.tsv", "net|GND|1" & vbLf)
|
||||
Call DxBridgeConsumeLocate(nRoot, nObjects)
|
||||
For Each nNet In ActiveView.Query(VDM_NET, VD_SELECTED)
|
||||
nTrace = nTrace & "LOCATED_NET=" & CStr(nNet.LogicalNetName) & vbLf
|
||||
Next
|
||||
End If
|
||||
nState = "no-apply"
|
||||
If nFso.FileExists(nRoot & "\\result.tsv") Then
|
||||
nClaim = DxBridgeClaimFile(nFso, nRoot & "\\result.tsv", nRoot & "\\result.processing")
|
||||
nTrace = nTrace & "CLAIM=" & CStr(nClaim) & vbLf
|
||||
If Not nClaim Then Err.Raise 997, "Acceptance", "Claim failed"
|
||||
On Error Resume Next
|
||||
nState = DxProcessApply(nRoot, nRunId, nSnapshotId, nObjects, nOriginals)
|
||||
nNumber = Err.Number
|
||||
nMessage = Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
nTrace = nTrace & "TRANSACTION_ERROR=" & CStr(nNumber) & " " & nMessage & vbLf
|
||||
End If
|
||||
nTrace = nTrace & "STATE=" & nState & vbLf
|
||||
If nFso.FileExists(nRoot & "\\apply-status.json") Then nFso.CopyFile nRoot & "\\apply-status.json", {vbs(case_dir / 'apply-status.json')}, True
|
||||
If nFso.FileExists(nRoot & "\\result.processing") Then nFso.CopyFile nRoot & "\\result.processing", {vbs(case_dir / 'claimed-schedule.tsv')}, True
|
||||
Set nAfterObjects = CreateObject("Scripting.Dictionary")
|
||||
Set nAfterOriginals = CreateObject("Scripting.Dictionary")
|
||||
If Not DxRefreshSnapshot(nRoot, nRunId, nAfterObjects, nAfterOriginals, nSnapshotId) Then Err.Raise 996, "Acceptance", "Readback snapshot failed"
|
||||
nFso.CopyFile nRoot & "\\request.json", {vbs(case_dir / 'after.json')}, True
|
||||
nResult = nShell.Run({vbs(check)}, 0, True)
|
||||
nTrace = nTrace & "PYTHON_VERIFY=" & CStr(nResult) & vbLf
|
||||
If {vbs(case)} = "value-stale" Then
|
||||
nFixtureComponent.FindAttribute("Value").Value = nFixtureValue
|
||||
nTrace = nTrace & "EXTERNAL_EDIT_FIXTURE_RESTORED=" & CStr(nFixtureComponent.FindAttribute("Value").Value) & vbLf
|
||||
End If
|
||||
End Sub
|
||||
'''
|
||||
script = case_dir / "run-native.vbs"
|
||||
script.write_text(source + terminal, encoding="ascii")
|
||||
print(script)
|
||||
|
||||
|
||||
def operation_value(component, op, name):
|
||||
if op == OpType.REFDES:
|
||||
return component.refdes
|
||||
attr = next((a for a in component.attributes if a.name.casefold() == name.casefold()), None)
|
||||
if attr is None:
|
||||
return None
|
||||
return ("1" if attr.visible else "0") if op == OpType.PROPERTY_VISIBILITY else attr.value
|
||||
|
||||
|
||||
def restore_from(snapshot, name, store):
|
||||
prior = json.loads((BASE / name / "plan.json").read_text(encoding="utf-8"))
|
||||
backup = Path(prior["backup_path"])
|
||||
entry = HistoryEntry(datetime.now(timezone.utc), snapshot.run_id, snapshot.design_id, backup, "applied", 1)
|
||||
return build_restore_plan(snapshot, store.build_restore_settings(entry))
|
||||
|
||||
|
||||
def stage(case):
|
||||
case_dir = BASE / case
|
||||
snapshot = load_request(case_dir / "before.json")
|
||||
for name in ("apply-status.json", "apply-request.json", "result.tsv", "result.processing"):
|
||||
(MAILBOX / name).unlink(missing_ok=True)
|
||||
selected = tuple(c for c in snapshot.components if c.selected)
|
||||
by_uid = {c.stable_uid: c for c in snapshot.components}
|
||||
store = RunStore(BASE / "store")
|
||||
plan = None
|
||||
expected_state = "applied"
|
||||
if case in {"refdes", "refdes-repeat", "refdes-default-red"}:
|
||||
plan = build_annotation_plan(snapshot, AnnotationSettings(
|
||||
scope=Scope.SELECTED, processing_mode=ProcessingMode.REANNOTATE,
|
||||
start_number=7000 if case != "refdes-repeat" else 8000,
|
||||
))
|
||||
elif case.startswith("restore-"):
|
||||
plan = restore_from(snapshot, case.removeprefix("restore-"), store)
|
||||
elif case in {"value", "value1", "part-number", "missing-skip", "value-empty", "value1-empty"}:
|
||||
prop = {"value": "Value", "value1": "Value1", "part-number": "Part Number", "missing-skip": "Definitely Missing", "value-empty": "Value", "value1-empty": "Value1"}[case]
|
||||
plan = build_property_change_plan(snapshot, PropertyChangeSettings(prop,
|
||||
tuple((c.bridge_id, "" if case.endswith("empty") else f"native-{case}-changed") for c in selected)))
|
||||
elif case in {"part-name-show", "part-name-hide", "part-label-show", "part-label-hide"}:
|
||||
prop = "Part Name" if case.startswith("part-name") else "Part Label"
|
||||
plan = build_property_visibility_plan(snapshot, PropertyVisibilitySettings(prop, case.endswith("show")))
|
||||
elif case in {"stale", "digest", "rollback", "cycle", "project-stale", "value-stale"}:
|
||||
cap = by_uid[CAP]
|
||||
rows = []
|
||||
if case == "cycle":
|
||||
other = by_uid[OTHER_CAP]
|
||||
for comp, target in ((cap, other.refdes), (other, cap.refdes)):
|
||||
prefix = re.match(r"[A-Za-z]+", comp.refdes).group(0)
|
||||
rows.append(PlanRow(comp.stable_uid, (comp.bridge_id,), comp.full_path, prefix,
|
||||
comp.refdes, target, "pending", True))
|
||||
else:
|
||||
rows.append(PlanRow("native-value", (cap.bridge_id,), cap.full_path, None,
|
||||
operation_value(cap, OpType.PROPERTY_VALUE, "Value"), "native-failure-probe", "pending", True,
|
||||
op=OpType.PROPERTY_VALUE, property_name="Value"))
|
||||
if case == "rollback":
|
||||
rows.append(PlanRow("native-visibility", (cap.bridge_id,), cap.full_path, None,
|
||||
operation_value(cap, OpType.PROPERTY_VISIBILITY, "Part Name"), "not-a-boolean", "pending", True,
|
||||
op=OpType.PROPERTY_VISIBILITY, property_name="Part Name"))
|
||||
plan = AnnotationPlan(snapshot.snapshot_id, tuple(rows), (), build_apply_schedule(tuple(rows)))
|
||||
expected_state = "rolled-back" if case == "rollback" else ("applied" if case == "cycle" else "rejected")
|
||||
elif case.startswith("inspection") or case == "locate":
|
||||
audit = {
|
||||
"nets": [asdict(row) for row in net_list(snapshot)],
|
||||
"solitary": [asdict(row) for row in solitary_nets(snapshot)],
|
||||
"value_missing_empty": [asdict(row) for row in missing_attribute_values(snapshot, "Value")],
|
||||
"value_missing_all": [asdict(row) for row in missing_attribute_values(snapshot, "Value", include_missing=True)],
|
||||
"value1_missing_empty": [asdict(row) for row in missing_attribute_values(snapshot, "Value1")],
|
||||
"value1_missing_all": [asdict(row) for row in missing_attribute_values(snapshot, "Value1", include_missing=True)],
|
||||
"gnd_pages": [asdict(row) for row in net_cross_page(snapshot, "GND")],
|
||||
}
|
||||
dump(case_dir / "inspection.json", audit)
|
||||
if case == "locate":
|
||||
atomic_write_text(MAILBOX / "locate.tsv", by_uid[CAP].bridge_id + "\n")
|
||||
else:
|
||||
raise ValueError(case)
|
||||
report = {"case": case, "expected_state": expected_state, "snapshot_id": snapshot.snapshot_id,
|
||||
"design_path": snapshot.design_path, "component_count": len(snapshot.components), "net_count": len(snapshot.nets),
|
||||
"selected": [{"bridge_id": c.bridge_id, "uid": c.stable_uid, "refdes": c.refdes, "symbol_default": c.symbol_refdes_default} for c in selected],
|
||||
"rows": [], "schedule": [], "issues": [], "backup_path": None}
|
||||
if plan is not None:
|
||||
report.update(rows=[asdict(row) for row in plan.rows], schedule=[asdict(step) for step in plan.schedule], issues=[asdict(issue) for issue in plan.issues])
|
||||
if plan.can_apply:
|
||||
backup = store.write_backup(snapshot, plan)
|
||||
request = ApplyRequest(2, snapshot.run_id, "stale-id" if case == "stale" else snapshot.snapshot_id,
|
||||
backup.resolve(), schedule_sha256(plan.schedule))
|
||||
write_apply_request(MAILBOX / "apply-request.json", request)
|
||||
write_schedule(MAILBOX / "result.tsv", plan.schedule)
|
||||
if case == "project-stale":
|
||||
request_data = json.loads((MAILBOX / "request.json").read_text(encoding="utf-8-sig"))
|
||||
request_data["design_path"] = str(BASE / "different-copy.prj")
|
||||
dump(MAILBOX / "request.json", request_data)
|
||||
if case == "digest":
|
||||
with (MAILBOX / "result.tsv").open("a", encoding="utf-8") as handle:
|
||||
handle.write("\n")
|
||||
report["backup_path"] = str(backup)
|
||||
report["schedule_sha256"] = request.schedule_sha256
|
||||
(case_dir / "apply-request.json").write_bytes((MAILBOX / "apply-request.json").read_bytes())
|
||||
else:
|
||||
report["expected_state"] = "no-apply"
|
||||
else:
|
||||
report["expected_state"] = "no-apply"
|
||||
dump(case_dir / "plan.json", report)
|
||||
|
||||
|
||||
def verify(case):
|
||||
case_dir = BASE / case
|
||||
before = load_request(case_dir / "before.json")
|
||||
after = load_request(case_dir / "after.json")
|
||||
report = json.loads((case_dir / "plan.json").read_text(encoding="utf-8"))
|
||||
old_by_uid = {c.stable_uid: c for c in before.components}
|
||||
new_by_uid = {c.stable_uid: c for c in after.components}
|
||||
assert set(old_by_uid) == set(new_by_uid), "Native component identities changed"
|
||||
assert len(after.components) == 114
|
||||
assert len(after.nets) == 56
|
||||
assert after.current_sheet_name == "GE_PHY_8211"
|
||||
assert after.current_sheet_number == 1
|
||||
if case == "inspection-final":
|
||||
baseline = load_request(BASE / "refdes" / "before.json")
|
||||
for original in baseline.components:
|
||||
current = new_by_uid[original.stable_uid]
|
||||
assert current.refdes == original.refdes, (original.stable_uid, "final reference mismatch")
|
||||
assert (current.x, current.y) == (original.x, original.y)
|
||||
attribute_state = lambda comp: sorted((a.name.casefold(), a.value, a.visible) for a in comp.attributes)
|
||||
assert attribute_state(current) == attribute_state(original), (original.stable_uid, "final attribute mismatch")
|
||||
if case == "locate":
|
||||
assert "GND" in after.selected_nets
|
||||
assert report["expected_state"] == "no-apply" or (case_dir / "apply-status.json").is_file(), "Native apply did not publish a status"
|
||||
status = load_apply_status(case_dir / "apply-status.json") if (case_dir / "apply-status.json").is_file() else None
|
||||
if status is not None:
|
||||
assert status.state == report["expected_state"], asdict(status)
|
||||
actual_digest = hashlib.sha256((case_dir / "claimed-schedule.tsv").read_bytes()).hexdigest()
|
||||
assert (actual_digest == report["schedule_sha256"]) != (case == "digest")
|
||||
assert Path(report["backup_path"]).is_file()
|
||||
backup_changes = json.loads(Path(report["backup_path"]).read_text(encoding="utf-8"))["changes"]
|
||||
for change in backup_changes:
|
||||
original = old_by_uid[change["stable_uid"]]
|
||||
assert operation_value(original, OpType(change["op"]), change["property"]) == change["old_value"]
|
||||
if case == "rollback":
|
||||
assert status.rollback_state == "verified"
|
||||
assert status.failing_sequence == 2
|
||||
RunStore(BASE / "store").record_status(status, before.design_id)
|
||||
touched = {}
|
||||
records = []
|
||||
for row in report["rows"]:
|
||||
if not row["changed"]:
|
||||
continue
|
||||
for bridge_id in row["bridge_ids"]:
|
||||
original = next(c for c in before.components if c.bridge_id == bridge_id)
|
||||
current = new_by_uid[original.stable_uid]
|
||||
op = OpType(row["op"])
|
||||
target = row["new_refdes"] if report["expected_state"] == "applied" else row["old_refdes"]
|
||||
if case == "value-stale":
|
||||
target = "native-external-edit"
|
||||
actual = operation_value(current, op, row["property_name"])
|
||||
assert actual == target, (original.stable_uid, op, actual, target)
|
||||
touched.setdefault(original.stable_uid, set()).add((op, row["property_name"].casefold()))
|
||||
records.append({"uid": original.stable_uid, "before_refdes": original.refdes, "after_refdes": current.refdes,
|
||||
"op": op.value, "property": row["property_name"], "old": row["old_refdes"], "expected": target, "actual": actual})
|
||||
for uid, original in old_by_uid.items():
|
||||
current = new_by_uid[uid]
|
||||
changes = touched.get(uid, set())
|
||||
assert (current.x, current.y) == (original.x, original.y)
|
||||
if (OpType.REFDES, "") not in changes:
|
||||
assert current.refdes == original.refdes, (uid, "unexpected reference change")
|
||||
for attribute in original.attributes:
|
||||
if attribute.name.casefold() == "ref designator" and (OpType.REFDES, "") in changes:
|
||||
continue
|
||||
assert operation_value(current, OpType.PROPERTY_VALUE, attribute.name) == attribute.value or (OpType.PROPERTY_VALUE, attribute.name.casefold()) in changes
|
||||
assert operation_value(current, OpType.PROPERTY_VISIBILITY, attribute.name) == ("1" if attribute.visible else "0") or (OpType.PROPERTY_VISIBILITY, attribute.name.casefold()) in changes
|
||||
dump(case_dir / "verified.json", {"case": case, "state": status.state if status else "no-apply", "status": asdict(status) if status else None,
|
||||
"records": records, "integrity": "All 114 identities/positions and untouched references/attributes match before snapshot",
|
||||
"native_pid": 81576, "current_sheet": after.current_sheet_name, "net_count": len(after.nets)})
|
||||
|
||||
|
||||
def summary(_case):
|
||||
cases = []
|
||||
for folder in sorted(BASE.iterdir()):
|
||||
verified = folder / "verified.json"
|
||||
if not verified.is_file():
|
||||
continue
|
||||
trace = (folder / "host-trace.txt").read_text(encoding="utf-8")
|
||||
assert "PYTHON_VERIFY=0" in trace and "ERROR=0" in trace, folder
|
||||
data = json.loads(verified.read_text(encoding="utf-8"))
|
||||
data["evidence_path"] = str(folder)
|
||||
cases.append(data)
|
||||
assert len(cases) == 35
|
||||
counts = {state: sum(item["state"] == state for item in cases) for state in ("applied", "rejected", "rolled-back", "no-apply")}
|
||||
inspection = json.loads((BASE / "inspection" / "inspection.json").read_text(encoding="utf-8"))
|
||||
data = {"native_pid": 81576, "project_path": str(BASE.parent / "1GPHY_RTL8211F" / "1GPHY_RTL8211F.prj"),
|
||||
"passed_cases": len(cases), "states": counts, "component_count": 114, "net_count": 56,
|
||||
"final_integrity": "inspection-final compares all references, component positions and attribute values/visibility to refdes/before baseline",
|
||||
"fixture_note": "Value1=native-baseline was created only on the acceptance copy using real AddAttribute(String, X, Y, Visibility)",
|
||||
"inspection_counts": {key: len(value) for key, value in inspection.items()}, "cases": cases}
|
||||
dump(BASE / "native-feature-summary.json", data)
|
||||
lines = [
|
||||
"# DxDesigner native acceptance — 2026-10-10/11", "",
|
||||
"**35 real native cases verified:** 26 applied transactions, four rejected requests, one verified rollback, and four inspection/location/no-change cases.", "",
|
||||
f"Sole target was PID 81576 at `{data['project_path']}`. Each script checked the acceptance project path before mutation. No command was routed to original PID 68000 or the root's separate PID 45864.", "",
|
||||
"The native VBS exported actual snapshot/maps, invoked the source Python planner and RunStore, claimed result.tsv as result.processing, executed actual DxProcessApply, and exported actual readback. Every applied/rejected/rollback case checked the real schedule digest and persisted backup. No fake objects substituted for the native transaction or native readback.", "",
|
||||
"| Case | Actual state | Verified target records | Evidence |", "| --- | --- | ---: | --- |",
|
||||
]
|
||||
for item in cases:
|
||||
path = Path(item["evidence_path"]) / "verified.json"
|
||||
lines.append(f"| {item['case']} | {item['state']} | {len(item['records'])} | [records]({path.as_posix()}) |")
|
||||
lines += [
|
||||
"", "## Concrete results", "",
|
||||
"- Real symbol defaults were C? and L?. Automatic RefDes changed CE17→C7000 and LE03→L7000; a second apply in the same mailbox changed them to C8000/L8000. History restored both steps to CE17/LE03.",
|
||||
"- A CE17/CE18 swap used the source cycle scheduler and actual temporary CE? write. Native apply and cyclic history restoration passed after fixes.",
|
||||
"- Value changed on CE17 and LE03; Value1 changed on CE17 using the copied fixture's real added attribute; Part Number changed on both. Missing properties were skipped with issues. Clearing, historical restoration, and return to original values all passed.",
|
||||
"- Part Name and Part Label each passed show, hide and both historical restores. Final visible states match the baseline.",
|
||||
"- Actual inspection found 56 named nets, 56 single-page nets, two intentionally empty Values, six Value omissions including absent attributes, one intentionally empty Value1, and 64 Value1 omissions including absent attributes. GND lookup returned page 1. This project has one page; a native positive case spanning two pages was not available, while offline tests cover that case.",
|
||||
"- Strict component location began with CAP deselected and only LE03 selected. The final actual query selected only UID $5I2744/CE17. GND began deselected and was selected through the actual net mailbox route. See locate/host-trace.txt.",
|
||||
"- Stale snapshot ID, changed project descriptor, tampered SHA-256, and a real property edit between planning and preflight were all rejected. The latter preserved the external edit; the fixture edit was then restored through the real setter.",
|
||||
"- A real Value write followed by invalid visibility conversion failed on sequence 2. Actual status was rolled-back, rollback_state=verified, changed_count=0; both original attribute values were read back.",
|
||||
"- Final inspection compared all 114 reference values, all component positions, and every baseline attribute's value/visibility to the first baseline snapshot. All match. The extra Value1 fixture remains native-baseline only in the acceptance copy.",
|
||||
"", "## Native defects reproduced and fixed", "",
|
||||
"1. SymbolRefdesDefault was unavailable in 7.9.5; source export now falls back to SymbolBlock.FindAttribute('Ref Designator').Value.",
|
||||
"2. A repeated operation key in a cyclic schedule raised native Dictionary error 457 after partial writes. Transaction finals now updates the existing key; see cycle-red/host-trace.txt and cycle/verified.json.",
|
||||
"3. Cyclic history restore rows had no temporary prefix because refdes_prefix accepts letters only. Restore derives prefixes from formal values with split_refdes; the new automated formal-swap regression failed before the fix and passed after it.",
|
||||
"4. Project-path mismatch was allowed before the new preflight guard; it is now rejected before writes. The acceptance test altered only the snapshot descriptor, not the active hardware project; see project-stale-red and project-stale.",
|
||||
"5. VBS Trim left the LF from the published component locate request, making objectMap.Exists false and bypassing location. CR/LF is now normalized at the mailbox boundary. The additional speculative selection helper was reverted; the original native SelectByName path passed strict isolation after parser correction.",
|
||||
"", "## Evidence and handoff", "",
|
||||
f"Evidence root: `{BASE}`. Each case has before.json, plan.json, host-trace.txt and after.json; transaction cases also have the actual claimed schedule, apply-request, apply-status and verified readback. Backups and recorded history are under store/.",
|
||||
f"Final actual snapshot: `{BASE / 'inspection-final' / 'after.json'}`.",
|
||||
f"Summary JSON: `{BASE / 'native-feature-summary.json'}`.",
|
||||
"Native production edits owned here: Snapshot.vbs/DxBridgeSymbolDefault, Transaction.vbs/cycle verification and project guard, Mailbox.vbs/locate CR-LF normalization, domain/restore.py/formal cycle prefix; regression tests and tools/acceptance/native_features.py accompany them.",
|
||||
"PID 81576 was released to root after final integrity verification. No further host commands were issued by this agent. The current selected fixture objects are CAP, INDUCTOR and GRAPHIC; root should choose a single eligible component before the frozen GUI Apply smoke test. Persistent Start/save events, PDF, Excel output and Expedition remain with root/other native agents.",
|
||||
"Updated core/domain regression command: pytest tests/integration/test_vbs_bridge.py tests/domain/test_operation_restore.py tests/domain/test_restore.py -q. Latest result: 23 passed. git diff --check returned exit 0.",
|
||||
]
|
||||
report = REPO / "build" / "test-evidence" / "native-feature-report.md"
|
||||
report.parent.mkdir(parents=True, exist_ok=True)
|
||||
report.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
print(report)
|
||||
print(json.dumps({"cases": len(cases), "states": counts}))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("action", choices=("render", "stage", "verify", "summary"))
|
||||
parser.add_argument("case")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
{"render": render, "stage": stage, "verify": verify, "summary": summary}[args.action](args.case)
|
||||
except Exception:
|
||||
(BASE / args.case).mkdir(parents=True, exist_ok=True)
|
||||
(BASE / args.case / f"{args.action}-error.txt").write_text(traceback.format_exc(), encoding="utf-8")
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,167 @@
|
||||
"""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")
|
||||
options = parser.parse_args()
|
||||
root = options.executable.resolve().parent
|
||||
helper = Path(__file__).with_name("run_dx_script.py")
|
||||
install = 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)
|
||||
app = Application(backend="uia").connect(process=tool.pid, timeout=15)
|
||||
window = app.window(title="一叶知秋_重构版")
|
||||
window.wait("visible", timeout=15)
|
||||
texts = [x.window_text() for x in window.descendants(control_type="Text")]
|
||||
selected = [x.window_text() for x in window.descendants(control_type="ListItem") if x.is_selected()]
|
||||
assert selected == [expected], (feature, selected)
|
||||
assert "桥接已连接" in texts and PROJECT.name in texts, texts
|
||||
results.append({"feature": feature, "pid": tool.pid, "selected_page": selected[0], "bridge": "connected", "project": PROJECT.name, "executable": tool.executable})
|
||||
window.close()
|
||||
elif feature == "compatibility":
|
||||
def close_completion():
|
||||
probe = BASE.parent.parent / "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 = BASE.parent.parent / "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()
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Run real packaged update/restart/rollback against a disposable bundle copy."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from pywinauto import Application
|
||||
|
||||
from dx_productivity.update.installer import InstallPlan, prepare_updater
|
||||
from packaged_menu import tools_running, wait_for
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("release", type=Path)
|
||||
parser.add_argument("archive", type=Path)
|
||||
options = parser.parse_args()
|
||||
base = Path(tempfile.gettempdir()) / f"dx-packaged-update-{uuid.uuid4().hex[:8]}"
|
||||
current = base / "中文 便携工具"
|
||||
shutil.copytree(options.release, current)
|
||||
marker = current / "before-update.txt"
|
||||
marker.write_text("old-copy", encoding="utf-8")
|
||||
executable = current / "DxDesignerTools.exe"
|
||||
environment = os.environ.copy()
|
||||
environment["PATH"] = r"C:\Windows\System32;C:\Windows"
|
||||
environment.pop("PYTHONPATH", None)
|
||||
environment.pop("QT_QPA_PLATFORM", None)
|
||||
updater = prepare_updater(current, base / "cache")
|
||||
old_ui = subprocess.Popen([str(executable), "ui"], env=environment, cwd=current)
|
||||
old_window = Application(backend="uia").connect(process=old_ui.pid, timeout=15).window(title="一叶知秋_重构版")
|
||||
old_window.wait("visible", timeout=15)
|
||||
digest = hashlib.sha256(options.archive.read_bytes()).hexdigest()
|
||||
plan = InstallPlan(current_root=current, staged_zip=options.archive.resolve(), backup_root=base / "backups",
|
||||
restart_command=(str(executable), "ui", "--smoke-test-ms", "250"),
|
||||
launch_command=(str(executable), "ui"), sha256=digest)
|
||||
plan_file = base / "install-plan.json"
|
||||
plan_file.write_text(json.dumps(plan.to_mapping(), ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
process = subprocess.Popen([str(updater), "update", "--plan", str(plan_file)], env=environment, cwd=updater.parent)
|
||||
time.sleep(2)
|
||||
assert process.poll() is None and marker.exists(), "Updater failed to wait for the running UI"
|
||||
old_window.close()
|
||||
assert old_ui.wait(15) == 0
|
||||
assert process.wait(60) == 0, (base / "install.log").read_text(encoding="utf-8")
|
||||
assert not marker.exists()
|
||||
assert any(p.is_file() for p in (base / "backups").glob("*/before-update.txt"))
|
||||
|
||||
def restarted():
|
||||
for item in tools_running():
|
||||
if Path(item.executable).resolve() == executable.resolve():
|
||||
return item
|
||||
tool = wait_for(restarted)
|
||||
window = Application(backend="uia").connect(process=tool.pid, timeout=15).window(title="一叶知秋_重构版")
|
||||
window.wait("visible", timeout=15)
|
||||
time.sleep(2)
|
||||
assert window.exists(), "Updated UI closed after the smoke probe"
|
||||
window.close()
|
||||
wait_for(lambda: not restarted(), 15)
|
||||
print("PASS PACKAGED UPDATE AND PERSISTENT RESTART", flush=True)
|
||||
|
||||
rollback_marker = current / "before-rollback.txt"
|
||||
rollback_marker.write_text("restore-me", encoding="utf-8")
|
||||
rollback = InstallPlan(current_root=current, staged_zip=options.archive.resolve(), backup_root=base / "rollback-backups",
|
||||
restart_command=(r"C:\Windows\System32\cmd.exe", "/d", "/c", "exit", "3"), sha256=digest)
|
||||
rollback_file = base / "rollback-plan.json"
|
||||
rollback_file.write_text(json.dumps(rollback.to_mapping(), ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
failure = subprocess.run([str(updater), "update", "--plan", str(rollback_file)], env=environment, cwd=updater.parent, timeout=60)
|
||||
assert failure.returncode == 1
|
||||
assert rollback_marker.read_text(encoding="utf-8") == "restore-me"
|
||||
assert (current / "_runtime/python312.dll").is_file()
|
||||
assert "rolled-back" in (base / "install.log").read_text(encoding="utf-8")
|
||||
result = {"release": str(options.release.resolve()), "archive_sha256": digest, "test_root": str(base),
|
||||
"waited_for_open_ui": True, "installed": True, "persistent_restart": True,
|
||||
"smoke_failure_rolled_back": True, "source_release_modified": False, "python_on_path": False}
|
||||
report = Path.cwd() / "build/test-evidence/packaged-update.json"
|
||||
report.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print("PASS PACKAGED UPDATE ROLLBACK", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,45 @@
|
||||
Dim aProject, aStream, aComp, aAttr, aError
|
||||
aProject = Application.GetProjectData().GetProjectFilePath()
|
||||
If InStr(1, aProject, "\acceptance\native-20261010\", vbTextCompare) = 0 Then Err.Raise 999, "Acceptance", "Wrong host"
|
||||
Set aStream = CreateObject("Scripting.FileSystemObject").CreateTextFile("C:\Users\ABS_Windows\AppData\Local\DxProductivity\acceptance\native-20261010\native-attribute-probe.txt", True, True)
|
||||
aStream.WriteLine "PROJECT=" & aProject
|
||||
Application.PushPath "1GPHY_RTL8211F", "", "GE_PHY_8211"
|
||||
For Each aComp In ActiveView.Query(VDM_COMP, VD_ALL)
|
||||
If CStr(aComp.UID) = "$5I2744" Or CStr(aComp.UID) = "$5I2942" Then
|
||||
aStream.WriteLine "COMP=" & aComp.Refdes & " UID=" & aComp.UID
|
||||
Call ARecord("symbolblock_type", "TypeName(aComp.SymbolBlock)")
|
||||
Call ARecord("symbol_ref", "aComp.SymbolBlock.FindAttribute(""Ref Designator"").Value")
|
||||
Call ARecord("symbol_attr_count", "aComp.SymbolBlock.Attributes.Count")
|
||||
Call ARecord("value1", "aComp.FindAttribute(""Value1"").Value")
|
||||
If CStr(aComp.UID) = "$5I2744" Then
|
||||
On Error Resume Next
|
||||
Set aAttr = aComp.FindAttribute("Value1")
|
||||
Err.Clear
|
||||
If aAttr Is Nothing Then
|
||||
Set aAttr = aComp.AddAttribute("Value1=native-baseline", aComp.GetLocation().X, aComp.GetLocation().Y, 1)
|
||||
aError = Err.Number
|
||||
aStream.WriteLine "ADD2_ERROR=" & CStr(aError) & " " & Err.Description
|
||||
Err.Clear
|
||||
If aError <> 0 Then
|
||||
Set aAttr = aComp.FindAttribute("Value1")
|
||||
aStream.WriteLine "ADD4_ERROR=" & CStr(Err.Number) & " " & Err.Description
|
||||
Err.Clear
|
||||
End If
|
||||
End If
|
||||
On Error GoTo 0
|
||||
Call ARecord("value1_after", "aComp.FindAttribute(""Value1"").Value")
|
||||
End If
|
||||
End If
|
||||
Next
|
||||
aStream.WriteLine "DONE"
|
||||
aStream.Close
|
||||
Sub ARecord(label, expression)
|
||||
Dim value, number, description
|
||||
On Error Resume Next
|
||||
value = Eval(expression)
|
||||
number = Err.Number
|
||||
description = Err.Description
|
||||
Err.Clear
|
||||
aStream.WriteLine label & "=" & CStr(value) & " error=" & CStr(number) & " " & description
|
||||
On Error GoTo 0
|
||||
End Sub
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Forward a script to one explicitly selected DxDesigner acceptance instance."""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
import win32process
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
target = parser.add_mutually_exclusive_group(required=True)
|
||||
target.add_argument("--pid", type=int)
|
||||
target.add_argument("--moniker")
|
||||
target.add_argument("--project", type=Path)
|
||||
parser.add_argument("script", type=Path)
|
||||
args = parser.parse_args()
|
||||
context = pythoncom.CreateBindCtx(0)
|
||||
table = pythoncom.GetRunningObjectTable()
|
||||
entries = table.EnumRunning()
|
||||
while batch := entries.Next(1):
|
||||
moniker = batch[0]
|
||||
name = moniker.GetDisplayName(context, None)
|
||||
if not name.startswith("!Viewdraw.Application"):
|
||||
continue
|
||||
app = win32com.client.Dispatch(
|
||||
table.GetObject(moniker).QueryInterface(pythoncom.IID_IDispatch)
|
||||
)
|
||||
if args.project:
|
||||
try:
|
||||
data = app.GetProjectData()
|
||||
project = data.GetProjectFilePath
|
||||
project = project() if callable(project) else project
|
||||
matches = Path(project).resolve() == args.project.resolve()
|
||||
except Exception:
|
||||
matches = False
|
||||
elif args.moniker:
|
||||
matches = args.moniker.casefold() in name.casefold()
|
||||
else:
|
||||
handle = int(app.ActiveViewHandle)
|
||||
matches = bool(handle) and win32process.GetWindowThreadProcessId(handle)[1] == args.pid
|
||||
if matches:
|
||||
print(f"Executing {args.script.name} in {name}", flush=True)
|
||||
app.ExecuteCommand(f'run "{args.script.resolve()}"')
|
||||
return
|
||||
raise SystemExit("Selected DxDesigner instance was not found")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user