fix: stabilize native refresh and complete toolbar acceptance
This commit is contained in:
1 parent
b8acbc6de5
commit
b203806fd1
22 files changed
+898
-102
No files matched your search
@@ -1,6 +1,6 @@
|
||||
# 横向悬浮工具栏与紧凑面板 Implementation Plan
|
||||
|
||||
> **状态:界面实现、代码审查、源码 461 项及便携包 16 项验证已完成。** 原生选择五个用例通过;Windows 锁屏阻止前台点击验收和最终菜单切换,等待用户解锁。逐项结果见 `docs/testing/toolbar-acceptance-20261011.md`。
|
||||
> **状态:横向工具栏、九个面板、实机验收和正式菜单切换已完成。** 最终源码 476 项、便携包 16 项通过;写回/恢复、选择、PDF、BOM、原生菜单普通重启及展开/收起更新与回滚通过。用户当前 DX 已连接最终工具,逐项证据及 PON 限制见 `docs/testing/toolbar-acceptance-20261011.md`。
|
||||
>
|
||||
> **For agentic workers:** 使用 `superpowers:executing-plans` 按任务执行。步骤使用复选框记录进度;默认在当前会话顺序执行。
|
||||
|
||||
@@ -127,7 +127,7 @@ def set_selection_status(self, text: str, detail: str = "") -> None: ...
|
||||
def set_operation_status(self, text: str) -> None: ...
|
||||
```
|
||||
|
||||
以上是接口约定,不是已完成实现。页面标识继续遵循现有 `FEATURE_PAGE_INDEX`,工具栏与更多菜单引用同一份定义。当前 `app.py` 和 SelectionWatcher 直接修改 QLabel 的调用迁移到统一 setter;每个 setter 同时更新面板与工具栏,避免隐藏状态不同步。
|
||||
以上接口已按最终代码实现,行为以验收记录为准。页面标识继续遵循现有 `FEATURE_PAGE_INDEX`,工具栏与更多菜单引用同一份定义。当前 `app.py` 和 SelectionWatcher 直接修改 QLabel 的调用迁移到统一 setter;每个 setter 同时更新面板与工具栏,避免隐藏状态不同步。
|
||||
|
||||
区分面板关闭与应用退出:普通 closeEvent 收起面板,request_exit 执行控制器 shutdown 并关闭两个窗口。`app.py` 的 `_launch_update` 等程序主动退出路径迁移到 request_exit,防止安装更新时旧进程仅隐藏而占用文件。
|
||||
|
||||
@@ -135,55 +135,55 @@ def set_operation_status(self, text: str) -> None: ...
|
||||
|
||||
### 任务 1:工具栏与面板外壳
|
||||
|
||||
- [ ] 新增 FloatingToolbar,接入七个功能、Start、更多、展开/收起和拖动。
|
||||
- [ ] 修改 MainWindow,移除固定侧栏、重复内容标题和全局位号操作按钮;功能页继续使用现有实例。
|
||||
- [ ] 修改 app.py,保留指定功能启动路由;将位号预览/应用信号接到 RefDesPage 局部操作区。
|
||||
- [ ] 将更新安装和显式退出统一接到 request_exit;核对 `tests/ui/test_update_launch.py` 中的进程退出行为。
|
||||
- [ ] 更新 `tests/ui/test_main_window.py` 和 `test_compact_floating_window.py`:逐个入口到达正确页面,同入口重复点击收起,最小化可恢复,显式退出关闭两个窗口。
|
||||
- [ ] 形成可运行的外壳阶段版本,先用实际屏幕截图核对单行布局、占用面积和可读性。
|
||||
- [x] 新增 FloatingToolbar,接入七个功能、Start、更多、展开/收起和拖动。
|
||||
- [x] 修改 MainWindow,移除固定侧栏、重复内容标题和全局位号操作按钮;功能页继续使用现有实例。
|
||||
- [x] 修改 app.py,保留指定功能启动路由;将位号预览/应用信号接到 RefDesPage 局部操作区。
|
||||
- [x] 将更新安装和显式退出统一接到 request_exit;核对 `tests/ui/test_update_launch.py` 中的进程退出行为。
|
||||
- [x] 更新 `tests/ui/test_main_window.py` 和 `test_compact_floating_window.py`:逐个入口到达正确页面,同入口重复点击收起,最小化可恢复,显式退出关闭两个窗口。
|
||||
- [x] 形成可运行的外壳阶段版本,先用实际屏幕截图核对单行布局、占用面积和可读性。
|
||||
|
||||
交付:七个主入口和更多中的两页均可访问,面板可反复展开/收起,现有输入与任务实例保持连续。
|
||||
|
||||
### 任务 2:状态与窗口行为
|
||||
|
||||
- [ ] 集中工程、桥接、选择、操作状态 setter,迁移 app.py 与 SelectionWatcher 的直接标签赋值。
|
||||
- [ ] 将短状态和详细提示同步到工具栏;监听失效时展示暂停或断开状态。
|
||||
- [ ] 实现 layout_preferences,原子保存工具栏位置和每页尺寸;屏幕消失或坐标越界时重新放置。
|
||||
- [ ] 更新 `tests/ui/test_live_selection.py`,覆盖隐藏面板时单选、多选、取消选择、断连和工程变化;确认轮询器数量及页面实例不因展开增加。
|
||||
- [ ] 实机检查工具栏状态更新不抢焦点、拖动不触发功能;100%/125%/150% DPI、多屏及负坐标可用。
|
||||
- [x] 集中工程、桥接、选择、操作状态 setter,迁移 app.py 与 SelectionWatcher 的直接标签赋值。
|
||||
- [x] 将短状态和详细提示同步到工具栏;监听失效时展示暂停或断开状态。
|
||||
- [x] 实现 layout_preferences,原子保存工具栏位置和每页尺寸;屏幕消失或坐标越界时重新放置。
|
||||
- [x] 更新 `tests/ui/test_live_selection.py`,覆盖隐藏面板时单选、多选、取消选择、断连和工程变化;确认轮询器数量及页面实例不因展开增加。
|
||||
- [x] 实机检查工具栏状态更新及拖动;物理桌面实测 125% DPI,100%/150% 为 Qt 渲染证据,多屏及负坐标为模拟验证。
|
||||
|
||||
交付:不打开面板也能辨认当前选择和监听状态,窗口位置及尺寸可恢复。
|
||||
|
||||
### 任务 3:先精简 PDF 和自动位号
|
||||
|
||||
- [ ] PDF 高级选项收纳配色、文字处理和引擎路径;按范围显示 Block 或当前页摘要;保留打开目录与保存后自动导出。
|
||||
- [ ] 自动位号将规则改为顶部紧凑区域,低频选项折叠;按编号方式显示参数;精简预览默认列。
|
||||
- [ ] 更新 `test_pdf_export_page.py` 和 `test_refdes_page.py`,核对隐藏字段的实际值、范围验证、应用禁用条件和表单保留。
|
||||
- [ ] 在验收工程检查 PDF 三种范围、原生保存监听、配色和中文;检查位号预览、应用与恢复。
|
||||
- [x] PDF 高级选项收纳配色、文字处理和引擎路径;按范围显示 Block 或当前页摘要;保留打开目录与保存后自动导出。
|
||||
- [x] 自动位号将规则改为顶部紧凑区域,低频选项折叠;按编号方式显示参数;精简预览默认列。
|
||||
- [x] 更新 `test_pdf_export_page.py` 和 `test_refdes_page.py`,核对隐藏字段的实际值、范围验证、应用禁用条件和表单保留。
|
||||
- [x] 在验收工程检查 PDF 三种范围、原生保存监听、配色和中文;检查位号预览、应用与恢复。
|
||||
|
||||
交付:两张主要页面明显缩小,常用操作和影响结果的当前参数可见。
|
||||
|
||||
### 任务 4:精简其余页面
|
||||
|
||||
- [ ] 按第 4 节整理属性、显示、检查、网络、BOM、历史和设置页面。
|
||||
- [ ] 检查/网络采用类型选择与相关字段联动;BOM 高级参数显示取值摘要。
|
||||
- [ ] 更新对应现有 UI 验证,核对控制器事件绑定、范围、定位和操作禁用条件。
|
||||
- [ ] 对九个页面逐项拍摄默认与最小尺寸截图,确认按钮可达、表格可读、长路径和错误文本可查看。
|
||||
- [x] 按第 4 节整理属性、显示、检查、网络、BOM、历史和设置页面。
|
||||
- [x] 检查/网络采用类型选择与相关字段联动;BOM 高级参数显示取值摘要。
|
||||
- [x] 更新对应现有 UI 验证,核对控制器事件绑定、范围、定位和操作禁用条件。
|
||||
- [x] 对九个页面逐项拍摄默认与最小尺寸截图,确认按钮可达、表格可读、长路径和错误文本可查看。
|
||||
|
||||
交付:所有页面使用同一套紧凑布局规则,更多菜单中的功能同样可用。
|
||||
|
||||
### 任务 5:实机回归与发布
|
||||
|
||||
- [ ] 使用验收副本逐项验证自动位号、属性批改、属性显示、设计检查、网络、BOM、历史、PDF 和设置。
|
||||
- [ ] 单独验证 Start 重复执行、DxDesigner 普通重启后菜单持久保留、各菜单项打开对应面板。
|
||||
- [ ] 验证从展开和收起两种状态安装更新时,旧进程确实退出,工具栏没有残留。
|
||||
- [ ] 更新 `tools/acceptance/compact_window.py`,记录工具栏截图、点击结果、DPI、隐藏期间选择变化和后台保存触发。
|
||||
- [ ] 完成源码与便携包验证后,通过现有 `packaging/build_release.ps1` 构建,检查冻结程序的入口路由和 UI 偏好读写。
|
||||
- [ ] 写入 `docs/testing/toolbar-acceptance-20261011.md`,逐项记录通过、失败和证据;更新用户说明,再切换到通过验收的包。
|
||||
- [x] 使用验收副本逐项验证自动位号、属性批改、属性显示、设计检查、网络、BOM、历史、PDF 和设置。
|
||||
- [x] 单独验证 Start 重复执行、DxDesigner 普通重启后菜单持久保留、各菜单项打开对应面板。
|
||||
- [x] 验证从展开和收起两种状态安装更新时,旧进程确实退出,工具栏没有残留;实机通过工具栏 WM_CLOSE 触发 request_exit,安装按钮的退出绑定由控制器回归覆盖。
|
||||
- [x] 更新 `tools/acceptance/compact_window.py`,记录工具栏截图、点击结果、DPI、隐藏期间选择变化和后台保存触发。
|
||||
- [x] 完成源码与便携包验证后,通过现有 `packaging/build_release.ps1` 构建,检查冻结程序的入口路由和 UI 偏好读写。
|
||||
- [x] 写入 `docs/testing/toolbar-acceptance-20261011.md`,逐项记录通过、失败和证据;更新用户说明,再切换到通过验收的包。
|
||||
|
||||
交付:新发布包、界面截图和逐项验收记录。阶段 1—4 的改动按交付边界分别提交,便于定位和回退。
|
||||
|
||||
执行阶段验证命令示例(本轮未执行):
|
||||
复验命令示例(完整已执行结果见验收记录):
|
||||
|
||||
```powershell
|
||||
$env:PYTHONPATH = Join-Path (Get-Location) 'src'
|
||||
|
||||
@@ -1,37 +1,67 @@
|
||||
# 横向工具栏与紧凑面板验收(2026-10-11)
|
||||
|
||||
## 实现与已通过检查
|
||||
## 结果与交付
|
||||
|
||||
| 项目 | 证据与结果 |
|
||||
|---|---|
|
||||
| 一排工具栏 | 772×44 逻辑像素;位号、属性、显示、检查、网络、BOM、PDF 一级入口;历史、设置和应用操作在更多中 |
|
||||
| 面板生命周期 | 同一页面再次点击收起;关闭及最小化收起;显式退出关闭两个窗口并停止工作;更新安装走显式退出 |
|
||||
| 状态 | 单选位号、多选数量及首个位号、完整提示、后台任务;初始通道未确认和断连均有明确状态 |
|
||||
| 位置与尺寸 | 保存独立 UI 偏好;屏幕限制保留用户首选尺寸;恢复到较大屏幕后还原;负坐标、窄屏溢出与移除屏幕由模拟验证覆盖 |
|
||||
| 页面 | 自动位号规则移到顶部;PDF/BOM/设置高级选项折叠;检查/网络使用类型选择加运行;历史路径在详情/提示中;属性页面保留表格和局部操作 |
|
||||
| 最小窗口 | PDF 三范围在真实 660×340 窗口、生产字体下默认无滚动,高级参数可独立滚动;设置高级项及说明同时展开时独立滚动,操作区不重叠 |
|
||||
| Qt 渲染 | 100%/125%/150% 缩放均渲染九页,默认状态没有越界操作按钮;这是 Qt 渲染证据,不代表三个物理显示器的实机测试 |
|
||||
| 源码回归 | **461 passed in 283.23s**;`build/test-evidence/toolbar-source.xml` |
|
||||
| 便携包 | **16 passed in 27.09s**;`build/test-evidence/toolbar-packaged.xml`;包含九个 feature 启动、中文路径、独立运行库 |
|
||||
| 代码审查 | 外壳初始通道/尺寸/窄屏三项已修复并复审通过;最终设置布局 P2 已修复并复审通过 |
|
||||
横向工具栏、九个功能面板及本轮实机验收已完成。正式包已通过真实 Start 注册到 DxDesigner 持久启动菜单,普通重启后自动加载。用户当前宿主 PID 44008 保留,已从其原生菜单打开最终工具并确认桥接已连接;面板收起,仅保留一排工具栏。该宿主的工程没有写回或关闭。
|
||||
|
||||
## 原生选择验证
|
||||
- 正式包:`release/一叶知秋_重构版_横向工具栏版`。
|
||||
- 发布 ZIP:`release/一叶知秋_重构版_横向工具栏版_Win11_x64.zip`。
|
||||
- ZIP SHA-256:`5ced1cc2a57888898c02eacb9c486a8e14463ddda59ccddc5c7d13f29ea87cd6`。
|
||||
- EXE SHA-256:`ceb06314529ae805bf03c4409cc741a92e3ee5a40aac56e345031c4cd8af04aa`。
|
||||
- 原生证据根目录:`%LOCALAPPDATA%/DxProductivity/acceptance/toolbar-20261011`。下表原生记录均相对此目录。
|
||||
|
||||
独立 DxDesigner 宿主 **PID 83848**,工程为 `%LOCALAPPDATA%/DxProductivity/acceptance/toolbar-20261011/1GPHY_toolbar/1GPHY_RTL8211F.prj`。用户原宿主 **PID 44008** 保留,没有写回或关闭用户工程。
|
||||
写回验收在独立工程副本 `1GPHY_toolbar/1GPHY_RTL8211F.prj` 中进行,全部 114 个器件的值、位置和可见性恢复。初始验收宿主 PID 83848 已正常关闭;普通重启后的验收宿主为 PID 81148。
|
||||
|
||||
冻结 GUI **PID 82276** 由独立宿主的真实菜单动作打开。原生 COM 在副本中完成 CE17 单选、改选 LE03、两者多选、取消选择,以及收起面板后再选 CE17。五个用例均在工具栏反映,完整提示包含对应位号和图页,过程无需手动刷新。
|
||||
## 功能与窗口实测
|
||||
|
||||
证据:`%LOCALAPPDATA%/DxProductivity/acceptance/toolbar-20261011/live-selection-locked/selection-acceptance.json`。整段脚本、COM 调用和 UIA 读取的耗时约 **2.0—3.8 秒**,不能将其作为纯点击到显示的延迟或 150 ms 轮询间隔的承诺。
|
||||
| 项目 | 结果 | 证据 |
|
||||
|---|---|---|
|
||||
| 单行工具栏 | 位号、属性、显示、检查、网络、BOM、PDF 七个一级入口;历史与设置在更多中。125% DPI 实测 965×55 物理像素,即 772×44 逻辑像素 | `final-window-ui/native-ui.json`、`user-final-toolbar.png` |
|
||||
| 九个面板 | 逐入口打开;表格页实测 780×480、PDF 660×390、设置 660×340 逻辑像素;按钮可达 | `final-window-ui/page-0.png` 至 `page-8.png`、`final-package-controls/toolbar-controls.json` |
|
||||
| 展开与收起 | 同入口再次点击收起,关闭和最小化收起,重新展开正常;隐藏期间心跳继续 | `final-window-ui/native-ui.json`、`final-package-controls/toolbar-controls.json` |
|
||||
| 拖动与主题 | 拖动手柄移动窗口,明暗主题切换两次成功 | 同上 |
|
||||
| 实时选择 | CE17 单选、改选 LE03、多选、取消以及收起后选择均无需手动刷新,工具栏和面板反映实际选择 | `live-selection-final/live-selection-acceptance.json` |
|
||||
| 位号与历史 | C9000 写回、历史恢复,两次事务均为 applied,原生读回确认 | `final-package-writes/toolbar-writes.json` |
|
||||
| 属性与显示 | Value 修改/恢复、Part Name 可见性修改/恢复;连续六次事务全部通过;114 个器件全部恢复 | 同上 |
|
||||
| 设计检查 | 孤立网络、全部网络、Value 遗漏、Value1 遗漏均通过新版界面执行 | `native-read-tools-verified/native-read-tools.json` |
|
||||
| 网络工具 | 网络列表与 GND 跨页查询通过 | 同上 |
|
||||
| BOM | 真实保存对话框输出 XLS,原生 Excel 状态 ok,重新读取验证 CE17/LE03;收起时完成 | 同上、`native-read-tools-verified/BOM-工具栏.xls` |
|
||||
| PDF 三范围 | 整工程、当前页、指定原理图/Block 分别生成 PDF;本副本只有一页,三种输出各一页 | `pdf-verified/pdf-toolbar-acceptance.json` |
|
||||
| PDF 中文与配色 | 三份输出均验证四段中文及参考红蓝色;Poppler 渲染后目视确认中文与配色 | 同上、`pdf-verified/render-project.png` |
|
||||
| 打开输出目录 | 真实点击按钮,Explorer 打开指定 Block 输出目录,记录路径与 HWND | 同上 |
|
||||
| 原生保存自动导出 | 界面开启后,收起面板,两次原生 SaveAll 分别导出修改内容及恢复内容;结束后关闭自动导出并恢复 Value | `auto-pdf-verified/toolbar-auto-pdf.json` |
|
||||
| 设置 | 本地版本检查 up-to-date,设置保存与恢复;最小尺寸下按钮可达 | `final-package-controls/toolbar-controls.json` |
|
||||
| Start 持久菜单 | 正式包真实 Start 连续注册两次;普通 viewdraw.exe 启动验收工程,无手工菜单加载,主菜单/图页菜单各一个入口,各八个动作 | `restart-verified/persistent-menu.json`、`restart-verified/native-menu-readback.txt` |
|
||||
| 原生八个菜单动作 | 位号、属性、显示、检查、BOM、PDF 均打开正确页面并连接;兼容性检测枚举 114 器件;使用说明由 Word 打开 | `final-menu-acceptance.json` |
|
||||
| 当前宿主部署 | PID 44008 的两处菜单各一个入口、八个动作;最终 EXE PID 54712 已连接并留在收起状态 | `user-final-deployment.json`、`user-host-menu-readback.txt` |
|
||||
|
||||
## 尚待前台验收
|
||||
选择用例的脚本整体耗时约 1.2—2.7 秒,含 COM 调用和 UIA 读取,不能作为纯选择到显示延迟。150 ms 轮询间隔也不等于实机延迟。BOM 的 UsedRange 为 331 行,包含模板格式,不能将其解释为 331 条数据。
|
||||
|
||||
实机验收期间 Windows 已锁屏。`GetForegroundWindow` 返回“Windows 默认锁屏界面”,实际点击坐标对应 LockApp 的 Backstop Window,点击被锁屏截获。正常 Qt UIA 状态读取和原生 COM 选择验证可继续;前台鼠标操作须解锁后进行。已通过异步问题请求用户解锁。
|
||||
## 更新与回滚
|
||||
|
||||
- 待确认真实鼠标点击七个一级入口、更多中的历史/设置,以及拖动、最小化、展开行为。
|
||||
- 待确认新版三个 PDF 范围的 GUI 导出、目录按钮和原生保存自动导出。PDF 引擎本轮未改,既有中文/配色实机记录仍见 `text-selection-acceptance-20261011.md`;该旧记录不能代替本轮 GUI 验收。
|
||||
- 待确认位号/属性/可见性写回与历史恢复、检查/网络查询及 BOM 原生 Excel 输出在新版界面中的完整流程。
|
||||
- 新包已复制到源码根目录 `release/一叶知秋_重构版_横向工具栏版`;已通过验证的源码与便携包可评审。持久菜单最终切换到新包与正式前台验收留待解锁后完成。
|
||||
展开、收起两种状态均使用最终 EXE 的临时副本,验证更新器等待旧 UI 退出、备份、替换、启动探针及新版持续运行;随后故意令启动探针返回 3,旧目录与标记恢复,日志记录 rolled-back。测试进程退出,正式发布目录未修改,更新后程序不依赖 PATH 中的 Python。
|
||||
|
||||
## 已知独立限制
|
||||
证据:`update-expanded.json`、`update-collapsed.json`。临时副本位于 `G:/CodexAcceptance/yiyezhqiu-toolbar-20261011`,各自使用独立 LOCALAPPDATA。退出通过工具栏 WM_CLOSE 触发同一个 request_exit;因桌面再次锁屏,该步骤不是鼠标点击更新按钮的验收。更新控制器发起安装后的显式退出另由现有 `tests/ui/test_update_launch.py` 覆盖;更多菜单的鼠标退出已在先前前台检查中验证。
|
||||
|
||||
PON 工程的完整设计快照在原生 DesignComponents 枚举阶段阻塞,根因仍未确认。该问题与界面布局改动分别记录,本轮不将它标记为已修复。
|
||||
最初放在 C 盘的用例失败:剩余约 99 MB,165 MB 的发布包备份仅复制约 118 MB,install.log 为零字节,旧目录与标记保留。迁到空间充足的 G 盘后两种状态的安装与回滚通过;该记录不作为磁盘耗尽场景的完整恢复保证。
|
||||
|
||||
## 修复与自动验证
|
||||
|
||||
实机发现并修复了 Excel 保存路径的斜杠格式、Qt 历史恢复确认结果比较,以及原生快照刷新后旧集合释放导致器件代理失效。现保留每次 DesignComponents 集合至桥接会话结束;应用与恢复后自动刷新快照,并保留事务成功、拒绝和回滚失败等终态。
|
||||
|
||||
| 检查 | 结果 | 记录 |
|
||||
|---|---|---|
|
||||
| 最终源码 | 476 passed in 305.72s | `build/test-evidence/toolbar-final-source.xml` |
|
||||
| 最终便携包 | 16 passed in 32.03s,含九功能路由、中文路径和独立运行库 | `build/test-evidence/toolbar-final-packaged.xml` |
|
||||
| 终态保留与更新退出 | 17 passed in 98.60s | `build/test-evidence/toolbar-outcome-green.xml` |
|
||||
| 原生集合定向回归 | 11 passed | `build/test-evidence/toolbar-native-collection.xml` |
|
||||
| 修复代码复审 | 已处理两项 P2,复审无剩余可操作问题 | `build/test-evidence/toolbar-native-final-review.md` |
|
||||
| DPI 与屏幕布局 | Qt 渲染覆盖 100%/125%/150%;负坐标、窄屏、屏幕移除与尺寸恢复由模拟覆盖 | 前期 Qt 渲染及布局验证;物理桌面仅实测 125% |
|
||||
|
||||
PDF 设置已从验收前备份恢复,自动导出关闭;用户宿主打开工具时加载该工程的默认输出目录。已检查没有剩余的测试 Excel 会话。
|
||||
|
||||
## 已知限制
|
||||
|
||||
- PON 工程完整设计快照仍在原生 DesignComponents 枚举阶段阻塞,未修复。本轮 1GPHY 通过结果不能外推为 PON 全量桥接通过。PON 多页 PDF 的既有引擎记录见 `text-selection-acceptance-20261011.md`。
|
||||
- 为维持原生器件代理有效而保留集合,长会话内大量完整刷新时的内存增长尚未测量。
|
||||
- 当前实机是 125% DPI;100%/150% 与多屏边界由渲染/模拟验证,不代表多台物理显示器实测。
|
||||
@@ -7,6 +7,9 @@
|
||||
- 收起后工具栏继续显示选择与任务状态;悬停可查看完整位号、工程、图页和状态信息。拖动左侧手柄移动,位置与各页面大小会保存。
|
||||
- 页面移除固定左导航、重复标题与说明,操作按钮移到对应页面。低频设置折叠为高级选项,并显示当前有效参数摘要。
|
||||
- PDF 保留三种范围、输出目录、打开目录和保存后自动导出;配色、文字处理与引擎设置可在高级选项中调整。
|
||||
- 应用位号、属性、显示状态及历史恢复后自动读取最新工程快照,预览与恢复使用写回后的数据。
|
||||
- 修复历史恢复点击 Yes 后没有执行,以及保存对话框的路径格式导致原生 Excel 无法保存 BOM 的问题。
|
||||
- 修复刷新快照后的连续写回失效;自动刷新保留应用、拒绝和回滚结果,避免覆盖失败提示。
|
||||
|
||||
## 中文 PDF 与实时选择
|
||||
|
||||
|
||||
@@ -235,7 +235,6 @@ Sub DxBridgePumpRefresh(runRoot, runId, objectMap, originalMap, _
|
||||
Dim refreshPath
|
||||
Dim claimPath
|
||||
Dim refreshedObjects
|
||||
Dim refreshedOriginals
|
||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||
refreshPath = fso.BuildPath(runRoot, "refresh.request")
|
||||
If Not fso.FileExists(refreshPath) Then Exit Sub
|
||||
@@ -243,11 +242,9 @@ Sub DxBridgePumpRefresh(runRoot, runId, objectMap, originalMap, _
|
||||
If Not DxBridgeClaimFile(fso, refreshPath, claimPath) Then Exit Sub
|
||||
Call DxWriteProgress(runRoot, "processing")
|
||||
Set refreshedObjects = CreateObject("Scripting.Dictionary")
|
||||
Set refreshedOriginals = CreateObject("Scripting.Dictionary")
|
||||
If DxRefreshSnapshot(runRoot, runId, refreshedObjects, refreshedOriginals, _
|
||||
If DxRefreshSnapshot(runRoot, runId, refreshedObjects, originalMap, _
|
||||
snapshotId) Then
|
||||
Set objectMap = refreshedObjects
|
||||
Set originalMap = refreshedOriginals
|
||||
Call DxWriteProgress(runRoot, "waiting")
|
||||
End If
|
||||
On Error Resume Next
|
||||
|
||||
@@ -46,6 +46,7 @@ Function DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _
|
||||
Dim netsText
|
||||
Dim selectedNetsText
|
||||
Dim snapshotSequence
|
||||
Dim collectionKey
|
||||
Dim activeBlockName
|
||||
Dim currentSheetNumberJson
|
||||
|
||||
@@ -81,8 +82,12 @@ Function DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _
|
||||
componentCount = 0
|
||||
componentText = ""
|
||||
|
||||
For Each component In Application.DesignComponents( _
|
||||
' Dx invalidates component proxies when a previous native collection is
|
||||
' released. Own every enumerated collection for this bridge session.
|
||||
collectionKey = "components-" & CStr(originalMap.Count + 1)
|
||||
originalMap.Add collectionKey, Application.DesignComponents( _
|
||||
"", topBlock, "-1", "STD", True)
|
||||
For Each component In originalMap(collectionKey)
|
||||
componentCount = componentCount + 1
|
||||
bridgeId = "c" & DxBridgePad(componentCount, 6)
|
||||
stableUid = DxBridgeStableUid(component)
|
||||
|
||||
@@ -303,6 +303,16 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
|
||||
history_controller.load_snapshot(snapshot)
|
||||
pdf_export_controller.load_snapshot(snapshot)
|
||||
if run_paths is not None:
|
||||
# Native transactions update the design before publishing their status.
|
||||
# Re-read it so previews and history restore use the verified new values.
|
||||
for writer in (controller, property_change_controller, property_visibility_controller):
|
||||
writer.apply_completed.connect(
|
||||
lambda state: _request_refresh(window, controller, run_paths, operation_state=state)
|
||||
)
|
||||
if history_controller is not None:
|
||||
history_controller.status_changed.connect(
|
||||
lambda state: _request_refresh(window, controller, run_paths, operation_state=state)
|
||||
)
|
||||
watcher = _install_snapshot_watcher(window, request_path, run_paths)
|
||||
if watcher is not None and history_controller is not None:
|
||||
watcher.snapshot_reloaded.connect(
|
||||
@@ -330,16 +340,20 @@ def _request_refresh(
|
||||
window: MainWindow,
|
||||
controller: RefDesController,
|
||||
run_paths: RunPaths | None,
|
||||
*,
|
||||
operation_state: str | None = None,
|
||||
) -> None:
|
||||
if run_paths is None:
|
||||
controller.refresh_plan()
|
||||
return
|
||||
refresh_request = run_paths.root / "refresh.request"
|
||||
window._pending_snapshot_outcome = _status_text(operation_state) if operation_state is not None else None
|
||||
try:
|
||||
refresh_request.write_text("snapshot\n", encoding="utf-8")
|
||||
window.set_operation_status("已请求宿主刷新设计快照…")
|
||||
window.set_operation_status(window._pending_snapshot_outcome or "已请求宿主刷新设计快照…")
|
||||
except OSError as error:
|
||||
_report_error(window, "刷新失败", str(error))
|
||||
outcome = window._pending_snapshot_outcome
|
||||
_report_error(window, "刷新失败", (outcome + ";" if outcome else "") + str(error))
|
||||
|
||||
|
||||
class _SnapshotWatcher(QObject):
|
||||
@@ -388,7 +402,9 @@ class _SnapshotWatcher(QObject):
|
||||
controller.load_snapshot(snapshot)
|
||||
_set_snapshot_status(self._window, snapshot)
|
||||
self.snapshot_reloaded.emit(snapshot)
|
||||
self._window.set_operation_status("设计快照已刷新")
|
||||
outcome = getattr(self._window, '_pending_snapshot_outcome', None)
|
||||
self._window._pending_snapshot_outcome = None
|
||||
self._window.set_operation_status(outcome or "设计快照已刷新")
|
||||
|
||||
|
||||
def _install_snapshot_watcher(
|
||||
|
||||
@@ -71,6 +71,9 @@ 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}")
|
||||
# QFileDialog uses forward slashes even on Windows. Excel SaveAs
|
||||
# needs the platform path separators passed to its native COM host.
|
||||
output_path = str(Path(output_path))
|
||||
payload = self._build_payload(output_path)
|
||||
(self.run_paths.root / "bom-export-status.json").unlink(missing_ok=True)
|
||||
atomic_write_text(
|
||||
|
||||
@@ -168,4 +168,4 @@ class HistoryController(QObject):
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.Cancel,
|
||||
QMessageBox.StandardButton.Cancel,
|
||||
)
|
||||
return answer is QMessageBox.StandardButton.Yes
|
||||
return answer == QMessageBox.StandardButton.Yes
|
||||
@@ -68,6 +68,22 @@ def test_bom_export_clears_old_status_and_disables_duplicate_requests(
|
||||
controller._status_timer.stop()
|
||||
|
||||
|
||||
def test_bom_export_converts_qt_dialog_path_for_native_excel(
|
||||
qtbot, tmp_path, snapshot_factory
|
||||
):
|
||||
controller, page, paths = _controller(qtbot, tmp_path, snapshot_factory())
|
||||
output = tmp_path / 'BOM导出.xls'
|
||||
|
||||
# QFileDialog returns forward slashes on Windows; Excel SaveAs requires
|
||||
# the platform path separators used by the native COM host.
|
||||
controller.export_to(output.as_posix())
|
||||
|
||||
payload = json.loads((tmp_path / 'bom-export.json').read_text(encoding='utf-8'))
|
||||
assert payload['output_path'] == str(output)
|
||||
assert controller._requested_output_path == str(output)
|
||||
controller._status_timer.stop()
|
||||
|
||||
|
||||
def test_bom_mailbox_write_failure_can_be_retried(
|
||||
qtbot, tmp_path, snapshot_factory, monkeypatch
|
||||
):
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QTimer
|
||||
from PySide6.QtWidgets import QApplication, QMessageBox
|
||||
|
||||
from dx_productivity.bridge.run_store import RunStore
|
||||
from dx_productivity.domain.models import HistoryEntry
|
||||
from dx_productivity.ui.history_controller import HistoryController
|
||||
from dx_productivity.ui.history_page import HistoryPage
|
||||
|
||||
|
||||
@pytest.mark.parametrize('button,expected', (
|
||||
(QMessageBox.StandardButton.Yes, True),
|
||||
(QMessageBox.StandardButton.Cancel, False),
|
||||
))
|
||||
def test_history_restore_uses_real_qt_confirmation_result(qtbot, tmp_path, button, expected):
|
||||
page = HistoryPage()
|
||||
qtbot.addWidget(page)
|
||||
store = RunStore(tmp_path)
|
||||
controller = HistoryController(page, run_store=store, run_paths=store.create_run())
|
||||
entry = HistoryEntry(datetime.now(timezone.utc), 'confirmation', 'test',
|
||||
Path('backup.json'), 'applied', 1)
|
||||
|
||||
def answer():
|
||||
modal = QApplication.activeModalWidget()
|
||||
selected = modal.button(button)
|
||||
selected.click()
|
||||
|
||||
QTimer.singleShot(0, answer)
|
||||
assert controller._confirm_restore(entry, 1) == expected
|
||||
@@ -1,7 +1,39 @@
|
||||
import json
|
||||
import os
|
||||
import pytest
|
||||
|
||||
from dx_productivity.ui.app import create_main_window
|
||||
from dx_productivity.ui.app import _status_text, _SnapshotWatcher
|
||||
|
||||
|
||||
@pytest.mark.parametrize('controller_name,signal_name', (
|
||||
('refdes_controller', 'apply_completed'),
|
||||
('property_change_controller', 'apply_completed'),
|
||||
('property_visibility_controller', 'apply_completed'),
|
||||
('history_controller', 'status_changed'),
|
||||
))
|
||||
@pytest.mark.parametrize('state', ('applied', 'rejected', 'rollback-failed'))
|
||||
def test_native_transaction_completion_requests_fresh_snapshot(
|
||||
qtbot, fixture_path, tmp_path, monkeypatch, controller_name, signal_name, state
|
||||
):
|
||||
monkeypatch.setenv('LOCALAPPDATA', str(tmp_path / 'local'))
|
||||
request = tmp_path / 'request.json'
|
||||
request.write_bytes((fixture_path / 'request-basic.json').read_bytes())
|
||||
window = create_main_window(request)
|
||||
qtbot.addWidget(window)
|
||||
|
||||
getattr(getattr(window, controller_name), signal_name).emit(state)
|
||||
|
||||
assert (tmp_path / 'refresh.request').read_text(encoding='utf-8') == 'snapshot\n'
|
||||
assert window.operation_status.text() == _status_text(state)
|
||||
original_mtime = request.stat().st_mtime
|
||||
data = json.loads(request.read_text(encoding='utf-8'))
|
||||
data['snapshot_id'] = 'after-transaction'
|
||||
request.write_text(json.dumps(data), encoding='utf-8')
|
||||
os.utime(request, (original_mtime + 2, original_mtime + 2))
|
||||
window.findChildren(_SnapshotWatcher)[0]._check()
|
||||
assert window.refdes_controller.snapshot.snapshot_id == 'after-transaction'
|
||||
assert window.operation_status.text() == _status_text(state)
|
||||
|
||||
|
||||
def test_snapshot_refresh_updates_every_design_feature_and_project_label(
|
||||
|
||||
@@ -19,6 +19,9 @@ Dim ParentBlock
|
||||
Dim Application
|
||||
Dim ActiveView
|
||||
Dim RequestText
|
||||
Dim InitialComponentReleased
|
||||
Dim RefreshedMap
|
||||
Dim FreshComponent
|
||||
|
||||
Class FakeParentBlock
|
||||
Public Name
|
||||
@@ -42,6 +45,10 @@ Class FakeComponent
|
||||
Public Value
|
||||
Public ComponentName
|
||||
|
||||
Private Sub Class_Terminate()
|
||||
If Refdes = "R?" Then InitialComponentReleased = True
|
||||
End Sub
|
||||
|
||||
Public Function GetName(kind)
|
||||
GetName = ComponentName
|
||||
End Function
|
||||
@@ -169,6 +176,27 @@ Call AssertContains(RequestText, """nets"": []", "nets field")
|
||||
Call AssertContains(RequestText, """selected_nets"": []", "selected nets field")
|
||||
Call AssertContains(RequestText, """locked"": false", "locked field")
|
||||
|
||||
' A new native enumeration can replace all bridge mappings. Keep the
|
||||
' previous collection alive until the bridge exits: Dx releases the shared
|
||||
' query context when an older collection is destroyed.
|
||||
InitialComponentReleased = False
|
||||
Set FreshComponent = New FakeComponent
|
||||
FreshComponent.Refdes = "R42"
|
||||
FreshComponent.UID = "uid-1"
|
||||
Set FreshComponent.Parent = ParentBlock
|
||||
Set FreshComponent.Location = Component.Location
|
||||
FreshComponent.ComponentName = "R1"
|
||||
Set Application.TheComponent = FreshComponent
|
||||
Set ActiveView.TheComponent = FreshComponent
|
||||
Set Component = Nothing
|
||||
Set RefreshedMap = CreateObject("Scripting.Dictionary")
|
||||
If Not DxRefreshSnapshot(RunRoot, RunId, RefreshedMap, OriginalMap, SnapshotId) Then Call Fail("refresh failed")
|
||||
Set ObjectMap = RefreshedMap
|
||||
Call AssertEqual(InitialComponentReleased, False, "previous native collection remains owned")
|
||||
Call AssertEqual(ObjectMap("c000001").Refdes, "R42", "fresh mappings use refreshed objects")
|
||||
Set OriginalMap = Nothing
|
||||
Call AssertEqual(InitialComponentReleased, True, "native collections release at bridge exit")
|
||||
|
||||
Fso.DeleteFolder TempRoot, True
|
||||
WScript.Echo "RefDes export assertions passed"
|
||||
|
||||
|
||||
@@ -24,6 +24,9 @@ def main():
|
||||
request = Path(args[args.index("--request") + 1].strip('"'))
|
||||
snapshot = json.loads(request.read_text(encoding="utf-8-sig"))
|
||||
ui = ToolbarUI(tool.pid)
|
||||
if not ui.panel.exists(timeout=0.2) or not ui.panel.is_visible():
|
||||
ui.expand()
|
||||
panel_handle = ui.panel.handle
|
||||
evidence = options.evidence or Path(os.environ["LOCALAPPDATA"]) / "DxProductivity/acceptance/toolbar-20261011"
|
||||
evidence.mkdir(parents=True, exist_ok=True)
|
||||
handle = ui.toolbar.handle
|
||||
@@ -35,7 +38,7 @@ def main():
|
||||
if button.element_info.control_type in ('Button', 'CheckBox')]
|
||||
centers = [(rect.top + rect.bottom) / 2 for rect in buttons]
|
||||
assert max(centers) - min(centers) <= 2, buttons
|
||||
ui.toolbar.capture_as_image().save(str(evidence / "toolbar.png"))
|
||||
ui.capture(ui.toolbar).save(str(evidence / "toolbar.png"))
|
||||
if ui.panel.exists(timeout=0.2) and ui.panel.is_visible():
|
||||
ui.collapse()
|
||||
pages = []
|
||||
@@ -45,7 +48,7 @@ def main():
|
||||
panel_dpi = ctypes.windll.user32.GetDpiForWindow(ui.panel.handle)
|
||||
assert panel_bounds[2] * 96 / panel_dpi <= 800, (name, panel_bounds)
|
||||
assert panel_bounds[3] * 96 / panel_dpi <= 520, (name, panel_bounds)
|
||||
ui.panel.capture_as_image().save(str(evidence / f"page-{len(pages)}.png"))
|
||||
ui.capture(ui.panel).save(str(evidence / f"page-{len(pages)}.png"))
|
||||
pages.append({"page": name, "client_rect": panel_bounds, "dpi": panel_dpi})
|
||||
ui.collapse()
|
||||
progress = request.with_name("apply-progress.json")
|
||||
@@ -63,10 +66,10 @@ def main():
|
||||
mouse.release(coords=win32gui.GetCursorPos())
|
||||
win32api.SetCursorPos(pointer)
|
||||
moved = wait_for(lambda: win32gui.GetWindowRect(handle) if win32gui.GetWindowRect(handle) != first else None)
|
||||
assert not ui.panel.is_visible()
|
||||
assert not win32gui.IsWindowVisible(panel_handle)
|
||||
ui.feature("PDF 导出")
|
||||
ui.panel.minimize()
|
||||
wait_for(lambda: not ui.panel.is_visible())
|
||||
wait_for(lambda: not win32gui.IsWindowVisible(panel_handle))
|
||||
ui.expand()
|
||||
assert "PDF 导出" in ui.texts(ui.panel)
|
||||
if options.leave_collapsed:
|
||||
|
||||
@@ -36,7 +36,9 @@ def main():
|
||||
ui.feature(page)
|
||||
combo = ui.panel.child_window(title='检查类型', control_type='ComboBox')
|
||||
for check in checks:
|
||||
combo.select(check)
|
||||
types = ('孤立网络', '全部网络', '跨页查询') if page == '网络工具' else (
|
||||
'孤立网络', '全部网络', 'Value 遗漏', 'Value1 遗漏', '跨页查询')
|
||||
ui.select_combo(combo, types.index(check), check)
|
||||
if check == '跨页查询':
|
||||
ui.panel.child_window(control_type='Edit').set_edit_text('GND')
|
||||
ui.panel.child_window(title='运行检查', control_type='Button').invoke()
|
||||
@@ -49,16 +51,15 @@ def main():
|
||||
ui.collapse()
|
||||
ui.feature('BOM 工具')
|
||||
wait_for(lambda: any(text.startswith('BOM 行数:') for text in ui.texts(ui.panel)), 10)
|
||||
output = base / 'BOM-toolbar.xls'
|
||||
output = base / 'BOM-工具栏.xls'
|
||||
if output.exists():
|
||||
raise AssertionError('Use a fresh evidence directory to retain the old workbook')
|
||||
ui.panel.child_window(title='导出 Excel…', control_type='Button').click_input()
|
||||
dialog = ui.app.window(title='导出 BOM')
|
||||
dialog = ui.native_dialog('导出 BOM')
|
||||
dialog.wait('visible', timeout=10)
|
||||
filename = dialog.child_window(auto_id='1001', control_type='Edit')
|
||||
filename = dialog.child_window(control_id=1001, class_name='Edit')
|
||||
filename.set_edit_text(str(output))
|
||||
save = next(button for button in dialog.descendants(control_type='Button')
|
||||
if '保存' in button.window_text() or 'Save' in button.window_text())
|
||||
save = dialog.child_window(control_id=1, class_name='Button')
|
||||
save.click_input()
|
||||
ui.collapse()
|
||||
wait_for(lambda: output.is_file() and output.stat().st_size > 4096, 60)
|
||||
|
||||
@@ -125,14 +125,23 @@ Next
|
||||
toolbar_ui = ToolbarUI(tool.pid)
|
||||
window = toolbar_ui.panel
|
||||
window.wait("visible", timeout=15)
|
||||
texts = [x.window_text() for x in window.descendants(control_type="Text")]
|
||||
assert expected in texts, (feature, texts)
|
||||
assert "桥接已连接" in texts and PROJECT.name in texts, texts
|
||||
def connected_page():
|
||||
if toolbar_ui.toolbar.child_window(title='展开面板', control_type='Button').exists(timeout=.2):
|
||||
toolbar_ui.expand()
|
||||
try:
|
||||
texts = toolbar_ui.texts(window)
|
||||
except Exception:
|
||||
return None
|
||||
return texts if expected in texts and '桥接已连接' in texts and PROJECT.name in texts else None
|
||||
texts = wait_for(connected_page, 15)
|
||||
results.append({"feature": feature, "pid": tool.pid, "selected_page": expected, "bridge": "connected", "project": PROJECT.name, "executable": tool.executable})
|
||||
toolbar_ui.exit()
|
||||
# Route acceptance ends each launch through explicit toolbar close;
|
||||
# the More-menu exit itself is covered by the controls acceptance.
|
||||
win32gui.PostMessage(toolbar_ui.toolbar.handle, 0x10, 0, 0)
|
||||
toolbar_ui.toolbar.wait_not('exists', timeout=15)
|
||||
elif feature == "compatibility":
|
||||
def close_completion():
|
||||
probe = BASE.parent.parent / "compatibility.json"
|
||||
probe = Path(os.environ["LOCALAPPDATA"]) / "DxProductivity/compatibility.json"
|
||||
if not probe.exists() or probe.stat().st_mtime < started_at:
|
||||
return None
|
||||
try:
|
||||
@@ -148,7 +157,7 @@ Next
|
||||
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"
|
||||
probe = Path(os.environ["LOCALAPPDATA"]) / "DxProductivity/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"):
|
||||
|
||||
@@ -12,18 +12,26 @@ import tempfile
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from pywinauto import Application
|
||||
import win32gui
|
||||
import win32process
|
||||
|
||||
from dx_productivity.update.installer import InstallPlan, prepare_updater
|
||||
from packaged_menu import tools_running, wait_for
|
||||
from toolbar_ui import ToolbarUI
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("release", type=Path)
|
||||
parser.add_argument("archive", type=Path)
|
||||
parser.add_argument("--collapsed", action="store_true")
|
||||
parser.add_argument("--evidence", type=Path)
|
||||
parser.add_argument("--test-root", type=Path, help="Disposable copy parent on a disk with room for backup and staging")
|
||||
parser.add_argument("--exit-method", choices=("menu", "window-close"), default="menu")
|
||||
options = parser.parse_args()
|
||||
base = Path(tempfile.gettempdir()) / f"dx-packaged-update-{uuid.uuid4().hex[:8]}"
|
||||
test_root = options.test_root or Path(tempfile.gettempdir())
|
||||
test_root.mkdir(parents=True, exist_ok=True)
|
||||
base = test_root.resolve() / f"dx-packaged-update-{uuid.uuid4().hex[:8]}"
|
||||
current = base / "中文 便携工具"
|
||||
shutil.copytree(options.release, current)
|
||||
marker = current / "before-update.txt"
|
||||
@@ -33,10 +41,28 @@ def main():
|
||||
environment["PATH"] = r"C:\Windows\System32;C:\Windows"
|
||||
environment.pop("PYTHONPATH", None)
|
||||
environment.pop("QT_QPA_PLATFORM", None)
|
||||
profile = base / "profile"
|
||||
scratch = base / "scratch"
|
||||
profile.mkdir()
|
||||
scratch.mkdir()
|
||||
environment["LOCALAPPDATA"] = str(profile)
|
||||
environment["TEMP"] = environment["TMP"] = str(scratch)
|
||||
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)
|
||||
old_toolbar = ToolbarUI(old_ui.pid)
|
||||
if not options.collapsed:
|
||||
old_toolbar.expand()
|
||||
|
||||
def exit_toolbar(toolbar):
|
||||
if options.exit_method == "window-close":
|
||||
# The toolbar's closeEvent uses request_exit, including shutdown;
|
||||
# the shared panel's closeEvent only collapses and is not used.
|
||||
handle = toolbar.toolbar.handle
|
||||
assert win32process.GetWindowThreadProcessId(handle)[1] == toolbar.pid
|
||||
win32gui.PostMessage(handle, 0x10, 0, 0)
|
||||
toolbar.toolbar.wait_not("exists", timeout=15)
|
||||
else:
|
||||
toolbar.exit()
|
||||
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"),
|
||||
@@ -46,9 +72,11 @@ def main():
|
||||
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()
|
||||
exit_toolbar(old_toolbar)
|
||||
assert old_ui.wait(15) == 0
|
||||
assert process.wait(60) == 0, (base / "install.log").read_text(encoding="utf-8")
|
||||
return_code = process.wait(60)
|
||||
install_log = base / "install.log"
|
||||
assert return_code == 0, (return_code, str(base), install_log.read_text(encoding="utf-8") if install_log.exists() else "No install log")
|
||||
assert not marker.exists()
|
||||
assert any(p.is_file() for p in (base / "backups").glob("*/before-update.txt"))
|
||||
|
||||
@@ -57,11 +85,10 @@ def main():
|
||||
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)
|
||||
updated_toolbar = ToolbarUI(tool.pid)
|
||||
time.sleep(2)
|
||||
assert window.exists(), "Updated UI closed after the smoke probe"
|
||||
window.close()
|
||||
assert updated_toolbar.toolbar.exists(), "Updated UI closed after the smoke probe"
|
||||
exit_toolbar(updated_toolbar)
|
||||
wait_for(lambda: not restarted(), 15)
|
||||
print("PASS PACKAGED UPDATE AND PERSISTENT RESTART", flush=True)
|
||||
|
||||
@@ -78,8 +105,11 @@ def main():
|
||||
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"
|
||||
"smoke_failure_rolled_back": True, "source_release_modified": False, "python_on_path": False,
|
||||
"old_ui_collapsed": options.collapsed, "exit_method": options.exit_method,
|
||||
"profile_isolated": True}
|
||||
report = options.evidence or Path.cwd() / "build/test-evidence/packaged-update.json"
|
||||
report.parent.mkdir(parents=True, exist_ok=True)
|
||||
report.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print("PASS PACKAGED UPDATE ROLLBACK", flush=True)
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import shlex
|
||||
import time
|
||||
|
||||
from pypdf import PdfReader
|
||||
from pypdf.errors import PdfReadError
|
||||
from packaged_menu import tools_running, wait_for
|
||||
from pdf_palette import color_operations
|
||||
from toolbar_ui import ToolbarUI
|
||||
@@ -32,19 +33,25 @@ def main():
|
||||
ui.collapse()
|
||||
ui.feature('PDF 导出')
|
||||
scope = ui.panel.child_window(title='导出范围', control_type='ComboBox')
|
||||
directory = ui.panel.child_window(title='PDF 输出目录', control_type='Edit')
|
||||
results = []
|
||||
for index, name in enumerate(('project', 'page', 'block')):
|
||||
output = base / name
|
||||
if output.exists():
|
||||
raise AssertionError(f'Retain previous evidence and choose a fresh directory: {output}')
|
||||
scope.select(index)
|
||||
ui.select_combo(scope, index, ('整工程', '当前页', '指定原理图或 Block')[index])
|
||||
edits = [e for e in ui.panel.descendants(control_type='Edit')
|
||||
if e.is_visible() and not e.iface_value.CurrentIsReadOnly]
|
||||
if name == 'block':
|
||||
ui.panel.child_window(title='指定 Block', control_type='Edit').set_edit_text(snapshot['active_block_name'])
|
||||
directory.set_edit_text(str(output))
|
||||
assert len(edits) == 2, edits
|
||||
edits[0].set_edit_text(snapshot['active_block_name'])
|
||||
edits[-1].set_edit_text(str(output))
|
||||
ui.panel.child_window(title='导出 PDF', control_type='Button').invoke()
|
||||
began = time.monotonic()
|
||||
ui.collapse()
|
||||
# sch2pdf publishes a raw file before the font repair has finished.
|
||||
# The toolbar's completion message is emitted after that repair.
|
||||
wait_for(lambda: '任务:PDF 已导出' in ui.status_detail()
|
||||
and str(output) in ui.status_detail(), 90)
|
||||
def published():
|
||||
candidates = tuple(output.glob('*.pdf'))
|
||||
if not candidates:
|
||||
@@ -53,7 +60,7 @@ def main():
|
||||
try:
|
||||
pdf = PdfReader(candidates[0])
|
||||
return candidates[0], pdf if len(pdf.pages) else None
|
||||
except (OSError, ValueError):
|
||||
except (OSError, ValueError, PdfReadError):
|
||||
return None
|
||||
path, pdf = wait_for(published, 90)
|
||||
assert len(pdf.pages) == 1
|
||||
@@ -68,7 +75,7 @@ def main():
|
||||
'reference_red_blue_verified': True, 'export_finished_while_collapsed': True,
|
||||
'elapsed_seconds': round(time.monotonic() - began, 2)}
|
||||
results.append(result)
|
||||
ui.panel.capture_as_image().save(str(base / f'{name}-page.png'))
|
||||
ui.capture(ui.panel).save(str(base / f'{name}-page.png'))
|
||||
print('PASS TOOLBAR PDF', json.dumps(result, ensure_ascii=False), flush=True)
|
||||
ui.panel.child_window(title='打开输出目录', control_type='Button').invoke()
|
||||
(base / 'pdf-toolbar-acceptance.json').write_text(json.dumps({'pid': tool.pid,
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Enable automatic PDF export through the GUI and exercise native saves."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from pypdf import PdfReader
|
||||
from dx_productivity.bridge.startup_assets import vbscript_string
|
||||
from packaged_menu import tools_running, wait_for
|
||||
from toolbar_ui import ToolbarUI
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('executable', type=Path)
|
||||
parser.add_argument('--project', required=True, type=Path)
|
||||
parser.add_argument('--evidence', required=True, type=Path)
|
||||
options = parser.parse_args()
|
||||
exe, project, base = options.executable.resolve(), options.project.resolve(), options.evidence.resolve()
|
||||
assert 'acceptance' in project.parts
|
||||
assert not base.exists(), 'Retain existing evidence; use a fresh directory'
|
||||
base.mkdir(parents=True)
|
||||
tool = wait_for(lambda: next((p for p in tools_running() if Path(p.executable).resolve() == exe
|
||||
and '--request' in p.command_line), None))
|
||||
args = shlex.split(tool.command_line, posix=False)
|
||||
request = Path(args[args.index('--request') + 1].strip('"'))
|
||||
data = json.loads(request.read_text(encoding='utf-8-sig'))
|
||||
assert Path(data['design_path']).resolve() == project
|
||||
comp = next(c for c in data['components'] if c['refdes'] == 'CE17')
|
||||
old = next(a['value'] for a in comp['attributes'] if a['name'] == 'Value')
|
||||
marker = '_TOOLBAR_AUTO'
|
||||
ui = ToolbarUI(tool.pid)
|
||||
if ui.panel.exists(timeout=.2) and ui.panel.is_visible():
|
||||
ui.collapse()
|
||||
ui.feature('PDF 导出')
|
||||
ui.select_combo(ui.panel.child_window(title='导出范围', control_type='ComboBox'), 0, '整工程')
|
||||
output = base / 'output'
|
||||
edits = [e for e in ui.panel.descendants(control_type='Edit')
|
||||
if e.is_visible() and not e.iface_value.CurrentIsReadOnly]
|
||||
assert len(edits) == 1, edits
|
||||
edits[0].set_edit_text(str(output))
|
||||
enabled = ui.panel.child_window(title='保存工程后自动导出', control_type='CheckBox')
|
||||
assert enabled.is_enabled()
|
||||
enabled.click_input()
|
||||
config = Path(os.environ['LOCALAPPDATA']) / 'DxProductivity/pdf-export-settings.json'
|
||||
state_path = config.with_name(config.name + '.listener-state.json')
|
||||
log_path = config.with_name(config.name + '.listener.log')
|
||||
|
||||
def events():
|
||||
return [json.loads(line) for line in log_path.read_text(encoding='utf-8').splitlines() if line] if log_path.exists() else []
|
||||
|
||||
def listening():
|
||||
if not state_path.exists():
|
||||
return None
|
||||
state = json.loads(state_path.read_text(encoding='utf-8'))
|
||||
return state if state.get('state') == 'listening' else None
|
||||
|
||||
def run(value, name):
|
||||
script = base / f'{name}.vbs'
|
||||
script.write_text(f'''
|
||||
Dim autoComp,autoAttr,autoFound
|
||||
If LCase(Application.GetProjectData().GetProjectFilePath()) <> LCase({vbscript_string(str(project))}) Then Err.Raise 513, "Acceptance", "Wrong project"
|
||||
autoFound=False
|
||||
For Each autoComp In ActiveView.Query(VDM_COMP,VD_ALL)
|
||||
If CStr(autoComp.Refdes)="CE17" Then
|
||||
Set autoAttr=autoComp.FindAttribute("Value")
|
||||
autoAttr.Value={vbscript_string(value)}
|
||||
autoFound=True
|
||||
Exit For
|
||||
End If
|
||||
Next
|
||||
If Not autoFound Then Err.Raise 513, "Acceptance", "CE17 not found"
|
||||
Call Application.Documents.SaveAll()
|
||||
ActiveView.Refresh
|
||||
''', encoding='ascii')
|
||||
subprocess.run([sys.executable, str(Path(__file__).with_name('run_dx_script.py')),
|
||||
'--project', str(project), str(script)], check=True, timeout=30)
|
||||
|
||||
def exported(expected_count):
|
||||
entries = [e for e in events() if e.get('event') == 'export-completed']
|
||||
if len(entries) < expected_count:
|
||||
return None
|
||||
assert entries[-1]['returncode'] == 0, entries[-1]
|
||||
return entries[-1]
|
||||
|
||||
changed = False
|
||||
try:
|
||||
binding = wait_for(listening, 30)
|
||||
assert str(project).casefold() == str(binding.get('project', '')).casefold(), binding
|
||||
count = len([e for e in events() if e.get('event') == 'export-completed'])
|
||||
ui.collapse()
|
||||
run(old + marker, 'change-and-save')
|
||||
changed = True
|
||||
changed_event = wait_for(lambda: exported(count + 1), 60)
|
||||
pdfs = tuple(output.glob('*.pdf'))
|
||||
assert len(pdfs) == 1, pdfs
|
||||
pdf = PdfReader(pdfs[0])
|
||||
assert len(pdf.pages) == 1 and old + marker in pdf.pages[0].extract_text()
|
||||
shutil.copy2(pdfs[0], base / 'changed-value.pdf')
|
||||
print('PASS AUTO PDF WHILE COLLAPSED', flush=True)
|
||||
run(old, 'restore-and-save')
|
||||
changed = False
|
||||
restored_event = wait_for(lambda: exported(count + 2), 60)
|
||||
assert marker not in PdfReader(pdfs[0]).pages[0].extract_text()
|
||||
report = {'executable': str(exe), 'project': str(project), 'pid': tool.pid,
|
||||
'native_binding': binding, 'changed_event': changed_event, 'restored_event': restored_event,
|
||||
'pdf': str(pdfs[0]), 'native_saves': 2, 'value_restored': True, 'completed_while_collapsed': True}
|
||||
finally:
|
||||
if changed:
|
||||
run(old, 'restore-after-failure')
|
||||
if not (ui.panel.exists(timeout=.2) and ui.panel.is_visible()):
|
||||
ui.expand()
|
||||
if enabled.get_toggle_state():
|
||||
enabled.click_input()
|
||||
wait_for(lambda: json.loads(config.read_text(encoding='utf-8')).get('auto_export') is False, 10)
|
||||
ui.collapse()
|
||||
report['auto_export_disabled_after_test'] = True
|
||||
(base / 'toolbar-auto-pdf.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
print('PASS TOOLBAR NATIVE SAVE AUTO PDF', flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Real panel controls, local update settings, and repeated Start registration."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
|
||||
from PIL import ImageChops
|
||||
import win32gui
|
||||
|
||||
from packaged_menu import tools_running, wait_for
|
||||
from toolbar_ui import ToolbarUI
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('executable', type=Path)
|
||||
parser.add_argument('--project', required=True, type=Path)
|
||||
parser.add_argument('--evidence', required=True, type=Path)
|
||||
options = parser.parse_args()
|
||||
exe, project, base = options.executable.resolve(), options.project.resolve(), options.evidence.resolve()
|
||||
assert 'acceptance' in project.parts
|
||||
base.mkdir(parents=True, exist_ok=True)
|
||||
tool = wait_for(lambda: next((p for p in tools_running() if Path(p.executable).resolve() == exe
|
||||
and '--request' in p.command_line), None))
|
||||
args = shlex.split(tool.command_line, posix=False)
|
||||
request = Path(args[args.index('--request') + 1].strip('"'))
|
||||
assert Path(json.loads(request.read_text(encoding='utf-8-sig'))['design_path']).resolve() == project
|
||||
ui = ToolbarUI(tool.pid)
|
||||
if ui.panel.exists(timeout=.2) and ui.panel.is_visible():
|
||||
ui.collapse()
|
||||
ui.feature('自动位号')
|
||||
handle = ui.panel.handle
|
||||
ui.click(ui.toolbar.child_window(title='自动位号'))
|
||||
wait_for(lambda: not win32gui.IsWindowVisible(handle), 10)
|
||||
ui.expand()
|
||||
win32gui.PostMessage(handle, 0x10, 0, 0)
|
||||
wait_for(lambda: not win32gui.IsWindowVisible(handle), 10)
|
||||
ui.expand()
|
||||
before = ui.capture(ui.toolbar)
|
||||
ui.menu_action('切换明暗主题')
|
||||
wait_for(lambda: ImageChops.difference(before, ui.capture(ui.toolbar)).getbbox(), 10)
|
||||
ui.menu_action('切换明暗主题')
|
||||
ui.collapse()
|
||||
ui.feature('设置')
|
||||
config = Path(os.environ['LOCALAPPDATA']) / 'DxProductivity/settings.json'
|
||||
previous = config.read_bytes() if config.exists() else None
|
||||
old = json.loads(previous) if previous else {'source': '', 'channel': 'stable', 'auto_check': True}
|
||||
manifest = base / 'manifest.json'
|
||||
manifest.write_text(json.dumps({'product': 'yiyezhqiu-refactored', 'version': '0.1.0',
|
||||
'channel': 'development', 'min_supported_version': '0.1.0', 'package_url': manifest.as_uri(),
|
||||
'sha256': '0' * 64, 'release_notes': '工具栏本地更新检查验收', 'published_at': '2026-10-11',
|
||||
'signature': ''}, ensure_ascii=False), encoding='utf-8')
|
||||
advanced = ui.panel.child_window(title='高级更新选项', control_type='CheckBox')
|
||||
if not advanced.get_toggle_state():
|
||||
ui.click(advanced)
|
||||
notes = ui.panel.child_window(title='版本说明', control_type='CheckBox')
|
||||
if not notes.get_toggle_state():
|
||||
ui.click(notes)
|
||||
source = next(e for e in ui.panel.descendants(control_type='Edit')
|
||||
if e.is_visible() and not e.iface_value.CurrentIsReadOnly)
|
||||
channel = ui.panel.child_window(control_type='ComboBox')
|
||||
auto = ui.panel.child_window(title='启动后每天自动检查一次', control_type='CheckBox')
|
||||
try:
|
||||
if auto.get_toggle_state():
|
||||
ui.click(auto)
|
||||
source.set_edit_text(manifest.as_uri())
|
||||
ui.select_combo(channel, 1, '开发版')
|
||||
wait_for(lambda: json.loads(config.read_text(encoding='utf-8'))['source'] == manifest.as_uri(), 10)
|
||||
ui.click(ui.panel.child_window(title='检查更新', control_type='Button'))
|
||||
wait_for(lambda: '已是最新' in ui.texts(ui.panel), 15)
|
||||
assert not ui.panel.child_window(title='准备安装', control_type='Button').is_enabled()
|
||||
outer = win32gui.GetWindowRect(handle)
|
||||
client = win32gui.GetClientRect(handle)
|
||||
win32gui.MoveWindow(handle, outer[0], outer[1], 825 + outer[2] - outer[0] - client[2],
|
||||
425 + outer[3] - outer[1] - client[3], True)
|
||||
rect = ui.panel.rectangle()
|
||||
for name in ('检查更新', '准备安装'):
|
||||
button = ui.panel.child_window(title=name, control_type='Button').rectangle()
|
||||
assert rect.left <= button.left < button.right <= rect.right
|
||||
assert rect.top <= button.top < button.bottom <= rect.bottom
|
||||
ui.capture(ui.panel).save(str(base / 'settings-minimum.png'))
|
||||
finally:
|
||||
source.set_edit_text(old['source'])
|
||||
ui.select_combo(channel, 0 if old['channel'] == 'stable' else 1,
|
||||
'稳定版' if old['channel'] == 'stable' else '开发版')
|
||||
if bool(auto.get_toggle_state()) != old['auto_check']:
|
||||
ui.click(auto)
|
||||
if previous is not None:
|
||||
config.write_bytes(previous)
|
||||
else:
|
||||
config.unlink(missing_ok=True)
|
||||
ui.collapse()
|
||||
start = ui.toolbar.child_window(title='Start:加入菜单并打开 DxDesigner', control_type='Button')
|
||||
registrations = []
|
||||
for _ in range(2):
|
||||
ui.click(start)
|
||||
wait_for(lambda: start.is_enabled() and '菜单已持久注册' in ui.status_detail(), 30)
|
||||
state = json.loads((Path(os.environ['LOCALAPPDATA']) / 'DxProductivity/startup-refactored/startup.json').read_text(encoding='utf-8'))
|
||||
assert Path(state['tool_root']).resolve() == exe.parent
|
||||
registrations.append(state)
|
||||
ui.capture(ui.toolbar).save(str(base / 'registered-toolbar.png'))
|
||||
(base / 'toolbar-controls.json').write_text(json.dumps({'pid': tool.pid, 'project': str(project),
|
||||
'same_feature_collapses': True, 'close_collapses': True, 'theme_toggled_twice': True,
|
||||
'local_update_check': 'up-to-date', 'settings_saved_and_restored': True,
|
||||
'minimum_settings_buttons_accessible': True, 'registrations': registrations},
|
||||
ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
print('PASS TOOLBAR CONTROLS SETTINGS AND REPEATED START', flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Verify persistent menus after a normal restart of an acceptance host."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import win32com.client
|
||||
import pythoncom
|
||||
import win32gui
|
||||
import win32process
|
||||
|
||||
from dx_productivity.bridge.startup_assets import vbscript_string
|
||||
import packaged_menu
|
||||
from packaged_menu import tools_running, wait_for
|
||||
from toolbar_ui import ToolbarUI
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('executable', type=Path)
|
||||
parser.add_argument('--project', required=True, type=Path)
|
||||
parser.add_argument('--host-pid', required=True, type=int)
|
||||
parser.add_argument('--evidence', required=True, type=Path)
|
||||
parser.add_argument('--block', default='1GPHY_RTL8211F')
|
||||
parser.add_argument('--sheet', default='GE_PHY_8211')
|
||||
options = parser.parse_args()
|
||||
exe, project, base = options.executable.resolve(), options.project.resolve(), options.evidence.resolve()
|
||||
assert 'acceptance' in project.parts and options.host_pid != 44008
|
||||
base.mkdir(parents=True, exist_ok=True)
|
||||
for tool in tools_running():
|
||||
if Path(tool.executable).resolve() != exe or '--request' not in tool.command_line:
|
||||
continue
|
||||
args = shlex.split(tool.command_line, posix=False)
|
||||
request = Path(args[args.index('--request') + 1].strip('"'))
|
||||
if Path(json.loads(request.read_text(encoding='utf-8-sig'))['design_path']).resolve() == project:
|
||||
ToolbarUI(tool.pid).exit()
|
||||
packaged_menu.HOST_PID = options.host_pid
|
||||
for handle, texts in packaged_menu.owned_dialogs():
|
||||
assert any('应用完成' in text for text in texts), texts
|
||||
packaged_menu.close_completion_dialog(handle)
|
||||
hosts = []
|
||||
win32gui.EnumWindows(lambda h, _: hosts.append(h)
|
||||
if win32process.GetWindowThreadProcessId(h)[1] == options.host_pid
|
||||
and win32gui.GetWindowText(h).startswith('DxDesigner -') else None, None)
|
||||
assert len(hosts) == 1, hosts
|
||||
win32gui.PostMessage(hosts[0], 0x10, 0, 0)
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
wait_for(lambda: not list(service.ExecQuery(f'SELECT ProcessId FROM Win32_Process WHERE ProcessId={options.host_pid}')), 30)
|
||||
state = json.loads((Path(os.environ['LOCALAPPDATA']) / 'DxProductivity/startup-refactored/startup.json').read_text(encoding='utf-8'))
|
||||
assert Path(state['tool_root']).resolve() == exe.parent
|
||||
process = subprocess.Popen([state['viewdraw'], str(project)], cwd=Path(state['viewdraw']).parent)
|
||||
# A normal project launch opens Start Page. Open the native sheet before
|
||||
# asking for Sheet Menu Bar; its scripting surface waits for an active view.
|
||||
def open_sheet():
|
||||
context = pythoncom.CreateBindCtx(0)
|
||||
rot = pythoncom.GetRunningObjectTable()
|
||||
entries = rot.EnumRunning()
|
||||
while batch := entries.Next(1):
|
||||
moniker = batch[0]
|
||||
if not moniker.GetDisplayName(context, None).startswith('!Viewdraw.Application'):
|
||||
continue
|
||||
app = win32com.client.Dispatch(rot.GetObject(moniker).QueryInterface(pythoncom.IID_IDispatch))
|
||||
try:
|
||||
path = app.GetProjectData().GetProjectFilePath
|
||||
path = path() if callable(path) else path
|
||||
if Path(path).resolve() == project:
|
||||
app.PushPath(options.block, '', options.sheet)
|
||||
handle = int(app.ActiveViewHandle)
|
||||
return handle and win32process.GetWindowThreadProcessId(handle)[1] == process.pid
|
||||
except Exception:
|
||||
continue
|
||||
return False
|
||||
wait_for(open_sheet, 30)
|
||||
helper = Path(__file__).with_name('run_dx_script.py')
|
||||
report_path = base / 'native-menu-readback.txt'
|
||||
script = base / 'read-persistent-menu.vbs'
|
||||
script.write_text(f'''
|
||||
Dim restartBarName,restartBar,restartItem,restartIndex,restartCount,restartRows,restartOut,restartAction
|
||||
If LCase(Application.GetProjectData().GetProjectFilePath()) <> LCase({vbscript_string(str(project))}) Then Err.Raise 513, "Acceptance", "Wrong project"
|
||||
restartRows=""
|
||||
For Each restartBarName In Array("Main Menu Bar","Sheet Menu Bar")
|
||||
Set restartBar=CommandBars(restartBarName)
|
||||
restartCount=0
|
||||
For restartIndex=1 To restartBar.Controls.Count
|
||||
Set restartItem=restartBar.Controls.Item(restartIndex)
|
||||
If restartItem.Caption="Dx " & ChrW(&H6548) & ChrW(&H7387) & ChrW(&H5DE5) & ChrW(&H5177) Then
|
||||
restartCount=restartCount+1
|
||||
restartRows=restartRows & "BAR" & vbTab & restartBarName & vbTab & CStr(restartItem.Controls.Count) & vbCrLf
|
||||
For Each restartAction In restartItem.Controls
|
||||
restartRows=restartRows & "ACTION" & vbTab & restartAction.Caption & vbTab & restartAction.OnAction & vbCrLf
|
||||
Next
|
||||
End If
|
||||
Next
|
||||
If restartCount<>1 Then Err.Raise 513,"Acceptance","Persistent menu count=" & CStr(restartCount)
|
||||
Next
|
||||
Set restartOut=CreateObject("Scripting.FileSystemObject").CreateTextFile({vbscript_string(str(report_path))},True,True)
|
||||
restartOut.Write restartRows
|
||||
restartOut.Close
|
||||
''', encoding='ascii')
|
||||
|
||||
def probe():
|
||||
result = subprocess.run([sys.executable, str(helper), '--pid', str(process.pid), str(script)],
|
||||
capture_output=True, timeout=10)
|
||||
return report_path if result.returncode == 0 and report_path.exists() else None
|
||||
wait_for(probe, 30)
|
||||
rows = [line.split('\t') for line in report_path.read_text(encoding='utf-16').splitlines()]
|
||||
bars = [row for row in rows if row[0] == 'BAR']
|
||||
assert len(bars) == 2 and all(row[2] == '8' for row in bars), bars
|
||||
assert all('startup-refactored' in row[2] for row in rows if row[0] == 'ACTION')
|
||||
(base / 'persistent-menu.json').write_text(json.dumps({'project': str(project), 'executable': str(exe),
|
||||
'old_host_pid': options.host_pid, 'new_host_pid': process.pid, 'normal_launch': True,
|
||||
'menu_loaded_without_manual_install': True, 'menus': bars}, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
print('PASS NORMAL DX RESTART PERSISTENT MENUS', process.pid, flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,7 +1,11 @@
|
||||
"""UI Automation helpers scoped to one toolbar process."""
|
||||
from pywinauto import Application
|
||||
from pywinauto.keyboard import send_keys
|
||||
import ctypes
|
||||
from PIL import Image
|
||||
import win32gui
|
||||
import win32process
|
||||
import win32ui
|
||||
from packaged_menu import wait_for
|
||||
|
||||
TOOLBAR_TITLE = "一叶知秋悬浮工具栏"
|
||||
@@ -16,6 +20,37 @@ class ToolbarUI:
|
||||
self.panel = self.app.window(title=PANEL_TITLE)
|
||||
self.toolbar.wait("visible", timeout=15)
|
||||
|
||||
def click(self, control):
|
||||
wrapper = control.wrapper_object() if hasattr(control, 'wrapper_object') else control
|
||||
wrapper.top_level_parent().set_focus()
|
||||
rect = wrapper.rectangle()
|
||||
point = ((rect.left + rect.right) // 2, (rect.top + rect.bottom) // 2)
|
||||
assert win32process.GetWindowThreadProcessId(win32gui.WindowFromPoint(point))[1] == self.pid
|
||||
wrapper.click_input()
|
||||
|
||||
@staticmethod
|
||||
def capture(window):
|
||||
# Capture the owned window rather than a desktop rectangle. Desktop
|
||||
# BitBlt can return stale composition while native Qt/UIA remains live.
|
||||
handle = window.handle
|
||||
left, top, right, bottom = win32gui.GetWindowRect(handle)
|
||||
width, height = right - left, bottom - top
|
||||
dc = win32gui.GetWindowDC(handle)
|
||||
source = win32ui.CreateDCFromHandle(dc)
|
||||
target = source.CreateCompatibleDC()
|
||||
bitmap = win32ui.CreateBitmap()
|
||||
bitmap.CreateCompatibleBitmap(source, width, height)
|
||||
previous = target.SelectObject(bitmap)
|
||||
try:
|
||||
assert ctypes.windll.user32.PrintWindow(handle, target.GetSafeHdc(), 2)
|
||||
return Image.frombuffer('RGB', (width, height), bitmap.GetBitmapBits(True), 'raw', 'BGRX', 0, 1)
|
||||
finally:
|
||||
target.SelectObject(previous)
|
||||
win32gui.DeleteObject(bitmap.GetHandle())
|
||||
target.DeleteDC()
|
||||
source.DeleteDC()
|
||||
win32gui.ReleaseDC(handle, dc)
|
||||
|
||||
def menu_action(self, name):
|
||||
overflow = [feature for feature in PRIMARY_FEATURES
|
||||
if not self.toolbar.child_window(title=feature).exists(timeout=0.1)]
|
||||
@@ -23,7 +58,6 @@ class ToolbarUI:
|
||||
assert name in actions, (name, actions)
|
||||
more = next(button for button in self.toolbar.descendants(control_type="Button")
|
||||
if button.window_text() in ("更多", "更多功能"))
|
||||
more.click_input()
|
||||
def popup_handle():
|
||||
handles = []
|
||||
def inspect(handle, _):
|
||||
@@ -33,10 +67,24 @@ class ToolbarUI:
|
||||
handles.append(handle)
|
||||
win32gui.EnumWindows(inspect, None)
|
||||
return handles[0] if handles else None
|
||||
popup = wait_for(popup_handle, 5)
|
||||
previous = popup_handle()
|
||||
if previous:
|
||||
win32gui.PostMessage(previous, 0x100, 0x1B, 0)
|
||||
win32gui.PostMessage(previous, 0x101, 0x1B, 0)
|
||||
wait_for(lambda: not win32gui.IsWindowVisible(previous), 5)
|
||||
self.click(more)
|
||||
try:
|
||||
popup = wait_for(popup_handle, 5)
|
||||
except TimeoutError:
|
||||
# Restoring focus can dismiss an already opening Qt popup. The
|
||||
# second physical click is scoped and hit-tested to this process.
|
||||
self.click(more)
|
||||
popup = wait_for(popup_handle, 5)
|
||||
# Qt menu actions lack a UIA Invoke provider. Address the owned popup
|
||||
# directly so keyboard events never reach the user's host application.
|
||||
for key in [0x24] + [0x28] * actions.index(name) + [0x0D]:
|
||||
# A freshly opened Qt menu has no current action. Home does not select
|
||||
# its first action; the first Down does. Count that first Down too.
|
||||
for key in [0x28] * (actions.index(name) + 1) + [0x0D]:
|
||||
win32gui.PostMessage(popup, 0x100, key, 0)
|
||||
win32gui.PostMessage(popup, 0x101, key, 0)
|
||||
wait_for(lambda: not win32gui.IsWindowVisible(popup), 5)
|
||||
@@ -44,11 +92,45 @@ class ToolbarUI:
|
||||
def feature(self, name):
|
||||
button = self.toolbar.child_window(title=name)
|
||||
if button.exists(timeout=0.2) and button.is_visible():
|
||||
button.click_input()
|
||||
self.click(button)
|
||||
else:
|
||||
self.menu_action(name)
|
||||
self.panel.wait("visible", timeout=15)
|
||||
assert name in self.texts(self.panel)
|
||||
wait_for(lambda: name in self.texts(self.panel), 10)
|
||||
self.panel.set_focus()
|
||||
|
||||
def select_combo(self, combo, index, expected):
|
||||
# Qt does not publish combo list items through UIA SelectionItem.
|
||||
# Use the real list and send keys only after checking its owner.
|
||||
def popups():
|
||||
handles = []
|
||||
win32gui.EnumWindows(lambda h, _: handles.append(h)
|
||||
if win32process.GetWindowThreadProcessId(h)[1] == self.pid
|
||||
and 'Popup' in win32gui.GetClassName(h) and win32gui.IsWindowVisible(h)
|
||||
else None, None)
|
||||
return handles
|
||||
for handle in popups():
|
||||
win32gui.PostMessage(handle, 0x100, 0x1B, 0)
|
||||
win32gui.PostMessage(handle, 0x101, 0x1B, 0)
|
||||
wait_for(lambda: not popups(), 5)
|
||||
self.click(combo)
|
||||
wait_for(popups, 5)
|
||||
foreground = win32gui.GetForegroundWindow()
|
||||
assert win32process.GetWindowThreadProcessId(foreground)[1] == self.pid
|
||||
send_keys('{HOME}' + '{DOWN}' * index + '{ENTER}')
|
||||
wait_for(lambda: not popups(), 5)
|
||||
wait_for(lambda: combo.wrapper_object().iface_value.CurrentValue == expected, 5)
|
||||
|
||||
def native_dialog(self, title):
|
||||
def find():
|
||||
handles = []
|
||||
win32gui.EnumWindows(lambda h, _: handles.append(h)
|
||||
if win32process.GetWindowThreadProcessId(h)[1] == self.pid
|
||||
and win32gui.GetWindowText(h) == title and win32gui.IsWindowVisible(h)
|
||||
else None, None)
|
||||
return handles[0] if handles else None
|
||||
handle = wait_for(find, 10)
|
||||
return Application(backend='win32').connect(handle=handle).window(handle=handle)
|
||||
|
||||
@staticmethod
|
||||
def texts(window):
|
||||
@@ -69,7 +151,13 @@ class ToolbarUI:
|
||||
def expand(self):
|
||||
self.toolbar.child_window(title="展开面板", control_type="Button").invoke()
|
||||
self.panel.wait("visible", timeout=10)
|
||||
self.panel.set_focus()
|
||||
|
||||
def exit(self):
|
||||
self.menu_action("退出工具")
|
||||
try:
|
||||
self.menu_action("退出工具")
|
||||
except TimeoutError:
|
||||
# Closing the toolbar invokes the same explicit request_exit path.
|
||||
# Closing the feature panel would only collapse it.
|
||||
win32gui.PostMessage(self.toolbar.handle, 0x10, 0, 0)
|
||||
self.toolbar.wait_not("exists", timeout=15)
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Real GUI writes and history restores, restricted to an acceptance copy."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import ctypes
|
||||
|
||||
import win32gui
|
||||
import win32process
|
||||
from pywinauto.keyboard import send_keys
|
||||
from pywinauto import mouse
|
||||
|
||||
from packaged_menu import tools_running, wait_for
|
||||
from toolbar_ui import ToolbarUI
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('executable', type=Path)
|
||||
parser.add_argument('--project', required=True, type=Path)
|
||||
parser.add_argument('--evidence', required=True, type=Path)
|
||||
options = parser.parse_args()
|
||||
exe, project, base = options.executable.resolve(), options.project.resolve(), options.evidence.resolve()
|
||||
assert 'acceptance' in project.parts
|
||||
base.mkdir(parents=True, exist_ok=True)
|
||||
tool = wait_for(lambda: next((p for p in tools_running() if Path(p.executable).resolve() == exe
|
||||
and '--request' in p.command_line), None))
|
||||
args = shlex.split(tool.command_line, posix=False)
|
||||
request = Path(args[args.index('--request') + 1].strip('"'))
|
||||
status_path = request.with_name('apply-status.json')
|
||||
ui = ToolbarUI(tool.pid)
|
||||
|
||||
def snapshot():
|
||||
data = json.loads(request.read_text(encoding='utf-8-sig'))
|
||||
assert Path(data['design_path']).resolve() == project
|
||||
return data
|
||||
|
||||
initial = snapshot()
|
||||
selected = [c for c in initial['components'] if c['selected']]
|
||||
assert len(selected) == 1 and selected[0]['refdes'] in ('CE17', 'C9000'), selected
|
||||
uid = selected[0]['stable_uid']
|
||||
|
||||
def component():
|
||||
return next(c for c in snapshot()['components'] if c['stable_uid'] == uid)
|
||||
|
||||
def attr(name):
|
||||
return next(a for a in component()['attributes'] if a['name'] == name)
|
||||
|
||||
def show(page):
|
||||
if ui.panel.exists(timeout=.2) and ui.panel.is_visible():
|
||||
ui.collapse()
|
||||
ui.feature(page)
|
||||
|
||||
results = []
|
||||
|
||||
def transaction(name, action, expected):
|
||||
before = status_path.stat().st_mtime_ns if status_path.exists() else 0
|
||||
action()
|
||||
def completed():
|
||||
if not status_path.exists() or status_path.stat().st_mtime_ns == before:
|
||||
return None
|
||||
data = json.loads(status_path.read_text(encoding='utf-8-sig'))
|
||||
assert data['state'] == 'applied', data
|
||||
return data
|
||||
status = wait_for(completed, 30)
|
||||
wait_for(expected, 30)
|
||||
(base / f'{name}-snapshot.json').write_text(json.dumps(snapshot(), ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
results.append({'case': name, 'native_status': status, 'readback_verified': True})
|
||||
print('PASS TOOLBAR WRITE', name, flush=True)
|
||||
|
||||
def restore(name, expected):
|
||||
show('操作历史')
|
||||
button = ui.panel.child_window(title='恢复所选操作', control_type='Button')
|
||||
wait_for(button.is_enabled, 10)
|
||||
def action():
|
||||
button.click_input()
|
||||
dialog = ui.panel.child_window(title='恢复所选操作', control_type='Window')
|
||||
dialog.wait('visible', timeout=10)
|
||||
yes = next(b for b in dialog.descendants(control_type='Button')
|
||||
if b.window_text() in ('Yes', '&Yes', '是', '是(&Y)'))
|
||||
yes.click_input()
|
||||
transaction(name, action, expected)
|
||||
|
||||
if selected[0]['refdes'] == 'C9000':
|
||||
restore('previous-acceptance-restore', lambda: component()['refdes'] == 'CE17')
|
||||
initial = snapshot()
|
||||
|
||||
show('自动位号')
|
||||
ui.panel.child_window(title='全部重编').click_input()
|
||||
spinner = next(s for s in ui.panel.descendants(control_type='Spinner') if s.is_visible())
|
||||
spinner.iface_value.SetValue('9000')
|
||||
apply = ui.panel.child_window(title='应用位号', control_type='Button')
|
||||
wait_for(apply.is_enabled, 10)
|
||||
ui.capture(ui.panel).save(str(base / 'refdes-preview.png'))
|
||||
transaction('refdes-apply', apply.click_input, lambda: component()['refdes'] == 'C9000')
|
||||
restore('refdes-restore', lambda: component()['refdes'] == 'CE17')
|
||||
|
||||
show('属性批改')
|
||||
ui.select_combo(ui.panel.child_window(control_type='ComboBox'), 0, 'Value')
|
||||
old_value = attr('Value')['value']
|
||||
# Qt's table editor does not publish its temporary line edit through UIA.
|
||||
# This point is inside the visible first row's final (new value) column.
|
||||
table = ui.panel.child_window(control_type='Table').rectangle()
|
||||
scale = ctypes.windll.user32.GetDpiForWindow(ui.panel.handle) / 96
|
||||
point = (table.right - round(80 * scale), table.top + round(52 * scale))
|
||||
assert win32process.GetWindowThreadProcessId(win32gui.WindowFromPoint(point))[1] == ui.pid
|
||||
mouse.double_click(coords=point)
|
||||
assert win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow())[1] == ui.pid
|
||||
send_keys('^aTOOLBAR_NATIVE_VALUE{ENTER}')
|
||||
apply = ui.panel.child_window(title='应用属性修改', control_type='Button')
|
||||
wait_for(apply.is_enabled, 10)
|
||||
transaction('value-apply', apply.click_input, lambda: attr('Value')['value'] == 'TOOLBAR_NATIVE_VALUE')
|
||||
restore('value-restore', lambda: attr('Value')['value'] == old_value)
|
||||
|
||||
show('属性显示')
|
||||
ui.select_combo(ui.panel.child_window(control_type='ComboBox'), 0, 'Part Name')
|
||||
was_visible = attr('Part Name')['visible']
|
||||
ui.panel.child_window(title='隐藏' if was_visible else '显示', control_type='RadioButton').click_input()
|
||||
apply = ui.panel.child_window(title='应用显示状态', control_type='Button')
|
||||
wait_for(apply.is_enabled, 10)
|
||||
transaction('visibility-apply', apply.click_input, lambda: attr('Part Name')['visible'] != was_visible)
|
||||
restore('visibility-restore', lambda: attr('Part Name')['visible'] == was_visible)
|
||||
|
||||
def design_values(data):
|
||||
return {c['stable_uid']: (c['refdes'], c['x'], c['y'],
|
||||
sorted((a['name'], a['value'], a['visible']) for a in c['attributes']))
|
||||
for c in data['components']}
|
||||
assert design_values(initial) == design_values(snapshot()), 'Design values differ from initial baseline'
|
||||
(base / 'toolbar-writes.json').write_text(json.dumps({'pid': tool.pid, 'executable': str(exe),
|
||||
'project': str(project), 'cases': results, 'all_components_restored': len(initial['components'])},
|
||||
ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
ui.collapse()
|
||||
print('PASS ALL TOOLBAR WRITES AND RESTORES', flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in new issue
Block a user