Author SHA1 Message Date
阿白叔 3a65401c23 fix: exit toolbar when owning DxDesigner closes 2026-10-13 10:10:57 +08:00
阿白叔 8b1e19ff0f fix: explain missing active DxDesigner view 2026-10-13 09:33:30 +08:00
阿白叔 f3b027b494 feat: follow connected DX minimize and restore state 2026-10-12 23:23:36 +08:00
阿白叔 b51bcb0b3e fix: prevent More menu arrow overlapping its label 2026-10-12 22:14:01 +08:00
阿白叔 da9d1dc25f docs: record toolbar polish package hashes 2026-10-12 19:39:26 +08:00
阿白叔 b9d7daca0f ui: refine toolbar toggle and expanded panel 2026-10-12 19:22:29 +08:00
阿白叔 b203806fd1 fix: stabilize native refresh and complete toolbar acceptance 2026-10-11 15:41:50 +08:00
阿白叔 b8acbc6de5 docs: record toolbar verification and pending unlocked desktop acceptance 2026-10-11 12:25:47 +08:00
阿白叔 c96a27c033 test: verify approved panel minimum and native toolbar outputs 2026-10-11 11:56:34 +08:00
阿白叔 f00dee7791 fix: keep settings actions visible while expanded options scroll 2026-10-11 11:54:04 +08:00
阿白叔 5e0ba81c3e feat: compact PDF and annotation panels with contextual options 2026-10-11 11:46:32 +08:00
阿白叔 717129c844 feat: simplify secondary pages with contextual controls and advanced options 2026-10-11 11:45:35 +08:00
阿白叔 d6df3f99fb fix: preserve live selection validity and preferred panel geometry 2026-10-11 11:44:00 +08:00
阿白叔 9caf33df38 chore: adapt acceptance tools and usage notes for horizontal toolbar 2026-10-11 11:33:00 +08:00
阿白叔 19361fd1cc Replace leaf entry with persistent horizontal toolbar and shared panel state 2026-10-11 11:31:07 +08:00
阿白叔 d2501d0112 docs: plan horizontal toolbar and compact feature panels 2026-10-11 11:17:12 +08:00
阿白叔 12ce0c4140 fix: repair Chinese PDF text and sync native component selection 2026-10-11 10:53:02 +08:00
阿白叔 734a10b5c7 feat: add compact floating UI and reference PDF palette 2026-10-11 09:55:31 +08:00
阿白叔 1f1390e1b7 docs: record completed native validation and delivery 2026-10-11 00:38:31 +08:00
阿白叔 cd88a9950a fix: persist native menus and validate every tool workflow 2026-10-11 00:37:45 +08:00
阿白叔 7a471fec24 fix: register DxDesigner menus from Start and keep the bridge alive 2026-10-10 22:51:29 +08:00
阿白叔 c8caaf8daf feat: add current-project PDF export 2026-10-10 18:18:33 +08:00
阿白叔 771d8efb87 docs: approve current-project PDF export design 2026-10-10 17:43:36 +08:00
137 changed files with 12504 additions and 645 deletions

No files matched your search

+2
View File
@@ -10,3 +10,5 @@ build/
dist/
release/
.zcode/
.worktrees/
.superpowers/
@@ -0,0 +1,150 @@
# 当前工程 PDF 导出实现计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 在一叶知秋工具中为 DxDesigner 当前工程提供整工程、当前页、指定 Block 的 PDF 手动导出,并提供默认关闭的保存后自动导出。
**Architecture:** 新增独立 `features/pdf_export` 服务层,负责原生引擎发现、参数构造、源工程变更核验、PDF 校验和原子发布。Qt 页面使用现有桥接快照并通过工作线程执行导出;自动导出由 32 位 WSH/VBScript 连接 DxDesigner 7.9.5 保存事件,再启动便携工具的无 UI 子命令。
**Tech Stack:** Python 3.12、PySide6、pypdf、PyWin32、VBScript、32 位 Windows Script Host、DxDesigner 7.9.5 `sch2pdf.exe`。
**Spec:** `docs/superpowers/specs/2026-10-10-current-project-pdf-design.md`
## Global Constraints
- 一次导出只处理桥接快照或保存事件中的当前 `.prj` 工程。
- 范围固定为整工程、当前活动页、指定原理图或 Block。
- 自动导出默认关闭;关闭后监听器停止,监听器不得拦截或延迟原生保存。
- PDF 和运行记录均写入源工程目录以外;默认输出位于 `%LOCALAPPDATA%\\DxProductivity\\pdf-output`。
- 先输出到临时 PDF,完成校验和源变更检查后才替换正式文件。
- 不迁入独立批量工具的工程扫描器、批量队列、独立主窗口、字体修复或矢量配色界面。
- 64 位 Python 不连接 DxDesigner COM;COM 保存事件只由 32 位 WSH/VBScript 监听。
- 当前会话未要求新增或运行测试;实施中不添加或运行测试,使用静态语法和差异检查做最小验证。
---
### Task 1: 固化桥接活动 Block 输入
**Files:**
- Modify: `integration/dxdesigner795/core/Snapshot.vbs`
- Modify: `src/dx_productivity/bridge/protocol.py`
- Modify: `src/dx_productivity/domain/models.py`
**Interfaces:**
- Produces: `DesignSnapshot.active_block_name: str`,旧版快照缺少字段时默认空字符串。
- VBS 从 `ActiveView.Block.GetName(1)` 和 `ActiveView.Block.SheetNum` 读取活动 Block 短名称与页码。
- [x] 在快照 JSON 中增加 `active_block_name` 与 `current_sheet_number`;读取活动视图失败时写空名称与 `null` 页码。
- [x] 扩展 `DesignSnapshot` 和 `load_request`,允许旧请求不带新字段。
- [x] 查看新增字段的读取路径,确认项目名称和 Unicode JSON 转义继续使用既有桥接协议。
### Task 2: 创建工程范围与导出配置模型
**Files:**
- Create: `src/dx_productivity/features/pdf_export/__init__.py`
- Create: `src/dx_productivity/features/pdf_export/models.py`
- Create: `src/dx_productivity/features/pdf_export/settings.py`
- Modify: `pyproject.toml`
**Interfaces:**
- Produces: `ExportScope`,值为 `project`、`current-page`、`block`。
- Produces: `PdfExportSettings`,包含当前工程路径、范围、Block 名称、输出目录、自动导出开关和可选引擎路径。
- Settings 使用 `%LOCALAPPDATA%\\DxProductivity\\pdf-export-settings.json`,并保存归属工程路径;配置工程不匹配时自动导出保持关闭。
- [x] 添加范围和设置数据类型;导出服务拒绝空 Block 名称,设置对象拒绝带换行符或空字符的输入。
- [x] 实现原子 JSON 读写;缺少配置时使用自动导出关闭和工程外默认目录。
- [x] 将 `pypdf` 与 `pywin32` 加入运行依赖,并确认它们只用于 PDF 验证及 Windows 子进程生命周期管理。
### Task 3: 实现单工程原生导出服务
**Files:**
- Create: `src/dx_productivity/features/pdf_export/engine.py`
- Create: `src/dx_productivity/features/pdf_export/exporter.py`
- Modify: `pyproject.toml`
- Modify: `packaging/DxDesignerTools.spec`
- Modify: `packaging/build_release.ps1`
**Interfaces:**
- Produces: `discover_engine(explicit: Path | None) -> Path`。
- Produces: `build_command(engine, project, output, scope, block_name) -> list[str]`。
- Produces: `export_project(settings, cancel, on_event=None, *, active_block_name, overwrite) -> PdfExportResult`。
- [x] 从 `SDD_HOME\\wv\\win32\\bin\\sch2pdf.exe` 和已安装 Mentor 目录发现引擎;显式路径无效时报告错误。
- [x] 将工程、临时输出和可选 `-schematic` 参数按参数数组传给引擎;工程配置和字体保持原生。
- [x] 为源工程文件生成前后 SHA-256 清单,只接受规格允许的原生数据库/运行记录更新。
- [x] 将 PDF 输出到目标目录的唯一临时文件,以 pypdf 解析页数并读取所有内容流。
- [x] 导出成功且源文件检查通过后原子发布;失败、超时或验证错误保留已有 PDF。
- [x] 将请求、事件、PDF 校验、源变更和最终结果记录到 `pdf-runs`。
- [x] 使用受控 Windows Job Object 启动及等待原生子进程,支持取消与超时,不让后台子进程脱离跟踪。
- [x] 更新便携包构建收集项,使 PyInstaller 包含新增运行依赖。
### Task 4: 实现导出页面与工作线程
**Files:**
- Create: `src/dx_productivity/ui/pdf_export_page.py`
- Create: `src/dx_productivity/ui/pdf_export_controller.py`
- Modify: `src/dx_productivity/ui/main_window.py`
- Modify: `src/dx_productivity/ui/app.py`
**Interfaces:**
- Produces: 侧栏页 `PDF 导出`,连接 `PdfExportController`。
- Controller 接收 `DesignSnapshot`,加载/保存对应工程设置并通过 Qt worker 调用 `export_project`。
- [x] 增加工程路径只读显示、三段范围选择、Block 名称输入、输出目录选择、手动导出/取消按钮和自动导出开关。
- [x] 选择“当前页”时使用快照中的活动 Block 名称;名称为空时禁用导出并报告桥接数据缺失。
- [x] 手动导出发现同名 PDF 时显示覆盖确认;自动导出仅在临时文件验证通过后替换。
- [x] worker 完成时在工具状态栏显示结果;导出期间锁定范围和路径控件,允许取消。
- [x] 菜单 `--feature pdf-export` 打开该页;无当前工程快照时显示未连接状态并禁用导出。
### Task 5: 实现保存事件监听与后台触发
**Files:**
- Create: `integration/dxdesigner795/PdfSaveListener.vbs`
- Create: `src/dx_productivity/features/pdf_export/listener.py`
- Modify: `src/dx_productivity/bridge/launcher.py`
- Modify: `src/dx_productivity/ui/pdf_export_controller.py`
**Interfaces:**
- Listener 接收便携工具根目录和当前工程设置路径,通过 `GetObject(, "ViewDraw.Application")` 和 `WScript.ConnectObject` 订阅 `AfterDocumentSave(Doc)`。
- Produces: `pdf-export-event --project PATH --active-block NAME`,无 Qt 初始化地重新加载工程设置并导出。
- [x] 仅在用户打开自动导出开关后启动 `SysWOW64\\wscript.exe` 监听器;配置保存当前工程路径。
- [x] DxDesigner 启动脚本只在自动导出开启时恢复监听;关闭开关写入关闭状态并让监听器退出。
- [x] 保存事件中读取 `Application.ProjectPath` 与 `ActiveView.Block.GetName(1)`;COM 读取失败时只记录错误并返回。
- [x] 对短时间内相同工程/Block 的保存通知做合并;后台子进程不初始化 Qt,不弹出模态对话框。
- [x] 后台命令重新核对事件工程与配置工程;保存和导出各自失败时写入运行记录,且不得阻塞 DxDesigner 保存。
- [x] 使用类型库确认 `IVdApp.StatusBarText`,监听器将自动导出结果写入 DxDesigner 状态栏和本地运行记录。
### Task 6: 接入 DxDesigner 菜单和便携发布
**Files:**
- Modify: `integration/dxdesigner795/MenuAdd.vbs`
- Modify: `packaging/build_release.ps1`
- Create: `docs/user/PDF_export.md`
**Interfaces:**
- Produces: 菜单项 `PDF 导出` -> `DxToolsStartFeature("pdf-export")`。
- Release contains `PdfSaveListener.vbs` at the path expected by `listener.py` and `MenuAdd.vbs`.
- [x] 增加菜单动作并保持现有脚本 ASCII 编码和路径可搬迁约定。
- [x] 将监听器脚本复制进发布目录,并纳入发布文件存在性检查。
- [x] 为 PDF 导出添加简短 Markdown 用户说明,描述三种范围、输出目录和自动导出开关。
### Task 7: 静态检查与交付记录
**Files:**
- Modify: `docs/superpowers/plans/2026-10-10-current-project-pdf-export.md`
- Modify: `docs/superpowers/specs/2026-10-10-current-project-pdf-design.md`
- [x] 使用 `py -3.12 -m compileall -q src/dx_productivity` 检查 Python 语法。
- [x] 检查新增及修改的 VBS 文件,确认没有非 ASCII 字节。
- [x] 使用 `git diff --check` 检查空白错误,并检查源工程输出目录保护与设置默认值。
- [x] 在规格中记录未完成的 DxDesigner 7.9.5 现场验收:事件订阅、启动/停止、活动 Block 名称、输出三种范围。
- [x] 未新增或运行测试,也未生成发布包;当前回合未要求测试,DxDesigner 实机验收仍待完成。
## Self-Review
- 规格目标与文件覆盖:快照活动页输入由 Task 1 覆盖;导出配置/引擎/校验由 Task 2-3 覆盖;用户页面和手动工作流由 Task 4 覆盖;保存后自动导出和失败隔离由 Task 5 覆盖;菜单、便携包与用户说明由 Task 6 覆盖;验证限制由 Task 7 覆盖。
- 路径安全:默认目录在 `%LOCALAPPDATA%`;用户选择目录要在发布前再次验证与源目录不重叠。
- 事件安全:不依赖 64 位 Python COM,不替换原生 Save 命令,不把事件失败传回 DxDesigner 保存调用。
- 接口一致性:短名称统一来自 `IVdBlock.GetName(1)`;整工程不带 `-schematic`,当前页和指定 Block 都带准确名称。
@@ -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 装配整理逐项记录。
- [x] 完成隔离构建、395 项源码测试、16 项便携包测试、最终菜单/冻结监听器/更新安装验收,并提交推送当前分支。实现提交 `cd88a99` 已推送至 `feat/current-project-pdf-export`。
结果与边界:`docs/testing/native-acceptance-20261010.md`。额外修复发布 ZIP 目录兼容、Windows 更新程序自锁、持续重启与计划文件竞争,实际便携包更新及回滚通过。
@@ -0,0 +1,209 @@
# 横向悬浮工具栏与紧凑面板 Implementation Plan
> **状态:横向工具栏、九个面板、实机验收和正式菜单切换已完成。** 最终源码 476 项、便携包 16 项通过;写回/恢复、选择、PDF、BOM、原生菜单普通重启及展开/收起更新与回滚通过。用户当前 DX 已连接最终工具,逐项证据及 PON 限制见 `docs/testing/toolbar-acceptance-20261011.md`。
>
> **For agentic workers:** 使用 `superpowers:executing-plans` 按任务执行。步骤使用复选框记录进度;默认在当前会话顺序执行。
**Goal:** 将圆形叶子悬浮入口改为常驻的一排工具栏,点击功能展开紧凑面板,简化页面并保持实时选择、菜单注册和后台任务的连续性。
**Architecture:** 工具栏负责入口与简短状态,现有 MainWindow 改为承载功能页的共享面板。两个窗口使用同一组控制器、同一个桥接会话和现有 SelectionWatcher;隐藏面板时保持实例与表单输入。业务操作仍由对应页面及控制器处理。
**Tech Stack:** Windows 11、Python 3.12、PySide6、现有 DxDesigner 7.9.5 原生桥接与 PyInstaller 发布流程。
**Spec:** 用户 2026-10-11 的要求“应该做成工具栏,一排的那种,页面也可以把不必要的地方简化掉”;本文件第 2—4 节给出具体布局、交互与页面要求。尺寸为设计目标,最终以 Windows 实际显示验收为准。
## 1. 当前问题与实施约束
当前主窗口默认 960×600,最小 860×540;左侧导航固定占 172 像素。顶部工具栏和内容标题各占 44 像素,底部状态栏占 28 像素。全局“生成预览”和“应用位号”始终显示,多个页面还有重复标题和常驻说明。
当前收起入口是 56×56 的圆形叶子按钮。收起后选择监听继续运行,但必须打开大窗口才能看见选中器件及任务状态。
实施约束:
- 工具栏始终保持单行;空间不足时将低优先级入口放入“更多”,使用同一套页面路由。
- Start 继续承担启动宿主、持久菜单注册与重连入口;连接成功状态和菜单注册成功状态分别判断。
- PDF 保持直接可见的入口,顺序位于设置之前。
- 收起、展开与切换页面使用现有页面实例;后台监听、原生保存触发和正在运行的任务由应用生命周期管理。
- 页面压缩通过减少重复区域与折叠选项完成;正文建议 9—10 pt、可点击控件至少 28 个逻辑像素高。
- 写回设计的操作保留预览、确认和冲突阻断;入口点击只打开功能。
- 使用独立验收副本验证写回,不关闭用户正在使用的宿主或修改其工程。
- UI 状态写入 `%LOCALAPPDATA%/DxProductivity/ui-layout.json`,与更新设置和 PDF 设置分别保存,避免更新设置保存时覆盖窗口位置。
## 2. 横向工具栏
推荐布局,以下为逻辑顺序:
```text
[拖动柄] [Start] │ 位号 属性 显示 检查 网络 BOM PDF │ ● 已选 CE18 [更多] [展开/收起]
```
- 标准宽度约 700—780 个逻辑像素,高度约 42—46 个逻辑像素;按钮使用小图标与短文字。
- 拖动仅从左侧手柄开始,避免点击功能时误拖动。记住位置,重启和更换显示器后将窗口限制在可用屏幕区域内。
- Start 常驻;注册过程中显示忙碌且防止重复触发。注册成功不能直接显示“桥接已连接”,后者依据有效会话状态显示。
- 一级功能顺序为位号、属性、显示、检查、网络、BOM、PDF,分别打开当前对应页面。
- “更多”包含操作历史、设置、刷新快照、明暗主题和退出。原有全部功能都可到达。
- 桥接状态使用图标和文本提示;单选显示位号,多选显示数量与首个位号。鼠标悬停显示完整名单、工程和当前页。
- 状态区宽度固定,长位号或任务文本省略,完整信息在提示中查看,避免每次选择改变工具栏长度。
- 导出或应用进行时,状态区显示任务摘要,例如“PDF 导出中”;提示中同时保留选中器件信息。
- 监听暂停、工程切换或桥接断开时明确显示状态,不继续把过期的位号标为当前选择。
- 默认置顶;展示工具栏及后台状态更新不抢走 DxDesigner 焦点。功能面板只在用户点击入口后激活。
- 狭窄可用屏幕优先保留 Start、位号、属性、PDF、状态和更多;将显示、检查、网络、BOM 依次移入更多,仍保持一排。
## 3. 展开与收起
工具栏是常驻入口,共享面板是按需展示的内容区:
```text
┌ 拖动柄 Start │ 位号 属性 显示 检查 网络 BOM PDF │ 已选 CE18 ⋯ ▴ ┐
└────────────────────────────────────────────────────────────────┘
┌ 自动位号 [收起] ┐
│ 范围 / 处理方式 / 编号方式 / 起始编号 │
│ 高级选项 ▸ │
│ 搜索与筛选 │
│ 变更预览表 │
│ 变更摘要 [预览] [应用位号] │
└──────────────────────────────────────────────────┘
```
- 普通独立启动先显示工具栏;从 DxDesigner 的指定功能菜单启动时显示工具栏并展开对应面板,沿用 `--feature` 路由。
- 点击功能按钮打开或切换对应面板,按钮显示当前激活状态。再次点击已展开的同一功能收起面板。
- 右侧展开按钮重新打开上次使用的页面;面板打开时变为收起按钮。
- 面板默认贴近工具栏下方;下方空间不足则移到上方,整体限制在可用屏幕内。
- 面板打开时拖动工具栏,两者一起移动;手动调整面板大小后记住各页面尺寸。
- 面板关闭按钮和最小化动作均收起到工具栏;“更多 → 退出”关闭整个应用,沿用正在注册菜单等操作的关闭保护。
- 点击宿主时面板保持显示,以支持对照和选中器件;只有显式收起才隐藏。
- 切换页面不重建控制器或快照监听。收起后继续同步选择与保存事件,展开显示最新状态。
- 选中范围发生变化时,延续现有属性输入保留规则和事务期间延后同步规则。
- 紧凑 PDF/设置面板目标约 660×340—400;表格类面板目标约 780×460—500,最小目标约 720×420。展开高级选项可增加面板高度,超出屏幕时滚动参数区。
- 用户已调整的页面尺寸优先使用;没有调整记录时使用对应页面的默认尺寸。
## 4. 页面精简规则
| 页面 | 默认保留 | 折叠或移出常驻区域 |
|---|---|---|
| 自动位号 | 范围、处理方式、编号方式、适用的起始参数、搜索/筛选、变更表、摘要、预览/应用 | 排列顺序和同行容差移至高级选项;连续编号隐藏每页跨度与页内起始;按页编号仅展示该模式适用参数;层级路径等辅助列放入详情或列选择 |
| 属性批改 | 属性名、目标值、当前选中器件表、应用按钮 | 长段使用说明移至帮助提示;重复标题删除;高级批处理参数折叠 |
| 属性显示 | 属性选择、显示/隐藏方式、选中器件表、应用按钮 | 说明段落移至提示;重复标题删除 |
| 设计检查 | 检查类型、运行按钮、结果列表、定位与摘要 | 多个平铺检查入口改为检查类型选择;缺失项选项按检查类型展示 |
| 网络工具 | 查询/检查类型、必要的网络名输入、结果与定位 | 跨页查询字段只在对应类型下显示;常驻说明移至提示 |
| BOM | 范围、预览表、统计、导出 | 描述来源和 NC 选项归入高级选项,并在摘要显示实际取值 |
| PDF | 三种范围、必要的 Block 输入、当前页摘要、输出目录、浏览/打开目录、保存后自动导出、导出/取消、状态 | 配色、文字处理、引擎路径归入高级选项;长工程路径移至提示;技术说明移至帮助;当前页和整工程时隐藏不适用的 Block 编辑框 |
| 操作历史 | 记录、差异、恢复操作 | 路径等详情按需展开 |
| 设置 | 外观/工具栏偏好、更新状态、检查/安装 | 更新源与频道归入高级更新选项,版本说明按需展开;重复“设置”标题删除 |
通用要求:面板只有一个页面标题,一行范围或工程摘要,一个主要结果区和一行操作区。错误、冲突及会影响操作结果的提示继续展示。高级选项有非默认取值时显示简短摘要,避免隐藏生效条件。中文兼容和参考配色沿用现有默认值。
## 5. 文件与接口安排
| 文件 | 计划职责 |
|---|---|
| 新增 `src/dx_productivity/ui/floating_toolbar.py` | 一排功能入口、更多菜单、状态显示、拖动手柄、屏幕边界处理 |
| 新增 `src/dx_productivity/ui/layout_preferences.py` | 读取/保存位置、屏幕与各页面尺寸;验证 JSON 类型、损坏时使用默认值;原子写入 UI 专用文件 |
| 修改 `src/dx_productivity/ui/main_window.py` | 工具栏与共享面板协调、显示/隐藏、锚定、统一状态更新、移除固定左导航和重复顶栏 |
| 修改 `src/dx_productivity/ui/app.py` | 入口与控制器绑定,保留 feature 路由,初始显示策略,统一退出;更新安装退出路径同步迁移 |
| 修改 `src/dx_productivity/ui/selection_watcher.py` | 通过主窗口状态接口更新工具栏和面板;继续使用轻量选择通道 |
| 修改各 `*_page.py` 与 `theme.py` | 页面局部操作区、高级选项、条件字段、尺寸与样式 |
| 修改对应 UI 验证及 `tools/acceptance/compact_window.py` | 从旧叶子和侧栏定位切换到新工具栏;用功能路由和可见内容验收 |
| 退役 `src/dx_productivity/ui/floating_button.py` | 新工具栏完整接入后删除旧入口及无效引用 |
计划接口:
```python
# FloatingToolbar 的主要信号;只请求动作,不直接调用业务逻辑。
page_requested = Signal(int)
start_requested = Signal()
refresh_requested = Signal()
theme_requested = Signal()
toggle_panel_requested = Signal()
exit_requested = Signal()
# MainWindow 保留 set_active_page(index),并集中状态更新。
def show_panel(self, index: int) -> None: ...
def hide_panel(self) -> None: ...
def request_exit(self) -> None: ...
def set_project_status(self, name: str, path: str) -> None: ...
def set_bridge_status(self, text: str) -> None: ...
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 同时更新面板与工具栏,避免隐藏状态不同步。
区分面板关闭与应用退出:普通 closeEvent 收起面板,request_exit 执行控制器 shutdown 并关闭两个窗口。`app.py` 的 `_launch_update` 等程序主动退出路径迁移到 request_exit,防止安装更新时旧进程仅隐藏而占用文件。
## 6. 执行顺序与阶段交付
### 任务 1:工具栏与面板外壳
- [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:状态与窗口行为
- [x] 集中工程、桥接、选择、操作状态 setter,迁移 app.py 与 SelectionWatcher 的直接标签赋值。
- [x] 将短状态和详细提示同步到工具栏;监听失效时展示暂停或断开状态。
- [x] 实现 layout_preferences,原子保存工具栏位置和每页尺寸;屏幕消失或坐标越界时重新放置。
- [x] 更新 `tests/ui/test_live_selection.py`,覆盖隐藏面板时单选、多选、取消选择、断连和工程变化;确认轮询器数量及页面实例不因展开增加。
- [x] 实机检查工具栏状态更新及拖动;物理桌面实测 125% DPI,100%/150% 为 Qt 渲染证据,多屏及负坐标为模拟验证。
交付:不打开面板也能辨认当前选择和监听状态,窗口位置及尺寸可恢复。
### 任务 3:先精简 PDF 和自动位号
- [x] PDF 高级选项收纳配色、文字处理和引擎路径;按范围显示 Block 或当前页摘要;保留打开目录与保存后自动导出。
- [x] 自动位号将规则改为顶部紧凑区域,低频选项折叠;按编号方式显示参数;精简预览默认列。
- [x] 更新 `test_pdf_export_page.py` 和 `test_refdes_page.py`,核对隐藏字段的实际值、范围验证、应用禁用条件和表单保留。
- [x] 在验收工程检查 PDF 三种范围、原生保存监听、配色和中文;检查位号预览、应用与恢复。
交付:两张主要页面明显缩小,常用操作和影响结果的当前参数可见。
### 任务 4:精简其余页面
- [x] 按第 4 节整理属性、显示、检查、网络、BOM、历史和设置页面。
- [x] 检查/网络采用类型选择与相关字段联动;BOM 高级参数显示取值摘要。
- [x] 更新对应现有 UI 验证,核对控制器事件绑定、范围、定位和操作禁用条件。
- [x] 对九个页面逐项拍摄默认与最小尺寸截图,确认按钮可达、表格可读、长路径和错误文本可查看。
交付:所有页面使用同一套紧凑布局规则,更多菜单中的功能同样可用。
### 任务 5:实机回归与发布
- [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'
$env:PYTHONUTF8 = '1'
$env:QT_QPA_PLATFORM = 'offscreen'
$toolbarPython = 'F:\Sync Tool Skyworth\Work Maps\mentor_PDF_output\.venv\Scripts\python.exe'
& $toolbarPython -m pytest tests/ui/test_main_window.py tests/ui/test_compact_floating_window.py tests/ui/test_live_selection.py tests/ui/test_pdf_export_page.py tests/ui/test_refdes_page.py
```
后续实机运行需移除 `QT_QPA_PLATFORM=offscreen` 并使用验收副本。显式设置本仓库 `PYTHONPATH=src`,防止误导入另一份旧 editable 安装。每阶段先跑对应现有验证;最终发布时执行完整回归与便携包验收。
## 7. 最终验收标准与已知问题
- 工具常态是一排横向栏,标准 DPI 下高度不超过 46 个逻辑像素;小屏也不换行。
- 七个一级功能加历史与设置都有可访问入口,PDF 入口保持在设置之前。
- 面板展开、收起、切换、最小化及退出行为一致;表单输入、当前页和后台任务保持连续。
- 收起时单选、多选、取消选择能在工具栏反映;断连与暂停可辨认。记录真实端到端延迟,不将 150 ms 的轮询间隔当作实机响应时间。
- 中文长路径、长位号和 125%/150% DPI 不遮挡按钮;工具栏位置不会落到不可见屏幕区域。
- 位号、属性等写回仅在对应面板显式执行,预览及冲突阻断正常。
- PDF 三范围、中文、颜色、打开输出目录与原生保存自动导出均有实际输出证据。
- Start 后菜单持久保留,普通重启和指定功能菜单启动正常。
**独立稳定性问题:** 现有 PON 工程的完整设计快照在原生 DesignComponents 枚举阶段阻塞,根因尚未确认。界面改版不能作为该问题的修复结论。将其单独安排为“复现副本 → 枚举阶段日志定位 → 确认可中断的边界和修复方式 → PON 菜单及切页实机验证”;没有宿主实际通过证据前,验收记录继续标明此限制。
@@ -0,0 +1,69 @@
# 当前工程 PDF 导出集成设计
日期:2026-10-10
状态:用户已确认设计
## 1. 目标
在“一叶知秋_重构版”中为 DxDesigner 当前打开的工程增加 PDF 导出。功能支持手动导出和可选的保存后自动导出;一次任务只处理当前工程,不扫描目录或建立批量队列。
导出范围提供三种选择:
1. 整工程;
2. 当前活动页;
3. 用户指定的原理图或 Block。
## 2. 边界
- 当前工程以桥接快照中的 `design_path` 为准,不另行扫描或猜测工程。
- 当前页指发起手动导出时或收到保存完成事件时的活动 Block;DxDesigner 7.9.5 的 `IVdBlock.GetName(1)` 返回短名称,`IVdBlock.SheetNum` 返回页码。通过类型库核验了成员签名,尚未在活动工程上做现场调用验收。
- 指定范围使用真实原理图/Block 名称,并传给本机 `sch2pdf.exe`。
- 使用当前工程已有的 DxDesigner 配置生成 PDF。首版不迁入批量工具的字体替换、GBK 解码修复和矢量配色后处理界面。
- 不复制独立 PDF 工具的工程扫描器、批量队列、独立主窗口或发布包。
- 依赖本机 DxDesigner/Mentor 安装、许可和 `sch2pdf.exe`;不分发 Mentor 二进制或许可。
## 3. 集成方式
### 3.1 当前工具页面
新增“PDF 导出”侧栏页及 DxDesigner 菜单入口。页面显示快照中的工程路径,提供三个范围、指定 Block 名称输入、输出目录、手动导出按钮和“保存后自动导出”开关。手动导出和自动导出共享同一工程、范围和输出设置。
输出目录保存在 `%LOCALAPPDATA%\\DxProductivity` 下的用户设置中,默认使用 `%LOCALAPPDATA%\\DxProductivity\\pdf-output\\{工程名}-{路径摘要}`,确保不落入源工程目录;用户选择目录时也必须通过源工程外部校验。PDF 文件名按工程名和范围生成,避免不同范围互相覆盖。
### 3.2 DxDesigner 保存事件
本机 DxDesigner 7.9.5 注册的 `ViewDraw` 类型库包含 `IVdAppEvents.AfterDocumentSave(Doc)` 事件,`IVdBlock.GetName(1)` 与 `IVdBlock.SheetNum` 成员,`ViewDraw.Application` 注册为 32 位本地 COM 服务器。采用独立的 32 位 Windows Script Host/VBScript 事件监听器订阅该事件;64 位 Python UI 不直接连接 DxDesigner COM。
自动导出默认关闭。开启后持久化开关和当前工程、范围及输出设置,并启动监听器;DxDesigner 启动脚本只在开关开启时恢复监听。关闭开关后监听器退出。收到保存完成事件后,监听器读取当前工程与活动 Block,合并短时间内重复通知,再异步启动便携工具的单工程导出命令。导出进程必须重新读取配置并核对事件工程路径,避免设置变更或监听器残留触发错误工程。监听器或导出失败不得阻止 DxDesigner 保存。
监听器应按当前 DxDesigner 实例单例运行;收到应用关闭事件、配置关闭或与宿主断连时退出。不得通过替换或拦截 DxDesigner 原生 Save 命令模拟保存事件。
## 4. 导出流程与文件安全
导出服务从本机发现或让用户指定 `sch2pdf.exe`,按所选范围生成命令,在后台执行并应用超时与取消管理。PDF 先写入输出目录的临时文件;通过结构、页数和内容流验证后才原子发布。
输出必须位于源工程目录之外。手动导出遇到同名 PDF 时要求用户确认覆盖;自动导出可替换既有 PDF,但只能在新文件验证通过后替换。失败、超时或验证不通过时保留原 PDF。
导出服务记录源工程导出前后的文件指纹。与已知数据库/运行日志相关的更新按提示记录;工程配置、设计文件或未知路径变化会阻止 PDF 发布并标记待核验。直接调用原生引擎不承诺源工程只读,界面须明确说明这一点。
运行日志与结果保存在 `%LOCALAPPDATA%\\DxProductivity\\pdf-runs`。自动导出通过 DxDesigner 状态栏及运行记录报告成功或失败,不显示会打断保存的模态窗口。
## 5. 复用与新增组件
复用 `mentor_PDF_output` 中经过验证的单工程原生引擎启动、PDF 结构校验、源变更指纹和临时文件发布逻辑,并改造成当前项目自己的 `features/pdf_export` 模块。新增当前工程/活动页输入适配、范围解析、页面与控制器、自动保存事件监听器及其设置持久化。
复用前逐项核对路径策略、子进程 Job 生命周期和覆盖语义;不以复制整个独立工具替代集成设计。
## 6. 验收要求
- 手动导出三种范围均只生成当前工程对应的 PDF;当前页和指定 Block 的输出范围正确。
- 工程路径含中文和空格时,输出路径及命令参数保持正确。
- 自动导出关闭时保存不会触发 PDF 任务;开启后原生保存成功才触发,重复事件合并,导出失败不影响保存。
- 输出目录位于工程外;验证失败时不替换已有 PDF,自动导出成功后才原子替换。
- 关闭工具后重启 DxDesigner,启用状态可恢复;关闭自动导出后监听器停止。
- 在 DxDesigner 7.9.5 实机确认 `AfterDocumentSave` 事件订阅、活动 Block 解析、异步启动和宿主退出行为。类型库存在事件只证明接口定义,不替代实机验收。
## 7. 已知限制
原生 `sch2pdf.exe` 仍可能更新工程数据库或运行记录。保存事件能力依赖当前 DxDesigner 7.9.5 的 COM 事件连接点和 Windows Script Host;若实机无法稳定订阅或清理监听器,不以键盘钩子、菜单替换或未经验证的新版本 API 作为回退方案。
@@ -0,0 +1,45 @@
# 紧凑窗口、悬浮入口和 PDF 配色验收(2026-10-11)
## 实现
- PDF 导出位于设置上方;页面路由和菜单打开的功能一致。
- 默认窗口 960 × 600,最小 860 × 540;字体、间距和表格高度同步缩小,位号规则支持滚动。
- 点击收起或原生最小化后显示置顶悬浮入口;拖动移动、点击展开、右键打开或退出。收起保留页面和输入,桥接继续工作。
- PDF 默认采用 mentor_PDF_output 的工程参考颜色,另可选择原生配色。配色随设置保存,手动导出和自动导出共用设置。
- 导出进程使用本次运行目录下独立的 DxDesigner.xml 和 WDIR;继承本机 Mentor 环境,未写入工程或全局颜色配置。
- “打开输出目录”打开当前填写的目录,尚未创建时自动创建;导出期间可用,打开失败时显示原因。
## 验收结果
| 检查 | 结果 | 证据 |
|---|---|---|
| 源码回归 | 410 passed | build/test-evidence/compact-pdf-source.xml |
| 便携包 | 16 passed;九个页面及 CLI 在 PATH 不含 Python 时运行 | build/test-evidence/compact-pdf-packaged.xml |
| 紧凑布局 | 默认尺寸和最小尺寸所有页按钮可访问;PDF 新增控件正常显示 | tests/ui/test_compact_floating_window.py、build/ui-previews/compact/pdf-latest.png、pdf-minimum.png |
| 真实 GUI Start | 点击新版包的 Start,收到持久注册和当前宿主加载回执;关闭注册窗口后配置仍指向新版 | compact-floating-20261011/latest-package-ui.json |
| 原生菜单与桥接 | Sheet Menu Bar 的 PDF 动作打开新版 exe,桥接当前工程;原生 Dx 实例 PID 44008 保持运行 | latest-package-ui.json、native-ui.json |
| 悬浮窗 | 实机 125% DPI 下客户区 1200 × 750;真实拖动移动 30 × 20 像素,未误展开;展开保留 PDF 页,快照刷新成功;系统最小化恢复成功 | compact-floating-20261011/native-ui.json |
| 收起期间桥接 | apply-progress.json 更新继续增长;最终新版 GUI PID 66148 留在悬浮状态 | native-ui.json |
| 打开目录 | 真实按钮打开资源管理器中的当前工程输出目录;空值禁用、未创建目录创建、失败消息及导出期间可用由回归覆盖 | latest-package-ui.json、tests/ui/test_pdf_export_page.py |
| 原生 PDF 范围 | Audio 整工程 1 页;PON 当前 03_FLASH 页 1 页、指定 PON Block 17 页、整工程 24 页 | pdf-palette-20261011/palette-acceptance.json |
| 参考颜色 | 同一个 Audio 副本分别使用本工具与原工具参考配置导出,RGB 绘图颜色及出现次数一致 | palette-acceptance.json |
| exe 原生出图 | 冻结 exe 的自动导出命令实际生成一页 PDF,配色与参考样例一致;PATH 不含 Python,保留 Mentor 运行库目录 | frozen-palette-acceptance.json |
| 配置兼容 | 旧配置缺少配色字段时使用参考配色;原生配色持久化,保存事件转发原设置;父进程环境不变 | tests/features/test_pdf_export_settings.py、test_pdf_native_palette.py |
外部证据目录均在 `%LOCALAPPDATA%/DxProductivity/acceptance` 下。本轮 PDF 使用上一轮的 Audio / PON 独立副本;用户当前工程只做快照读取、菜单和界面操作。
Audio 样例的主要 RGB 绘图颜色次数:蓝色 990、紫色 271、青绿色 288、绿色 65、红色 380、属性青色 286。工程中显式指定的其他颜色仍遵循原生规则。
## 发布包
- 目录:`release/一叶知秋_重构版_悬浮窗与PDF配色修复版`。
- ZIP:同目录名加 `_Win11_x64.zip`。
- SHA-256 清单:同目录名加 `_SHA256SUMS.txt`。
- ZIP SHA-256:`f01336492799ac7afb82e5be6e4773cb69129b6fcd190aab2a0e3593efc4659c`。
- exe SHA-256:`6da01d9e0a2e6fce35b60c0348d511cb44683eb39d885b85afd8cf97faa315b1`。
## 适用边界
颜色对齐通过原生参考样例和 RGB 内容比较验证;工程中显式对象颜色继续优先。三种导出范围保留本工具的当前工程绑定和精确书签筛页,没有引入原工具的批量扫描流程。
本机原生字体造成的中文乱码或裁切仍存在,已在渲染样例中记录;本轮处理配色。原生 PDF 引擎需要本机 Mentor 安装、许可和运行库路径。仅保留 Windows 系统 PATH 时引擎缺少 DLL;保留 Mentor 运行库、移除 Python 路径后,冻结 exe 导出通过。
+16 -9
View File
@@ -1,6 +1,6 @@
# DxDesigner 7.9.5 现场验收记录
> 发布状态:离线构建已验证;真实 DxDesigner 7.9.5 验收待完成。所有关键项目通过前,不得把模拟测试结果表述为实机兼容结论。
> 当前验收:2026-10-10 至 2026-10-11 已完成持久菜单、原生写回与恢复、定位、BOM、PCB、PDF 范围及自动导出的副本测试,详见 [逐项验收报告](native-acceptance-20261010.md)。下文保留早期记录与扩展验收模板,不代表本轮仍未验证。
## 1. 测试信息
@@ -9,7 +9,7 @@
| Windows 版本 / Build | |
| DxDesigner / Expedition Enterprise 完整版本与 Build | |
| 工具 ZIP SHA-256 | |
| 解压根目录 | |
| 解压根目录 | `release\一叶知秋_重构版_Start修复版` |
| `script_path_source` | |
| 解析到的脚本完整路径 | |
| 菜单回调路径 | |
@@ -17,17 +17,24 @@
| `compatibility.json` 路径 | |
| 测试工程 / 副本说明 | |
| 测试器 | |
| 日期 | |
| 日期 | 2026-10-10 |
## 2. 发布包与启动脚本
- [ ] ZIP 在离线 Win11 x64 目标机完整解压,无需安装 Python、联网、管理员权限或环境变量。
- [ ] 解压路径包含中文和空格时,`DxDesignerTools.exe` 可启动。
- [ ] 仅通过 `Settings -> Run at Startup -> Scripts` 导入根目录 `MenuAdd.vbs`。
- [ ] 首次重启后只出现一个“Dx 效率工具”菜单。
- [ ] 连续重启两次后仍只有一个同名菜单,没有重复按钮。
- [ ] 菜单包含“自动位号”“兼容性检测”“使用说明”,三个动作均能打开对应功能。
- [ ] 移动完整工具目录后,旧路径失效提示明确;删除旧项并重新导入后恢复正常。
- [x] 目录包含中文和空格时,`DxDesignerTools.exe` 可启动。
- [x] 点击工具的 Start,自动生成用户目录中的启动配置并加载菜单。
- [ ] 未打开 DxDesigner 时,Start 会带菜单配置启动宿主。
- [x] 已打开的 DxDesigner 7.9.5 可即时加载菜单;2026-10-10 收到宿主回执。
- [x] 连续注册两次,Main Menu Bar 与 Sheet Menu Bar 各只有一个菜单,每个含八个动作。
- [ ] 菜单各功能在副本工程中均能完成操作。
- [ ] 移动完整工具目录后重新打开 exe 并点击 Start,入口更新到新位置。
本次菜单实机检查记录:`%LOCALAPPDATA%\DxProductivity\startup-refactored\installed-menu.txt`。该记录只验证菜单与入口,工程写回、PDF 出图及保存事件仍需按后续条目验收。
2026-10-10 补充:通过真实 Sheet Menu Bar 的 PDF 菜单命令打开工具,读取 `1GPHY_RTL8211F.prj` 的完整路径与 114 个器件;同一连接连续刷新两次,快照序号从 1 增至 3,心跳继续更新。运行目录为 `%LOCALAPPDATA%\DxProductivity\runs\20261010T224256-4E6E617F`,宿主日志为 `%LOCALAPPDATA%\DxProductivity\bridge-diagnostics.log`。本次操作未执行应用或 PDF 出图。当前工程的命名图页返回非数字页名,`current_sheet_number` 尚为空,网络读取及所有写回功能仍未验收。
最终包补充:从 `release\一叶知秋_重构版_Start修复版\DxDesignerTools.exe` 启动 GUI 并调用 Start,返回“菜单已加入当前 DxDesigner”;触发 Sheet Menu Bar 的自动位号菜单命令后,实际启动同一目录下的 exe,显示当前工程及“桥接已连接”。运行目录为 `%LOCALAPPDATA%\DxProductivity\runs\20261010T225035-5245617F`。exe SHA-256 为 `978AF94FBB4646E80D6678B3E937A486D73E09A2EDB9D3F580B2DFFAD6FBB639`。本包采用隔离 PATH 的构建环境,避免混入其他软件的运行库。
## 3. 兼容性检测
@@ -0,0 +1,42 @@
# 关闭 DX 自动退出工具验收(2026-10-13)
## 问题与修复
此前宿主监听器在所属 DX 窗口失效时仅忽略本次检查,工具继续运行。本次在已绑定的宿主窗口失效后调用统一退出入口,关闭工具栏和面板、停止定时器及各控制器,并结束 Qt 事件循环。DX 最小化仍只隐藏工具,恢复时还原此前的页面状态。
绑定沿用桥接 run ID、工程路径和原生视图的顶层 HWND/PID,不按前台窗口或进程名称选择宿主。Start 菜单注册进行中时,统一退出入口暂缓关闭;监听器继续运行,注册结束后重试退出。未绑定 DX 的独立工具维持手动退出方式。
## 自动检查
| 检查 | 结果 | 证据 |
|---|---|---|
| 修改前所属宿主消失 | 1 failed,工具未进入退出状态 | `build/test-evidence/host-close-red.xml` |
| 初次修复后宿主监听 | 9 passed,1 skipped | `build/test-evidence/host-close-green.xml` |
| 最终窗口回归 | 24 passed,1 skipped | `build/test-evidence/host-close-ui-final.xml` |
| 最终便携包 | 16 passed | `build/test-evidence/host-close-packaged-final.xml` |
窗口回归覆盖面板展开、收起、DX 最小化的四种组合,以及关闭另一宿主不退出、注册结束后重试。offscreen 跳过的是原生焦点保留用例;此前 Windows 后端结果见 `host-visibility-acceptance-20261012.md`。最终包检查包含九页入口、中文空格路径和 ZIP 校验。
更新发布说明后的一次便携包复查在复制中文路径用例时遇到 C 盘 `WinError 112`(磁盘空间不足),结果为 15 passed、1 failed;记录保留在 `build/test-evidence/host-close-packaged-disk-full.xml`。最终复查通过 `--basetemp` 使用 F 盘的独立目录,未修改产品实现。
## 实机关闭
使用独立副本 `%LOCALAPPDATA%/DxProductivity/acceptance/native-20261010/1GPHY_RTL8211F/1GPHY_RTL8211F.prj`,进入 `GE_PHY_8211` 原理图页,由持久化菜单打开最终包。
- DX PID:28712,主窗口 HWND:6628030。
- 工具 PID:67600,工具栏 HWND:1838946,面板 HWND:1249096。
- DX 最初已最小化,两处工具窗口均隐藏。恢复 DX 后工具栏显示,随后展开面板。
- 验收程序核对 DX 主窗口 PID 和工程路径后,仅向该主窗口发送 `WM_CLOSE`,未向工具发送退出指令。
- 3.047 秒内 DX 和工具进程均退出,工具栏与面板窗口均销毁。
- 工程 `.prj` 和 `sch` 目录文件的 SHA-256 在操作前后一致。
原始记录:`%LOCALAPPDATA%/DxProductivity/acceptance/host-close-20261013/before-close.json` 和 `host-close.json`。本轮实机覆盖面板展开状态;收起、隐藏和其他宿主隔离由自动回归覆盖。
## 发布包
- 目录:`release/一叶知秋_重构版_横向工具栏版`。
- ZIP:`release/一叶知秋_重构版_横向工具栏版_Win11_x64.zip`。
- ZIP SHA-256:`76a3990b4dc0d341cd502fd2c6915afb847df3f50176cdc12073b000a8a01361`。
- EXE SHA-256:`0adaeea27bd2e7a23c7840e47b76b210d12f6e3e1decb54695e00e03f4e6e352`。
此记录仅说明宿主关闭联动及相关窗口行为,不代替业务模块验收。
@@ -0,0 +1,45 @@
# 跟随 DX 最小化验收(2026-10-12)
工具现在跟随所连接的 DxDesigner 窗口。DX 最小化时隐藏工具栏、面板和打开的更多菜单;DX 恢复时还原此前的展开或收起状态,保留页面与表单输入。隐藏只改变可见性,后台定时器及桥接会话继续运行。
## 实现与范围
原生快照和轻量选择状态增加可选的 `host_view_handle`。UI 验证其桥接 run ID 和工程路径,通过 Win32 GA_ROOTOWNER 找到所属 DX 顶层窗口,并保存 HWND/PID。独立 150 ms 监听器读取 IsIconic,不依赖选择变化或事务完成。切页后原视图关闭也不影响已缓存的顶层绑定;句柄或 PID 失效时不读取其他窗口。
初始 DX 已最小化时,工具延后显示。若此时还没有创建原生窗口句柄,也按隐藏处理。恢复采用 WA_ShowWithoutActivating,不走显式用户点击入口的激活路径;退出时停止监听器。无桥接的独立启动或没有宿主标识的旧桥接文件维持独立工具栏行为,后续匹配的选择状态可补全宿主绑定。
## 自动检查
| 检查 | 结果 | 记录 |
|---|---|---|
| 新行为修改前 | 8 项因行为或监听器缺失而失败 | `build/test-evidence/host-visibility-red.xml` |
| 最小化与恢复、初始隐藏、输入保留、后台定时器、退出、弹出菜单、所属宿主和延后绑定 | 8 passed;1 项焦点检查在 offscreen 跳过 | `build/test-evidence/host-visibility-green.xml` |
| 相关窗口、更新退出、选择、协议及原生 VBS 回归 | 68 passed;同一 offscreen 焦点检查跳过 | `build/test-evidence/host-visibility-targeted.xml` |
| 原生 Windows 焦点检查 | 1 passed,恢复后另一测试窗口保持活动 | `build/test-evidence/host-native-focus.xml` |
| VBScript 请求与选择的宿主标识 | cscript 断言通过,含标识不可用时的零值 | `tests/vbs/test_refdes_export.vbs` |
| 最终便携包 | 16 passed,包含九页入口、中文路径、运行库和 ZIP 校验 | `build/test-evidence/host-visibility-packaged.xml` |
| 独立代码审查 | 无剩余可操作 P1/P2 | `build/test-evidence/host-visibility-review.md` |
offscreen 平台会激活每个显示的窗口,不能用于验证原生焦点,因此该项单独在 Windows 后端执行。上表的检查集有重叠,不将数量相加。
## 最终包实机
独立工程为 `%LOCALAPPDATA%/DxProductivity/acceptance/native-20261010/1GPHY_RTL8211F/1GPHY_RTL8211F.prj`,DX PID 57584、主 HWND 9051710。由更新后的原生菜单打开最终 EXE PID 86508,其视图 HWND 593196 正确解析为该主窗口。
- DX 初始已最小化,启动后工具保持隐藏;恢复 DX 后工具栏和自动位号面板显示,桥接已连接。
- 面板展开时两轮最小化/恢复,工具栏与面板同步隐藏,恢复仍展开。
- 面板收起时两轮最小化/恢复,工具栏隐藏,恢复仅显示工具栏。
- 每轮隐藏期间 `apply-progress.json` 时间继续更新,DX 没有被后台桥接还原;恢复后前台 PID 均未变为工具 PID。
- 最终恢复用户原本的 DX 最小化状态,工具随之隐藏;未写回器件。
证据:`%LOCALAPPDATA%/DxProductivity/acceptance/host-visibility-20261012/host-native.json`,同目录含恢复后的工具栏及面板截图。循环脚本为 `tools/acceptance/host_visibility.py`。
本轮实机使用一个 DX;第二宿主隔离由模拟窗口后端覆盖。尝试强制设置 DX 前台时,Windows 的前台限制拒绝了验收辅助程序,最终用例验证工具恢复后不占用前台;原生 Qt 焦点检查另验证活动窗口保留。
## 发布
- 包目录:`release/一叶知秋_重构版_横向工具栏版`。
- ZIP SHA-256:`5d9bb051690eba512bd1017fee4e2afa8a35f85cd817f709d433fb8990debb55`。
- EXE SHA-256:`d1af32fca413de8a9e857d093c5843414598ab779bcb6e2b805e67d795dae9d6`。
业务功能全量验收见 `toolbar-acceptance-20261011.md`。本次未解决 PON 全工程快照阻塞,亦未测量长会话原生集合保留的内存增长。
@@ -0,0 +1,25 @@
# “更多”按钮重叠修复验收(2026-10-12)
原按钮继承全局 QToolButton 的 30 像素内容宽度,实际外宽 32 像素;“更多”文字宽 26 像素,菜单指示器还占 12 像素,因此无法并排显示。此前仅修正展开/收起按钮,遗漏了此菜单按钮。
修复使用独立样式和 60 逻辑像素按钮,显式下箭头与文字由 Qt 并排布局,隐藏重复的自动菜单指示器。极窄屏进入箭头菜单模式,恢复可用宽度后重新显示“更多”。InstantPopup 及原有菜单动作保持原路由。
## 验证
- 回归断言在修改前失败:实际 32 像素小于文字、箭头及间距所需的 52 像素。记录:`build/test-evidence/more-button-red.xml`。
- 修复后工具栏、主窗口、窄屏溢出、位置恢复等 33 项通过。记录:`build/test-evidence/more-button-green.xml`。
- 明暗主题在 100%/125%/150% Qt 缩放下渲染;图片:`build/test-evidence/more-button/scale-*.png`。
- 最终便携包 15 项入口/运行库检查通过,另 1 项 ZIP 校验通过。记录:`build/test-evidence/more-button-packaged.xml`、`more-button-manifest.xml`。
- 最终 EXE 在独立 1GPHY 验收工程中由原生菜单打开,桥接已连接。实际 125% DPI 下“更多”外宽 75 物理像素,真实鼠标打开菜单、设置路由及两次主题切换均通过;PrintWindow 截图确认文字和箭头没有重叠。
- 收起后工具栏持续运行,未写回器件。原生记录:`%LOCALAPPDATA%/DxProductivity/acceptance/more-button-20261012/more-native.json`;图片:同目录 `toolbar-final.png`、`toolbar-dark.png`、`more-popup.png`。
拖动和位置恢复的现有测试原先假设固定的 20 像素横坐标;增加菜单宽度后会触及离屏测试显示器的右边界。断言改为验证边界限制后的坐标和实际保存位置,边界处理逻辑未修改。
## 发布包
- 目录:`release/一叶知秋_重构版_横向工具栏版`。
- ZIP:`release/一叶知秋_重构版_横向工具栏版_Win11_x64.zip`。
- ZIP SHA-256:`a35f46113e6693d9b1129d64fb91955c02cdd853d6c1817d7c979a11e494c90c`。
- EXE SHA-256:`2ce88c0df54c2d28f8f7990aa7debbe85a4ab44d2c7d2efdf9c91a30b0a97a25`。
本记录仅验证菜单按钮修复及相关窗口行为;业务功能的完整实机记录见 `toolbar-acceptance-20261011.md`。PON 全工程快照阻塞和长会话集合内存增长未在本次解决。
@@ -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`。
+3 -1
View File
@@ -2,9 +2,11 @@
本清单用于在真实 DxDesigner 7.9.5 / Expedition PCB 环境中验收原生迁移后的功能。各功能的计算逻辑已由自动化测试覆盖;本清单关注 COM 宿主行为(属性写回、读回验证、定位、Excel 输出)与端到端体验。没有真实宿主运行记录时,不得写成“已验证”。
2026-10-10 至 2026-10-11 的逐项实际结果见 [本轮验收报告](native-acceptance-20261010.md),包括持久菜单、PDF 三种范围、自动导出关闭检查及失败回滚。以下为后续工程复测清单。
## 通用前置条件
- 使用便携包根目录的 `MenuAdd.vbs`,通过 DxDesigner 7.9.5 的启动脚本设置导入;Expedition 侧导入 `expedition\ExpeditionBridge.vbs`。
- 从完整便携包打开 `DxDesignerTools.exe`,点击 Start 自动注册并加载 DxDesigner 菜单;Expedition 侧导入 `expedition\ExpeditionBridge.vbs`。
- 准备可恢复的样例工程,先复制工程目录和原理图文件。
- 运行“兼容性检测”,保存诊断输出和宿主版本信息。
@@ -0,0 +1,21 @@
# 无活动原理图页错误修复验收(2026-10-13)
## 根因
今天三次菜单启动均在 `snapshot.design` 后报 `131: 集合中找不到对象`。诊断到当时 DxDesigner 处于 `DxDesigner - [Start Page]`,工程路径为空,`ActiveViewHandle=0`。原生 `Application.DesignComponents` 在没有活动原理图页时返回该错误。
## 修复
原生快照在读取器件集合前检查 `ActiveView`;菜单动作在启动桥接前也执行同样检查。无活动视图时显示“请先打开工程并进入原理图页后再使用工具”,并停止当前动作,不创建半成品工具会话。正常工程页仍写出 `host_view_handle` 并连接工具。
## 验证
- 修复前 VBS 回归按预期失败:`DxBridgeHasActiveView` 不存在。记录:`build/test-evidence/no-active-view-red.xml`(由首次 cscript 失败复现)。
- 修复后 VBS 快照/选择回归 5 项通过:`build/test-evidence/no-active-view-vbs.xml`。
- 最终便携包 16 项通过:`build/test-evidence/no-active-view-packaged.xml`。
- 独立 1GPHY 工程页实机启动最终 EXE,桥接已连接、自动位号面板正常:`%LOCALAPPDATA%/DxProductivity/acceptance/no-active-view-20261013`。
- 原生运行时已同步到正式包;更新后的 `MenuAdd.vbs` 已重新生成菜单动作。
- 当前 ZIP SHA-256:`02b06a57415f943797fea33f85ec8682b4c53ab45386251381f6616aebb88dd1`。
- 当前 EXE SHA-256:`cbc6ba0e1ac3abb1459b46d195d2fdd805053283615c43e9f35363a7a717e2ec`。
用户使用时先在 DxDesigner 打开工程并进入任一原理图页,再点击工具菜单。Start Page 场景现在有明确提示,不会再显示 131。
@@ -0,0 +1,40 @@
# 中文 PDF 与实时器件选择验收(2026-10-11)
## 修复与验证
| 项目 | 验证结果 |
|---|---|
| 中文根因 | 原生 WinAnsi 字体保存 GBK 字节;旧 `-udx` 还会将部分错误字符绘制为笔画,单纯替换字体无法恢复 |
| 正式导出 | 默认中文兼容模式关闭旧笔画映射,按 GBK 解码,嵌入 Arial / 宋体子集、CIDToGIDMap 和 ToUnicode;原生色彩、矢量图形与文字推进量保持 |
| 1GPHY | 原生副本实际出图,411 段文字转换、25 段中文恢复、2 个字体子集;“输入网络”“输出网络”“靠近CPU放置”“电源输入3V3”显示及提取正常 |
| 冻结 exe | PATH 不含 Python、保留 Mentor 运行库;exe 实际生成中文 PDF,重新打开提取及 Poppler 渲染通过 |
| Audio / PON PDF | Audio 整工程 1 页;PON 当前页 1 页、指定 Block 17 页、整工程 24 页;中文处理完成后再发布 |
| 颜色 | Audio 的 RGB 绘图颜色及出现次数与原工具参考模式一致;文字修复不重绘图形,不改变颜色 |
| 选择根因 | 旧版只在初次快照和手动刷新时读取 selected;打开后点击器件不会更新工具 |
| 原生选择 | 1GPHY 独立实例单选 CE17、改选 LE03、多选、取消选择和收起状态下的选择均同步,无需手动刷新;测试含脚本启动与 UI 自动化共 1.28—1.91 秒 |
| 选择范围 | 位号、属性、可见性和 BOM 的选中范围随原生选择更新;底部显示数量和位号,提示中显示完整名单及当前页 |
| 输入及事务 | 保留仍选中器件的新属性输入和 PDF 表单;应用与恢复进行时暂缓消费选择,结束后读取最新状态;旧快照和其他工程的选择消息拒绝 |
| 运行中的工具 | 旧 GUI 正常退出,新版 GUI PID 43192 从用户宿主 PID 44008 的 PDF 菜单打开;Start 持久入口指向新版,实际显示当前选择 CE18,属性页内容匹配 |
| 当前工程 GUI 出图 | 使用新版 GUI 实际重新导出当前 1GPHY 工程,确认中文显示和提取正常;旧乱码 PDF 先备份为 previous-user-garbled.pdf;详细记录 current-user-pdf-acceptance.json |
| 源码 | 420 passed,build/test-evidence/text-selection-source.xml |
| 便携包 | 16 passed,build/test-evidence/text-selection-packaged.xml |
证据根目录:`%LOCALAPPDATA%/DxProductivity/acceptance/pdf-text-selection-20261011`。
- `source-text-acceptance.json`、`frozen-text-acceptance.json` 和对应 PDF。
- `pdf-scopes/palette-acceptance.json` 和三种范围的输出。
- `live-selection/live-selection-acceptance.json`,五个原生选择用例。
- `latest-package-ui.json`、`current-live-ui.png`,新版菜单、配色、输出目录和当前选择。
- `current-user-pdf-acceptance.json`,当前工程重新导出的结果及旧 PDF 备份。
## 发布包
- 目录:`release/一叶知秋_重构版_中文PDF与实时选择版`。
- ZIP:目录名后增加 `_Win11_x64.zip`。
- ZIP SHA-256:`bc8ecca30ca67259badc4a4f8ff43009010477dd60337fa28b60a33f90c59d99`。
## 已知边界
本次源码及打包后的中文恢复通过 1GPHY、Audio 和 PON PDF 验证。中文兼容模式针对 GBK;西文工程需选择西文兼容,原生字体不修复编码。未支持的复合文字、Form 旧编码文字或无法取得可靠字宽时,导出失败并保留旧文件。工程自身的文字重叠、长行超出图框未做重排。
PON 的 PDF 引擎导出三种范围通过,但同一副本从工具菜单生成完整设计快照时,在原生 DesignComponents 枚举阶段阻塞,无法完成整条 GUI 切页验收。测试实例 PID 80668 不响应关闭请求后已结束;当时执行只读快照,没有设计值写回,用户宿主 PID 44008 保持运行。本项不是已通过的 GUI 功能;切页状态消费由离线回归覆盖。
@@ -0,0 +1,69 @@
# 横向工具栏与紧凑面板验收(2026-10-11)
## 结果与交付
横向工具栏、九个功能面板及本轮实机验收已完成。正式包已通过真实 Start 注册到 DxDesigner 持久启动菜单,普通重启后自动加载。用户当前宿主 PID 44008 保留,已从其原生菜单打开最终工具并确认桥接已连接;面板收起,仅保留一排工具栏。该宿主的工程没有写回或关闭。
2026-10-12 界面修订:尾部切换入口改为明确的“展开 ▾ / 收起 ▴”文字箭头按钮;展开页改为无标题栏、置顶的紧凑工具卡片。独立验收副本实际打开最终包验证通过,记录见 `%LOCALAPPDATA%/DxProductivity/acceptance/toolbar-20261012-ui-polish`。
- 正式包:`release/一叶知秋_重构版_横向工具栏版`。
- 发布 ZIP:`release/一叶知秋_重构版_横向工具栏版_Win11_x64.zip`。
- ZIP SHA-256:`26275747dc28e2937c3dcae0dcd6525e9691d4868c729a5ba92ccbbd3b65adb8`。
- EXE SHA-256:`fbd86ddc9184ca598c1f113886d4d5842bf0d6e7471ca7277ebc0d89b7f9351f`。
- 原生证据根目录:`%LOCALAPPDATA%/DxProductivity/acceptance/toolbar-20261011`。下表原生记录均相对此目录。
写回验收在独立工程副本 `1GPHY_toolbar/1GPHY_RTL8211F.prj` 中进行,全部 114 个器件的值、位置和可见性恢复。初始验收宿主 PID 83848 已正常关闭;普通重启后的验收宿主为 PID 81148。
## 功能与窗口实测
| 项目 | 结果 | 证据 |
|---|---|---|
| 单行工具栏 | 位号、属性、显示、检查、网络、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 条数据。
## 更新与回滚
展开、收起两种状态均使用最终 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` 覆盖;更多菜单的鼠标退出已在先前前台检查中验证。
最初放在 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% 与多屏边界由渲染/模拟验证,不代表多台物理显示器实测。
+27
View File
@@ -0,0 +1,27 @@
# PDF 导出
在 DxDesigner 的“Dx 效率工具”菜单中打开“PDF 导出”,工具会按当前桥接工程执行导出。
也可点击悬浮工具栏的 PDF 按钮展开面板。面板常驻显示范围、输出目录、保存后自动导出与操作按钮;配色、文字处理和引擎路径放在“高级选项”中,当前有效取值会显示为摘要。
范围有三种:
- **整工程**:导出当前工程中的全部原理图页。
- **当前页**:导出活动视图对应的命名图页,多页 Block 只保留该页。
- **指定原理图或 Block**:输入本机 DxDesigner 工程中的实际 Block 名称。
默认输出到 `%LOCALAPPDATA%\DxProductivity\pdf-output` 下按工程区分的目录。可在页面选择其他输出目录,但不能选择源工程目录或其子目录。覆盖现有 PDF 前,手动导出会先询问;自动导出只在新 PDF 验证成功后替换原文件。
点击“打开输出目录”可在资源管理器中打开当前填写的目录;尚未创建的目录会自动创建,导出过程中也可使用该按钮。
PDF 配色默认使用“工程参考配色(mentor_PDF_output)”:红色连线、青绿色引脚、蓝色图形和文字、紫色方框、绿色网络名。颜色通过本次导出进程的独立配置加载;原理图中明确指定的对象颜色仍按原生规则显示。也可选择“原生配色”,配色选择会保存,并用于保存工程后自动导出。
文字处理默认“中文兼容(GBK,推荐)”:原生输出使用可映射文字,再修复本工程的 GBK 中文,并嵌入本机 Arial / 宋体子集及 Unicode 映射。中文可显示、复制和搜索,绘图颜色及矢量图形保持原样。西文工程可选“西文兼容”,保留 WinAnsi 符号;“原生字体”沿用旧映射,不执行编码修复。字体处理无法可靠完成时不会覆盖已有 PDF,页面显示具体原因。
DxDesigner 中切换原理图页后,工具会同步当前页;选择“当前页”导出时,页面显示最新的 Block 和图页名称。
“保存工程后自动导出”默认关闭。EE iCDB 工程会即时保存设计变更,工具收到原生变更事件、等待变更稳定后导出当前数据库;传统文件工程在保存完成后导出。重复通知会合并,已有导出进程结束后才执行下一次导出。监听器按配置中的工程路径绑定实例,关闭开关后自行退出。导出状态显示在 DxDesigner 状态栏,详细记录位于 `%LOCALAPPDATA%\DxProductivity\pdf-runs`。
PDF 使用本机 `sch2pdf.exe`、DxDesigner 配置和许可。原生出图可能更新工程数据库或运行记录;发布 PDF 前工具会检查工程文件变化,未确认的变化会阻止发布。
工程打开时数据库可能被锁定,工具会明确记录无法核验数据库内容;工程配置和其他可读设计文件继续进行变化检查。
@@ -1,12 +1,48 @@
# 一叶知秋_重构版 更新说明
## 横向工具栏与功能面板
- 工具以一排置顶工具栏常驻,提供 Start、位号、属性、显示、检查、网络、BOM 和 PDF;历史、设置、刷新、主题及退出放在“更多”中。
- 点击功能展开对应面板,再点同一功能或“收起面板”收起。面板关闭和最小化也会收起;退出整个工具使用“更多 → 退出工具”。
- 工具栏末尾使用明确的“展开 ▾ / 收起 ▴”按钮;展开内容以无标题栏卡片贴在工具栏下方,不再显示独立应用窗口的标题框。
- 修复“更多”的文字与菜单箭头重叠;正常宽度下两者并排,极窄屏自动保留箭头菜单入口,屏幕恢复后显示文字。
- 工具跟随所属 DxDesigner 窗口:DX 最小化时隐藏工具栏和面板,DX 恢复时还原此前的展开或收起状态,并保留表单输入。隐藏期间选择监听和导出继续运行;恢复工具不会抢走 DX 焦点。
- 关闭所属 DxDesigner 时,工具自动退出,同时关闭工具栏、面板和后台监听;展开、收起或随 DX 隐藏时均生效。关闭其他 DX 窗口不会退出当前工具。
- 如果 DxDesigner 还停在 Start Page、没有打开工程和活动原理图页,菜单动作会直接提示“请先打开工程并进入原理图页后再使用工具”,不再显示原生 131 集合错误。
- 收起后工具栏继续显示选择与任务状态;悬停可查看完整位号、工程、图页和状态信息。拖动左侧手柄移动,位置与各页面大小会保存。
- 页面移除固定左导航、重复标题与说明,操作按钮移到对应页面。低频设置折叠为高级选项,并显示当前有效参数摘要。
- PDF 保留三种范围、输出目录、打开目录和保存后自动导出;配色、文字处理与引擎设置可在高级选项中调整。
- 应用位号、属性、显示状态及历史恢复后自动读取最新工程快照,预览与恢复使用写回后的数据。
- 修复历史恢复点击 Yes 后没有执行,以及保存对话框的路径格式导致原生 Excel 无法保存 BOM 的问题。
- 修复刷新快照后的连续写回失效;自动刷新保留应用、拒绝和回滚结果,避免覆盖失败提示。
## 中文 PDF 与实时选择
- 修复 GBK 中文被按西文输出造成的乱码;默认采用中文兼容模式,嵌入字体及 Unicode 映射,保留图形和颜色。可选西文兼容或原生字体,手动和自动导出共用文字设置。
- DxDesigner 的单选、多选、取消选择及切页会实时同步;底部显示当前选中数量和位号。位号、属性、可见性、BOM 的选中范围同步更新,PDF 的当前页随宿主切页更新。
- 选择同步保留仍选中器件的新属性输入及 PDF 表单;应用或恢复进行时暂缓更新,操作结束后读取最新选择。无法识别的新增器件会自动请求完整快照。
## PDF 配色与输出目录
- PDF 默认采用 mentor_PDF_output 的工程参考配色,也可选择原生配色;手动导出与保存后自动导出使用同一设置。
- PDF 页新增“打开输出目录”按钮,可打开当前填写的目录,尚未创建时自动创建。
## 本版变更(原生迁移版)
- 打开完整工具包中的 `DxDesignerTools.exe`,点击顶部 **Start**,即可自动加入 DxDesigner 菜单。已打开的 DxDesigner 会加载菜单;未打开时工具会带菜单配置启动它。
- 菜单包含自动位号、属性批改、属性显示、设计检查、BOM、PDF 导出、兼容性检测及使用说明。Start 会先备份,再向 DxDesigner 平时使用的 `scripts.ini` 注册入口,保留公司原有启动脚本;关闭工具、普通重启 DxDesigner、切换工程后菜单继续存在。生成的动作保存在用户目录,绑定当前工具包,支持中文及空格路径。
- 移动完整工具包后重新打开其中的 exe 并点击 Start,入口会更新到新位置。工具目录不完整或宿主未加载成功时,界面会显示原因。DxDesigner 若正在等待报错对话框,先关闭该对话框,再点击 Start。
- 修复中文宿主需要本地化启动键、命名图页、器件坐标与属性读取、网络名称、定位请求末尾换行、循环位号交换和事务信箱读取等实机兼容问题。
- 菜单点击、快照生成与工具启动阶段写入 `%LOCALAPPDATA%\DxProductivity\bridge-diagnostics.log`,桥接异常会显示具体错误。
- 原“一叶知秋”七大功能全部**原生迁移**进新工具,不再桥接旧 EFM/VBS:Value/Value1/Part Number 批量修改、PartName/PartLabel 批量隐藏(新增“显示”方向)、孤立网络/网络列表/跨页互动、Value/Value1 遗漏查找、BOM 导出(含创维料号校验)与 Expedition PCB 装配位号整理。
- 全部功能共用统一事务通道:预检(摘要与状态一致性校验)→ 逐项写回并读回验证 → 失败自动回滚 → 全设计终检。
- 桥接协议升级到 v2:快照包含属性全集、可见性、网络分布与真实锁定状态;调度表按“操作类型 + 属性名”泛化,同一事务核心承载所有功能。
- 宿主侧信箱支持多次应用、真实休眠(不再空转占用 CPU)、心跳检测与旧运行目录自动清理;界面增加“刷新设计快照”的真实重新导出。
- 更新通道安全强化:stable 频道强制 Ed25519 签名验证(公钥内置于程序),下载地址仅允许 https 与 file 协议,阻止跨协议重定向;更新器加单实例互斥并等待主程序退出后再切换版本。
- PDF 支持整工程、当前页、指定原理图或 Block。当前页通过原生 PDF 的准确书签保留一页;书签缺失或歧义时保留旧输出并报错。自动导出默认关闭,开启后监听原生事件;EE 数据库即时保存后等待变更稳定再导出。
- 修复 BOM 只输出表头、合并行内重复位号检测及 Excel 失败后的资源清理;修复 Expedition 的工具目录解析、菜单接口和脚本入口。
- 修复更新器对发布 ZIP 外层目录的处理,并将更新程序复制到缓存后运行,避免 Windows 上自身锁住待替换 exe。
## 设置页
@@ -14,4 +50,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`;中文字体与实时选择的新版结果另有验收记录。
+17 -1
View File
@@ -1,5 +1,20 @@
' Shared DxDesigner 7.9.5 bridge helpers. Keep this file ASCII-only.
Sub DxToolsAppendDiagnostic(stage, detail)
Dim fso, root, stream
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
root = CreateObject("WScript.Shell").ExpandEnvironmentStrings( _
"%LOCALAPPDATA%\DxProductivity")
If Not fso.FolderExists(root) Then fso.CreateFolder root
Set stream = fso.OpenTextFile( _
fso.BuildPath(root, "bridge-diagnostics.log"), 8, True, -1)
stream.WriteLine CStr(Now) & " " & CStr(stage) & " " & CStr(detail)
stream.Close
Err.Clear
On Error GoTo 0
End Sub
Function DxToolsQuote(value)
Dim text
Dim expression
@@ -221,7 +236,8 @@ Sub DxBridgeIdleWait()
Dim shell
On Error Resume Next
Set shell = CreateObject("WScript.Shell")
shell.Run "%ComSpec% /d /s /c ping -n 2 -w 400 127.0.0.1 > nul", 0, True
shell.Run DxToolsQuote(DxToolsHome & "\DxDesignerTools.exe") & _
" bridge-wait --milliseconds 150", 0, True
Err.Clear
On Error GoTo 0
Call DxBridgeYield()
@@ -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
@@ -36,9 +36,34 @@ Sub DxToolsRunDesignBridge(featureKey)
Exit Sub
End If
On Error GoTo 0
If Not DxToolsHasActiveView() Then
MsgBox DxToolsNoActiveViewMessage(), vbExclamation
Exit Sub
End If
Call DxToolsDesignBridgeStart(CStr(featureKey))
End Sub
Function DxToolsHasActiveView()
Dim view
DxToolsHasActiveView = False
On Error Resume Next
Set view = ActiveView
If Err.Number = 0 And Not view Is Nothing Then
DxToolsHasActiveView = True
End If
Err.Clear
On Error GoTo 0
End Function
Function DxToolsNoActiveViewMessage()
DxToolsNoActiveViewMessage = ChrW(&H8BF7) & ChrW(&H5148) & _
ChrW(&H6253) & ChrW(&H5F00) & ChrW(&H5DE5) & ChrW(&H7A0B) & _
ChrW(&H5E76) & ChrW(&H8FDB) & ChrW(&H5165) & ChrW(&H539F) & _
ChrW(&H7406) & ChrW(&H56FE) & ChrW(&H9875) & ChrW(&H540E) & _
ChrW(&H518D) & ChrW(&H4F7F) & ChrW(&H7528) & ChrW(&H5DE5) & _
ChrW(&H5177)
End Function
Function DxToolsPathErrorMessage()
DxToolsPathErrorMessage = ChrW(&H65E0) & ChrW(&H6CD5) & _
ChrW(&H786E) & ChrW(&H5B9A) & ChrW(&H5DE5) & ChrW(&H5177) & _
+23
View File
@@ -0,0 +1,23 @@
' Request the current DxDesigner host to execute the generated menu script.
' This external adapter only forwards a command; design APIs run in the host.
Option Explicit
Dim app, path, errorText
If WScript.Arguments.Count <> 1 Then WScript.Quit 2
path = WScript.Arguments(0)
If Not CreateObject("Scripting.FileSystemObject").FileExists(path) Then WScript.Quit 2
On Error Resume Next
Set app = GetObject(, "ViewDraw.Application")
If Err.Number <> 0 Or app Is Nothing Then
Err.Clear
WScript.Quit 3
End If
Err.Clear
app.ExecuteCommand "run " & Chr(34) & path & Chr(34)
If Err.Number <> 0 Then
errorText = Err.Description
Err.Clear
WScript.Echo errorText
WScript.Quit 1
End If
On Error GoTo 0
WScript.Quit 0
+119 -2
View File
@@ -17,9 +17,66 @@ 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")
On Error Resume Next
Call DxToolsMaybeStartPdfListener()
Err.Clear
On Error GoTo 0
End Sub
Sub DxToolsInstallMenuBar(barName)
Dim menuBar
Dim existing
Dim button
@@ -27,7 +84,7 @@ Sub DxToolsInstallMenu()
Dim caption
caption = DxToolsSuiteCaption()
Set menuBar = CommandBars("Sheet Menu Bar")
Set menuBar = CommandBars(CStr(barName))
For i = menuBar.Controls.Count To 1 Step -1
Set existing = menuBar.Controls.Item(i)
If existing.Caption = caption Then
@@ -38,7 +95,8 @@ Sub DxToolsInstallMenu()
End If
Next
Set DxToolsMenu = menuBar.Controls.Add(cmdControlPopup)
' CommandBarSvr70/75 defines cmdControlPopup as 1; Run does not inject it.
Set DxToolsMenu = menuBar.Controls.Add(1)
DxToolsMenu.Caption = caption
Set button = DxToolsMenu.Controls.Add
@@ -61,6 +119,10 @@ Sub DxToolsInstallMenu()
button.Caption = DxToolsBomCaption()
button.OnAction = "DxToolsOpenBom"
Set button = DxToolsMenu.Controls.Add
button.Caption = DxToolsPdfExportCaption()
button.OnAction = "DxToolsOpenPdfExport"
Set button = DxToolsMenu.Controls.Add
button.Caption = DxToolsCompatibilityCaption()
button.OnAction = "DxToolsOpenCompatibility"
@@ -90,6 +152,10 @@ Sub DxToolsOpenBom()
Call DxToolsStartFeature("bom")
End Sub
Sub DxToolsOpenPdfExport()
Call DxToolsStartFeature("pdf-export")
End Sub
Sub DxToolsStartFeature(featureKey)
If Not DxToolsEnsureRoot() Then Exit Sub
Call DxToolsEnsureCommonLoaded()
@@ -132,6 +198,53 @@ Sub DxToolsOpenGuide()
shell.Run Chr(34) & guidePath & Chr(34), 1, False
End Sub
Sub DxToolsMaybeStartPdfListener()
Dim shell
Dim fso
Dim stream
Dim settingsPath
Dim settingsText
Dim expression
Dim listenerPath
Dim executablePath
Dim hostPath
Dim commandLine
Call DxToolsEnsureCommonLoaded()
Set shell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
settingsPath = shell.ExpandEnvironmentStrings( _
"%LOCALAPPDATA%\DxProductivity\pdf-export-settings.json")
If Not fso.FileExists(settingsPath) Then Exit Sub
On Error Resume Next
Set stream = CreateObject("ADODB.Stream")
stream.Type = 2
stream.Charset = "utf-8"
stream.Open
stream.LoadFromFile settingsPath
settingsText = stream.ReadText
stream.Close
If Err.Number <> 0 Then
Err.Clear
On Error GoTo 0
Exit Sub
End If
On Error GoTo 0
Set expression = CreateObject("VBScript.RegExp")
expression.Pattern = Chr(34) & "auto_export" & Chr(34) & "\s*:\s*true"
expression.IgnoreCase = True
expression.Global = False
If Not expression.Test(settingsText) Then Exit Sub
executablePath = fso.BuildPath(DxToolsHome, "DxDesignerTools.exe")
If Not fso.FileExists(executablePath) Then Exit Sub
commandLine = DxToolsQuote(executablePath) & " pdf-export-listen --settings " & _
DxToolsQuote(settingsPath)
shell.Run commandLine, 0, False
End Sub
Function DxToolsEnsureRoot()
If DxToolsHome = "" Then DxToolsHome = DxToolsResolveRoot()
DxToolsEnsureRoot = (DxToolsHome <> "")
@@ -256,6 +369,10 @@ Function DxToolsBomCaption()
DxToolsBomCaption = "BOM " & ChrW(&H5BFC) & ChrW(&H51FA)
End Function
Function DxToolsPdfExportCaption()
DxToolsPdfExportCaption = "PDF " & ChrW(&H5BFC) & ChrW(&H51FA)
End Function
Function DxToolsCompatibilityCaption()
DxToolsCompatibilityCaption = ChrW(&H517C) & ChrW(&H5BB9) & _
ChrW(&H6027) & ChrW(&H68C0) & ChrW(&H6D4B)
@@ -0,0 +1,283 @@
' DxDesigner 7.9.5 save-event listener. Keep this file ASCII-only.
Option Explicit
Const ForReading = 1
Const ForWriting = 2
Const TristateTrue = -1
Dim fso, shell, wmi, app
Dim configPath, toolPath, launchMode, workingRoot, lockPath, statusPath, logPath
Dim running, busyPid, pendingProject, pendingBlock, hasPending
Dim lastEventKey, lastEventAt
Set fso = CreateObject("Scripting.FileSystemObject")
Set shell = CreateObject("WScript.Shell")
If WScript.Arguments.Count < 4 Then WScript.Quit 2
configPath = CStr(WScript.Arguments(0))
toolPath = CStr(WScript.Arguments(1))
launchMode = LCase(CStr(WScript.Arguments(2)))
workingRoot = CStr(WScript.Arguments(3))
lockPath = configPath & ".listener-lock"
statusPath = configPath & ".last-status"
logPath = fso.BuildPath(fso.GetParentFolderName(configPath), "pdf-listener.log")
running = True
busyPid = 0
hasPending = False
lastEventKey = ""
lastEventAt = 0
If Not DxPdfAutoEnabled() Then WScript.Quit 0
If Not DxPdfAcquireLock() Then WScript.Quit 0
On Error Resume Next
Set wmi = GetObject("winmgmts:\\.\root\cimv2")
Set app = GetObject(, "ViewDraw.Application")
If Err.Number <> 0 Then
Call DxPdfLog("Could not connect to ViewDraw.Application: " & Err.Description)
Err.Clear
On Error GoTo 0
Call DxPdfReleaseLock()
WScript.Quit 0
End If
WScript.ConnectObject app, "DxPdf_"
If Err.Number <> 0 Then
Call DxPdfLog("Could not connect ViewDraw events: " & Err.Description)
Err.Clear
On Error GoTo 0
Call DxPdfReleaseLock()
WScript.Quit 0
End If
On Error GoTo 0
Do While running
If Not DxPdfAutoEnabled() Then Exit Do
If Not DxPdfHostAvailable() Then Exit Do
Call DxPdfTouchLock()
If busyPid > 0 Then
If Not DxPdfProcessRunning(busyPid) Then
Call DxPdfPublishStatus()
busyPid = 0
If hasPending Then
Call DxPdfLaunch(pendingProject, pendingBlock)
hasPending = False
End If
End If
End If
WScript.Sleep 400
Loop
On Error Resume Next
WScript.DisconnectObject app
Err.Clear
On Error GoTo 0
Call DxPdfReleaseLock()
WScript.Quit 0
Sub DxPdf_AfterDocumentSave(Doc)
Dim projectPath, blockName, eventKey, eventTime
If Not DxPdfAutoEnabled() Then Exit Sub
projectPath = ""
blockName = ""
On Error Resume Next
projectPath = CStr(app.GetProjectData().GetProjectFilePath())
blockName = CStr(app.ActiveView.Block.GetName(1))
If Err.Number <> 0 Then
Call DxPdfLog("Could not read saved project or active Block: " & Err.Description)
Err.Clear
On Error GoTo 0
Exit Sub
End If
On Error GoTo 0
If Len(projectPath) = 0 Then Exit Sub
eventKey = LCase(projectPath) & Chr(9) & LCase(blockName)
eventTime = Timer
If eventKey = lastEventKey Then
If eventTime >= lastEventAt And eventTime - lastEventAt < 2 Then Exit Sub
End If
lastEventKey = eventKey
lastEventAt = eventTime
If busyPid > 0 And DxPdfProcessRunning(busyPid) Then
pendingProject = projectPath
pendingBlock = blockName
hasPending = True
Call DxPdfSetStatus("PDF export queued")
Exit Sub
End If
Call DxPdfLaunch(projectPath, blockName)
End Sub
Sub DxPdf_Shutdown()
running = False
End Sub
Sub DxPdfLaunch(projectPath, blockName)
Dim command, prefix
On Error Resume Next
If fso.FileExists(statusPath) Then fso.DeleteFile statusPath, True
prefix = DxPdfQuote(toolPath)
If launchMode = "module" Then prefix = prefix & " -m dx_productivity"
command = prefix & " pdf-export-event" & _
" --settings " & DxPdfQuote(configPath) & _
" --project " & DxPdfQuote(projectPath) & _
" --active-block " & DxPdfQuote(blockName) & _
" --status-file " & DxPdfQuote(statusPath)
shell.CurrentDirectory = workingRoot
busyPid = CLng(shell.Run(command, 0, False))
If Err.Number <> 0 Then
Call DxPdfLog("Could not start PDF export: " & Err.Description)
Err.Clear
busyPid = 0
Call DxPdfSetStatus("PDF auto-export could not start")
On Error GoTo 0
Exit Sub
End If
On Error GoTo 0
Call DxPdfSetStatus("PDF auto-export started")
End Sub
Sub DxPdfPublishStatus()
Dim resultText
resultText = "PDF auto-export finished; see local run records"
On Error Resume Next
If fso.FileExists(statusPath) Then
resultText = DxPdfReadUtf8(statusPath)
fso.DeleteFile statusPath, True
End If
If Err.Number <> 0 Then
Call DxPdfLog("Could not read export status: " & Err.Description)
Err.Clear
End If
On Error GoTo 0
If Len(resultText) > 240 Then resultText = Left(resultText, 237) & "..."
Call DxPdfSetStatus(Trim(resultText))
End Sub
Sub DxPdfSetStatus(value)
On Error Resume Next
app.StatusBarText = CStr(value)
If Err.Number <> 0 Then
Call DxPdfLog("Could not update DxDesigner status bar: " & Err.Description)
Err.Clear
End If
On Error GoTo 0
End Sub
Function DxPdfAutoEnabled()
Dim text, expression
DxPdfAutoEnabled = False
On Error Resume Next
text = DxPdfReadUtf8(configPath)
If Err.Number <> 0 Then
Err.Clear
On Error GoTo 0
Exit Function
End If
Set expression = CreateObject("VBScript.RegExp")
expression.Pattern = Chr(34) & "auto_export" & Chr(34) & "\s*:\s*true"
expression.IgnoreCase = True
expression.Global = False
DxPdfAutoEnabled = expression.Test(text)
On Error GoTo 0
End Function
Function DxPdfReadUtf8(path)
Dim stream
Set stream = CreateObject("ADODB.Stream")
stream.Type = 2
stream.Charset = "utf-8"
stream.Open
stream.LoadFromFile CStr(path)
DxPdfReadUtf8 = stream.ReadText
stream.Close
End Function
Function DxPdfProcessRunning(pid)
Dim matches, process, commandLine
DxPdfProcessRunning = False
On Error Resume Next
Set matches = wmi.ExecQuery("SELECT CommandLine FROM Win32_Process WHERE ProcessId=" & CLng(pid))
If Err.Number = 0 Then
For Each process In matches
commandLine = ""
If Not IsNull(process.CommandLine) Then commandLine = CStr(process.CommandLine)
If InStr(1, commandLine, "pdf-export-event", vbTextCompare) > 0 Then
DxPdfProcessRunning = True
End If
Next
End If
Err.Clear
On Error GoTo 0
End Function
Function DxPdfHostAvailable()
Dim projectPath
DxPdfHostAvailable = False
On Error Resume Next
projectPath = CStr(app.GetProjectData().GetProjectFilePath())
DxPdfHostAvailable = (Err.Number = 0)
Err.Clear
On Error GoTo 0
End Function
Function DxPdfAcquireLock()
Dim lockFile
DxPdfAcquireLock = False
On Error Resume Next
If fso.FileExists(lockPath) Then
If DateDiff("s", fso.GetFile(lockPath).DateLastModified, Now) < 15 Then
On Error GoTo 0
Exit Function
End If
fso.DeleteFile lockPath, True
End If
Set lockFile = fso.CreateTextFile(lockPath, False, True)
If Err.Number = 0 Then
lockFile.WriteLine CStr(Now)
lockFile.Close
DxPdfAcquireLock = True
End If
Err.Clear
On Error GoTo 0
End Function
Sub DxPdfTouchLock()
Dim lockFile
On Error Resume Next
If fso.FileExists(lockPath) Then
Set lockFile = fso.OpenTextFile(lockPath, ForWriting, False, TristateTrue)
lockFile.WriteLine CStr(Now)
lockFile.Close
End If
Err.Clear
On Error GoTo 0
End Sub
Sub DxPdfReleaseLock()
On Error Resume Next
If fso.FileExists(lockPath) Then fso.DeleteFile lockPath, True
Err.Clear
On Error GoTo 0
End Sub
Sub DxPdfLog(value)
Dim stream
On Error Resume Next
Set stream = fso.OpenTextFile(logPath, 8, True, TristateTrue)
stream.WriteLine CStr(Now) & " " & CStr(value)
stream.Close
Err.Clear
On Error GoTo 0
End Sub
Function DxPdfQuote(value)
Dim text, expression
text = CStr(value)
Set expression = CreateObject("VBScript.RegExp")
expression.Pattern = "\\+$"
expression.Global = False
text = expression.Replace(text, "$&$&")
DxPdfQuote = Chr(34) & Replace(text, Chr(34), Chr(92) & Chr(34)) & Chr(34)
End Function
+27 -6
View File
@@ -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)
+130 -15
View File
@@ -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
@@ -63,6 +65,7 @@ Function DxLaunchUi(runRoot, featureKey)
Exit Function
End If
Set DxLaunchUi = process
Call DxToolsAppendDiagnostic("ui.started", "pid=" & CStr(process.ProcessID) & " " & runRoot)
End Function
Function DxBridgeUiCommand(runRoot, featureKey)
@@ -83,17 +86,23 @@ Function DxBridgeMailboxLoop(process, runRoot, runId, snapshotId, _
Dim resultPath
Dim claimPath
Dim state
Dim lastSelection, pageContext, pageKeys
Set fso = CreateObject("Scripting.FileSystemObject")
resultPath = fso.BuildPath(runRoot, "result.tsv")
claimPath = fso.BuildPath(runRoot, "result.processing")
state = ""
lastSelection = ""
pageContext = ""
pageKeys = "[]"
Do While process.Status = 0
Call DxBridgeConsumeLocate(runRoot, objectMap)
Call DxBridgePumpRefresh(runRoot, runId, objectMap, originalMap, _
snapshotId)
Call DxBridgePumpBomExport(runRoot)
Call DxBridgeWriteProgress(runRoot, "waiting")
Call DxBridgePublishSelection(runRoot, runId, snapshotId, _
lastSelection, pageContext, pageKeys)
Call DxWriteProgress(runRoot, "waiting")
If fso.FileExists(resultPath) Then
If DxBridgeClaimFile(fso, resultPath, claimPath) Then
Call DxWriteProgress(runRoot, "processing")
@@ -113,6 +122,101 @@ Function DxBridgeMailboxLoop(process, runRoot, runId, snapshotId, _
DxBridgeMailboxLoop = state
End Function
Sub DxBridgePublishSelection(runRoot, runId, snapshotId, _
ByRef lastSelection, ByRef pageContext, ByRef pageKeys)
Dim designPath, blockName, sheetName, currentContext, selectedKeys
Dim text, numberJson, ready, newPageKeys
Dim hostViewHandleJson
On Error Resume Next
hostViewHandleJson = DxBridgeHostViewHandleJson()
designPath = DxBridgeDesignPath()
blockName = DxBridgeCurrentBlockName()
sheetName = DxBridgeCurrentSheetName()
ready = (designPath <> "" And blockName <> "" And sheetName <> "")
currentContext = designPath & vbTab & blockName & vbTab & sheetName & vbTab & snapshotId
If currentContext <> pageContext Then
newPageKeys = DxBridgeSelectionKeys(VD_ALL)
If Err.Number = 0 Then
pageKeys = newPageKeys
pageContext = currentContext
Else
ready = False
Err.Clear
End If
End If
selectedKeys = DxBridgeSelectionKeys(VD_SELECTED)
numberJson = DxBridgeCurrentSheetNumberJson()
If Err.Number <> 0 Then
ready = False
Err.Clear
End If
text = "{""state"":""unavailable"",""run_id"":""" & _
DxToolsJson(runId) & """,""snapshot_id"":""" & _
DxToolsJson(snapshotId) & """,""design_path"":""" & _
DxToolsJson(designPath) & """,""host_view_handle"":" & hostViewHandleJson & "}"
If ready Then
text = "{""state"":""ready"",""run_id"":""" & _
DxToolsJson(runId) & """,""snapshot_id"":""" & _
DxToolsJson(snapshotId) & """,""design_path"":""" & _
DxToolsJson(designPath) & """,""host_view_handle"":" & hostViewHandleJson & _
",""active_block_name"":""" & _
DxToolsJson(blockName) & """,""current_sheet_name"":""" & _
DxToolsJson(sheetName) & """,""current_sheet_number"":" & _
numberJson & ",""selected_keys"":" & selectedKeys & _
",""current_sheet_keys"":" & pageKeys & ",""selected_nets"":" & _
DxBridgeExportSelectedNets() & "}"
End If
If text <> lastSelection Then
Call DxToolsWriteUtf8Atomic(fsoBuildPath(runRoot, "selection.json"), text)
If Err.Number = 0 Then lastSelection = text
Err.Clear
End If
On Error GoTo 0
End Sub
Function DxBridgeSelectionKeys(queryMode)
Dim keys, component, key, values, index, text
Set keys = CreateObject("Scripting.Dictionary")
For Each component In ActiveView.Query(VDM_COMP, queryMode)
key = DxBridgeComponentIdentity(component)
If key <> "" And Not keys.Exists(key) Then keys.Add key, True
Next
text = ""
If keys.Count > 0 Then
values = keys.Keys
If keys.Count > 1 Then Call DxBridgeSortSelectionKeys(values, 0, UBound(values))
For index = 0 To UBound(values)
If text <> "" Then text = text & ","
text = text & """" & DxToolsJson(values(index)) & """"
Next
End If
DxBridgeSelectionKeys = "[" & text & "]"
End Function
Sub DxBridgeSortSelectionKeys(ByRef keys, first, last)
Dim leftIndex, rightIndex, pivot, temporary
leftIndex = first
rightIndex = last
pivot = keys((first + last) \ 2)
Do While leftIndex <= rightIndex
Do While keys(leftIndex) < pivot
leftIndex = leftIndex + 1
Loop
Do While keys(rightIndex) > pivot
rightIndex = rightIndex - 1
Loop
If leftIndex <= rightIndex Then
temporary = keys(leftIndex)
keys(leftIndex) = keys(rightIndex)
keys(rightIndex) = temporary
leftIndex = leftIndex + 1
rightIndex = rightIndex - 1
End If
Loop
If first < rightIndex Then Call DxBridgeSortSelectionKeys(keys, first, rightIndex)
If leftIndex < last Then Call DxBridgeSortSelectionKeys(keys, leftIndex, last)
End Sub
Function DxBridgeClaimFile(fso, sourcePath, claimPath)
DxBridgeClaimFile = False
If fso.FileExists(claimPath) Then
@@ -133,14 +237,17 @@ Sub DxBridgePumpRefresh(runRoot, runId, objectMap, originalMap, _
Dim fso
Dim refreshPath
Dim claimPath
Dim refreshedObjects
Set fso = CreateObject("Scripting.FileSystemObject")
refreshPath = fso.BuildPath(runRoot, "refresh.request")
If Not fso.FileExists(refreshPath) Then Exit Sub
claimPath = fso.BuildPath(runRoot, "refresh.processing")
If Not DxBridgeClaimFile(fso, refreshPath, claimPath) Then Exit Sub
Call DxWriteProgress(runRoot, "processing")
If DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _
Set refreshedObjects = CreateObject("Scripting.Dictionary")
If DxRefreshSnapshot(runRoot, runId, refreshedObjects, originalMap, _
snapshotId) Then
Set objectMap = refreshedObjects
Call DxWriteProgress(runRoot, "waiting")
End If
On Error Resume Next
@@ -177,7 +284,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
@@ -204,6 +311,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
@@ -215,13 +323,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
@@ -247,15 +364,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
+151 -21
View File
@@ -13,6 +13,7 @@ Function DxExportSnapshot(objectMap, originalMap, ByRef runRoot, _
"%LOCALAPPDATA%\DxProductivity\runs")
runRoot = fsoBuildPath(runsRoot, CStr(runId))
Call DxBridgeEnsureFolder(runRoot)
Call DxToolsAppendDiagnostic("snapshot.begin", runRoot)
DxExportSnapshot = DxRefreshSnapshot(runRoot, runId, objectMap, _
originalMap, snapshotId)
End Function
@@ -45,8 +46,15 @@ Function DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _
Dim netsText
Dim selectedNetsText
Dim snapshotSequence
Dim collectionKey
Dim activeBlockName
Dim currentSheetNumberJson
DxRefreshSnapshot = False
If Not DxBridgeHasActiveView() Then
Call DxBridgeExportFailed(DxBridgeNoActiveViewMessage())
Exit Function
End If
Set selectedKeys = CreateObject("Scripting.Dictionary")
On Error Resume Next
For Each selected In ActiveView.Query(VDM_COMP, VD_SELECTED)
@@ -67,15 +75,23 @@ Function DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _
Exit Function
End If
On Error GoTo 0
Call DxToolsAppendDiagnostic("snapshot.project", "project data available")
Set designs = projectData.GetiCDBDesigns()
designId = CStr(designs.GetItem(1))
topBlock = projectData.GetiCDBDesignRootBlock(designId)
Call DxToolsAppendDiagnostic("snapshot.design", "id=" & designId & " root=" & CStr(topBlock))
designPath = DxBridgeDesignPath()
activeBlockName = DxBridgeCurrentBlockName()
currentSheetNumberJson = DxBridgeCurrentSheetNumberJson()
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)
@@ -92,10 +108,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
@@ -141,15 +158,44 @@ Function DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _
" ""snapshot_id"": """ & DxToolsJson(snapshotId) & """," & vbCrLf & _
" ""design_id"": """ & DxToolsJson(designId) & """," & vbCrLf & _
" ""design_path"": """ & DxToolsJson(designPath) & """," & vbCrLf & _
" ""host_view_handle"": " & DxBridgeHostViewHandleJson() & "," & vbCrLf & _
" ""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 & _
" ]" & vbCrLf & "}" & vbCrLf
Call DxToolsWriteUtf8Atomic(fsoBuildPath(runRoot, "request.json"), _
requestText)
Call DxToolsAppendDiagnostic("snapshot.ready", runRoot & " components=" & CStr(componentCount))
DxRefreshSnapshot = True
End Function
Function DxBridgeHostViewHandleJson()
Dim handle
handle = 0
On Error Resume Next
handle = CLng(Application.ActiveViewHandle)
If Err.Number <> 0 Then handle = 0
Err.Clear
On Error GoTo 0
DxBridgeHostViewHandleJson = CStr(handle)
End Function
Function DxBridgeHasActiveView()
Dim view
DxBridgeHasActiveView = False
On Error Resume Next
Set view = ActiveView
If Err.Number = 0 And Not view Is Nothing Then
DxBridgeHasActiveView = True
End If
Err.Clear
On Error GoTo 0
End Function
Function DxBridgeExportAttributes(component)
Dim attribute
Dim text
@@ -204,12 +250,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()
@@ -219,7 +265,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
@@ -245,7 +291,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
@@ -282,6 +328,7 @@ Function DxBridgeNextSnapshotSequence(runRoot)
End Function
Sub DxBridgeExportFailed(message)
Call DxToolsAppendDiagnostic("snapshot.error", message)
MsgBox DxBridgeExportFailedPrefix() & vbCrLf & message, vbExclamation
End Sub
@@ -316,7 +363,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
@@ -357,47 +404,120 @@ 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
Function DxBridgeCurrentBlockName()
DxBridgeCurrentBlockName = ""
On Error Resume Next
DxBridgeCurrentBlockName = CStr(ActiveView.Block.GetName(SHORT_NAME))
Err.Clear
On Error GoTo 0
End Function
Function DxBridgeCurrentSheetNumberJson()
Dim number
number = DxBridgeCurrentSheetNumber()
If number > 0 Then
DxBridgeCurrentSheetNumberJson = CStr(number)
Else
DxBridgeCurrentSheetNumberJson = "null"
End If
End Function
Function DxBridgeCoordinate(component, readX)
Dim value
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
@@ -430,7 +550,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
@@ -441,15 +561,16 @@ 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
Function DxBridgeDesignPath()
DxBridgeDesignPath = ""
On Error Resume Next
DxBridgeDesignPath = CStr(Application.ProjectPath)
DxBridgeDesignPath = CStr(Application.GetProjectData().GetProjectFilePath())
Err.Clear
On Error GoTo 0
End Function
@@ -482,6 +603,15 @@ Function DxBridgeProjectUnavailableMessage()
ChrW(&H5DE5) & ChrW(&H7A0B)
End Function
Function DxBridgeNoActiveViewMessage()
DxBridgeNoActiveViewMessage = ChrW(&H8BF7) & ChrW(&H5148) & _
ChrW(&H6253) & ChrW(&H5F00) & ChrW(&H5DE5) & ChrW(&H7A0B) & _
ChrW(&H5E76) & ChrW(&H8FDB) & ChrW(&H5165) & ChrW(&H539F) & _
ChrW(&H7406) & ChrW(&H56FE) & ChrW(&H9875) & ChrW(&H540E) & _
ChrW(&H518D) & ChrW(&H4F7F) & ChrW(&H7528) & ChrW(&H5DE5) & _
ChrW(&H5177)
End Function
Function DxBridgeIdentityUnavailableMessage()
DxBridgeIdentityUnavailableMessage = ChrW(&H67D0) & ChrW(&H5668) & _
ChrW(&H4EF6) & ChrW(&H8EAB) & ChrW(&H4EFD) & ChrW(&H4E0D) & _
+26 -6
View File
@@ -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
+7
View File
@@ -1,15 +1,22 @@
# -*- mode: python ; coding: utf-8 -*-
from pathlib import Path
import sys
from PyInstaller.utils.hooks import collect_data_files, collect_submodules
ROOT = Path(SPEC).resolve().parent.parent
sys.path.insert(0, str(ROOT / "src"))
hiddenimports = (
collect_submodules("dx_productivity")
+ collect_submodules("qtawesome")
+ collect_submodules("cryptography")
+ collect_submodules("pypdf")
+ collect_submodules("fontTools")
+ ["pypdf", "win32job", "win32con", "win32process", "pywintypes",
"pythoncom", "win32com.client", "win32com.client.gencache",
"win32com.client.genpy", "win32com.client.makepy"]
)
datas = collect_data_files("qtawesome")
+9 -1
View File
@@ -34,7 +34,7 @@ if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $pythonExe -PathType Le
throw "Could not resolve the Python 3.12 executable."
}
& $pythonExe -c "import PyInstaller, PySide6, qtawesome"
& $pythonExe -c "import PyInstaller, PySide6, qtawesome, pypdf, win32job"
if ($LASTEXITCODE -ne 0) {
throw "Build dependencies are missing. Install the project build extras before running this script."
}
@@ -82,6 +82,8 @@ Copy-Item -LiteralPath $distRoot -Destination $releaseRoot -Recurse
Copy-Item -LiteralPath (Join-Path $repoRoot "integration\dxdesigner795\MenuAdd.vbs") -Destination (Join-Path $releaseRoot "MenuAdd.vbs")
Copy-Item -LiteralPath (Join-Path $repoRoot "integration\dxdesigner795\DesignBridge.vbs") -Destination (Join-Path $releaseRoot "DesignBridge.vbs")
Copy-Item -LiteralPath (Join-Path $repoRoot "integration\dxdesigner795\CompatibilityProbe.vbs") -Destination (Join-Path $releaseRoot "CompatibilityProbe.vbs")
Copy-Item -LiteralPath (Join-Path $repoRoot "integration\dxdesigner795\PdfSaveListener.vbs") -Destination (Join-Path $releaseRoot "PdfSaveListener.vbs")
Copy-Item -LiteralPath (Join-Path $repoRoot "integration\dxdesigner795\LoadMenu.vbs") -Destination (Join-Path $releaseRoot "LoadMenu.vbs")
$runtimeVbs = Join-Path $releaseRoot "_runtime\vbs"
New-Item -ItemType Directory -Path $runtimeVbs -Force | Out-Null
@@ -103,6 +105,9 @@ New-Item -ItemType Directory -Path $docsRoot -Force | Out-Null
$guideSource = Join-Path $repoRoot "docs\user\DxDesigner_7.9.5_自动位号工具使用说明_v0.5.docx"
$guideDestination = Join-Path $docsRoot "DxDesigner_7.9.5_自动位号工具使用说明.docx"
Copy-Item -LiteralPath $guideSource -Destination $guideDestination
$pdfGuideDestination = Join-Path $docsRoot "PDF导出.md"
Copy-Item -LiteralPath (Join-Path $repoRoot "docs\user\PDF_export.md") -Destination $pdfGuideDestination
Copy-Item -LiteralPath (Join-Path $repoRoot "docs\user\一叶知秋_重构版_更新说明.md") -Destination (Join-Path $docsRoot "更新说明.md")
$env:PYTHONPATH = Join-Path $repoRoot "src"
$productVersion = (& $pythonExe -c "import dx_productivity; print(dx_productivity.__version__)").Trim()
@@ -135,6 +140,8 @@ $expected = @(
(Join-Path $releaseRoot "MenuAdd.vbs"),
(Join-Path $releaseRoot "DesignBridge.vbs"),
(Join-Path $releaseRoot "CompatibilityProbe.vbs"),
(Join-Path $releaseRoot "PdfSaveListener.vbs"),
(Join-Path $releaseRoot "LoadMenu.vbs"),
(Join-Path $releaseRoot "_runtime\vbs\BridgeCommon.vbs"),
(Join-Path $releaseRoot "_runtime\vbs\Snapshot.vbs"),
(Join-Path $releaseRoot "_runtime\vbs\Transaction.vbs"),
@@ -143,6 +150,7 @@ $expected = @(
(Join-Path $releaseRoot "templates\BOM模板.xls"),
(Join-Path $releaseRoot "expedition\ExpeditionBridge.vbs"),
(Join-Path $docsRoot "DxDesigner_7.9.5_自动位号工具使用说明.docx"),
$pdfGuideDestination,
$versionFile,
$updateManifestFile
)
+3
View File
@@ -11,6 +11,9 @@ dependencies = [
"PySide6-Essentials>=6.7,<7",
"qtawesome>=1.3,<2",
"cryptography>=42,<46",
"pypdf>=5,<7",
"fonttools>=4.55,<5",
"pywin32>=306,<312; sys_platform == 'win32'",
]
[project.optional-dependencies]
+25
View File
@@ -8,6 +8,21 @@ from collections.abc import Sequence
def main(argv: Sequence[str] | None = None) -> int:
arguments = list(sys.argv[1:] if argv is None else argv)
if arguments and arguments[0] == "bridge-wait":
import argparse
import time
parser = argparse.ArgumentParser()
parser.add_argument("--milliseconds", type=int, default=150)
options = parser.parse_args(arguments[1:])
if not 0 <= options.milliseconds <= 1000:
parser.error("milliseconds must be between 0 and 1000")
time.sleep(options.milliseconds / 1000)
return 0
if arguments and arguments[0] in ("startup", "start"):
from dx_productivity.bridge.startup import main as startup_main
return startup_main(arguments[1:])
if arguments and arguments[0] == "probe":
from dx_productivity.bridge.probe_host import main as probe_main
@@ -34,6 +49,16 @@ def main(argv: Sequence[str] | None = None) -> int:
result = UpdateInstaller().install(plan)
return 0 if result.state == "installed" else 1
if arguments and arguments[0] == "pdf-export-event":
from dx_productivity.features.pdf_export.cli import main as pdf_export_main
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:]
+12
View File
@@ -49,6 +49,15 @@ def load_request(path: Path) -> DesignSnapshot:
nets = _parse_nets(data)
selected_nets = _parse_selected_nets(data)
active_block_name = data.get("active_block_name", "")
if not isinstance(active_block_name, str):
raise ProtocolError("active_block_name must be a string")
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,
@@ -59,6 +68,9 @@ def load_request(path: Path) -> DesignSnapshot:
components=components,
nets=nets,
selected_nets=selected_nets,
active_block_name=active_block_name,
current_sheet_number=current_sheet_number,
current_sheet_name=current_sheet_name,
)
+10 -8
View File
@@ -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 ""
+181
View File
@@ -0,0 +1,181 @@
"""Install the tool menu and start or reuse DxDesigner without UI automation."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import time
from dx_productivity.bridge.startup_assets import REQUIRED_FILES, StartupAssets, generate_startup_assets, write_atomic
class StartupError(RuntimeError):
pass
@dataclass(frozen=True)
class StartupConfiguration:
assets: StartupAssets
scripts_ini: Path
viewdraw: Path
launch_environment: dict[str, str]
def discover_viewdraw(environment: dict[str, str]) -> Path:
candidates = []
explicit = environment.get("VIEWDRAW_EXE")
if explicit:
candidates.append(Path(explicit.strip('"')))
sdd_home = environment.get("SDD_HOME")
if sdd_home:
candidates.append(Path(sdd_home) / "wv/win32/bin/viewdraw.exe")
on_path = shutil.which("viewdraw.exe", path=environment.get("PATH", ""))
if on_path:
candidates.append(Path(on_path))
for drive in "CDEFG":
root = Path(f"{drive}:/Mentor")
if root.is_dir():
candidates.extend(root.glob("7.9.5*/SDD_HOME/wv/win32/bin/viewdraw.exe"))
for candidate in candidates:
if candidate.is_file() and candidate.name.lower() == "viewdraw.exe":
return candidate.resolve()
raise StartupError("未找到 DxDesigner 7.9.5,请确认已安装该版本,或设置 VIEWDRAW_EXE 指定可执行文件。")
def _read_ini(path: Path) -> tuple[str, str]:
if not path.exists():
return "", "gbk"
data = path.read_bytes()
if data.startswith(b"\xef\xbb\xbf"):
return data.decode("utf-8-sig"), "utf-8-sig"
if data.startswith((b"\xff\xfe", b"\xfe\xff")):
return data.decode("utf-16"), "utf-16"
for encoding in ("gbk", "utf-8"):
try:
return data.decode(encoding), encoding
except UnicodeError:
continue
raise StartupError(f"无法读取启动配置编码:{path}")
def _register_menu(text: str, menu: Path) -> str:
lines = text.splitlines()
start = next((i for i, line in enumerate(lines) if line.strip().lower() == "[viewdraw]"), None)
if start is None:
lines += ["[ViewDraw]"]
start = len(lines) - 1
end = next((i for i in range(start + 1, len(lines)) if lines[i].strip().startswith("[")), len(lines))
entry = str(menu)
used = set()
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):
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"
def prepare_startup(tool_root: Path, viewdraw: Path, environment: dict[str, str]) -> StartupConfiguration:
tool_root = tool_root.resolve()
missing = [name for name in REQUIRED_FILES if not (tool_root / name).is_file()]
if missing:
raise StartupError("工具目录不完整,缺少:" + ", ".join(missing))
if not viewdraw.is_file():
raise StartupError(f"DxDesigner 可执行文件不存在:{viewdraw}")
profile = environment.get("LOCALAPPDATA", "")
if not profile:
raise StartupError("无法读取用户配置目录 LOCALAPPDATA")
startup_root = Path(profile) / "DxProductivity" / "startup-refactored"
# 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():
path = Path(os.path.expandvars(entry.strip().strip('"')))
if path.resolve() != startup_root.resolve():
wdir.append(path)
standard = viewdraw.resolve().parents[3] / "standard"
if standard not in wdir:
wdir.append(standard)
vendor_ini = next((path / "scripts.ini" for path in wdir if (path / "scripts.ini").is_file()), None)
text, encoding = _read_ini(vendor_ini) if vendor_ini else ("", "gbk")
catalog = next((path / "vllib.vmb" for path in wdir if (path / "vllib.vmb").is_file()), None)
if catalog is None:
raise StartupError("DxDesigner 安装不完整,未找到消息目录 vllib.vmb")
assets = generate_startup_assets(tool_root, startup_root)
ini = 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"
backups.mkdir(parents=True, exist_ok=True)
shutil.copy2(ini, backups / f"startup-scripts.{datetime.now():%Y%m%d-%H%M%S-%f}.bak")
if not ini.exists() or ini.read_bytes() != content:
write_atomic(ini, content)
child_environment = dict(environment)
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)}
write_atomic(startup_root / "startup.json", json.dumps(state, ensure_ascii=False, indent=2).encode("utf-8"))
return StartupConfiguration(assets, ini, viewdraw.resolve(), child_environment)
def start_dxdesigner(tool_root: Path, *, viewdraw: Path | None = None, environment: dict[str, str] | None = None, timeout: float = 20) -> str:
environment = dict(os.environ if environment is None else environment)
configuration = prepare_startup(tool_root, viewdraw or discover_viewdraw(environment), environment)
host = Path(environment.get("WINDIR", "C:/Windows")) / "SysWOW64/cscript.exe"
if not host.is_file():
host = host.parent.parent / "System32/cscript.exe"
command = [str(host), "//B", "//NoLogo", str(tool_root / "LoadMenu.vbs"), str(configuration.assets.menu_script)]
try:
loaded = subprocess.run(command, capture_output=True, timeout=timeout, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
except subprocess.TimeoutExpired as error:
raise StartupError("DxDesigner 正在等待对话框或忙于操作,请关闭报错对话框后再次点击 Start。") from error
reused = loaded.returncode == 0
if loaded.returncode == 3:
subprocess.Popen([str(configuration.viewdraw)], cwd=configuration.viewdraw.parent, env=configuration.launch_environment)
elif loaded.returncode != 0:
detail = (loaded.stdout + loaded.stderr).decode("mbcs", errors="replace").strip()
raise StartupError("无法让当前 DxDesigner 加载菜单:" + (detail or str(loaded.returncode)))
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
if configuration.assets.ready_file.read_text(encoding="utf-16").strip() == configuration.assets.token:
return "菜单已持久注册并加入当前 DxDesigner" if reused else "DxDesigner 已启动,工具菜单已持久注册"
except (OSError, UnicodeError):
pass
time.sleep(0.1)
raise StartupError("未收到 DxDesigner 的菜单加载回执,请查看宿主报错;启动配置已准备,可再次点击 Start。")
def main(argv=None) -> int:
import argparse
import sys
parser = argparse.ArgumentParser(description="Register the tool menu and start DxDesigner")
parser.add_argument("--tool-root", type=Path, default=Path(sys.executable).resolve().parent)
parser.add_argument("--viewdraw", type=Path)
options = parser.parse_args(argv)
try:
print(start_dxdesigner(options.tool_root, viewdraw=options.viewdraw))
except (StartupError, OSError, ValueError) as error:
print(str(error), file=sys.stderr)
return 1
return 0
+128 -18
View File
@@ -1,31 +1,141 @@
"""Describe startup menu actions included in a portable release."""
"""Generate self-contained scripts for the DxDesigner 7.9.5 Run host."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import re
import uuid
FEATURE_ACTIONS = {
"refdes": ("DxToolsOpenRefDes", "DxRefDesAction.vbs"),
"property-change": ("DxToolsOpenPropertyChange", "DxPropertyChangeAction.vbs"),
"property-visibility": ("DxToolsOpenPropertyVisibility", "DxPropertyVisibilityAction.vbs"),
"inspection": ("DxToolsOpenInspection", "DxInspectionAction.vbs"),
"bom": ("DxToolsOpenBom", "DxBomAction.vbs"),
"pdf-export": ("DxToolsOpenPdfExport", "DxPdfExportAction.vbs"),
"compatibility": ("DxToolsOpenCompatibility", "DxCompatibilityAction.vbs"),
"guide": ("DxToolsOpenGuide", "DxGuideAction.vbs"),
}
CORE_FILES = ("Snapshot.vbs", "Transaction.vbs", "Mailbox.vbs", "BomExport.vbs")
REQUIRED_FILES = (
"DxDesignerTools.exe", "MenuAdd.vbs", "DesignBridge.vbs",
"CompatibilityProbe.vbs", "LoadMenu.vbs", "_runtime/vbs/BridgeCommon.vbs",
*(f"_runtime/vbs/{name}" for name in CORE_FILES),
)
@dataclass(frozen=True, slots=True)
class StartupAssets:
tool_root: Path
action_scripts: dict[str, str]
menu_script: Path
action_scripts: dict[str, Path]
ready_file: Path
token: str
def generate_startup_assets(tool_root: Path) -> StartupAssets:
"""Return stable named actions for the startup-imported menu.
def generate_startup_assets(tool_root: Path, startup_root: Path) -> StartupAssets:
"""Bind the package location explicitly; host path metadata is unreliable."""
tool_root = tool_root.resolve()
startup_root = startup_root.resolve()
startup_root.mkdir(parents=True, exist_ok=True)
menu_script = startup_root / "MenuAdd.vbs"
ready_file = startup_root / "menu-ready.txt"
token = uuid.uuid4().hex
actions = {key: startup_root / value[1] for key, value in FEATURE_ACTIONS.items()}
menu = (tool_root / "MenuAdd.vbs").read_text(encoding="ascii")
assignment = "\n".join((
f"DxToolsHome = {vbscript_string(str(tool_root))}",
'DxToolsScriptPathSource = "Start generated configuration"',
f"DxToolsScriptFullName = {vbscript_string(str(menu_script))}",
))
root_entry = r"(?m)^DxToolsHome = DxToolsResolveRoot\(\)$"
if len(re.findall(root_entry, menu)) != 1:
raise ValueError("MenuAdd.vbs does not contain the expected startup entry")
menu = re.sub(root_entry, lambda _match: assignment, menu)
for key, (procedure, _) in FEATURE_ACTIONS.items():
old = f'button.OnAction = "{procedure}"'
if menu.count(old) != 1:
raise ValueError(f"MenuAdd.vbs is missing action: {key}")
command = 'run "' + str(actions[key]) + '"'
menu = menu.replace(old, f"button.OnAction = {vbscript_string(command)}")
menu = menu.replace(
" Call DxToolsInstallMenu()",
" Call DxToolsInstallMenu()\n Call DxToolsWriteMenuReady()", 1,
)
menu += "\n" + "\n".join((
"Sub DxToolsWriteMenuReady()", " Dim stream",
" Set stream = CreateObject(\"Scripting.FileSystemObject\").CreateTextFile( _",
f" {vbscript_string(str(ready_file))}, True, True)",
f" stream.WriteLine {vbscript_string(token)}", " stream.Close", "End Sub", "",
))
common = (tool_root / "_runtime/vbs/BridgeCommon.vbs").read_text(encoding="ascii")
design = "\n".join(
(tool_root / "_runtime/vbs" / name).read_text(encoding="ascii")
for name in CORE_FILES
) + "\n" + (tool_root / "DesignBridge.vbs").read_text(encoding="ascii")
for key, action_path in actions.items():
context = "\n".join((
"' Generated by the Start button. Do not edit.",
"' ViewDraw supplies its VDM/VD enums to Run actions. Do not redeclare them.",
"Dim DxToolsHome, DxToolsScriptPathSource, DxToolsScriptFullName",
f"DxToolsHome = {vbscript_string(str(tool_root))}",
'DxToolsScriptPathSource = "generated Run action"',
f"DxToolsScriptFullName = {vbscript_string(str(action_path))}",
))
if key == "compatibility":
content = context + "\n" + common + "\n" + (tool_root / "CompatibilityProbe.vbs").read_text(encoding="ascii")
entry = 'Call DxToolsProbeExecute("run")'
elif key == "guide":
guide = tool_root / "docs" / "DxDesigner_7.9.5_自动位号工具使用说明.docx"
content = context
entry = 'CreateObject("WScript.Shell").Run ' + vbscript_string('"' + str(guide) + '"') + ", 1, False"
else:
content = context + "\nDim DxToolsDesignBridgeCoreLoaded\nDxToolsDesignBridgeCoreLoaded = True\n" + common + "\n" + design
entry = "\n".join((
f'Call DxToolsAppendDiagnostic("menu.click", "{key} root=" & DxToolsHome)',
"Dim DxToolsActionError",
"On Error Resume Next",
f'Call DxToolsRunDesignBridge("{key}")',
'DxToolsActionError = ""',
"If Err.Number <> 0 Then DxToolsActionError = CStr(Err.Number) & \": \" & Err.Description",
"Err.Clear",
"On Error GoTo 0",
'If DxToolsActionError <> "" Then',
' Call DxToolsAppendDiagnostic("bridge.error", DxToolsActionError)',
' MsgBox DxToolsActionError, vbExclamation, "Dx tools bridge"',
"End If",
))
write_atomic(action_path, (content + "\n' DXTOOLS_ENTRY\n" + entry + "\n").encode("ascii"))
write_atomic(menu_script, menu.replace("\r\n", "\n").replace("\n", "\r\n").encode("ascii"))
return StartupAssets(menu_script, actions, ready_file, token)
The values are action routes, not filesystem paths. This deliberately keeps
the menu relocatable and prevents feature actions from entering RefDes state.
"""
actions = {
"refdes": "DxToolsOpenRefDes",
"property-change": "DxToolsOpenPropertyChange",
"property-visibility": "DxToolsOpenPropertyVisibility",
"inspection": "DxToolsOpenInspection",
"bom": "DxToolsOpenBom",
"compatibility": "DxToolsOpenCompatibility",
"guide": "DxToolsOpenGuide",
}
return StartupAssets(tool_root=Path(tool_root), action_scripts=actions)
def vbscript_string(value: str) -> str:
"""Represent Unicode paths in ASCII VBS, including UTF-16 surrogate pairs."""
parts = []
buffer = []
def flush():
if buffer:
parts.append('"' + "".join(buffer).replace('"', '""') + '"')
buffer.clear()
for char in value:
if ord(char) < 128:
buffer.append(char)
else:
flush()
encoded = char.encode("utf-16-le")
for index in range(0, len(encoded), 2):
parts.append(f"ChrW(&H{int.from_bytes(encoded[index:index + 2], 'little'):04X})")
flush()
return " & ".join(parts) if parts else '""'
def write_atomic(path: Path, data: bytes) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
try:
temporary.write_bytes(data)
temporary.replace(path)
finally:
temporary.unlink(missing_ok=True)
+3
View File
@@ -194,6 +194,9 @@ class DesignSnapshot:
components: tuple[ComponentRecord, ...]
nets: tuple[NetRecord, ...] = ()
selected_nets: tuple[str, ...] = ()
active_block_name: str = ""
current_sheet_number: int | None = None
current_sheet_name: str = ""
@property
def component_count(self) -> int:
+68 -28
View File
@@ -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()}"
+2 -2
View File
@@ -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,
+4 -1
View File
@@ -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,
)
@@ -0,0 +1 @@
"""Single-project PDF export for DxDesigner."""
@@ -0,0 +1,43 @@
from __future__ import annotations
import argparse
import os
from pathlib import Path
import threading
import uuid
from .exporter import export_project
from .settings import load_settings, normalized_project_path
def _write_status(path: Path, value: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex[:8]}.tmp")
try:
temporary.write_text(value.strip() + "\n", encoding="utf-8")
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="DxDesignerTools pdf-export-event")
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)
if not settings.auto_export or normalized_project_path(settings.project_path) != normalized_project_path(options.project):
_write_status(options.status_file, "自动导出已忽略:设置未启用或当前工程不同")
return 0
result = export_project(
settings,
threading.Event(),
active_block_name=options.active_block,
active_sheet_name=options.active_sheet,
overwrite=True,
)
_write_status(options.status_file, result.message)
return 0 if result.state == "success" else 1
@@ -0,0 +1,133 @@
"""Embed subsets of installed Windows fonts with explicit Unicode mappings."""
from __future__ import annotations
from dataclasses import dataclass
from io import BytesIO
import os
from pathlib import Path
from pypdf.generic import ArrayObject, DecodedStreamObject, DictionaryObject, NameObject, NumberObject, FloatObject, TextStringObject
@dataclass
class UnicodeFont:
name: str
reference: object
cids: dict[int, int]
widths: dict[int, int]
def encode(self, text: str) -> bytes:
return b''.join(self.cids[ord(char)].to_bytes(2, 'big') for char in text)
def advance(self, text: str, size: float) -> float:
return sum(self.widths[ord(char)] for char in text) * size / 1000
def _load(filename: str):
from fontTools.ttLib import TTFont
path = Path(os.environ.get('WINDIR', 'C:/Windows')) / 'Fonts' / filename
if not path.is_file():
raise ValueError(f'本机缺少 {filename},无法生成可阅读的 PDF 文字')
return TTFont(path, fontNumber=0, recalcTimestamp=False)
def _subset(writer, font, characters: set[str], name: str) -> UnicodeFont:
from fontTools import subset
points = sorted(ord(char) for char in characters)
missing = set(points) - (font.getBestCmap() or {}).keys()
if missing:
raise ValueError('字体缺少字符:' + ', '.join(f'U+{cp:04X}' for cp in sorted(missing)[:12]))
if len(points) > 65534:
raise ValueError('PDF 文字字符集超出单个字体子集容量')
if getattr(font.get('OS/2'), 'fsType', 0) & (0x0002 | 0x0100 | 0x0200):
raise ValueError('本机字体的嵌入限制不支持 PDF 字体子集')
options = subset.Options()
options.recalc_timestamp = False
options.layout_features = []
options.drop_tables.extend(['meta', 'MERG'])
worker = subset.Subsetter(options=options)
worker.populate(unicodes=points)
worker.subset(font)
buffer = BytesIO()
font.flavor = None
font.save(buffer)
units = font['head'].unitsPerEm
cmap = font.getBestCmap()
cids = {cp: index for index, cp in enumerate(points, 1)}
widths = {cp: round(font['hmtx'][cmap[cp]][0] * 1000 / units) for cp in points}
def stream(data: bytes):
obj = DecodedStreamObject()
obj.set_data(data)
return writer._add_object(obj.flate_encode())
payload = buffer.getvalue()
file = DecodedStreamObject()
file.set_data(payload)
file[NameObject('/Length1')] = NumberObject(len(payload))
base_name = '/YYZQAA+' + name
metric = lambda number: NumberObject(round(number * 1000 / units))
head, hhea, os2 = font['head'], font['hhea'], font.get('OS/2')
descriptor = DictionaryObject({
NameObject('/Type'): NameObject('/FontDescriptor'), NameObject('/FontName'): NameObject(base_name),
NameObject('/Flags'): NumberObject(32),
NameObject('/FontBBox'): ArrayObject([metric(number) for number in (head.xMin, head.yMin, head.xMax, head.yMax)]),
NameObject('/ItalicAngle'): FloatObject(font['post'].italicAngle),
NameObject('/Ascent'): metric(hhea.ascent), NameObject('/Descent'): metric(hhea.descent),
NameObject('/CapHeight'): metric(getattr(os2, 'sCapHeight', hhea.ascent)),
NameObject('/StemV'): NumberObject(80), NameObject('/FontFile2'): writer._add_object(file.flate_encode()),
})
# Each Unicode character receives its own CID, even when two characters
# share a glyph outline. This preserves symbols in extracted/search text.
gid_map = b'\x00\x00' + b''.join(font.getGlyphID(cmap[cp]).to_bytes(2, 'big') for cp in points)
descendant = DictionaryObject({
NameObject('/Type'): NameObject('/Font'), NameObject('/Subtype'): NameObject('/CIDFontType2'),
NameObject('/BaseFont'): NameObject(base_name),
NameObject('/CIDSystemInfo'): DictionaryObject({NameObject('/Registry'): TextStringObject('Adobe'),
NameObject('/Ordering'): TextStringObject('Identity'), NameObject('/Supplement'): NumberObject(0)}),
NameObject('/FontDescriptor'): writer._add_object(descriptor), NameObject('/CIDToGIDMap'): stream(gid_map),
NameObject('/DW'): NumberObject(1000),
NameObject('/W'): ArrayObject([NumberObject(1), ArrayObject([NumberObject(widths[cp]) for cp in points])]),
})
rows = ['/CIDInit /ProcSet findresource begin', '12 dict begin', 'begincmap',
'/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def',
'/CMapName /YiyeUnicode def', '/CMapType 2 def', '1 begincodespacerange', '<0000> <FFFF>', 'endcodespacerange']
for offset in range(0, len(points), 100):
chunk = points[offset:offset + 100]
rows.append(f'{len(chunk)} beginbfchar')
rows.extend(f'<{cids[cp]:04X}> <{chr(cp).encode("utf-16-be").hex().upper()}>' for cp in chunk)
rows.append('endbfchar')
rows.extend(['endcmap', 'CMapName currentdict /CMap defineresource pop', 'end', 'end'])
resource = DictionaryObject({
NameObject('/Type'): NameObject('/Font'), NameObject('/Subtype'): NameObject('/Type0'),
NameObject('/BaseFont'): NameObject(base_name), NameObject('/Encoding'): NameObject('/Identity-H'),
NameObject('/DescendantFonts'): ArrayObject([writer._add_object(descendant)]),
NameObject('/ToUnicode'): stream('\n'.join(rows).encode('ascii')),
})
return UnicodeFont('/Yiye' + name, writer._add_object(resource), cids, widths)
def build_fonts(writer, texts: list[str]) -> dict[str, UnicodeFont]:
primary = _load('arial.ttf')
fallback = None
try:
cmap = primary.getBestCmap() or {}
groups = {False: set(), True: set()}
assignments = {}
for text in texts:
needs_cjk = any(ord(char) not in cmap for char in text)
assignments[text] = needs_cjk
groups[needs_cjk].update(text)
fonts = {}
if groups[False]:
fonts[False] = _subset(writer, primary, groups[False], 'Arial')
if groups[True]:
fallback = _load('simsun.ttc')
fonts[True] = _subset(writer, fallback, groups[True], 'SimSun')
return {text: fonts[needs_cjk] for text, needs_cjk in assignments.items()}
finally:
primary.close()
if fallback is not None:
fallback.close()
@@ -0,0 +1,246 @@
from __future__ import annotations
import os
import subprocess
import time
from pathlib import Path
from threading import Event
from typing import Callable, Sequence
def discover_engine(explicit: Path | None = None) -> Path:
candidates = [Path(explicit)] if explicit else []
if not explicit and os.environ.get("SDD_HOME"):
candidates.append(Path(os.environ["SDD_HOME"]) / "wv/win32/bin/sch2pdf.exe")
if not explicit:
for drive in "CDEFG":
for vendor in ("Mentor", "MentorGraphics"):
parent = Path(f"{drive}:/") / vendor
if not parent.is_dir():
continue
for version in sorted(parent.iterdir(), reverse=True):
candidates.append(version / "SDD_HOME/wv/win32/bin/sch2pdf.exe")
for candidate in candidates:
if candidate.is_file() and candidate.name.casefold() == "sch2pdf.exe":
return candidate.resolve()
raise FileNotFoundError(
"未找到 sch2pdf.exe,请选择本机 DxDesigner EE 安装中的原生导出引擎"
)
class _WindowsProcess:
def __init__(self, args: Sequence[str], handle: int, pid: int) -> None:
self.args = list(args)
self.handle = handle
self.pid = pid
self.returncode: int | None = None
def poll(self) -> int | None:
import _winapi
if self.returncode is None and _winapi.WaitForSingleObject(self.handle, 0) == _winapi.WAIT_OBJECT_0:
self.returncode = _winapi.GetExitCodeProcess(self.handle)
return self.returncode
def wait(self, timeout: float) -> int:
import _winapi
if _winapi.WaitForSingleObject(self.handle, max(0, int(timeout * 1000))) == _winapi.WAIT_TIMEOUT:
raise subprocess.TimeoutExpired(self.args, timeout)
self.returncode = _winapi.GetExitCodeProcess(self.handle)
return self.returncode
def kill(self) -> None:
import _winapi
try:
_winapi.TerminateProcess(self.handle, 1)
except OSError as error:
if error.winerror != 5 or _winapi.WaitForSingleObject(self.handle, 10000) != _winapi.WAIT_OBJECT_0:
raise
def close(self) -> None:
import _winapi
if self.handle is not None:
_winapi.CloseHandle(self.handle)
self.handle = None
def _create_job(process: _WindowsProcess):
import win32job
job = win32job.CreateJobObject(None, "")
try:
info = win32job.QueryInformationJobObject(
job, win32job.JobObjectExtendedLimitInformation
)
info["BasicLimitInformation"]["LimitFlags"] |= (
win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
)
win32job.SetInformationJobObject(
job, win32job.JobObjectExtendedLimitInformation, info
)
win32job.AssignProcessToJobObject(job, process.handle)
except BaseException:
job.Close()
raise
return job
def _start_windows_process(
args: Sequence[str], cwd: Path, stdout, stderr, cancel: Event, env: dict[str, str] | None = None
):
import _winapi
import msvcrt
import win32con
import win32process
process = None
job = None
thread_handle = None
inherited = []
with open(os.devnull, "rb") as stdin:
try:
current = _winapi.GetCurrentProcess()
for stream in (stdin, stdout, stderr):
inherited.append(
_winapi.DuplicateHandle(
current,
msvcrt.get_osfhandle(stream.fileno()),
current,
0,
True,
_winapi.DUPLICATE_SAME_ACCESS,
)
)
startup = subprocess.STARTUPINFO()
startup.dwFlags = subprocess.STARTF_USESTDHANDLES
startup.hStdInput, startup.hStdOutput, startup.hStdError = inherited
startup.lpAttributeList = {"handle_list": inherited}
handle, thread_handle, pid, _ = _winapi.CreateProcess(
None,
subprocess.list2cmdline([os.fspath(arg) for arg in args]),
None,
None,
True,
win32con.CREATE_SUSPENDED | subprocess.CREATE_NO_WINDOW,
env,
os.fspath(cwd),
startup,
)
process = _WindowsProcess(args, handle, pid)
job = _create_job(process)
if cancel.is_set():
raise InterruptedError("导出已取消")
win32process.ResumeThread(thread_handle)
return process, job
except BaseException:
try:
if job is not None:
job.Close()
finally:
if process is not None:
try:
if process.poll() is None:
process.kill()
process.wait(10)
finally:
process.close()
raise
finally:
if thread_handle is not None:
_winapi.CloseHandle(thread_handle)
for handle in inherited:
_winapi.CloseHandle(handle)
def _preserve_completed_job_children(job) -> None:
import win32job
info = win32job.QueryInformationJobObject(
job, win32job.JobObjectExtendedLimitInformation
)
info["BasicLimitInformation"]["LimitFlags"] &= (
~win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
)
win32job.SetInformationJobObject(
job, win32job.JobObjectExtendedLimitInformation, info
)
def run_engine(
args: Sequence[str],
cwd: Path,
log_dir: Path,
cancel: Event,
timeout: float,
on_event: Callable[[str], None] | None = None,
*,
env: dict[str, str] | None = None,
) -> int:
log_dir = Path(log_dir)
log_dir.mkdir(parents=True, exist_ok=True)
emit = on_event or (lambda _message: None)
started = time.monotonic()
process = None
job = None
with (log_dir / "stdout.log").open("wb") as stdout, (log_dir / "stderr.log").open("wb") as stderr:
try:
if os.name == "nt":
process, job = _start_windows_process(args, Path(cwd), stdout, stderr, cancel, env)
else:
process = subprocess.Popen(
args,
cwd=cwd,
stdin=subprocess.DEVNULL,
stdout=stdout,
stderr=stderr,
env=env,
)
emit(f"原生引擎已启动,PID={process.pid}")
last_heartbeat = started
while process.poll() is None:
if cancel.is_set():
raise InterruptedError("导出已取消")
now = time.monotonic()
if now - started > timeout:
raise TimeoutError(f"原生导出超过 {timeout:g} 秒")
if now - last_heartbeat >= 10:
emit(f"等待原生引擎,已用时 {now - started:.0f} 秒")
last_heartbeat = now
time.sleep(0.05)
if job is not None and process.returncode == 0:
import win32job
_preserve_completed_job_children(job)
announced = False
while win32job.QueryInformationJobObject(
job, win32job.JobObjectBasicAccountingInformation
)["ActiveProcesses"]:
if not announced:
emit("原生出图完成,等待后台数据库服务完成写回")
announced = True
if cancel.is_set():
raise InterruptedError("导出已取消;后台数据库服务继续完成写回")
if time.monotonic() - started > timeout:
raise TimeoutError("后台数据库服务未在限时内完成写回,未发布 PDF")
time.sleep(0.05)
if cancel.is_set():
raise InterruptedError("导出已取消")
return int(process.returncode)
finally:
try:
if job is not None:
if process is not None and process.poll() is not None:
_preserve_completed_job_children(job)
job.Close()
finally:
if process is not None:
try:
if process.poll() is None:
process.kill()
process.wait(timeout=10) if os.name != "nt" else process.wait(10)
finally:
if os.name == "nt":
process.close()
@@ -0,0 +1,563 @@
from __future__ import annotations
from datetime import datetime
import hashlib
import json
import os
from pathlib import Path, PureWindowsPath
import re
import stat
import threading
import time
import uuid
from contextlib import suppress
from typing import Callable
from pypdf import PdfReader, PdfWriter
from .engine import discover_engine, run_engine
from .models import ExportScope, PdfExportResult, PdfExportSettings
from .native_profile import prepare_environment
from .text_repair import repair_text
HEADER_LIMIT = 512 * 1024
PRUNED_DIRS = frozenset(
{"pcb", "projectbackup", "backup", "backups", ".git", ".venv", "__pycache__", "output", "runs", "artifacts", "dist", "build", "log files"}
)
FRONT_END = re.compile(rb'^\s*KEY\s+FrontEndSnapshot\s+"DxD"\s*$', re.I | re.M)
DATABASE = re.compile(rb'^\s*KEY\s+iCDBDir\s+"([^"]+)"\s*$', re.I | re.M)
_WRITE_LOCK = threading.Lock()
def _is_link(path: Path) -> bool:
details = path.lstat()
return stat.S_ISLNK(details.st_mode) or bool(
getattr(details, "st_file_attributes", 0)
& getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
)
def validate_project(project: Path) -> tuple[Path, Path]:
project = Path(project).absolute()
if project.suffix.casefold() != ".prj" or not project.is_file() or _is_link(project):
raise ValueError("当前文件不是有效的 DxDesigner .prj 工程")
project = project.resolve()
source_root = project.parent
if _is_link(source_root):
raise ValueError("工程目录是链接或重解析点,无法安全核验")
with project.open("rb") as stream:
header = stream.read(HEADER_LIMIT)
if not FRONT_END.search(header):
raise ValueError("工程文件不是 DxDesigner 原理图工程")
match = DATABASE.search(header)
if not match:
raise ValueError("工程文件缺少 iCDBDir 数据库路径")
raw = match.group(1)
database_text = ""
for encoding in ("utf-8-sig", "gb18030", "cp1252"):
try:
database_text = raw.decode(encoding)
break
except UnicodeDecodeError:
continue
if not database_text:
raise ValueError("无法解码工程数据库路径")
relative = PureWindowsPath(database_text)
if relative.is_absolute() or relative.drive or relative.root or ".." in relative.parts:
raise ValueError("工程数据库路径必须位于工程目录内")
database = source_root.joinpath(*relative.parts)
current = source_root
for part in relative.parts:
current = current / part
if current.exists() and _is_link(current):
raise ValueError("工程数据库路径含链接或重解析点")
if not database.is_dir():
raise ValueError("工程数据库目录不存在,或是链接")
resolved_database = database.resolve()
if not resolved_database.is_relative_to(source_root):
raise ValueError("工程数据库目录解析到了工程目录之外")
return project, resolved_database
def _source_files(root: Path):
def walk(directory: Path):
for path in sorted(directory.iterdir(), key=lambda item: item.name.casefold()):
if path.is_dir() and path.name.casefold() in PRUNED_DIRS:
continue
if _is_link(path):
raise ValueError(f"工程含链接或重解析点,无法安全核验:{path}")
if path.is_dir():
yield from walk(path)
elif path.is_file():
yield path
yield from walk(root)
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()
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
def _changes(before: dict[str, str], after: dict[str, str]) -> dict[str, list[str]]:
old, new = set(before), set(after)
return {
"modified": sorted(name for name in old & new if before[name] != after[name]),
"added": sorted(new - old),
"removed": sorted(old - new),
}
def _classify_changes(
changes: dict[str, list[str]], database_relative: str
) -> tuple[dict[str, list[str]], dict[str, list[str]]]:
accepted = {kind: [] for kind in changes}
blocked = {kind: [] for kind in changes}
prefix = tuple(part.casefold() for part in database_relative.strip("/").split("/") if part)
runtime_dirs = {"events", "log", "plog", "dbcheck", "dbupgrade"}
for kind, names in changes.items():
for name in names:
parts = tuple(name.split("/"))
folded = tuple(part.casefold() for part in parts)
relative = folded[len(prefix):] if folded[: len(prefix)] == prefix else ()
native = False
if relative == ("icdb.dat",):
native = kind == "modified"
elif relative in {("cdbsvr", "saddress.adr"), ("cdbsvr", "backup.lck")}:
native = True
elif len(relative) > 2 and relative[0] == "cdbsvr" and relative[1] in runtime_dirs:
native = True
elif len(relative) == 2 and relative[0] == "cdbback" and relative[1].endswith(".zip"):
native = kind == "added"
(accepted if native else blocked)[kind].append(name)
return accepted, blocked
def _validate_pdf(path: Path) -> tuple[int, int, str]:
if not path.is_file():
raise ValueError("原生引擎未生成 PDF")
try:
with path.open("rb") as stream:
if stream.read(5) != b"%PDF-":
raise ValueError("输出不是有效 PDF")
stream.seek(0)
reader = PdfReader(stream, strict=True)
if reader.is_encrypted:
raise ValueError("输出 PDF 已加密,无法验证")
pages = len(reader.pages)
if pages < 1:
raise ValueError("PDF 页数为零")
for page in reader.pages:
contents = page.get_contents()
if contents is not None:
contents.get_data()
except ValueError:
raise
except Exception as error:
raise ValueError(f"PDF 结构验证失败:{error}") from error
digest = hashlib.sha256()
with path.open("rb") as stream:
while chunk := stream.read(1024 * 1024):
digest.update(chunk)
return pages, path.stat().st_size, digest.hexdigest()
def _write_json(path: Path, payload: object) -> None:
temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex[:8]}.tmp")
try:
with temporary.open("x", encoding="utf-8", newline="\n") as stream:
json.dump(payload, stream, ensure_ascii=False, indent=2)
stream.write("\n")
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
def _safe_name(value: str) -> str:
cleaned = re.sub(r'[<>:"/\\|?*\x00-\x1f]+', "_", value).strip(" .")
return cleaned[:80] or "block"
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:
suffix = "whole-project"
elif settings.scope is ExportScope.CURRENT_PAGE:
name = active_block_name.strip()
if not name:
raise ValueError("无法读取当前活动页的 Block 名称,请刷新设计快照")
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:
raise ValueError("请输入原理图或 Block 名称")
digest = hashlib.sha256(name.casefold().encode("utf-8")).hexdigest()[:6]
suffix = f"block-{_safe_name(name)}-{digest}"
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,
output: Path,
scope: ExportScope,
block_name: str = "",
*,
text_mode: str = "chinese",
) -> list[str]:
command = [
str(engine),
"-project",
str(project),
"-a",
str(output),
"-c",
"4",
"-p",
"-e",
"-i2s",
]
if text_mode == "original":
command.append("-udx")
if scope is not ExportScope.PROJECT:
if not block_name.strip() or any(char in block_name for char in "\r\n\x00"):
raise ValueError("当前页或指定范围缺少有效 Block 名称")
command.extend(("-schematic", block_name.strip()))
return command
def _validate_output_location(project_root: Path, output_dir: Path) -> Path:
output = Path(output_dir).expanduser().resolve(strict=False)
if output == project_root or output.is_relative_to(project_root):
raise ValueError("PDF 输出目录必须位于源工程目录之外")
return output
def export_project(
settings: PdfExportSettings,
cancel: threading.Event,
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,
) -> PdfExportResult:
began = time.monotonic()
emit_external = on_event or (lambda _message: None)
run_root = Path(
local_app_data or os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local")
) / "DxProductivity" / "pdf-runs"
state_root = run_root.parent
run_dir = run_root / (datetime.now().strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8])
stage: Path | None = None
final_path: Path | None = None
pages = 0
state, message = "failed", ""
warnings: list[str] = []
lock_acquired = False
file_lock = None
file_lock_acquired = False
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:
emit_external(value)
except Exception:
pass
try:
with (run_dir / "events.log").open("a", encoding="utf-8") as stream:
stream.write(datetime.now().isoformat(timespec="seconds") + " " + value + "\n")
except OSError:
pass
try:
if not _WRITE_LOCK.acquire(blocking=False):
return PdfExportResult(Path(settings.project_path), "failed", "已有 PDF 导出正在执行")
lock_acquired = True
state_root.mkdir(parents=True, exist_ok=True)
file_lock = (state_root / "pdf-export.lock").open("a+b")
file_lock.seek(0, os.SEEK_END)
if file_lock.tell() == 0:
file_lock.write(b"0")
file_lock.flush()
file_lock.seek(0)
if os.name == "nt":
import msvcrt
try:
msvcrt.locking(file_lock.fileno(), msvcrt.LK_NBLCK, 1)
except OSError:
return PdfExportResult(Path(settings.project_path), "failed", "已有 PDF 导出正在执行")
else:
import fcntl
try:
fcntl.flock(file_lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
return PdfExportResult(Path(settings.project_path), "failed", "已有 PDF 导出正在执行")
file_lock_acquired = True
run_dir.mkdir(parents=True, exist_ok=False)
project, database = validate_project(Path(settings.project_path))
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, active_sheet_name)
final_path = output_dir / final_path.name
if final_path.exists() and not overwrite:
state, message = "exists", f"已有同名 PDF:{final_path}"
return PdfExportResult(project, state, message, final_path, run_dir=run_dir)
engine = discover_engine(settings.engine_path)
block_name = (
active_block_name.strip()
if settings.scope is ExportScope.CURRENT_PAGE
else settings.block_name.strip()
)
stage = output_dir / f".{final_path.stem}.{uuid.uuid4().hex[:8]}.partial.pdf"
command = build_command(engine, project, stage, settings.scope, block_name, text_mode=settings.text_mode)
environment = prepare_environment(run_dir, settings.print_theme)
_write_json(
run_dir / "request.json",
{
"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),
"print_theme": settings.print_theme,
"text_mode": settings.text_mode,
"native_profile": str(run_dir / "native-profile" / "DxDesigner.xml")
if environment is not None else "",
"command": command,
},
)
output_dir.mkdir(parents=True, exist_ok=True)
emit("核验当前工程和输出目录")
before = _fingerprint(source_root, cancel, database_relative, unverified_native)
_write_json(run_dir / "source-before.json", before)
palette = "工程参考配色" if settings.print_theme == "reference" else "原生配色"
emit(f"直接调用本机 sch2pdf.exe;使用{palette}")
return_code = run_engine(command, source_root, run_dir, cancel, timeout, emit, env=environment)
if return_code != 0:
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)
emit("核验并嵌入 PDF 文字字体")
text_check = repair_text(stage, settings.text_mode, cancel)
_write_json(run_dir / "text-check.json", text_check)
pages, size, sha256 = _validate_pdf(stage)
_write_json(
run_dir / "pdf-check.json",
{"pages": pages, "size": size, "sha256": sha256},
)
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, "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("原生数据库或运行记录发生变化;这不代表源工程只读")
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:
os.replace(stage, final_path)
elif os.name == "nt":
os.rename(stage, final_path)
else:
os.link(stage, final_path)
stage.unlink()
stage = None
state = "success"
message = f"PDF 已导出,共 {pages} 页:{final_path}"
if warnings:
message += "。" + "。".join(warnings)
except InterruptedError as error:
state, message = "cancelled", str(error)
except TimeoutError as error:
state, message = "timeout", str(error)
except Exception as error:
state, message = "failed", str(error)
finally:
if (
before is not None
and source_root is not None
and database_relative is not None
and run_dir.exists()
and state not in {"success", "uncertain"}
):
try:
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, "unverified_native_files": sorted(unverified_native)})
if any(blocked.values()):
state = "uncertain"
message += ";失败期间源工程也发生变化,请核对 source-assessment.json"
except Exception as error:
state = "uncertain"
message += f";无法完成失败路径的源工程检查:{error}"
if stage is not None:
try:
stage.unlink(missing_ok=True)
except OSError:
message += ";临时 PDF 清理失败,请检查运行记录"
if run_dir.exists():
try:
_write_json(
run_dir / "result.json",
{
"state": state,
"message": message,
"output": str(final_path) if final_path else "",
"pages": pages,
"duration_seconds": round(time.monotonic() - began, 3),
},
)
except Exception as error:
message += f";运行结果记录失败:{error}"
if file_lock_acquired and file_lock is not None:
with suppress(OSError):
file_lock.seek(0)
if os.name == "nt":
import msvcrt
msvcrt.locking(file_lock.fileno(), msvcrt.LK_UNLCK, 1)
else:
import fcntl
fcntl.flock(file_lock.fileno(), fcntl.LOCK_UN)
if file_lock is not None:
file_lock.close()
if lock_acquired:
_WRITE_LOCK.release()
return PdfExportResult(
Path(settings.project_path), state, message, final_path, pages, run_dir
)
@@ -0,0 +1,39 @@
from __future__ import annotations
import os
import subprocess
import sys
from pathlib import Path
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):
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,
close_fds=True,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
except OSError as error:
return f"无法启动保存事件监听:{error}"
return None
@@ -0,0 +1,44 @@
from __future__ import annotations
from dataclasses import dataclass
from enum import StrEnum
from pathlib import Path
class ExportScope(StrEnum):
PROJECT = "project"
CURRENT_PAGE = "current-page"
BLOCK = "block"
@dataclass(frozen=True, slots=True)
class PdfExportSettings:
project_path: Path
scope: ExportScope
block_name: str
output_dir: Path
auto_export: bool = False
engine_path: Path | None = None
print_theme: str = "reference"
text_mode: str = "chinese"
def __post_init__(self) -> None:
if self.print_theme not in {"reference", "original"}:
raise ValueError("不支持的 PDF 配色")
if self.text_mode not in {"chinese", "western", "original"}:
raise ValueError("不支持的 PDF 文字处理模式")
values = [str(self.project_path), str(self.output_dir), self.block_name]
if self.engine_path is not None:
values.append(str(self.engine_path))
if any(any(char in value for char in "\r\n\x00") for value in values):
raise ValueError("PDF 导出设置含无效换行或空字符")
@dataclass(frozen=True, slots=True)
class PdfExportResult:
project_path: Path
state: str
message: str
output_path: Path | None = None
pages: int = 0
run_dir: Path | None = None
@@ -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)
@@ -0,0 +1,47 @@
"""Provide the reference drawing palette to one native export process."""
from __future__ import annotations
import os
from pathlib import Path
import xml.etree.ElementTree as ET
# DxDesigner.xml stores RGB values. Explicit colors on drawing objects keep
# their native precedence over these defaults.
REFERENCE_COLORS = {
"NET": "0xff0000",
"COMPONENT": "0x800080",
"PIN": "0x008080",
"LINE": "0x0000ff",
"BOX": "0x800080",
"CIRCLE": "0x008000",
"ARC": "0x0000ff",
"TEXT": "0x0000ff",
"LABEL": "0x008000",
"ATTRIBUTE": "0x388e8e",
}
def prepare_environment(run_dir: Path, print_theme: str) -> dict[str, str] | None:
if print_theme == "original":
return None
if print_theme != "reference":
raise ValueError("不支持的 PDF 配色")
directory = Path(run_dir).resolve() / "native-profile"
if ";" in str(directory):
raise ValueError("运行记录路径含分号,无法加入原生配置搜索路径")
directory.mkdir(parents=True, exist_ok=True)
root = ET.Element("DxDesigner_Configuration_file", version="1.2", name="DxDesigner.xml")
designer = ET.SubElement(root, "DxDesigner")
objects = ET.SubElement(designer, "OBJECTS")
for name, color in REFERENCE_COLORS.items():
item = ET.SubElement(objects, "object", name=name)
ET.SubElement(item, "key", name="COLOR", value=color)
layers = ET.SubElement(designer, "LAYERS")
border = ET.SubElement(layers, "layer", name="BORDER_LAYER")
ET.SubElement(border, "key", name="COLOR", value="0x0000ff")
ET.ElementTree(root).write(directory / "DxDesigner.xml", encoding="utf-8", xml_declaration=True)
environment = dict(os.environ)
inherited = environment.get("WDIR", "")
environment["WDIR"] = str(directory) + (";" + inherited if inherited else "")
return environment
@@ -0,0 +1,135 @@
from __future__ import annotations
import hashlib
import json
import os
import re
import uuid
from pathlib import Path
from .models import ExportScope, PdfExportSettings
def settings_path(local_app_data: Path | None = None) -> Path:
root = Path(
local_app_data
or os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local")
)
return root / "DxProductivity" / "pdf-export-settings.json"
def normalized_project_path(path: Path | str) -> str:
return os.path.normcase(str(Path(path).expanduser().resolve(strict=False)))
def default_output_dir(
project_path: Path | str, local_app_data: Path | None = None
) -> Path:
project = Path(project_path).expanduser().resolve(strict=False)
root = Path(
local_app_data
or os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local")
)
digest = hashlib.sha256(normalized_project_path(project).encode("utf-8")).hexdigest()[:8]
safe_stem = re.sub(r"[<>:\"/\\|?*\x00-\x1f]+", "_", project.stem).strip(" .") or "project"
return root / "DxProductivity" / "pdf-output" / f"{safe_stem}-{digest}"
def default_settings(
project_path: Path | str, local_app_data: Path | None = None
) -> PdfExportSettings:
project = Path(project_path).expanduser().resolve(strict=False)
return PdfExportSettings(
project_path=project,
scope=ExportScope.PROJECT,
block_name="",
output_dir=default_output_dir(project, local_app_data),
)
def load_settings(
project_path: Path | str,
*,
config_path: Path | None = None,
local_app_data: Path | None = None,
) -> PdfExportSettings:
defaults = default_settings(project_path, local_app_data)
target = Path(config_path or settings_path(local_app_data))
try:
data = json.loads(target.read_text(encoding="utf-8"))
except (OSError, ValueError):
return defaults
if not isinstance(data, dict):
return defaults
try:
matches_project = normalized_project_path(
str(data.get("project_path", ""))
) == normalized_project_path(defaults.project_path)
except (OSError, TypeError, ValueError):
return defaults
if not matches_project:
return defaults
try:
scope = ExportScope(data.get("scope", ExportScope.PROJECT.value))
except (TypeError, ValueError):
scope = ExportScope.PROJECT
block_name = data.get("block_name", "")
output_value = data.get("output_dir", "")
engine_value = data.get("engine_path", "")
print_theme = data.get("print_theme", "reference")
if print_theme not in ("reference", "original"):
print_theme = "reference"
text_mode = data.get("text_mode", "chinese")
if text_mode not in ("chinese", "western", "original"):
text_mode = "chinese"
if not isinstance(block_name, str) or not isinstance(output_value, str):
return defaults
if not isinstance(engine_value, str):
engine_value = ""
try:
return PdfExportSettings(
project_path=defaults.project_path,
scope=scope,
block_name=block_name,
output_dir=Path(output_value) if output_value else defaults.output_dir,
auto_export=data.get("auto_export") is True,
engine_path=Path(engine_value) if engine_value else None,
print_theme=print_theme,
text_mode=text_mode,
)
except (OSError, TypeError, ValueError):
return defaults
def save_settings(
settings: PdfExportSettings, *, config_path: Path | None = None
) -> Path:
target = Path(config_path or settings_path())
target.parent.mkdir(parents=True, exist_ok=True)
payload = {
"format_version": 1,
"project_path": str(settings.project_path.resolve(strict=False)),
"scope": settings.scope.value,
"block_name": settings.block_name,
"output_dir": str(settings.output_dir.resolve(strict=False)),
"auto_export": bool(settings.auto_export),
"print_theme": settings.print_theme,
"text_mode": settings.text_mode,
"engine_path": str(settings.engine_path.resolve(strict=False))
if settings.engine_path
else "",
}
temporary = target.with_name(f".{target.name}.{uuid.uuid4().hex[:8]}.tmp")
try:
with temporary.open("x", encoding="utf-8", newline="\n") as stream:
json.dump(payload, stream, ensure_ascii=False, indent=2)
stream.write("\n")
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, target)
finally:
try:
temporary.unlink(missing_ok=True)
except OSError:
pass
return target
@@ -0,0 +1,175 @@
"""Repair native WinAnsi/GBK text while retaining drawing geometry and colors."""
from __future__ import annotations
import os
from pathlib import Path
from threading import Event
import uuid
from pypdf import PdfReader, PdfWriter
from pypdf.generic import ByteStringObject, ContentStream, DictionaryObject, FloatObject, NameObject
from .embedded_fonts import build_fonts
def _cancelled(cancel: Event) -> None:
if cancel.is_set():
raise InterruptedError('导出已取消')
def _raw(value) -> bytes:
if isinstance(value, ByteStringObject):
return bytes(value)
if hasattr(value, 'original_bytes'):
return value.original_bytes
return str(value).encode('cp1252')
def _decode(raw: bytes, mode: str) -> tuple[str, bool]:
if mode == 'chinese':
try:
text = raw.decode('gbk', errors='strict')
return ''.join(char for char in text if ord(char) >= 32), any(byte >= 128 for byte in raw)
except UnicodeDecodeError:
pass
text = raw.decode('cp1252', errors='strict')
return ''.join(char for char in text if ord(char) >= 32), False
def _legacy(font) -> bool:
return (font.get('/Encoding') == '/WinAnsiEncoding'
and font.get('/Subtype') in ('/TrueType', '/Type1') and '/ToUnicode' not in font)
def _text_operations(stream, resources, reader):
font_name, size, scale, char_space, word_space, rendering = None, 12., 100., 0., 0., 0
stack = []
fonts = resources.get('/Font', DictionaryObject()).get_object()
for operands, operator in ContentStream(stream, reader).operations:
if operator == b'q':
stack.append((font_name, size, scale, char_space, word_space, rendering))
elif operator == b'Q' and stack:
font_name, size, scale, char_space, word_space, rendering = stack.pop()
elif operator == b'Tf':
font_name, size = operands[0], float(operands[1])
elif operator == b'Tz': scale = float(operands[0])
elif operator == b'Tc': char_space = float(operands[0])
elif operator == b'Tw': word_space = float(operands[0])
elif operator == b'Tr': rendering = int(operands[0])
font = fonts.get(font_name)
font = font.get_object() if font is not None else None
if operator in (b'Tj', b'TJ', b"'", b'"') and font is not None and _legacy(font):
if operator != b'Tj':
raise ValueError(f'暂不能修复 {operator.decode()} 复合文字,未发布乱码 PDF')
raw = _raw(operands[0])
if str(font.get('/BaseFont', '')).lstrip('/').casefold().startswith('fstroke'):
if rendering == 3 and raw.isascii():
yield operands, operator, None
continue
raise ValueError('原生输出仍含中文笔画文字,无法保证中文修复,未发布 PDF')
if char_space or word_space:
raise ValueError('原生文字使用字符间距或词间距,无法保证字体转换,未发布 PDF')
yield operands, operator, (font, font_name, raw, size, scale)
elif operator == b'Do':
form = resources.get('/XObject', {}).get(operands[0])
if form is not None and form.get_object().get('/Subtype') == '/Form':
form = form.get_object()
for _, _, text in _text_operations(form, form.get('/Resources', resources).get_object(), reader):
if text is not None:
raise ValueError('暂不能转换 Form 内旧编码文字,未发布乱码 PDF')
yield operands, operator, None
else:
yield operands, operator, None
def _old_advance(font, raw: bytes, size: float) -> float:
raw = bytes(byte for byte in raw if byte >= 32)
values = font.get('/Widths')
if values is not None:
values = values.get_object()
first = int(font.get('/FirstChar', 0))
if any(not 0 <= byte - first < len(values) for byte in raw):
raise ValueError('原字体缺少字符宽度,未发布 PDF')
widths = [float(values[byte - first]) for byte in raw]
else:
from pypdf._codecs.core_font_metrics import CORE_FONT_METRICS
from pypdf._codecs import _win_encoding
metrics = CORE_FONT_METRICS.get(str(font.get('/BaseFont', '')).lstrip('/'))
if metrics is None:
raise ValueError('原字体缺少可靠字宽信息,未发布 PDF')
widths = [metrics.character_widths.get(_win_encoding[byte], metrics.character_widths['default']) for byte in raw]
return sum(widths) * size / 1000
def repair_text(path: Path, mode: str, cancel: Event) -> dict:
_cancelled(cancel)
report = {'mode': mode, 'font_strings': 0, 'repaired_strings': 0, 'embedded_fonts': 0}
if mode == 'original':
return report
if mode not in ('chinese', 'western'):
raise ValueError('不支持的 PDF 文字处理模式')
reader = PdfReader(path, strict=True)
decoded = {}
for page in reader.pages:
_cancelled(cancel)
resources = page.get('/Resources', DictionaryObject()).get_object()
for _, _, state in _text_operations(page.get_contents(), resources, reader):
if state is not None:
decoded[state[2]] = _decode(state[2], mode)
if not decoded:
return report
writer = PdfWriter()
writer.clone_document_from_reader(reader)
assignments = build_fonts(writer, [text for text, _ in decoded.values() if text])
fonts = {font.name: font for font in assignments.values()}
report['embedded_fonts'] = len(fonts)
for page in writer.pages:
_cancelled(cancel)
resources = DictionaryObject(dict(page.get('/Resources', DictionaryObject()).get_object()))
page[NameObject('/Resources')] = resources
original_fonts = DictionaryObject(dict(resources.get('/Font', DictionaryObject()).get_object()))
stream = ContentStream(page.get_contents(), writer)
rebuilt = []
for operands, operator, state in _text_operations(stream, resources, writer):
if state is None:
rebuilt.append((operands, operator))
continue
original, name, raw, size, scale = state
text, repaired = decoded[raw]
if not text:
rebuilt.append((operands, operator))
continue
font = assignments[text]
old_width = _old_advance(original, raw, size)
width = font.advance(text, size)
new_scale = scale * old_width / width if width > 0 else scale
rebuilt.extend([([NameObject(font.name), FloatObject(size)], b'Tf'),
([FloatObject(new_scale)], b'Tz'), ([ByteStringObject(font.encode(text))], b'Tj'),
([name, FloatObject(size)], b'Tf'), ([FloatObject(scale)], b'Tz')])
report['font_strings'] += 1
report['repaired_strings'] += int(repaired)
for name, font in fonts.items():
if name in original_fonts:
raise ValueError('嵌入字体名称与原 PDF 冲突')
original_fonts[NameObject(name)] = font.reference
resources[NameObject('/Font')] = original_fonts
stream.operations = rebuilt
stream.get_data()
page[NameObject('/Contents')] = writer._add_object(stream.flate_encode())
temporary = Path(path).with_name(f'.{Path(path).name}.{uuid.uuid4().hex[:8]}.text.tmp')
try:
_cancelled(cancel)
with temporary.open('xb') as output:
writer.write(output)
output.flush()
os.fsync(output.fileno())
verified = PdfReader(temporary, strict=True)
if len(verified.pages) != len(reader.pages):
raise ValueError('文字处理改变了 PDF 页数,未发布 PDF')
for page in verified.pages:
page.get_contents().get_data()
_cancelled(cancel)
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
return report
+120 -38
View File
@@ -23,12 +23,17 @@ from dx_productivity.domain.models import RunPaths
from dx_productivity.ui.bom_controller import BomController
from dx_productivity.ui.bom_page import BomPage
from dx_productivity.ui.main_window import MainWindow
from dx_productivity.ui.selection_watcher import SelectionWatcher
from dx_productivity.ui.host_window_watcher import HostWindowWatcher
from dx_productivity.ui.startup_controller import StartupController
from dx_productivity.ui.property_change_controller import PropertyChangeController
from dx_productivity.ui.property_change_page import PropertyChangePage
from dx_productivity.ui.property_visibility_controller import (
PropertyVisibilityController,
)
from dx_productivity.ui.property_visibility_page import PropertyVisibilityPage
from dx_productivity.ui.pdf_export_controller import PdfExportController
from dx_productivity.ui.pdf_export_page import PdfExportPage
from dx_productivity.ui.history_controller import HistoryController
from dx_productivity.ui.history_page import HistoryPage
from dx_productivity.ui.inspection_controller import InspectionController
@@ -57,7 +62,7 @@ def _load_windows_ui_fonts(application: QApplication) -> None:
path = font_root / filename
if path.exists():
QFontDatabase.addApplicationFont(str(path))
application.setFont(QFont("Microsoft YaHei UI", 13))
application.setFont(QFont("Microsoft YaHei UI", 10))
def build_parser() -> argparse.ArgumentParser:
@@ -73,9 +78,11 @@ FEATURE_PAGE_INDEX = {
"property-change": 1,
"property-visibility": 2,
"inspection": 3,
"network": 4,
"bom": 5,
"history": 6,
"settings": 7,
"pdf-export": 7,
"settings": 8,
}
STATUS_TEXT = {
@@ -90,6 +97,14 @@ def _status_text(state: str) -> str:
return STATUS_TEXT.get(state, state)
def _set_snapshot_status(window: MainWindow, snapshot) -> None:
window.set_project_status(Path(snapshot.design_path).name or snapshot.design_id, snapshot.design_path)
window.set_bridge_status('桥接已连接')
refs = [component.refdes or '未标注器件' for component in snapshot.components if component.selected]
summary = f'已选 {refs[0]}' if len(refs) == 1 else f'已选 {len(refs)} 个' + (f':{refs[0]}' if refs else '器件')
window.set_selection_status(summary, f'当前页:{snapshot.active_block_name} / {snapshot.current_sheet_name}\n选中器件:' + ('、'.join(refs) or '无'))
def create_main_window(request_path: Path | None = None) -> MainWindow:
window = MainWindow()
page = RefDesPage()
@@ -119,7 +134,7 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
window.set_page(0, page, "自动位号")
controller.can_apply_changed.connect(window.apply_button.setEnabled)
controller.apply_completed.connect(
lambda state: window.operation_status.setText(_status_text(state))
lambda state: window.set_operation_status(_status_text(state))
)
controller.apply_failed.connect(
lambda message: _report_error(window, "应用位号失败", message)
@@ -127,7 +142,9 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
window.refresh_requested.connect(
lambda: _request_refresh(window, controller, run_paths)
)
page.preview_requested.connect(controller.refresh_plan)
window.preview_requested.connect(controller.refresh_plan)
page.apply_requested.connect(controller.apply)
window.apply_requested.connect(controller.apply)
history_page = HistoryPage()
window.set_page(6, history_page, "操作历史")
@@ -139,7 +156,7 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
run_paths=run_paths,
)
history_controller.status_changed.connect(
lambda state: window.operation_status.setText(_status_text(state))
lambda state: window.set_operation_status(_status_text(state))
)
history_controller.restore_failed.connect(
lambda message: _report_error(window, "恢复位号失败", message)
@@ -156,7 +173,7 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
property_change_page.set_can_apply
)
property_change_controller.apply_completed.connect(
lambda state: window.operation_status.setText(_status_text(state))
lambda state: window.set_operation_status(_status_text(state))
)
property_change_controller.apply_failed.connect(
lambda message: _report_error(window, "应用属性修改失败", message)
@@ -173,7 +190,7 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
property_visibility_page.set_can_apply
)
property_visibility_controller.apply_completed.connect(
lambda state: window.operation_status.setText(_status_text(state))
lambda state: window.set_operation_status(_status_text(state))
)
property_visibility_controller.apply_failed.connect(
lambda message: _report_error(window, "应用显示状态失败", message)
@@ -185,9 +202,14 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
inspection_page,
run_paths=run_paths,
)
inspection_controller.status_changed.connect(window.operation_status.setText)
inspection_controller.status_changed.connect(window.set_operation_status)
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.set_operation_status)
window.set_page(4, network_page, "网络工具")
window.network_controller = network_controller
bom_page = BomPage()
bom_controller = BomController(
bom_page,
@@ -197,12 +219,12 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
Path(snapshot.design_path).name if snapshot is not None else ""
),
)
bom_controller.status_changed.connect(window.operation_status.setText)
bom_controller.status_changed.connect(window.set_operation_status)
bom_controller.export_failed.connect(
lambda message: _report_error(window, "BOM 导出失败", message)
)
bom_controller.export_completed.connect(
lambda path: window.operation_status.setText(f"BOM 已导出:{path}")
lambda path: window.set_operation_status(f"BOM 已导出:{path}")
)
window.set_page(5, bom_page, "BOM 工具")
window.bom_controller = bom_controller
@@ -246,19 +268,27 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
settings_page.auto_check_checkbox.isChecked(),
)
)
window.set_page(7, settings_page, "设置")
window.set_page(FEATURE_PAGE_INDEX["settings"], settings_page, "设置")
window.settings_controller = settings_controller
window.settings_page = settings_page
pdf_export_page = PdfExportPage()
pdf_export_controller = PdfExportController(
pdf_export_page,
tool_root=_tool_root(),
)
pdf_export_controller.status_changed.connect(window.set_operation_status)
window.set_page(FEATURE_PAGE_INDEX["pdf-export"], pdf_export_page, "PDF 导出")
window.pdf_export_controller = pdf_export_controller
if settings_controller.auto_check_due(persisted_settings):
QTimer.singleShot(
0,
lambda: settings_page.check_requested.emit(
lambda: not window._closing and settings_page.check_requested.emit(
settings_page.source_input.text().strip(), settings_page.channel_combo.currentData()
),
)
if snapshot is not None:
window.project_label.setText(Path(snapshot.design_path).name or snapshot.design_id)
window.bridge_status.setText("桥接已连接")
_set_snapshot_status(window, snapshot)
controller.load_snapshot(snapshot)
if window.property_change_controller is not None:
window.property_change_controller.load_snapshot(snapshot)
@@ -266,19 +296,45 @@ 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:
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(
lambda _snapshot: history_controller.refresh()
)
window.navigation.setCurrentRow(0)
window.pages.setCurrentIndex(0)
window.page_title.setText("自动位号")
if watcher is not None:
watcher.snapshot_reloaded.connect(pdf_export_controller.load_snapshot)
window.selection_watcher = SelectionWatcher(window, request_path)
window.host_window_watcher = HostWindowWatcher(window, request_path)
window.set_active_page(0)
startup_controller = StartupController(_tool_root(), window)
window.startup_controller = startup_controller
window.start_requested.connect(startup_controller.start)
startup_controller.started.connect(lambda: window.start_button.setEnabled(False))
startup_controller.started.connect(lambda: window.set_operation_status("正在自动加入 DxDesigner 菜单…"))
def startup_finished(success: bool, message: str) -> None:
window.start_button.setEnabled(True)
window.set_operation_status(message)
if not success:
QMessageBox.warning(window, "Start 未完成", message)
startup_controller.completed.connect(startup_finished)
return window
@@ -286,16 +342,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.operation_status.setText("已请求宿主刷新设计快照…")
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):
@@ -331,10 +391,22 @@ 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)
_set_snapshot_status(self._window, snapshot)
self.snapshot_reloaded.emit(snapshot)
self._window.operation_status.setText("设计快照已刷新")
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(
@@ -347,7 +419,7 @@ def _install_snapshot_watcher(
def _report_error(window: MainWindow, title: str, message: str) -> None:
window.operation_status.setText(f"{title}:{message}")
window.set_operation_status(f"{title}:{message}")
QMessageBox.warning(window, title, message)
@@ -365,53 +437,62 @@ def _install_excepthook() -> None:
def _tool_root() -> Path:
# A copied portable executable must never use a cached root from another
# release inherited through DXTOOLS_HOME.
if getattr(sys, "frozen", False):
return Path(sys.executable).resolve().parent
configured = os.environ.get("DXTOOLS_HOME")
if configured:
return Path(configured)
if getattr(sys, "frozen", False):
return Path(sys.executable).resolve().parent
return Path(__file__).resolve().parents[3] / "integration" / "dxdesigner795"
def _launch_update(window: MainWindow, controller: SettingsController, manifest: object) -> None:
"""Write a post-exit install plan and hand control to the portable updater."""
startup = getattr(window, 'startup_controller', None)
if startup is not None and startup.is_running():
window.set_operation_status('正在完成菜单注册,请稍候再安装更新')
return
staged_zip = controller.staged_path(manifest)
if staged_zip is None or not staged_zip.is_file():
window.operation_status.setText("更新包尚未准备好,请重新检查")
window.set_operation_status("更新包尚未准备好,请重新检查")
return
if not getattr(sys, "frozen", False):
window.operation_status.setText("开发运行环境已完成校验,便携式包中可执行安装")
window.set_operation_status("开发运行环境已完成校验,便携式包中可执行安装")
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:
window.operation_status.setText(f"无法启动更新器:{error}")
window.set_operation_status(f"无法启动更新器:{error}")
return
window.operation_status.setText(f"已确认安装 {manifest.version},程序即将退出更新")
application = QApplication.instance()
if application is not None:
application.quit()
window.set_operation_status(f"已确认安装 {manifest.version},程序即将退出更新")
if window.request_exit():
application = QApplication.instance()
if application is not None:
application.quit()
def main(argv: Sequence[str] | None = None) -> int:
@@ -423,10 +504,11 @@ def main(argv: Sequence[str] | None = None) -> int:
_install_excepthook()
app = create_application([sys.argv[0], *arguments])
window = create_main_window(options.request)
window.show()
window.window_closed.connect(app.quit)
window.show_toolbar()
if options.feature is not None:
index = FEATURE_PAGE_INDEX[options.feature]
window.set_active_page(index)
window.show_panel(index)
if options.smoke_test_ms is not None:
QTimer.singleShot(options.smoke_test_ms, app.quit)
QTimer.singleShot(options.smoke_test_ms, window.request_exit)
return app.exec()
+24 -8
View File
@@ -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,19 @@ 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()
# 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(
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 +92,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 +126,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 +144,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", " ")
+34 -16
View File
@@ -9,6 +9,7 @@ from PySide6.QtWidgets import (
QComboBox,
QFileDialog,
QHBoxLayout,
QHeaderView,
QLabel,
QPushButton,
QRadioButton,
@@ -18,6 +19,7 @@ from PySide6.QtWidgets import (
)
from dx_productivity.features.bom import BOMResult, BOMSettings
from dx_productivity.ui.collapsible_section import CollapsibleSection
class BomPage(QWidget):
@@ -30,16 +32,8 @@ class BomPage(QWidget):
def _build_ui(self) -> None:
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 16, 20, 16)
layout.setSpacing(10)
hint = QLabel(
"BOM 导出:按页分组、合并同料号、NC 过滤与创维料号校验全部在本地完成;"
"点击导出后由 DxDesigner 宿主调用 Excel 按模板输出。"
)
hint.setObjectName("secondaryLabel")
hint.setWordWrap(True)
layout.addWidget(hint)
layout.setContentsMargins(12, 10, 12, 10)
layout.setSpacing(8)
options = QHBoxLayout()
options.addWidget(QLabel("范围"))
@@ -53,15 +47,21 @@ class BomPage(QWidget):
self.selected_button,
):
options.addWidget(button)
options.addWidget(QLabel("描述来源"))
options.addStretch(1)
layout.addLayout(options)
self.advanced_section = CollapsibleSection("高级选项")
advanced_options = QHBoxLayout()
advanced_options.addWidget(QLabel("描述来源"))
self.description_combo = QComboBox()
self.description_combo.addItem("Value", "value")
self.description_combo.addItem("Part Label", "part-label")
options.addWidget(self.description_combo)
advanced_options.addWidget(self.description_combo)
self.nc_checkbox = QCheckBox("剔除 NC 器件")
options.addWidget(self.nc_checkbox)
options.addStretch(1)
layout.addLayout(options)
advanced_options.addWidget(self.nc_checkbox)
advanced_options.addStretch(1)
self.advanced_section.content_layout.addLayout(advanced_options)
layout.addWidget(self.advanced_section)
self.model = QStandardItemModel(0, 6, self)
self.model.setHorizontalHeaderLabels(
@@ -69,8 +69,15 @@ class BomPage(QWidget):
)
self.table = QTableView()
self.table.setModel(self.model)
self.table.setMinimumHeight(360)
self.table.setMinimumHeight(160)
self.table.setEditTriggers(QTableView.EditTrigger.NoEditTriggers)
self.table.setAlternatingRowColors(True)
self.table.verticalHeader().hide()
header = self.table.horizontalHeader()
header.setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
for column, width in ((0, 70), (1, 48), (2, 125), (3, 125), (5, 100)):
self.table.setColumnWidth(column, width)
header.setSectionResizeMode(4, QHeaderView.ResizeMode.Stretch)
layout.addWidget(self.table, 1)
self.summary_label = QLabel("")
@@ -83,6 +90,7 @@ class BomPage(QWidget):
self.export_button = QPushButton("导出 Excel…")
self.export_button.setObjectName("primaryButton")
self.export_button.setEnabled(False)
self.export_button.setToolTip("由 DxDesigner 调用 Excel,按模板导出预览中的 BOM")
self.export_button.clicked.connect(self._emit_export)
actions.addWidget(self.export_button)
layout.addLayout(actions)
@@ -91,6 +99,13 @@ class BomPage(QWidget):
button.toggled.connect(self.settings_changed)
self.description_combo.currentIndexChanged.connect(self.settings_changed)
self.nc_checkbox.toggled.connect(self.settings_changed)
self.description_combo.currentIndexChanged.connect(self._update_advanced_summary)
self.nc_checkbox.toggled.connect(self._update_advanced_summary)
self._update_advanced_summary()
def _update_advanced_summary(self) -> None:
nc = "剔除 NC" if self.nc_checkbox.isChecked() else "保留 NC"
self.advanced_section.set_summary(f"描述:{self.description_combo.currentText()} · {nc}")
def _emit_export(self) -> None:
path, _ = QFileDialog.getSaveFileName(
@@ -150,9 +165,11 @@ class BomPage(QWidget):
if result.excluded_count:
summary += f";NC 剔除:{result.excluded_count} 个器件"
self.summary_label.setText(summary)
self.summary_label.setToolTip(summary)
def set_summary(self, text: str) -> None:
self.summary_label.setText(text)
self.summary_label.setToolTip(text)
def set_can_export(self, enabled: bool) -> None:
self.export_button.setEnabled(enabled)
@@ -161,4 +178,5 @@ class BomPage(QWidget):
def _read_only(text: str) -> QStandardItem:
item = QStandardItem(text)
item.setEditable(False)
item.setToolTip(text)
return item
@@ -0,0 +1,49 @@
"""Advanced options with an always-visible effective summary."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QLabel, QToolButton, QVBoxLayout, QWidget
class CollapsibleSection(QWidget):
expanded_changed = Signal(bool)
def __init__(self, title: str, parent=None):
super().__init__(parent)
self._title = title
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(4)
self.toggle_button = QToolButton()
self.toggle_button.setObjectName('sectionToggle')
self.toggle_button.setCheckable(True)
self.toggle_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
self.toggle_button.setAccessibleName(title)
self.toggle_button.setToolTip('展开或收起' + title)
self.summary_label = QLabel()
self.summary_label.setObjectName('secondaryLabel')
self.summary_label.setWordWrap(True)
self.summary_label.hide()
self.content = QWidget()
self.content_layout = QVBoxLayout(self.content)
self.content_layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.toggle_button)
layout.addWidget(self.summary_label)
layout.addWidget(self.content)
self.toggle_button.toggled.connect(self._update_expanded)
self._update_expanded(False)
@property
def is_expanded(self) -> bool:
return self.toggle_button.isChecked()
def set_expanded(self, expanded: bool) -> None:
self.toggle_button.setChecked(expanded)
def _update_expanded(self, expanded: bool) -> None:
self.toggle_button.setText(self._title)
self.toggle_button.setArrowType(Qt.ArrowType.DownArrow if expanded else Qt.ArrowType.RightArrow)
self.content.setVisible(expanded)
self.expanded_changed.emit(expanded)
def set_summary(self, text: str) -> None:
self.summary_label.setText(text)
self.summary_label.setVisible(bool(text))
+256
View File
@@ -0,0 +1,256 @@
"""Persistent single-row entry points; business actions belong to pages."""
from __future__ import annotations
from PySide6.QtCore import QPoint, QSize, Qt, Signal
from PySide6.QtGui import QAction
from PySide6.QtWidgets import QApplication, QHBoxLayout, QLabel, QMenu, QPushButton, QToolButton, QWidget
from dx_productivity.ui.theme import Theme, themed_icon
NAVIGATION = (
('自动位号', 'fa6s.hashtag'), ('属性批改', 'fa6s.pen'),
('属性显示', 'fa6s.tag'), ('设计检查', 'fa6s.clipboard-check'),
('网络工具', 'fa6s.share-nodes'), ('BOM 工具', 'fa6s.table'),
('操作历史', 'fa6s.clock-rotate-left'), ('PDF 导出', 'fa6s.file-pdf'),
('设置', 'fa6s.gear'),
)
PRIMARY_PAGES = (0, 1, 2, 3, 4, 5, 7)
SHORT_LABELS = dict(zip(PRIMARY_PAGES, ('位号', '属性', '显示', '检查', '网络', 'BOM', 'PDF')))
# Below this width a 28-pixel clickable control cannot fit its frame.
MINIMUM_TOOLBAR_WIDTH = 34
class DragHandle(QLabel):
dragged = Signal(QPoint)
def __init__(self, parent):
super().__init__('⋮⋮', parent)
self.setFixedWidth(20)
self.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.setCursor(Qt.CursorShape.SizeAllCursor)
self.setToolTip('拖动工具栏')
self.setAccessibleName('拖动工具栏')
self._offset = None
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self._offset = event.globalPosition().toPoint() - self.window().pos()
event.accept()
def mouseMoveEvent(self, event):
if self._offset is not None and event.buttons() & Qt.MouseButton.LeftButton:
self.dragged.emit(event.globalPosition().toPoint() - self._offset)
event.accept()
def mouseReleaseEvent(self, event):
self._offset = None
event.accept()
class FloatingToolbar(QWidget):
page_requested = Signal(int)
start_requested = Signal()
refresh_requested = Signal()
theme_requested = Signal()
toggle_panel_requested = Signal()
exit_requested = Signal()
position_changed = Signal(QPoint)
def __init__(self):
super().__init__(None, Qt.WindowType.Tool | Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint)
self.setWindowTitle('一叶知秋悬浮工具栏')
self.setObjectName('floatingToolbar')
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
self.setFixedHeight(44)
self._exiting = False
self._theme = Theme.LIGHT
self._available_width = 780
self._status_text = '桥接待连接'
layout = QHBoxLayout(self)
layout.setContentsMargins(5, 4, 5, 4)
layout.setSpacing(4)
self.drag_handle = DragHandle(self)
self.drag_handle.dragged.connect(self.move_within_screen)
layout.addWidget(self.drag_handle)
self.start_button = QPushButton('Start')
self.start_button.setFixedWidth(64)
self.start_button.setAccessibleName('Start:加入菜单并打开 DxDesigner')
self.start_button.setToolTip('加入工具菜单并打开 DxDesigner;连接状态独立显示')
self.start_button.clicked.connect(self.start_requested)
layout.addWidget(self.start_button)
self.page_buttons = {}
for index, short in SHORT_LABELS.items():
button = QPushButton(short)
button.setObjectName('toolbarFeature')
button.setAccessibleName(NAVIGATION[index][0])
button.setToolTip(NAVIGATION[index][0])
button.setCheckable(True)
button.setFixedWidth(58)
button.clicked.connect(lambda _checked=False, i=index: self.page_requested.emit(i))
self.page_buttons[index] = button
layout.addWidget(button)
self.status_label = QLabel(self._status_text)
self.status_label.setFixedWidth(164)
self.status_label.setAccessibleName('当前桥接、选择与任务状态')
layout.addWidget(self.status_label)
self.more_button = QToolButton()
self.more_button.setObjectName('toolbarMore')
self.more_button.setText('更多')
self.more_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
self.more_button.setArrowType(Qt.ArrowType.DownArrow)
self.more_button.setAccessibleName('更多')
self.more_button.setToolTip('更多功能与应用操作')
self.more_button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
self.more_menu = QMenu(self.more_button)
self.more_button.setMenu(self.more_menu)
self.start_action = self.more_menu.addAction('Start:加入菜单并打开 DxDesigner')
self.start_action.triggered.connect(self.start_requested)
self.start_action.setVisible(False)
self.page_actions = {}
for index in PRIMARY_PAGES + (6, 8):
action = QAction(NAVIGATION[index][0], self)
action.setCheckable(True)
action.triggered.connect(lambda _checked=False, i=index: self.page_requested.emit(i))
self.page_actions[index] = action
self.more_menu.addAction(action)
self.more_menu.addSeparator()
self.toggle_action = self.more_menu.addAction('展开面板')
self.toggle_action.triggered.connect(self.toggle_panel_requested)
self.toggle_action.setVisible(False)
self.status_action = self.more_menu.addAction('状态:桥接待连接')
self.status_action.setEnabled(False)
self.status_action.setVisible(False)
for name, attribute, signal in (('刷新设计快照', 'refresh_action', self.refresh_requested),
('切换明暗主题', 'theme_action', self.theme_requested),
('退出工具', 'exit_action', self.exit_requested)):
action = self.more_menu.addAction(name)
action.triggered.connect(signal)
setattr(self, attribute, action)
layout.addWidget(self.more_button)
self.toggle_button = QToolButton()
self.toggle_button.setObjectName('panelToggle')
self.toggle_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
self.toggle_button.setFixedWidth(66)
self.toggle_button.clicked.connect(self.toggle_panel_requested)
layout.addWidget(self.toggle_button)
self.set_panel_state(0, False)
self.refresh_theme(Theme.LIGHT)
def set_panel_state(self, index: int, visible: bool):
for i, button in self.page_buttons.items():
button.setChecked(i == index and visible)
for i, action in self.page_actions.items():
action.setChecked(i == index and visible)
name = '收起面板' if visible else '展开面板'
self.toggle_button.setText('收起' if visible else '展开')
self.toggle_button.setArrowType(Qt.ArrowType.UpArrow if visible else Qt.ArrowType.DownArrow)
self.toggle_button.setAccessibleName(name)
self.toggle_button.setToolTip(name)
self.toggle_action.setText(name)
def set_status(self, text: str, detail: str):
self._status_text = text
self.status_label.setAccessibleName(text)
self.status_label.setText(self.status_label.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, self.status_label.width()))
self.status_label.setToolTip(detail)
self.status_label.setAccessibleDescription(detail)
self.status_action.setText('状态:' + self.status_label.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, 240))
self.status_action.setToolTip(detail)
self.more_button.setToolTip('更多功能与应用操作' + ('\n' + detail if self.status_label.isHidden() else ''))
self.start_action.setEnabled(self.start_button.isEnabled())
def fit_available_width(self, width: int):
width = max(MINIMUM_TOOLBAR_WIDTH, width)
self._available_width = width
layout = self.layout()
layout.setContentsMargins(5, 4, 5, 4)
layout.setSpacing(4)
self.more_button.setText('更多')
self.more_button.setFixedWidth(60)
self.drag_handle.show()
self.drag_handle.setFixedWidth(20)
self.start_button.show()
self.start_button.setText('Start')
self.start_button.setFixedWidth(64)
self.start_action.setVisible(False)
self.toggle_button.show()
self.toggle_action.setVisible(False)
self.status_label.show()
self.status_label.setFixedWidth(164)
self.status_action.setVisible(False)
for index, button in self.page_buttons.items():
button.setVisible(True)
button.setText(SHORT_LABELS[index])
button.setFixedWidth(58)
self.page_actions[index].setVisible(False)
for index in (2, 3, 4, 5):
if self.layout().sizeHint().width() <= width:
break
self.page_buttons[index].hide()
self.page_actions[index].setVisible(True)
# A very narrow monitor can shrink the status, keeping priority actions.
excess = self.layout().sizeHint().width() - width
if excess > 0:
self.status_label.setFixedWidth(max(24, 164 - excess))
if layout.sizeHint().width() > width:
# Icon mode retains names/tooltips, then overflows remaining entries
# in priority order. Start and PDF stay direct until the last stage.
layout.setContentsMargins(2, 4, 2, 4)
layout.setSpacing(2)
self.more_button.setText('')
self.more_button.setFixedWidth(28)
self.drag_handle.setFixedWidth(12)
self.start_button.setText('')
self.start_button.setFixedWidth(28)
for button in self.page_buttons.values():
button.setText('')
button.setFixedWidth(32)
self.page_buttons[7].setFixedWidth(28)
for index in (1, 0):
if layout.sizeHint().width() <= width:
break
self.page_buttons[index].hide()
self.page_actions[index].setVisible(True)
for widget, action in ((self.status_label, self.status_action),
(self.toggle_button, self.toggle_action),
(self.drag_handle, None),
(self.start_button, self.start_action),
(self.page_buttons[7], self.page_actions[7])):
if layout.sizeHint().width() <= width:
break
widget.hide()
if action is not None:
action.setVisible(True)
self.setFixedWidth(min(width, self.layout().sizeHint().width()))
layout.activate()
self.set_status(self._status_text, self.status_label.toolTip())
def move_within_screen(self, position: QPoint, screen=None):
screen = screen or QApplication.screenAt(position) or self.screen() or QApplication.primaryScreen()
if screen is not None:
bounds = screen.availableGeometry()
self.fit_available_width(bounds.width())
position = QPoint(max(bounds.left(), min(position.x(), bounds.right() - self.width() + 1)),
max(bounds.top(), min(position.y(), bounds.bottom() - self.height() + 1)))
self.move(position)
def moveEvent(self, event):
super().moveEvent(event)
self.position_changed.emit(self.pos())
def closeEvent(self, event):
if self._exiting:
event.accept()
else:
event.ignore()
self.exit_requested.emit()
def refresh_theme(self, theme):
self._theme = theme
self.drag_handle.setPixmap(themed_icon('fa6s.grip-vertical', theme).pixmap(14, 20))
self.start_button.setIcon(themed_icon('fa6s.play', theme))
for index, button in self.page_buttons.items():
button.setIcon(themed_icon(NAVIGATION[index][1], theme))
button.setIconSize(QSize(14, 14))
for index, action in self.page_actions.items():
action.setIcon(themed_icon(NAVIGATION[index][1], theme))
+9 -5
View File
@@ -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,16 +155,17 @@ 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,
QMessageBox.StandardButton.Cancel,
)
return answer is QMessageBox.StandardButton.Yes
return answer == QMessageBox.StandardButton.Yes
+29 -14
View File
@@ -16,6 +16,7 @@ from PySide6.QtWidgets import (
)
from dx_productivity.domain.models import HistoryEntry
from dx_productivity.ui.collapsible_section import CollapsibleSection
from dx_productivity.ui.theme import Theme, themed_icon
@@ -38,11 +39,12 @@ 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:
item.setEditable(False)
item.setToolTip(f"操作:{entry.run_id}\n设计:{entry.design_id}\n备份:{values[4]}")
self.model.appendRow(items)
if self._entries:
self.table.selectRow(0)
@@ -62,22 +64,15 @@ class HistoryPage(QWidget):
def _build_ui(self) -> None:
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 18, 20, 18)
layout.setSpacing(12)
layout.setContentsMargins(12, 10, 12, 10)
layout.setSpacing(8)
toolbar = QHBoxLayout()
title = QLabel("操作历史")
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)
)
self.restore_button.setEnabled(False)
self.restore_button.clicked.connect(self.restore_requested)
toolbar.addWidget(self.restore_button)
layout.addLayout(toolbar)
self.model = QStandardItemModel(0, 5, self)
self.model.setHorizontalHeaderLabels(
@@ -97,15 +92,35 @@ class HistoryPage(QWidget):
header.setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
header.setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents)
header.setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
header.setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)
header.setSectionResizeMode(4, QHeaderView.ResizeMode.Stretch)
header.setSectionResizeMode(3, QHeaderView.ResizeMode.Stretch)
self.table.setColumnHidden(4, True)
self.table.setMinimumHeight(160)
self.table.selectionModel().selectionChanged.connect(
self._update_restore_state
)
layout.addWidget(self.table, 1)
self.details_section = CollapsibleSection("所选操作详情")
self.details_label = QLabel("未选择操作")
self.details_label.setWordWrap(True)
self.details_label.setTextFormat(Qt.TextFormat.PlainText)
self.details_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
self.details_section.content_layout.addWidget(self.details_label)
layout.addWidget(self.details_section)
actions = QHBoxLayout()
actions.addStretch(1)
actions.addWidget(self.restore_button)
layout.addLayout(actions)
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)
if entry is None:
self.details_label.setText("未选择操作")
else:
backup = str(entry.backup_path) if entry.backup_path is not None else "无备份"
self.details_label.setText(f"操作:{entry.run_id}\n设计:{entry.design_id}\n备份:{backup}")
self.details_label.setToolTip(self.details_label.text())
def _state_text(state: str) -> str:
@@ -0,0 +1,95 @@
"""Follow only the native DxDesigner window that owns this bridge session."""
from __future__ import annotations
from dataclasses import dataclass
import json
import os
from pathlib import Path
from PySide6.QtCore import QObject, QTimer
@dataclass(frozen=True)
class HostWindow:
handle: int
pid: int
class WindowsHostWindows:
def resolve(self, view_handle: int) -> HostWindow | None:
if os.name != 'nt':
return None
import win32gui
import win32process
try:
# The 32-bit host can publish a signed HWND value.
view_handle &= 0xFFFFFFFF
if not win32gui.IsWindow(view_handle):
return None
handle = win32gui.GetAncestor(view_handle, 3) # GA_ROOTOWNER
if not handle or not win32gui.GetWindowText(handle).startswith('DxDesigner'):
return None
return HostWindow(handle, win32process.GetWindowThreadProcessId(handle)[1])
except win32gui.error:
return None
def is_minimized(self, host: HostWindow) -> bool | None:
import win32gui
import win32process
try:
if (not win32gui.IsWindow(host.handle)
or win32process.GetWindowThreadProcessId(host.handle)[1] != host.pid
or not win32gui.GetWindowText(host.handle).startswith('DxDesigner')):
return None
return bool(win32gui.IsIconic(host.handle))
except win32gui.error:
return None
class HostWindowWatcher(QObject):
def __init__(self, window, request_path: Path, *, backend=None) -> None:
super().__init__(window)
self.window = window
self.backend = backend if backend is not None else WindowsHostWindows()
self.selection_path = request_path.with_name('selection.json')
self.host = self._read_host(request_path)
self.timer = QTimer(self)
self.timer.setInterval(150)
self.timer.timeout.connect(self._check)
self.timer.start()
self._check()
def _read_host(self, path: Path):
try:
data = json.loads(path.read_text(encoding='utf-8-sig'))
except (OSError, ValueError):
return None
snapshot = self.window.refdes_controller.snapshot
if (snapshot is None or not isinstance(data, dict)
or data.get('run_id') != snapshot.run_id
or not isinstance(data.get('design_path'), str)
or os.path.normcase(os.path.normpath(data['design_path']))
!= os.path.normcase(os.path.normpath(snapshot.design_path))):
return None
handle = data.get('host_view_handle')
if type(handle) is not int or handle == 0:
return None
return self.backend.resolve(handle)
def _check(self) -> None:
if self.window._closing:
self.timer.stop()
return
if self.host is None:
self.host = self._read_host(self.selection_path)
if self.host is not None:
minimized = self.backend.is_minimized(self.host)
if minimized is None:
# The exact owning DX window disappeared. Close the tool via
# the normal shutdown path so controllers and listeners stop.
if self.window.request_exit():
self.timer.stop()
return
self.window.set_host_minimized(minimized)
@@ -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()
+75 -46
View File
@@ -6,7 +6,9 @@ from PySide6.QtCore import Signal
from PySide6.QtGui import QStandardItem, QStandardItemModel
from PySide6.QtWidgets import (
QCheckBox,
QComboBox,
QHBoxLayout,
QHeaderView,
QLabel,
QLineEdit,
QPushButton,
@@ -26,78 +28,102 @@ 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)
layout.setContentsMargins(20, 16, 20, 16)
layout.setSpacing(10)
layout.setContentsMargins(12, 10, 12, 10)
layout.setSpacing(8)
hint = QLabel(
"只读设计检查:孤立网络、网络列表、属性遗漏。"
"双击结果行可在原理图中定位。"
)
hint.setObjectName("secondaryLabel")
hint.setWordWrap(True)
layout.addWidget(hint)
buttons_row = QHBoxLayout()
self.solitary_button = QPushButton("孤立网络检查")
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,
):
buttons_row.addWidget(button)
controls = QHBoxLayout()
controls.addWidget(QLabel("查询类型" if self.network_only else "检查类型"))
self.check_type_combo = QComboBox()
self.check_type_combo.setAccessibleName("检查类型")
self.check_type_combo.addItem("孤立网络", "solitary")
self.check_type_combo.addItem("全部网络", "list")
if not self.network_only:
self.check_type_combo.addItem("Value 遗漏", "Value")
self.check_type_combo.addItem("Value1 遗漏", "Value1")
self.check_type_combo.addItem("跨页查询", "cross")
if self.network_only:
self.check_type_combo.setCurrentIndex(self.check_type_combo.findData("list"))
controls.addWidget(self.check_type_combo)
self.include_missing_checkbox = QCheckBox("属性缺失也算遗漏")
buttons_row.addWidget(self.include_missing_checkbox)
buttons_row.addStretch(1)
layout.addLayout(buttons_row)
search_row = QHBoxLayout()
search_row.addWidget(QLabel("跨页互动"))
controls.addWidget(self.include_missing_checkbox)
self.net_name_edit = QLineEdit()
self.net_name_edit.setPlaceholderText("输入网络名,查看其所有页分布")
search_row.addWidget(self.net_name_edit, 1)
self.cross_page_button = QPushButton("查询")
search_row.addWidget(self.cross_page_button)
layout.addLayout(search_row)
self.net_name_edit.setPlaceholderText("网络名")
self.net_name_edit.setToolTip("输入网络名,查询其所有页分布")
controls.addWidget(self.net_name_edit, 1)
controls.addStretch(1)
self.run_button = QPushButton("运行")
self.run_button.setAccessibleName("运行检查")
self.run_button.setObjectName("primaryButton")
self.run_button.clicked.connect(self._run_selected_check)
self.net_name_edit.returnPressed.connect(self._run_selected_check)
controls.addWidget(self.run_button)
layout.addLayout(controls)
self.model = QStandardItemModel(0, 4, self)
self.model.setHorizontalHeaderLabels(("检查项", "名称", "页号", "说明"))
self.table = QTableView()
self.table.setModel(self.model)
self.table.setMinimumHeight(380)
self.table.setMinimumHeight(160)
self.table.setEditTriggers(QTableView.EditTrigger.NoEditTriggers)
self.table.setToolTip("双击结果行可在原理图中定位")
self.table.setAlternatingRowColors(True)
self.table.verticalHeader().hide()
header = self.table.horizontalHeader()
header.setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
header.setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
header.setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
header.setSectionResizeMode(3, QHeaderView.ResizeMode.Stretch)
self.table.doubleClicked.connect(self._on_double_click)
layout.addWidget(self.table, 1)
self.summary_label = QLabel("")
self.summary_label.setObjectName("secondaryLabel")
self.summary_label.setWordWrap(True)
layout.addWidget(self.summary_label)
self.solitary_button.clicked.connect(self.solitary_requested)
self.net_list_button.clicked.connect(self.net_list_requested)
self.value_miss_button.clicked.connect(
lambda: self.value_miss_requested.emit("Value")
)
self.value1_miss_button.clicked.connect(
lambda: self.value_miss_requested.emit("Value1")
)
self.cross_page_button.clicked.connect(
lambda: self.cross_page_requested.emit(self.net_name_edit.text())
)
self.check_type_combo.currentIndexChanged.connect(self._update_check_fields)
self._update_check_fields()
def _update_check_fields(self) -> None:
kind = self.check_type_combo.currentData()
self.net_name_edit.setVisible(kind == "cross")
self.include_missing_checkbox.setVisible(kind in ("Value", "Value1"))
self.run_button.setText("查询" if kind == "cross" else "运行")
def _run_selected_check(self) -> None:
if not self.run_button.isEnabled():
return
kind = self.check_type_combo.currentData()
if kind == "solitary":
self.solitary_requested.emit()
elif kind == "list":
self.net_list_requested.emit()
elif kind in ("Value", "Value1"):
self.value_miss_requested.emit(kind)
elif kind == "cross":
self.cross_page_requested.emit(self.net_name_edit.text())
def include_missing(self) -> bool:
return self.include_missing_checkbox.isChecked()
def set_snapshot_available(self, available: bool) -> None:
for control in (
self.run_button, self.check_type_combo, 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):
@@ -122,8 +148,11 @@ class InspectionPage(QWidget):
page_item.setEditable(False)
detail_item = QStandardItem(row.detail)
detail_item.setEditable(False)
for item in (kind_item, name_item, page_item, detail_item):
item.setToolTip(item.text())
self.model.appendRow((kind_item, name_item, page_item, detail_item))
self.summary_label.setText(summary)
self.summary_label.setToolTip(summary)
def show_no_net_data(self) -> None:
self.set_rows(
@@ -0,0 +1,59 @@
"""Validated, independent storage for toolbar placement and page sizes."""
from __future__ import annotations
import json
import os
from pathlib import Path
import tempfile
from PySide6.QtCore import QPoint, QSize
class LayoutPreferences:
def __init__(self, path: Path | None = None) -> None:
self.path = path or Path(os.environ.get('LOCALAPPDATA', Path.home())) / 'DxProductivity' / 'ui-layout.json'
self.position: QPoint | None = None
self.page_sizes: dict[int, QSize] = {}
self.screen_name = ''
self.load()
def load(self) -> None:
try:
data = json.loads(self.path.read_text(encoding='utf-8'))
except (OSError, ValueError):
return
if not isinstance(data, dict):
return
position = data.get('toolbar_position')
if self._pair(position) and all(abs(n) <= 100000 for n in position):
self.position = QPoint(*position)
screen = data.get('screen')
if isinstance(screen, str):
self.screen_name = screen
sizes = data.get('page_sizes')
if isinstance(sizes, dict):
for index, size in sizes.items():
if isinstance(index, str) and index in tuple(str(i) for i in range(9)) and self._pair(size) and all(100 <= n <= 10000 for n in size):
self.page_sizes[int(index)] = QSize(*size)
@staticmethod
def _pair(value) -> bool:
return isinstance(value, list) and len(value) == 2 and all(type(n) is int for n in value)
def save(self) -> None:
data = {'version': 1, 'toolbar_position': [self.position.x(), self.position.y()] if self.position is not None else None,
'screen': self.screen_name,
'page_sizes': {str(index): [size.width(), size.height()] for index, size in self.page_sizes.items()}}
temporary = None
try:
self.path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=self.path.parent, suffix='.tmp', delete=False) as stream:
temporary = Path(stream.name)
json.dump(data, stream, ensure_ascii=False, indent=2)
temporary.replace(self.path)
except OSError:
# Placement is optional; a read-only user directory must not block UI.
pass
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
+343 -188
View File
@@ -1,217 +1,386 @@
"""Shared productivity-suite window shell."""
"""Shared compact feature panel coordinated with a persistent toolbar."""
from __future__ import annotations
from PySide6.QtCore import QSize, Qt, Signal
from PySide6.QtWidgets import (
QFrame,
QHBoxLayout,
QLabel,
QListWidget,
QListWidgetItem,
QMainWindow,
QPushButton,
QApplication,
QStackedWidget,
QToolButton,
QVBoxLayout,
QWidget,
)
from PySide6.QtCore import QEvent, QPoint, QSize, QTimer, Qt, Signal
from PySide6.QtWidgets import QApplication, QFrame, QHBoxLayout, QLabel, QMainWindow, QPushButton, QSizePolicy, QStackedWidget, QVBoxLayout, QWidget
from dx_productivity import __version__
from dx_productivity.ui.theme import Theme, apply_theme, themed_icon, theme_tokens
NAVIGATION = (
("自动位号", "fa6s.hashtag"),
("属性批改", "fa6s.pen"),
("属性显示", "fa6s.tag"),
("设计检查", "fa6s.clipboard-check"),
("网络工具", "fa6s.share-nodes"),
("BOM 工具", "fa6s.table"),
("操作历史", "fa6s.clock-rotate-left"),
("设置", "fa6s.gear"),
)
from dx_productivity.ui.floating_toolbar import FloatingToolbar, NAVIGATION
from dx_productivity.ui.layout_preferences import LayoutPreferences
from dx_productivity.ui.theme import Theme, apply_theme
class MainWindow(QMainWindow):
start_requested = Signal()
refresh_requested = Signal()
preview_requested = Signal()
apply_requested = Signal()
page_changed = Signal(int)
window_closed = Signal()
def __init__(self, *, theme: Theme = Theme.LIGHT) -> None:
def __init__(self, *, theme: Theme = Theme.LIGHT, layout_path=None) -> None:
super().__init__()
# The expanded view is an attached tool card below the toolbar. Keep
# the shared page window out of the taskbar and remove the native app
# title bar so it reads as one floating tool surface.
self.setWindowFlags(
Qt.WindowType.Tool
| Qt.WindowType.FramelessWindowHint
| Qt.WindowType.WindowStaysOnTopHint
)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self._closing = False
self._host_minimized = False
self._host_restore_toolbar = False
self._host_restore_panel = False
self._placing = False
self._effective_page_size = None
self._active_page = 0
self._toolbar_positioned = False
self._operation_text = '就绪'
self.layout_preferences = LayoutPreferences(layout_path)
self.theme = theme
self.setWindowTitle("一叶知秋_重构版")
self.setMinimumSize(1100, 700)
self.resize(1240, 780)
self.setWindowTitle('一叶知秋_重构版')
self.toolbar = FloatingToolbar()
self.start_button = self.toolbar.start_button
self.theme_action = self.toolbar.theme_action
self.toolbar.page_requested.connect(self._page_requested)
self.toolbar.start_requested.connect(self.start_requested)
self.toolbar.refresh_requested.connect(self.refresh_requested)
self.toolbar.theme_requested.connect(self._toggle_theme)
self.toolbar.toggle_panel_requested.connect(self._toggle_panel)
self.toolbar.exit_requested.connect(self.request_exit)
self.toolbar.position_changed.connect(self._toolbar_moved)
self._build_ui()
self._refresh_icons()
self._set_page_size(0)
application = QApplication.instance()
if application is not None:
apply_theme(application, self.theme)
application.screenAdded.connect(self._screen_added)
application.screenRemoved.connect(self._screens_changed)
for screen in application.screens():
self._screen_added(screen)
self._refresh_icons()
self._sync_status()
self._operation_timer = QTimer(self)
self._operation_timer.setInterval(150)
self._operation_timer.timeout.connect(self._sync_status)
self._operation_timer.start()
def navigation_items(self) -> list[str]:
return [self.navigation.item(index).text() for index in range(self.navigation.count())]
return [text for text, _ in NAVIGATION]
def set_page(self, index: int, widget: QWidget, title: str) -> None:
previous = self.pages.widget(index)
self.pages.removeWidget(previous)
previous.deleteLater()
self.pages.insertWidget(index, widget)
self.pages.setCurrentIndex(index)
self.page_title.setText(title)
self.pages.setCurrentIndex(self._active_page)
if index == 0 and hasattr(widget, 'apply_button'):
self.apply_button = widget.apply_button
self.preview_button = widget.preview_button
def set_active_page(self, index: int) -> None:
if 0 <= index < self.pages.count():
self.navigation.setCurrentRow(index)
if not 0 <= index < self.pages.count():
return
if index != self._active_page:
self._remember_size()
self._active_page = index
self.pages.setCurrentIndex(index)
self.page_title.setText(NAVIGATION[index][0])
self._set_page_size(index)
self.page_changed.emit(index)
self.page_title.setText(NAVIGATION[index][0])
self.toolbar.set_panel_state(index, self.isVisible())
if self.isVisible():
self._anchor_panel()
def closeEvent(self, event) -> None:
for controller in (
getattr(self, "settings_controller", None),
getattr(self, "refdes_controller", None),
getattr(self, "history_controller", None),
):
shutdown = getattr(controller, "shutdown", None)
def show_toolbar(self) -> None:
if self._closing:
return
if self._host_minimized:
self._host_restore_toolbar = True
return
if not self._toolbar_positioned:
screen = self.toolbar.screen() or QApplication.primaryScreen()
position = self.layout_preferences.position
if position is None and screen is not None:
bounds = screen.availableGeometry()
position = QPoint(bounds.left() + 24, bounds.top() + 24)
self.toolbar.move_within_screen(position or QPoint(24, 24))
self._toolbar_positioned = True
else:
self.toolbar.move_within_screen(self.toolbar.pos())
self.toolbar.show()
def show_panel(self, index: int | None = None) -> None:
if self._closing:
return
if self._host_minimized:
self.set_active_page(self._active_page if index is None else index)
self._host_restore_toolbar = True
self._host_restore_panel = True
return
self.show_toolbar()
self.set_active_page(self._active_page if index is None else index)
self._anchor_panel()
self.showNormal()
self._anchor_panel()
self.toolbar.set_panel_state(self._active_page, True)
self.raise_()
self.activateWindow()
def hide_panel(self) -> None:
if self._closing:
return
if self._host_minimized:
self._host_restore_panel = False
return
self._remember_size()
self.hide()
self.show_toolbar()
self.toolbar.set_panel_state(self._active_page, False)
def set_host_minimized(self, minimized: bool) -> None:
"""Temporarily hide tool surfaces without changing their working state."""
if self._closing or self._host_minimized == minimized:
return
self._host_minimized = minimized
if minimized:
self._host_restore_toolbar = self.toolbar.isVisible()
self._host_restore_panel = self.isVisible()
self._remember_size()
self.toolbar.more_menu.close()
self.hide()
self.toolbar.hide()
return
if self._host_restore_toolbar:
self.show_toolbar()
if self._host_restore_panel:
# Restore passively; explicit user clicks still use show_panel().
passive = self.testAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, True)
self._anchor_panel()
self.showNormal()
self._anchor_panel()
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, passive)
self._host_restore_toolbar = False
self._host_restore_panel = False
collapse_to_floating = hide_panel
restore_from_floating = show_panel
def _page_requested(self, index: int) -> None:
if self.isVisible() and index == self._active_page:
self.hide_panel()
else:
self.show_panel(index)
def _toggle_panel(self) -> None:
self.hide_panel() if self.isVisible() else self.show_panel()
def request_exit(self) -> bool:
if self._closing:
return True
startup = getattr(self, 'startup_controller', None)
if startup is not None and startup.is_running():
self.set_operation_status('正在完成菜单注册,请稍候再关闭')
return False
self._remember_size()
self._closing = True
for timer in self.findChildren(QTimer):
timer.stop()
for name in ('settings_controller', 'refdes_controller', 'property_change_controller',
'property_visibility_controller', 'inspection_controller', 'network_controller',
'bom_controller', 'history_controller', 'pdf_export_controller'):
shutdown = getattr(getattr(self, name, None), 'shutdown', None)
if callable(shutdown):
shutdown()
super().closeEvent(event)
self.toolbar._exiting = True
self.toolbar.close()
self.close()
self.window_closed.emit()
return True
def closeEvent(self, event) -> None:
if self._closing:
super().closeEvent(event)
else:
event.ignore()
self.hide_panel()
def showEvent(self, event) -> None:
super().showEvent(event)
if not self._closing:
self.show_toolbar()
self.toolbar.set_panel_state(self._active_page, True)
def changeEvent(self, event) -> None:
super().changeEvent(event)
if event.type() == QEvent.Type.WindowStateChange and self.isMinimized() and not self._closing:
QTimer.singleShot(0, self.hide_panel)
def resizeEvent(self, event) -> None:
super().resizeEvent(event)
if hasattr(self, 'layout_preferences') and self.isVisible() and not self._placing and not self.isMinimized():
if self.size() != self._effective_page_size:
# Internal placement sets its expected size before resizing.
# A different resize is a new user preference, including an
# external resize() call used by window-management clients.
self._effective_page_size = self.size()
self.layout_preferences.page_sizes[self._active_page] = self.size()
self.layout_preferences.save()
def _remember_size(self) -> None:
if self.isVisible() and not self._placing and not self.isMinimized():
self.layout_preferences.save()
def _preferred_page_size(self, index: int) -> QSize:
return self.layout_preferences.page_sizes.get(index, QSize(660, 390) if index in (7, 8) else QSize(780, 480))
def _set_page_size(self, index: int) -> None:
self._placing = True
compact = index in (7, 8)
self.setMinimumSize(660 if compact else 720, 340 if compact else 420)
self._effective_page_size = self._preferred_page_size(index)
self.resize(self._effective_page_size)
self._placing = False
def _toolbar_moved(self, position: QPoint) -> None:
self.layout_preferences.position = position
screen = QApplication.screenAt(self.toolbar.frameGeometry().center()) or self.toolbar.screen()
if screen is not None:
self.layout_preferences.screen_name = screen.name()
self.layout_preferences.save()
if self.isVisible():
self._anchor_panel()
def _screen_added(self, screen) -> None:
screen.availableGeometryChanged.connect(self._screens_changed)
if self.toolbar.isVisible():
self._screens_changed()
def _screens_changed(self, *_args) -> None:
if self._closing:
return
if self.toolbar.isVisible():
self.toolbar.move_within_screen(self.toolbar.pos())
if self.isVisible():
self._anchor_panel()
def _anchor_panel(self) -> None:
screen = QApplication.screenAt(self.toolbar.frameGeometry().center()) or self.toolbar.screen()
if screen is None:
return
bounds = screen.availableGeometry()
self._placing = True
frame_extra = self.frameGeometry().size() - self.size()
max_width = max(1, bounds.width() - max(0, frame_extra.width()))
max_height = max(1, bounds.height() - max(0, frame_extra.height()))
compact = self._active_page in (7, 8)
self.setMinimumSize(min(660 if compact else 720, max_width), min(340 if compact else 420, max_height))
preferred = self._preferred_page_size(self._active_page)
self._effective_page_size = QSize(min(preferred.width(), max_width), min(preferred.height(), max_height))
self.resize(self._effective_page_size)
toolbar_rect = self.toolbar.frameGeometry()
height = self.frameGeometry().height()
below = toolbar_rect.bottom() + 6
y = below if below + height <= bounds.bottom() + 1 else toolbar_rect.top() - height - 6
y = max(bounds.top(), min(y, bounds.bottom() - height + 1))
x = max(bounds.left(), min(toolbar_rect.left(), bounds.right() - self.frameGeometry().width() + 1))
self.move(x, y)
self._placing = False
def _build_ui(self) -> None:
root = QWidget()
root.setObjectName("appRoot")
root_layout = QVBoxLayout(root)
root_layout.setContentsMargins(0, 0, 0, 0)
root_layout.setSpacing(0)
root_layout.addWidget(self._build_title_bar())
body = QWidget()
body_layout = QHBoxLayout(body)
body_layout.setContentsMargins(0, 0, 0, 0)
body_layout.setSpacing(0)
body_layout.addWidget(self._build_navigation())
body_layout.addWidget(self._build_content(), 1)
root_layout.addWidget(body, 1)
root_layout.addWidget(self._build_status_strip())
self.setCentralWidget(root)
def _build_title_bar(self) -> QFrame:
bar = QFrame()
bar.setObjectName("titleBar")
bar.setFixedHeight(52)
layout = QHBoxLayout(bar)
layout.setContentsMargins(18, 0, 14, 0)
layout.setSpacing(10)
brand = QLabel("一叶知秋_重构版")
self.brand_label = brand
brand.setObjectName("brandLabel")
layout.addWidget(brand)
self.project_label = QLabel("未连接设计")
self.project_label.setObjectName("projectLabel")
layout.addWidget(self.project_label)
layout.addStretch(1)
self.theme_button = self._tool_button("切换明暗主题")
self.theme_button.clicked.connect(self._toggle_theme)
layout.addWidget(self.theme_button)
self.refresh_button = self._tool_button("刷新设计快照")
self.refresh_button.clicked.connect(self.refresh_requested)
layout.addWidget(self.refresh_button)
self.preview_button = self._tool_button("生成预览")
self.preview_button.clicked.connect(self.preview_requested)
layout.addWidget(self.preview_button)
self.apply_button = QPushButton("应用位号")
self.apply_button.setObjectName("primaryButton")
self.apply_button.setMinimumWidth(112)
self.apply_button.setEnabled(False)
self.apply_button.clicked.connect(self.apply_requested)
layout.addWidget(self.apply_button)
return bar
def _build_navigation(self) -> QFrame:
rail = QFrame()
rail.setObjectName("navigationRail")
rail.setFixedWidth(218)
layout = QVBoxLayout(rail)
layout.setContentsMargins(8, 10, 8, 10)
layout.setSpacing(6)
section = QLabel("工作台")
section.setObjectName("secondaryLabel")
layout.addWidget(section)
self.navigation = QListWidget()
self.navigation.setObjectName("navigationList")
self.navigation.setIconSize(QSize(16, 16))
self.navigation.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
for text, _ in NAVIGATION:
self.navigation.addItem(QListWidgetItem(text))
self.navigation.setCurrentRow(0)
self.navigation.currentRowChanged.connect(self._select_page)
layout.addWidget(self.navigation, 1)
version = QLabel(f"DxDesigner 7.9.5 · v{__version__}")
version.setObjectName("secondaryLabel")
layout.addWidget(version)
return rail
def _build_content(self) -> QWidget:
content = QWidget()
layout = QVBoxLayout(content)
root.setObjectName('appRoot')
layout = QVBoxLayout(root)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
header = QFrame()
header.setObjectName("contentHeader")
header.setFixedHeight(58)
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(20, 0, 20, 0)
header.setObjectName('contentHeader')
header.setFixedHeight(34)
row = QHBoxLayout(header)
row.setContentsMargins(10, 0, 8, 0)
self.page_title = QLabel(NAVIGATION[0][0])
self.page_title.setObjectName("pageTitle")
header_layout.addWidget(self.page_title)
header_layout.addStretch(1)
self.page_title.setObjectName('pageTitle')
row.addWidget(self.page_title)
self.project_label = QLabel('未连接设计')
self.project_label.setObjectName('projectLabel')
self.project_label.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
row.addWidget(self.project_label, 1)
self.collapse_button = QPushButton('收起')
self.collapse_button.setAccessibleName('收起面板')
self.collapse_button.setToolTip('收起到工具栏;后台任务继续运行')
self.collapse_button.clicked.connect(self.hide_panel)
row.addWidget(self.collapse_button)
layout.addWidget(header)
self.pages = QStackedWidget()
for text, _ in NAVIGATION:
placeholder = QLabel(text)
placeholder.setAlignment(Qt.AlignmentFlag.AlignCenter)
placeholder.setObjectName("secondaryLabel")
self.pages.addWidget(placeholder)
for title, _ in NAVIGATION:
self.pages.addWidget(QLabel(title))
layout.addWidget(self.pages, 1)
return content
def _build_status_strip(self) -> QFrame:
strip = QFrame()
strip.setObjectName("statusStrip")
strip.setFixedHeight(32)
layout = QHBoxLayout(strip)
layout.setContentsMargins(14, 0, 14, 0)
self.bridge_status = QLabel("桥接待连接")
self.bridge_status.setObjectName("secondaryLabel")
layout.addWidget(self.bridge_status)
layout.addStretch(1)
self.operation_status = QLabel("就绪")
self.operation_status.setObjectName("secondaryLabel")
layout.addWidget(self.operation_status)
return strip
strip.setObjectName('statusStrip')
strip.setFixedHeight(26)
row = QHBoxLayout(strip)
row.setContentsMargins(10, 0, 10, 0)
self.bridge_status = QLabel('桥接待连接')
self.selection_status = QLabel('选择同步等待宿主')
self.operation_status = QLabel('就绪')
for label in (self.bridge_status, self.selection_status, self.operation_status):
label.setObjectName('secondaryLabel')
label.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
row.addWidget(label, 1)
layout.addWidget(strip)
self.setCentralWidget(root)
def _tool_button(self, label: str) -> QToolButton:
button = QToolButton()
button.setAccessibleName(label)
button.setToolTip(label)
button.setIconSize(QSize(16, 16))
button.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
return button
def set_project_status(self, name: str, path: str) -> None:
previous_path = self.project_label.toolTip()
self.project_label.setText(name)
self.project_label.setToolTip(path)
if previous_path and previous_path != path:
self.set_selection_status('等待当前工程选择同步')
self._sync_status()
def _select_page(self, index: int) -> None:
if index < 0:
return
self.pages.setCurrentIndex(index)
self.page_title.setText(NAVIGATION[index][0])
self.page_changed.emit(index)
def set_bridge_status(self, text: str) -> None:
self.bridge_status.setText(text)
if '断开' in text and self.selection_status.text().startswith('已选'):
self.set_selection_status('选择同步已暂停', '桥接断开,等待宿主重新连接。')
self._sync_status()
def set_selection_status(self, text: str, detail: str = '') -> None:
self.selection_status.setText(text)
self.selection_status.setToolTip(detail)
self._sync_status()
def set_operation_status(self, text: str) -> None:
self._operation_text = text
self.operation_status.setText(text)
self.operation_status.setToolTip(text)
self._sync_status()
def _sync_status(self) -> None:
bridge, selection = self.bridge_status.text(), self.selection_status.text()
operation = self._active_operation() or self._operation_text
self.operation_status.setText(operation)
self.operation_status.setToolTip(operation)
busy = any(word in operation for word in ('导出中', '导出…', '正在', '应用中', '恢复中', '处理中'))
stale = any(word in selection for word in ('暂停', '切换', '未打开', '断开'))
text = '● ' + selection if stale else ('● ' + operation if busy else ('● ' + selection if bridge == '桥接已连接' else '○ ' + bridge))
detail = f'{bridge}\n工程:{self.project_label.text()}\n{self.project_label.toolTip()}\n{selection}\n{self.selection_status.toolTip()}\n任务:{operation}'
self.toolbar.set_status(text, detail)
def _active_operation(self) -> str:
pdf = getattr(self, 'pdf_export_controller', None)
thread = getattr(pdf, '_thread', None)
if thread is not None and thread.isRunning():
return 'PDF 导出中'
for name, text, flag in (('refdes_controller', '位号应用中', '_apply_in_flight'),
('property_change_controller', '属性应用中', '_apply_in_flight'),
('property_visibility_controller', '显示状态应用中', '_apply_in_flight'),
('history_controller', '位号恢复中', '_restore_in_flight'),
('bom_controller', 'BOM 导出中', '_export_in_flight')):
if getattr(getattr(self, name, None), flag, False):
return text
return ''
def _toggle_theme(self) -> None:
self.theme = Theme.DARK if self.theme is Theme.LIGHT else Theme.LIGHT
@@ -221,22 +390,8 @@ class MainWindow(QMainWindow):
self._refresh_icons()
def _refresh_icons(self) -> None:
tokens = theme_tokens(self.theme)
self.theme_button.setIcon(
themed_icon(
"fa6s.sun" if self.theme is Theme.DARK else "fa6s.moon",
self.theme,
)
)
self.refresh_button.setIcon(themed_icon("fa6s.arrows-rotate", self.theme))
self.preview_button.setIcon(themed_icon("fa6s.eye", self.theme))
self.apply_button.setIcon(
themed_icon("fa6s.check", self.theme, color=tokens.accent_text)
)
for index, (_, icon_name) in enumerate(NAVIGATION):
self.navigation.item(index).setIcon(themed_icon(icon_name, self.theme))
self.toolbar.refresh_theme(self.theme)
for index in range(self.pages.count()):
page = self.pages.widget(index)
refresh_icons = getattr(page, "refresh_icons", None)
if refresh_icons is not None:
refresh_icons(self.theme)
refresh = getattr(self.pages.widget(index), 'refresh_icons', None)
if callable(refresh):
refresh(self.theme)
@@ -0,0 +1,199 @@
from __future__ import annotations
import threading
from pathlib import Path
from PySide6.QtCore import QObject, QThread, Signal, Slot
from dx_productivity.domain.models import DesignSnapshot
from dx_productivity.features.pdf_export.exporter import export_project, output_path
from dx_productivity.features.pdf_export.listener import ensure_listener
from dx_productivity.features.pdf_export.models import (
ExportScope,
PdfExportResult,
PdfExportSettings,
)
from dx_productivity.features.pdf_export.settings import (
load_settings,
save_settings,
settings_path,
)
from dx_productivity.ui.pdf_export_page import PdfExportPage
class _ExportWorker(QObject):
finished = Signal(object)
progress = Signal(str)
def __init__(
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
@Slot()
def run(self) -> None:
result = export_project(
self.settings,
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)
class PdfExportController(QObject):
status_changed = Signal(str)
def __init__(self, page: PdfExportPage, *, tool_root: Path) -> None:
super().__init__(page)
self.page = page
self.tool_root = Path(tool_root)
self.config_path = settings_path()
self.snapshot: DesignSnapshot | None = None
self._thread: QThread | None = None
self._worker: _ExportWorker | None = None
self._cancel: threading.Event | None = None
page.settings_changed.connect(self._save_settings)
page.export_requested.connect(self.export)
page.cancel_requested.connect(self.cancel)
def load_snapshot(self, snapshot: DesignSnapshot) -> None:
self.snapshot = snapshot
settings = load_settings(
snapshot.design_path,
config_path=self.config_path,
)
self.page.bind(snapshot, settings)
effective_settings = self.page.settings()
if effective_settings is not None and settings.auto_export and not effective_settings.auto_export:
try:
save_settings(effective_settings, config_path=self.config_path)
except OSError as error:
self.page.set_status(f"无法保存 PDF 设置:{error}")
if effective_settings is not None and effective_settings.auto_export:
self._ensure_listener()
def _save_settings(self, settings: PdfExportSettings) -> None:
if self.snapshot is None:
return
try:
save_settings(settings, config_path=self.config_path)
except OSError as error:
self.page.set_status(f"无法保存 PDF 设置:{error}")
return
if settings.auto_export:
self._ensure_listener()
return
self.status_changed.emit("保存后自动导出已关闭")
def load_selection_snapshot(self, snapshot: DesignSnapshot) -> None:
self.snapshot = snapshot
self.page.snapshot = snapshot
self.page._loading = True
try:
self.page._scope_changed()
busy = self._thread is not None and self._thread.isRunning()
self.page.set_busy(busy)
finally:
self.page._loading = False
def _ensure_listener(self) -> None:
result = ensure_listener(self.config_path, self.tool_root)
if result:
self.status_changed.emit(result)
self.page.set_status(result)
else:
self.status_changed.emit("保存后自动导出已开启")
self.page.set_status("自动导出已启用,正在连接当前工程的保存事件")
def export(self) -> None:
if self.snapshot is None:
self.page.set_status("未连接 DxDesigner 工程")
return
if self._thread is not None and self._thread.isRunning():
return
settings = self.page.settings()
if settings is None:
return
if not str(settings.output_dir).strip():
self.page.set_status("请选择 PDF 输出目录")
return
if settings.scope is not ExportScope.PROJECT and not settings.block_name.strip():
self.page.set_status("当前范围没有可用的 Block 名称")
return
try:
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
overwrite = False
if target.exists():
if not self.page.confirm_overwrite(str(target)):
self.page.set_status("已取消导出")
return
overwrite = True
self._save_settings(settings)
self._cancel = threading.Event()
self._thread = QThread(self)
self._worker = _ExportWorker(
settings,
self.snapshot.active_block_name,
self.snapshot.current_sheet_name,
overwrite,
self._cancel,
)
self._worker.moveToThread(self._thread)
self._thread.started.connect(self._worker.run)
self._worker.progress.connect(self._set_status)
self._worker.finished.connect(self._on_finished)
self._worker.finished.connect(self._thread.quit)
self._worker.finished.connect(self._worker.deleteLater)
self._thread.finished.connect(self._finish_thread)
self._thread.finished.connect(self._thread.deleteLater)
self.page.set_busy(True)
self._set_status("正在调用原生 PDF 引擎…")
self._thread.start()
@Slot(object)
def _on_finished(self, result: PdfExportResult) -> None:
self._set_status(result.message)
self.page.set_busy(False)
self.page.set_can_export(self.snapshot is not None)
@Slot()
def _finish_thread(self) -> None:
self._thread = None
self._worker = None
self._cancel = None
def cancel(self) -> None:
if self._cancel is not None:
self._cancel.set()
self._set_status("正在取消导出…")
@Slot(str)
def _set_status(self, message: str) -> None:
self.page.set_status(message)
self.status_changed.emit(message)
def shutdown(self) -> None:
self.cancel()
if self._thread is not None and self._thread.isRunning():
self._thread.quit()
self._thread.wait()
+353
View File
@@ -0,0 +1,353 @@
from __future__ import annotations
from pathlib import Path
from PySide6.QtCore import QSize, Qt, QUrl, Signal
from PySide6.QtGui import QDesktopServices
from PySide6.QtWidgets import (
QCheckBox,
QComboBox,
QFileDialog,
QFormLayout,
QFrame,
QHBoxLayout,
QLabel,
QLineEdit,
QMessageBox,
QPushButton,
QScrollArea,
QVBoxLayout,
QWidget,
)
from dx_productivity.domain.models import DesignSnapshot
from dx_productivity.features.pdf_export.models import ExportScope, PdfExportSettings
from dx_productivity.ui.collapsible_section import CollapsibleSection
from dx_productivity.ui.theme import Theme, themed_icon
class PdfExportPage(QWidget):
settings_changed = Signal(object)
export_requested = Signal()
cancel_requested = Signal()
def __init__(self) -> None:
super().__init__()
self.snapshot: DesignSnapshot | None = None
self._loading = False
self._busy = False
self._theme = Theme.LIGHT
self._build_ui()
self._scope_changed()
def _build_ui(self) -> None:
layout = QVBoxLayout(self)
layout.setContentsMargins(10, 8, 10, 8)
layout.setSpacing(6)
parameters = QWidget()
parameter_layout = QVBoxLayout(parameters)
parameter_layout.setContentsMargins(0, 0, 0, 0)
parameter_layout.setSpacing(6)
self.parameters_scroll = QScrollArea()
self.parameters_scroll.setWidgetResizable(True)
self.parameters_scroll.setFrameShape(QFrame.Shape.NoFrame)
self.parameters_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.parameters_scroll.setWidget(parameters)
layout.addWidget(self.parameters_scroll, 1)
form = QFormLayout()
form.setHorizontalSpacing(14)
form.setVerticalSpacing(6)
self.project_input = QLineEdit()
self.project_input.setReadOnly(True)
self.project_input.setAccessibleName("当前工程")
self.project_input.setPlaceholderText("未连接 DxDesigner 工程")
form.addRow("当前工程", self.project_input)
self.scope_combo = QComboBox()
self.scope_combo.setAccessibleName("导出范围")
self.scope_combo.addItem("整工程", ExportScope.PROJECT.value)
self.scope_combo.addItem("当前页", ExportScope.CURRENT_PAGE.value)
self.scope_combo.addItem("指定原理图或 Block", ExportScope.BLOCK.value)
form.addRow("导出范围", self.scope_combo)
self.block_input = QLineEdit()
self.block_input.setAccessibleName("指定 Block")
self.block_input.setPlaceholderText("DxDesigner 原理图或 Block 名称")
form.addRow("Block", self.block_input)
self._block_row = form.rowCount() - 1
self.active_block_label = QLabel("")
self.active_block_label.setWordWrap(True)
self.active_block_label.setObjectName("secondaryLabel")
form.addRow("当前页", self.active_block_label)
self._active_row = form.rowCount() - 1
self._scope_form = form
self.advanced_section = CollapsibleSection("高级选项")
advanced_form = QFormLayout()
advanced_form.setHorizontalSpacing(14)
advanced_form.setVerticalSpacing(6)
self.advanced_section.content_layout.addLayout(advanced_form)
self.palette_combo = QComboBox()
self.palette_combo.setAccessibleName("PDF 配色")
self.palette_combo.addItem("工程参考配色(mentor_PDF_output)", "reference")
self.palette_combo.addItem("原生配色", "original")
advanced_form.addRow("PDF 配色", self.palette_combo)
self.text_combo = QComboBox()
self.text_combo.setAccessibleName("文字处理")
self.text_combo.addItem("中文兼容(GBK,推荐)", "chinese")
self.text_combo.addItem("西文兼容(保留西文符号)", "western")
self.text_combo.addItem("原生字体(不修复编码)", "original")
self.text_combo.setToolTip("中文兼容用于 GBK 中文工程;西文兼容保留 WinAnsi 工程符号。兼容模式会嵌入字体,便于分享和搜索。")
advanced_form.addRow("文字处理", self.text_combo)
output_row = QHBoxLayout()
self.output_input = QLineEdit()
self.output_input.setAccessibleName("PDF 输出目录")
self.output_button = QPushButton("浏览…")
self.output_button.setIconSize(QSize(16, 16))
self.output_button.clicked.connect(self._choose_output)
self.open_output_button = QPushButton("打开输出目录")
self.open_output_button.setAccessibleName("打开输出目录")
self.open_output_button.setIconSize(QSize(16, 16))
self.open_output_button.setEnabled(False)
self.open_output_button.clicked.connect(self._open_output)
output_row.addWidget(self.output_input, 1)
output_row.addWidget(self.output_button)
output_row.addWidget(self.open_output_button)
self.output_input.textChanged.connect(
lambda value: self.open_output_button.setEnabled(bool(value.strip()))
)
form.addRow("输出目录", output_row)
engine_row = QHBoxLayout()
self.engine_input = QLineEdit()
self.engine_input.setAccessibleName("原生引擎")
self.engine_input.setPlaceholderText("自动发现本机 sch2pdf.exe")
self.engine_button = QPushButton("浏览…")
self.engine_button.setIconSize(QSize(16, 16))
self.engine_button.clicked.connect(self._choose_engine)
engine_row.addWidget(self.engine_input, 1)
engine_row.addWidget(self.engine_button)
advanced_form.addRow("原生引擎", engine_row)
parameter_layout.addLayout(form)
self.auto_export_checkbox = QCheckBox("保存工程后自动导出")
self.auto_export_checkbox.setToolTip("EE 工程使用即时保存:原生设计变更稳定后导出;传统工程在保存完成后导出。")
self.auto_export_checkbox.setEnabled(False)
parameter_layout.addWidget(self.auto_export_checkbox)
parameter_layout.addWidget(self.advanced_section)
parameter_layout.addStretch(1)
self.status_label = QLabel("未连接工程")
self.status_label.setWordWrap(True)
layout.addWidget(self.status_label)
actions = QHBoxLayout()
actions.addStretch(1)
self.cancel_button = QPushButton("取消导出")
self.cancel_button.clicked.connect(self.cancel_requested)
self.cancel_button.setEnabled(False)
self.export_button = QPushButton("导出 PDF")
self.export_button.setAccessibleName("导出 PDF")
self.export_button.setToolTip("原生出图直接读取当前工程;DxDesigner 可能更新数据库或运行记录。")
self.export_button.setObjectName("primaryButton")
self.export_button.clicked.connect(self.export_requested)
self.export_button.setEnabled(False)
actions.addWidget(self.cancel_button)
actions.addWidget(self.export_button)
layout.addLayout(actions)
self.scope_combo.currentIndexChanged.connect(self._scope_changed)
self.palette_combo.currentIndexChanged.connect(self._emit_settings)
self.text_combo.currentIndexChanged.connect(self._emit_settings)
self.block_input.editingFinished.connect(self._emit_settings)
self.output_input.editingFinished.connect(self._emit_settings)
self.engine_input.editingFinished.connect(self._emit_settings)
self.auto_export_checkbox.toggled.connect(self._emit_settings)
for control in (
self.scope_combo, self.palette_combo, self.text_combo,
self.block_input, self.output_input, self.output_button,
self.open_output_button, self.engine_input, self.engine_button,
self.auto_export_checkbox, self.export_button, self.cancel_button,
self.advanced_section.toggle_button,
):
control.setMinimumHeight(28)
def bind(self, snapshot: DesignSnapshot | None, settings: PdfExportSettings) -> None:
self._loading = True
self.snapshot = snapshot
self.project_input.setText(Path(snapshot.design_path).name if snapshot else "")
self.project_input.setToolTip(snapshot.design_path if snapshot else "")
scope_index = self.scope_combo.findData(settings.scope.value)
self.scope_combo.setCurrentIndex(max(scope_index, 0))
self.palette_combo.setCurrentIndex(max(self.palette_combo.findData(settings.print_theme), 0))
self.text_combo.setCurrentIndex(max(self.text_combo.findData(settings.text_mode), 0))
self.block_input.setText(
settings.block_name
if settings.scope is ExportScope.BLOCK
else (snapshot.active_block_name if snapshot else "")
)
self.output_input.setText(str(settings.output_dir))
self.engine_input.setText(str(settings.engine_path or ""))
self.auto_export_checkbox.setChecked(settings.auto_export)
project_ready = bool(snapshot and Path(snapshot.design_path).suffix.casefold() == ".prj")
self.auto_export_checkbox.setEnabled(project_ready)
self.status_label.setText("就绪" if snapshot else "未连接 DxDesigner 工程")
self._scope_changed()
self._update_advanced_summary()
self._loading = False
self.set_can_export(project_ready)
def settings(self) -> PdfExportSettings | None:
if self.snapshot is None:
return None
output_value = self.output_input.text().strip()
if not output_value:
return None
scope = ExportScope(self.scope_combo.currentData())
engine_value = self.engine_input.text().strip()
block_name = self.block_input.text().strip()
if scope is ExportScope.PROJECT:
block_name = ""
elif scope is ExportScope.CURRENT_PAGE:
block_name = self.snapshot.active_block_name.strip()
return PdfExportSettings(
project_path=Path(self.snapshot.design_path),
scope=scope,
block_name=block_name,
output_dir=Path(output_value),
auto_export=self.auto_export_checkbox.isChecked(),
engine_path=Path(engine_value) if engine_value else None,
print_theme=self.palette_combo.currentData(),
text_mode=self.text_combo.currentData(),
)
def confirm_overwrite(self, path: str) -> bool:
answer = QMessageBox.question(
self,
"覆盖现有 PDF",
f"下列文件已存在,是否替换?\n{path}",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No,
)
return answer == QMessageBox.StandardButton.Yes
def set_can_export(self, enabled: bool) -> None:
settings = self.settings()
valid_project = bool(settings) and settings.project_path.suffix.casefold() == ".prj"
valid_scope = valid_project and (
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 and not self._busy)
auto_enabled = enabled and valid_scope
self.auto_export_checkbox.setEnabled(auto_enabled)
if not auto_enabled and self.auto_export_checkbox.isChecked():
was_blocked = self.auto_export_checkbox.blockSignals(True)
self.auto_export_checkbox.setChecked(False)
self.auto_export_checkbox.blockSignals(was_blocked)
def set_busy(self, busy: bool) -> None:
self._busy = busy
self.export_button.setEnabled(not busy and self.snapshot is not None)
self.cancel_button.setEnabled(busy)
self.scope_combo.setEnabled(not busy)
self.palette_combo.setEnabled(not busy)
self.text_combo.setEnabled(not busy)
self.output_input.setEnabled(not busy)
self.output_button.setEnabled(not busy)
self.engine_input.setEnabled(not busy)
self.engine_button.setEnabled(not busy)
project_ready = bool(self.snapshot and self.snapshot.design_path.casefold().endswith(".prj"))
self.auto_export_checkbox.setEnabled(not busy and project_ready)
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)
def refresh_icons(self, theme: Theme) -> None:
self._theme = theme
self.output_button.setIcon(themed_icon("fa6s.folder-open", theme))
self.open_output_button.setIcon(themed_icon("fa6s.folder-open", theme))
self.engine_button.setIcon(themed_icon("fa6s.folder-open", theme))
self.export_button.setIcon(themed_icon("fa6s.file-pdf", theme))
self.cancel_button.setIcon(themed_icon("fa6s.xmark", theme))
def _scope_changed(self, *_args) -> None:
scope = self.scope_combo.currentData()
current = scope == ExportScope.CURRENT_PAGE.value
specified = scope == ExportScope.BLOCK.value
self.block_input.setEnabled(specified and not self._busy)
self._scope_form.setRowVisible(self._block_row, specified)
self._scope_form.setRowVisible(self._active_row, current)
self.active_block_label.setText(
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 "")
)
if not self._loading:
self.set_can_export(self.snapshot is not None)
self._emit_settings()
def _emit_settings(self, *_args) -> None:
self._update_advanced_summary()
if self._loading:
return
settings = self.settings()
if settings is not None:
self.set_can_export(self.snapshot is not None)
settings = self.settings()
if settings is not None:
self.settings_changed.emit(settings)
def _update_advanced_summary(self) -> None:
parts = []
if self.palette_combo.currentData() != "reference":
parts.append(self.palette_combo.currentText())
if self.text_combo.currentData() != "chinese":
parts.append(self.text_combo.currentText().split("(", 1)[0])
engine = self.engine_input.text().strip()
if engine:
parts.append(f"引擎:{Path(engine).name}")
self.advanced_section.set_summary(" · ".join(parts))
self.advanced_section.summary_label.setToolTip(engine)
def _choose_output(self) -> None:
current = self.output_input.text().strip()
path = QFileDialog.getExistingDirectory(self, "选择 PDF 输出目录", current)
if path:
self.output_input.setText(path)
self._emit_settings()
def _choose_engine(self) -> None:
current = self.engine_input.text().strip()
path, _ = QFileDialog.getOpenFileName(
self,
"选择 DxDesigner 原生 sch2pdf.exe",
current,
"DxDesigner PDF 引擎 (sch2pdf.exe)",
)
if path:
self.engine_input.setText(path)
self._emit_settings()
def _open_output(self) -> None:
value = self.output_input.text().strip()
if not value:
return
try:
directory = Path(value).expanduser().resolve()
directory.mkdir(parents=True, exist_ok=True)
if not QDesktopServices.openUrl(QUrl.fromLocalFile(str(directory))):
raise OSError("系统未能打开该目录")
except (OSError, ValueError) as error:
self.set_status(f"无法打开输出目录:{error}")
@@ -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,39 @@ 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 load_selection_snapshot(self, snapshot: DesignSnapshot) -> None:
pending = dict(self.page.settings().overrides)
self.load_snapshot(snapshot)
model = self.page.model
from PySide6.QtCore import Qt
model.blockSignals(True)
for row in range(model.rowCount()):
bridge_id = model.item(row, 0).data(Qt.ItemDataRole.UserRole)
if bridge_id in pending:
model.item(row, 2).setText(pending[bridge_id])
model.blockSignals(False)
self.refresh_plan()
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 +126,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 +150,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 +211,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:
+19 -13
View File
@@ -7,6 +7,7 @@ from PySide6.QtGui import QStandardItem, QStandardItemModel
from PySide6.QtWidgets import (
QComboBox,
QHBoxLayout,
QHeaderView,
QLabel,
QLineEdit,
QPushButton,
@@ -31,20 +32,13 @@ class PropertyChangePage(QWidget):
def _build_ui(self) -> None:
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 16, 20, 16)
layout.setSpacing(10)
hint = QLabel(
"修改选中器件的属性值。先在 DxDesigner 中选中器件,"
"再为每个器件填写新值;没有该属性的器件会被跳过并在下方提示。"
)
hint.setObjectName("secondaryLabel")
hint.setWordWrap(True)
layout.addWidget(hint)
layout.setContentsMargins(12, 10, 12, 10)
layout.setSpacing(8)
selector_row = QHBoxLayout()
selector_row.addWidget(QLabel("属性"))
self.property_combo = QComboBox()
self.property_combo.setToolTip("先在 DxDesigner 选中器件,再填写表格中的新值;缺失属性会被跳过并提示")
for name in SUPPORTED_PROPERTIES:
self.property_combo.addItem(name)
self.property_combo.addItem("自定义…")
@@ -59,12 +53,20 @@ class PropertyChangePage(QWidget):
self.model.setHorizontalHeaderLabels(("位号", "当前值", "新值"))
self.table = QTableView()
self.table.setModel(self.model)
self.table.setMinimumHeight(360)
self.table.setMinimumHeight(160)
self.table.setAlternatingRowColors(True)
self.table.verticalHeader().hide()
header = self.table.horizontalHeader()
header.setSectionResizeMode(0, QHeaderView.ResizeMode.Interactive)
self.table.setColumnWidth(0, 110)
header.setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
header.setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch)
layout.addWidget(self.table, 1)
self.issue_label = QLabel("")
self.issue_label.setObjectName("secondaryLabel")
self.issue_label.setWordWrap(True)
self.issue_label.hide()
layout.addWidget(self.issue_label)
actions = QHBoxLayout()
@@ -80,10 +82,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()
@@ -123,11 +125,15 @@ class PropertyChangePage(QWidget):
current_item.setEditable(False)
new_item = QStandardItem(current)
new_item.setEditable(editable)
ref_item.setToolTip(refdes)
current_item.setToolTip(current)
self.model.appendRow((ref_item, current_item, new_item))
self.model.blockSignals(False)
def set_issue_text(self, text: str) -> None:
self.issue_label.setText(text)
self.issue_label.setToolTip(text)
self.issue_label.setVisible(bool(text))
def set_can_apply(self, enabled: bool) -> None:
self.apply_button.setEnabled(enabled)
@@ -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:
@@ -7,6 +7,7 @@ from PySide6.QtGui import QStandardItem, QStandardItemModel
from PySide6.QtWidgets import (
QComboBox,
QHBoxLayout,
QHeaderView,
QLabel,
QPushButton,
QRadioButton,
@@ -31,41 +32,39 @@ class PropertyVisibilityPage(QWidget):
def _build_ui(self) -> None:
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 16, 20, 16)
layout.setSpacing(10)
hint = QLabel(
"批量切换选中器件的属性显示状态。先在 DxDesigner 中选中器件,"
"选择属性与目标状态后生成预览。"
)
hint.setObjectName("secondaryLabel")
hint.setWordWrap(True)
layout.addWidget(hint)
layout.setContentsMargins(12, 10, 12, 10)
layout.setSpacing(8)
selector_row = QHBoxLayout()
selector_row.addWidget(QLabel("属性"))
self.property_combo = QComboBox()
self.property_combo.setToolTip("在 DxDesigner 选中器件后,选择要显示或隐藏的属性;下表同步预览")
for name in SUPPORTED_PROPERTIES:
self.property_combo.addItem(name)
selector_row.addWidget(self.property_combo)
selector_row.addStretch(1)
layout.addLayout(selector_row)
direction_row = QHBoxLayout()
direction_row.addWidget(QLabel("目标状态"))
selector_row.addSpacing(16)
selector_row.addWidget(QLabel("目标状态"))
self.hide_button = QRadioButton("隐藏")
self.hide_button.setChecked(True)
self.show_button = QRadioButton("显示")
direction_row.addWidget(self.hide_button)
direction_row.addWidget(self.show_button)
direction_row.addStretch(1)
layout.addLayout(direction_row)
selector_row.addWidget(self.hide_button)
selector_row.addWidget(self.show_button)
selector_row.addStretch(1)
layout.addLayout(selector_row)
self.model = QStandardItemModel(0, 3, self)
self.model.setHorizontalHeaderLabels(("位号", "属性值", "当前状态"))
self.table = QTableView()
self.table.setModel(self.model)
self.table.setMinimumHeight(360)
self.table.setMinimumHeight(160)
self.table.setAlternatingRowColors(True)
self.table.verticalHeader().hide()
header = self.table.horizontalHeader()
header.setSectionResizeMode(0, QHeaderView.ResizeMode.Interactive)
self.table.setColumnWidth(0, 110)
header.setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
header.setSectionResizeMode(2, QHeaderView.ResizeMode.Interactive)
self.table.setColumnWidth(2, 110)
self.table.setEditTriggers(
QTableView.EditTrigger.NoEditTriggers
)
@@ -74,6 +73,7 @@ class PropertyVisibilityPage(QWidget):
self.issue_label = QLabel("")
self.issue_label.setObjectName("secondaryLabel")
self.issue_label.setWordWrap(True)
self.issue_label.hide()
layout.addWidget(self.issue_label)
actions = QHBoxLayout()
@@ -102,12 +102,18 @@ 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)
for item in (ref_item, value_item, state_item):
item.setToolTip(item.text())
self.model.appendRow((ref_item, value_item, state_item))
def set_issue_text(self, text: str) -> None:
self.issue_label.setText(text)
self.issue_label.setToolTip(text)
self.issue_label.setVisible(bool(text))
def set_can_apply(self, enabled: bool) -> None:
self.apply_button.setEnabled(enabled)
+2 -2
View File
@@ -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)
+126 -41
View File
@@ -4,20 +4,24 @@ from __future__ import annotations
from decimal import Decimal
from PySide6.QtCore import Qt, Signal
from PySide6.QtCore import Qt, QTimer, Signal
from PySide6.QtGui import QStandardItem, QStandardItemModel
from PySide6.QtWidgets import (
QAbstractItemView,
QButtonGroup,
QCheckBox,
QComboBox,
QDoubleSpinBox,
QFrame,
QGridLayout,
QHBoxLayout,
QHeaderView,
QLabel,
QLineEdit,
QPushButton,
QSpinBox,
QScrollArea,
QSizePolicy,
QTableView,
QVBoxLayout,
QWidget,
@@ -31,9 +35,12 @@ from dx_productivity.domain.models import (
Severity,
SortOrder,
)
from dx_productivity.ui.collapsible_section import CollapsibleSection
class RefDesPage(QWidget):
preview_requested = Signal()
apply_requested = Signal()
settings_changed = Signal()
locate_requested = Signal(str)
@@ -90,6 +97,7 @@ class RefDesPage(QWidget):
items = [QStandardItem(value) for value in values]
for item in items:
item.setEditable(False)
item.setToolTip(row.full_path)
items[0].setData(row.bridge_ids, Qt.ItemDataRole.UserRole)
self.preview_model.appendRow(items)
@@ -107,27 +115,39 @@ class RefDesPage(QWidget):
self._apply_filter()
def _build_ui(self) -> None:
root = QHBoxLayout(self)
root.setContentsMargins(20, 18, 20, 18)
root.setSpacing(20)
root.addWidget(self._build_rules_panel())
root = QVBoxLayout(self)
root.setContentsMargins(10, 8, 10, 8)
root.setSpacing(6)
self.rules_scroll = QScrollArea()
self.rules_scroll.setObjectName("rulesScroll")
self.rules_scroll.setWidgetResizable(True)
self.rules_scroll.setFrameShape(QFrame.Shape.NoFrame)
self.rules_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.rules_scroll.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Maximum)
self.rules_panel = self._build_rules_panel()
self.rules_scroll.setWidget(self.rules_panel)
root.addWidget(self.rules_scroll)
root.addWidget(self._build_preview_panel(), 1)
self.advanced_section.expanded_changed.connect(
lambda _expanded: QTimer.singleShot(0, self._resize_rules)
)
self._numbering_changed()
self._resize_rules()
def _build_rules_panel(self) -> QFrame:
panel = QFrame()
panel.setObjectName("rulesPanel")
panel.setFixedWidth(318)
panel.setObjectName("compactRulesPanel")
layout = QVBoxLayout(panel)
layout.setContentsMargins(0, 0, 20, 0)
layout.setSpacing(10)
title = QLabel("标注规则")
title.setObjectName("pageTitle")
layout.addWidget(title)
subtitle = QLabel("所选规则会立即更新右侧预览")
subtitle.setObjectName("secondaryLabel")
layout.addWidget(subtitle)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(6)
grid = QGridLayout()
grid.setContentsMargins(0, 0, 0, 0)
grid.setHorizontalSpacing(12)
grid.setVerticalSpacing(6)
grid.setColumnStretch(0, 1)
grid.setColumnStretch(1, 1)
layout.addLayout(grid)
layout.addWidget(_field_label("处理范围"))
scope_row, scope_group = _segmented_row(
("选中器件", "当前页", "全设计")
)
@@ -135,40 +155,56 @@ class RefDesPage(QWidget):
scope_group.buttons()
)
self.selected_button.setChecked(True)
layout.addWidget(scope_row)
grid.addWidget(_labeled_control("处理范围", scope_row), 0, 0)
layout.addWidget(_field_label("处理方式"))
mode_row, mode_group = _segmented_row(("仅补空缺", "全部重编"))
self.fill_only_button, self.reannotate_button = mode_group.buttons()
self.fill_only_button.setChecked(True)
layout.addWidget(mode_row)
grid.addWidget(_labeled_control("处理方式", mode_row), 0, 1)
self.numbering_combo = QComboBox()
self.numbering_combo.addItem("连续编号", NumberingMode.CONTINUOUS)
self.numbering_combo.addItem("按页编号", NumberingMode.PAGE)
layout.addWidget(_labeled_control("编号方式", self.numbering_combo))
grid.addWidget(_labeled_control("编号方式", self.numbering_combo), 1, 0)
number_parameters = QWidget()
parameter_layout = QHBoxLayout(number_parameters)
parameter_layout.setContentsMargins(0, 0, 0, 0)
parameter_layout.setSpacing(10)
grid.addWidget(number_parameters, 1, 1)
self.start_spin = QSpinBox()
self.start_spin.setRange(1, 999999)
self.start_spin.setValue(1)
layout.addWidget(_labeled_control("起始编号", self.start_spin))
self.start_row = _labeled_control("起始编号", self.start_spin)
parameter_layout.addWidget(self.start_row)
self.page_step_spin = QSpinBox()
self.page_step_spin.setRange(1, 999999)
self.page_step_spin.setValue(100)
layout.addWidget(_labeled_control("每页跨度", self.page_step_spin))
self.page_step_row = _labeled_control("每页跨度", self.page_step_spin)
parameter_layout.addWidget(self.page_step_row)
self.page_start_spin = QSpinBox()
self.page_start_spin.setRange(0, 999999)
self.page_start_spin.setValue(1)
layout.addWidget(_labeled_control("页内起始", self.page_start_spin))
self.page_start_row = _labeled_control("页内起始", self.page_start_spin)
parameter_layout.addWidget(self.page_start_row)
self.advanced_section = CollapsibleSection("高级选项")
layout.addWidget(self.advanced_section)
advanced_row = QHBoxLayout()
advanced_row.setSpacing(12)
self.advanced_section.content_layout.addLayout(advanced_row)
self.sort_combo = QComboBox()
self.sort_combo.setMinimumContentsLength(8)
self.sort_combo.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
self.sort_combo.addItem("从上到下 · 从左到右", SortOrder.TOP_DOWN_LEFT_RIGHT)
self.sort_combo.addItem("从上到下 · 从右到左", SortOrder.TOP_DOWN_RIGHT_LEFT)
self.sort_combo.addItem("从左到右 · 从上到下", SortOrder.LEFT_RIGHT_TOP_DOWN)
self.sort_combo.addItem("从右到左 · 从上到下", SortOrder.RIGHT_LEFT_TOP_DOWN)
layout.addWidget(_labeled_control("排列顺序", self.sort_combo))
advanced_row.addWidget(_labeled_control("排列顺序", self.sort_combo), 1)
self.tolerance_spin = QDoubleSpinBox()
self.tolerance_spin.setRange(0, 100)
@@ -176,29 +212,28 @@ class RefDesPage(QWidget):
self.tolerance_spin.setSingleStep(0.5)
self.tolerance_spin.setValue(5)
self.tolerance_spin.setSuffix(" mm")
layout.addWidget(_labeled_control("同行容差", self.tolerance_spin))
layout.addStretch(1)
advanced_row.addWidget(_labeled_control("同行容差", self.tolerance_spin), 1)
return panel
def _build_preview_panel(self) -> QWidget:
panel = QWidget()
layout = QVBoxLayout(panel)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(10)
layout.setSpacing(6)
toolbar = QHBoxLayout()
preview_title = QLabel("变更预览")
preview_title.setObjectName("pageTitle")
toolbar.addWidget(preview_title)
toolbar.addStretch(1)
self.search_input = QLineEdit()
self.search_input.setPlaceholderText("搜索位号、料号或路径")
self.search_input.setClearButtonEnabled(True)
self.search_input.setMaximumWidth(280)
toolbar.addWidget(self.search_input)
self.search_input.setAccessibleName("搜索位号")
toolbar.addWidget(self.search_input, 1)
self.status_filter = QComboBox()
self.status_filter.addItems(("全部状态", "待更新", "已保留", "需确认", "阻断"))
self.status_filter.setMaximumWidth(130)
toolbar.addWidget(self.status_filter)
self.details_checkbox = QCheckBox("显示详情列")
self.details_checkbox.setToolTip("显示前缀与层级路径;搜索始终包括详情列")
self.details_checkbox.toggled.connect(self._show_details)
toolbar.addWidget(self.details_checkbox)
layout.addLayout(toolbar)
self.preview_model = QStandardItemModel(0, 8, self)
@@ -219,13 +254,32 @@ class RefDesPage(QWidget):
header = self.preview_table.horizontalHeader()
header.setMinimumSectionSize(44)
header.setStretchLastSection(True)
for column in range(7):
header.setSectionResizeMode(column, QHeaderView.ResizeMode.ResizeToContents)
for column in range(8):
header.setSectionResizeMode(column, QHeaderView.ResizeMode.Interactive)
for column, width in enumerate((76, 90, 90, 60, 72, 140, 100, 220)):
header.resizeSection(column, width)
self._show_details(False)
layout.addWidget(self.preview_table, 1)
self.issue_label = QLabel("0 项待更新")
self.issue_label.setObjectName("secondaryLabel")
layout.addWidget(self.issue_label)
actions = QHBoxLayout()
actions.addWidget(self.issue_label, 1)
self.preview_button = QPushButton("预览")
self.preview_button.setAccessibleName("生成预览")
self.preview_button.setToolTip("重新生成位号预览")
self.preview_button.clicked.connect(self.preview_requested)
self.apply_button = QPushButton("应用位号")
self.apply_button.setObjectName("primaryButton")
self.apply_button.setEnabled(False)
self.apply_button.clicked.connect(self.apply_requested)
actions.addWidget(self.preview_button)
actions.addWidget(self.apply_button)
layout.addLayout(actions)
for control in (self.search_input, self.status_filter, self.details_checkbox,
self.preview_button, self.apply_button,
self.advanced_section.toggle_button):
control.setMinimumHeight(28)
return panel
def _connect_controls(self) -> None:
@@ -237,19 +291,45 @@ class RefDesPage(QWidget):
self.reannotate_button,
):
button.clicked.connect(self.settings_changed)
for control in (self.numbering_combo, self.sort_combo):
control.currentIndexChanged.connect(self.settings_changed)
self.numbering_combo.currentIndexChanged.connect(self._numbering_changed)
self.sort_combo.currentIndexChanged.connect(self._advanced_changed)
for control in (
self.start_spin,
self.page_step_spin,
self.page_start_spin,
self.tolerance_spin,
):
control.valueChanged.connect(self.settings_changed)
self.tolerance_spin.valueChanged.connect(self._advanced_changed)
self.search_input.textChanged.connect(self._apply_filter)
self.status_filter.currentIndexChanged.connect(self._apply_filter)
self.preview_table.doubleClicked.connect(self._locate_row)
def _numbering_changed(self, *_args) -> None:
by_page = self.numbering_mode() is NumberingMode.PAGE
self.start_row.setVisible(not by_page)
self.page_step_row.setVisible(by_page)
self.page_start_row.setVisible(by_page)
self._resize_rules()
self.settings_changed.emit()
def _advanced_changed(self, *_args) -> None:
parts = []
if self.sort_order() is not SortOrder.TOP_DOWN_LEFT_RIGHT:
parts.append(self.sort_combo.currentText())
if self.tolerance_spin.value() != 5:
parts.append(f"同行容差 {self.tolerance_spin.value():g} mm")
self.advanced_section.set_summary(" · ".join(parts))
self._resize_rules()
self.settings_changed.emit()
def _resize_rules(self, *_args) -> None:
self.rules_panel.layout().invalidate()
self.rules_scroll.setFixedHeight(min(180, self.rules_panel.sizeHint().height() + 2))
def _show_details(self, enabled: bool) -> None:
self.preview_table.setColumnHidden(3, not enabled)
self.preview_table.setColumnHidden(7, not enabled)
def _apply_filter(self) -> None:
query = self.search_input.text().strip().casefold()
status = self.status_filter.currentText()
@@ -282,6 +362,8 @@ def _segmented_row(labels: tuple[str, ...]) -> tuple[QFrame, QButtonGroup]:
button = QPushButton(label)
button.setCheckable(True)
button.setObjectName("segmentButton")
button.setAccessibleName(label)
button.setMinimumHeight(28)
group.addButton(button)
layout.addWidget(button, 1)
return frame, group
@@ -297,9 +379,12 @@ def _labeled_control(text: str, control: QWidget) -> QFrame:
frame = QFrame()
layout = QHBoxLayout(frame)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(8)
layout.setSpacing(6)
label = _field_label(text)
label.setMinimumWidth(78)
label.setMinimumWidth(58)
control.setAccessibleName(text)
control.setMinimumHeight(28)
label.setBuddy(control)
layout.addWidget(label)
layout.addWidget(control, 1)
return frame
+147
View File
@@ -0,0 +1,147 @@
"""Consume lightweight native selection state without rebuilding design data."""
from __future__ import annotations
from dataclasses import replace
import json
import os
from pathlib import Path
import time
from PySide6.QtCore import QObject, QTimer
def identity(component) -> str:
return ('uid:' + component.stable_uid.casefold() if component.stable_uid
else 'path:' + component.full_path.casefold())
class SelectionWatcher(QObject):
def __init__(self, window, request_path: Path) -> None:
super().__init__(window)
self.window = window
self.path = request_path.with_name('selection.json')
self.last_signature = None
self._channel_confirmed = False
self._initial_deadline = time.monotonic() + 5.0
self._initial_detail = window.selection_status.toolTip()
self.timer = QTimer(self)
self.timer.setInterval(150)
self.timer.timeout.connect(self._check)
self.timer.start()
self._check()
def _check(self) -> None:
if self.window._closing:
self.timer.stop()
return
controller = self.window.refdes_controller
snapshot = controller.snapshot
if snapshot is None:
return
controllers = tuple(item for item in (
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, self.window.pdf_export_controller,
) if item is not None)
if any(getattr(item, '_apply_in_flight', False) or getattr(item, '_restore_in_flight', False) for item in controllers):
return
heartbeat = self.path.with_name('apply-progress.json')
try:
if heartbeat.exists() and time.time() - heartbeat.stat().st_mtime > 5:
self.window.set_bridge_status('桥接已断开')
self.window.set_selection_status('选择同步已暂停', '宿主桥接没有更新,请刷新快照或重新从 DxDesigner 菜单打开工具。')
self.last_signature = None
return
raw = self.path.read_text(encoding='utf-8-sig')
signature = (raw, snapshot.snapshot_id)
if signature == self.last_signature:
return
data = json.loads(raw)
except (OSError, ValueError):
self._channel_unavailable('选择状态无法读取,请刷新快照或重新连接宿主。')
return
if not isinstance(data, dict) or data.get('run_id') != snapshot.run_id:
self._channel_unavailable('选择状态不属于当前宿主会话。')
return
if os.path.normcase(str(data.get('design_path', ''))) != os.path.normcase(snapshot.design_path):
self.window.set_bridge_status('工程已切换')
self.window.set_selection_status('工程已切换,请重新打开工具', str(data.get('design_path', '')))
self.last_signature = None
return
if data.get('snapshot_id') != snapshot.snapshot_id:
self.window.set_bridge_status('等待设计快照刷新')
self.window.set_selection_status('等待设计快照刷新')
self.last_signature = None
return
state = data.get('state')
if state not in ('ready', 'unavailable', 'disconnected', 'closed', 'error'):
self._channel_unavailable('选择状态格式无效。')
return
if state != 'ready':
fresh = replace(snapshot, components=tuple(replace(component, selected=False, current_sheet=False)
for component in snapshot.components), selected_nets=(), active_block_name='',
current_sheet_name='', current_sheet_number=None)
self._load_snapshot(fresh, controllers)
self.last_signature = signature
self._channel_confirmed = True
disconnected = data.get('state') in ('disconnected', 'closed', 'error')
self.window.set_bridge_status('桥接已断开' if disconnected else '桥接已连接')
self.window.set_selection_status('桥接已断开' if disconnected else '未打开原理图页')
return
selected = data.get('selected_keys')
current = data.get('current_sheet_keys')
nets = data.get('selected_nets', [])
if any(not isinstance(value, list) or any(not isinstance(item, str) for item in value) for value in (selected, current, nets)):
self._channel_unavailable('选择列表格式无效。')
return
block = data.get('active_block_name')
sheet = data.get('current_sheet_name')
page = data.get('current_sheet_number')
if not isinstance(block, str) or not isinstance(sheet, str) or (page is not None and type(page) is not int):
self._channel_unavailable('当前页信息格式无效。')
return
selected, current = set(selected), set(current)
components = tuple(replace(component, selected=identity(component) in selected,
current_sheet=identity(component) in current) for component in snapshot.components)
fresh = replace(snapshot, components=components, active_block_name=block, current_sheet_name=sheet,
current_sheet_number=page, selected_nets=tuple(nets))
self._load_snapshot(fresh, controllers)
self.window.set_bridge_status('桥接已连接')
self.last_signature = signature
self._channel_confirmed = True
known = {identity(component) for component in components}
refs = [component.refdes or '未标注器件' for component in components if component.selected]
if selected - known:
summary = '所选器件需刷新快照'
refresh = self.path.with_name('refresh.request')
if not refresh.exists():
try:
refresh.write_text('snapshot\n', encoding='utf-8')
except OSError:
pass
else:
summary = f'已选 {refs[0]}' if len(refs) == 1 else f'已选 {len(refs)} 个' + (f':{refs[0]}' if refs else '器件')
self.window.set_selection_status(summary,
f'当前工程:{fresh.design_path}\n当前页:{block} / {sheet}\n选中器件:' + ('、'.join(refs) or '无')
)
def _channel_unavailable(self, detail: str) -> None:
self.last_signature = None
if not self._channel_confirmed and time.monotonic() < self._initial_deadline:
self.window.set_bridge_status('等待宿主选择通道')
self.window.set_selection_status('等待选择同步', detail + '\n初始快照(尚未确认实时选择):\n' + self._initial_detail)
else:
self.window.set_bridge_status('桥接已断开')
self.window.set_selection_status('选择同步已暂停', detail)
def _load_snapshot(self, fresh, controllers) -> None:
for item in controllers:
load = getattr(item, 'load_selection_snapshot', None)
if load is not None:
load(fresh)
elif item in (self.window.inspection_controller, self.window.network_controller, self.window.history_controller):
# Selection changes must not clear a highlighted inspection
# result or the history entry the user is reviewing.
item.snapshot = fresh
else:
item.load_snapshot(fresh)
@@ -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)
+45 -28
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
from pathlib import Path
from PySide6.QtCore import QSize, Signal
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (
QCheckBox,
QComboBox,
@@ -15,6 +15,7 @@ from PySide6.QtWidgets import (
QLineEdit,
QMessageBox,
QPushButton,
QScrollArea,
QTextEdit,
QVBoxLayout,
QWidget,
@@ -22,6 +23,7 @@ from PySide6.QtWidgets import (
from dx_productivity.update.models import UpdateManifest
from dx_productivity.update.service import UpdateCheckResult
from dx_productivity.ui.collapsible_section import CollapsibleSection
from dx_productivity.ui.theme import Theme, themed_icon
@@ -71,6 +73,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)
@@ -91,38 +95,41 @@ class SettingsPage(QWidget):
def _build_ui(self) -> None:
root = QVBoxLayout(self)
root.setContentsMargins(20, 18, 20, 18)
root.setSpacing(14)
root.setContentsMargins(12, 10, 12, 10)
root.setSpacing(8)
header = QFrame()
header.setObjectName("settingsIntro")
header_layout = QVBoxLayout(header)
header_layout.setContentsMargins(16, 12, 16, 12)
title = QLabel("设置")
title.setObjectName("pageTitle")
header_layout.addWidget(title)
subtitle = QLabel("在线更新默认只检查,不会静默安装或覆盖正在运行的程序")
subtitle.setObjectName("secondaryLabel")
header_layout.addWidget(subtitle)
root.addWidget(header)
parameters = QWidget()
parameter_layout = QVBoxLayout(parameters)
parameter_layout.setContentsMargins(0, 0, 0, 0)
parameter_layout.setSpacing(8)
self.parameters_scroll = QScrollArea()
self.parameters_scroll.setWidgetResizable(True)
self.parameters_scroll.setFrameShape(QFrame.Shape.NoFrame)
self.parameters_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.parameters_scroll.setWidget(parameters)
root.addWidget(self.parameters_scroll, 1)
form_frame = QFrame()
form_frame.setObjectName("settingsPanel")
form = QFormLayout(form_frame)
form.setContentsMargins(16, 14, 16, 14)
form.setHorizontalSpacing(16)
form.setVerticalSpacing(12)
self.auto_check_checkbox = QCheckBox("启动后每天自动检查一次")
self.auto_check_checkbox.setChecked(True)
self.auto_check_checkbox.setToolTip("自动检查仅提示新版本;下载和安装分别需要确认")
parameter_layout.addWidget(self.auto_check_checkbox)
self.advanced_section = CollapsibleSection("高级更新选项")
form = QFormLayout()
form.setHorizontalSpacing(12)
form.setVerticalSpacing(8)
self.source_input = QLineEdit()
self.source_input.setPlaceholderText("https://.../manifest.json 或 file://...")
self.channel_combo = QComboBox()
self.channel_combo.addItem("稳定版", "stable")
self.channel_combo.addItem("开发版", "development")
self.auto_check_checkbox = QCheckBox("启动后每天自动检查一次")
self.auto_check_checkbox.setChecked(True)
form.addRow("更新源", self.source_input)
form.addRow("频道", self.channel_combo)
form.addRow("检查策略", self.auto_check_checkbox)
root.addWidget(form_frame)
self.advanced_section.content_layout.addLayout(form)
parameter_layout.addWidget(self.advanced_section)
self.source_input.textChanged.connect(self._update_advanced_summary)
self.channel_combo.currentIndexChanged.connect(self._update_advanced_summary)
self._update_advanced_summary()
actions = QHBoxLayout()
self.check_button = QPushButton("检查更新")
@@ -141,20 +148,30 @@ class SettingsPage(QWidget):
self.version_label.setObjectName("secondaryLabel")
self.status_label = QLabel("尚未检查")
self.status_label.setObjectName("settingsStatus")
self.status_label.setWordWrap(True)
status_row.addWidget(self.version_label)
status_row.addStretch(1)
status_row.addWidget(self.status_label)
root.addLayout(status_row)
notes_title = QLabel("版本说明")
notes_title.setObjectName("moduleCardTitle")
root.addWidget(notes_title)
self.notes_section = CollapsibleSection("版本说明")
self.release_notes_view = QTextEdit()
self.release_notes_view.setReadOnly(True)
self.release_notes_view.setPlaceholderText("检查到新版本后显示版本说明")
root.addWidget(self.release_notes_view, 1)
self.release_notes_view.setMinimumHeight(80)
self.notes_section.content_layout.addWidget(self.release_notes_view)
parameter_layout.addWidget(self.notes_section)
parameter_layout.addStretch(1)
self.refresh_icons(Theme.LIGHT)
def _update_advanced_summary(self) -> None:
source = self.source_input.text().strip()
source_hint = (source[:45] + "…") if len(source) > 45 else source
summary = f"频道:{self.channel_combo.currentText()} · 更新源:{source_hint or '未配置'}"
self.advanced_section.set_summary(summary)
self.advanced_section.summary_label.setToolTip(source or "未配置更新源")
self.source_input.setToolTip(source)
def _check(self) -> None:
self.set_checking()
self.check_requested.emit(self.source_input.text().strip(), self.channel_combo.currentData())
@@ -0,0 +1,51 @@
"""Keep menu installation and host startup off the Qt UI thread."""
from pathlib import Path
from PySide6.QtCore import QObject, QThread, Signal, Slot
from dx_productivity.bridge.startup import start_dxdesigner
class _StartupWorker(QThread):
def __init__(self, tool_root, service, parent):
super().__init__(parent)
self.tool_root = tool_root
self.service = service
self.result = (False, "启动未完成")
def run(self):
try:
self.result = (True, self.service(self.tool_root))
except Exception as error:
self.result = (False, str(error))
class StartupController(QObject):
started = Signal()
completed = Signal(bool, str)
def __init__(self, tool_root: Path, parent=None, *, service=start_dxdesigner):
super().__init__(parent)
self.tool_root = tool_root
self.service = service
self._worker = None
def is_running(self):
return self._worker is not None and self._worker.isRunning()
@Slot()
def start(self):
if self.is_running():
return
self.started.emit()
self._worker = _StartupWorker(self.tool_root, self.service, self)
self._worker.finished.connect(self._finish)
self._worker.finished.connect(self._worker.deleteLater)
self._worker.start()
@Slot()
def _finish(self):
worker = self._worker
self._worker = None
if worker is not None:
self.completed.emit(*worker.result)
+59 -11
View File
@@ -121,12 +121,35 @@ def _stylesheet(tokens: ThemeTokens) -> str:
return f"""
* {{
font-family: "Microsoft YaHei UI";
font-size: 13pt;
font-size: 10pt;
letter-spacing: 0px;
}}
QMainWindow, QWidget#appRoot {{
QMainWindow {{
background: transparent;
border: none;
}}
QWidget#appRoot {{
background: {tokens.canvas};
color: {tokens.text_primary};
border: 1px solid {tokens.border};
border-radius: 10px;
}}
QWidget#floatingToolbar {{
background: {tokens.surface};
border: 1px solid {tokens.border};
border-radius: 6px;
}}
QPushButton#toolbarFeature:checked {{
background: {tokens.accent};
color: {tokens.accent_text};
border-color: {tokens.accent};
}}
QToolButton#sectionToggle {{
min-width: 100px;
max-width: 16777000px;
min-height: 28px;
padding: 0 7px;
text-align: left;
}}
QFrame#titleBar, QFrame#contentHeader {{
background: {tokens.surface};
@@ -137,8 +160,13 @@ def _stylesheet(tokens: ThemeTokens) -> str:
border-right: 1px solid {tokens.border};
}}
QFrame#rulesPanel {{
background: {tokens.canvas};
border-right: 1px solid {tokens.border};
}}
QScrollArea#rulesScroll {{
background: {tokens.canvas};
border: none;
}}
QFrame#legacyIntro {{
background: {tokens.surface};
border: 1px solid {tokens.border};
@@ -194,27 +222,31 @@ def _stylesheet(tokens: ThemeTokens) -> str:
QLabel {{
color: {tokens.text_primary};
}}
QCheckBox, QRadioButton {{
min-height: 28px;
color: {tokens.text_primary};
}}
QLabel#secondaryLabel, QLabel#projectLabel {{
color: {tokens.text_secondary};
font-size: 10pt;
}}
QLabel#brandLabel {{
font-size: 15pt;
font-size: 13pt;
font-weight: 600;
}}
QLabel#pageTitle {{
font-size: 16pt;
font-size: 11pt;
font-weight: 600;
}}
QListWidget#navigationList {{
background: transparent;
border: none;
outline: none;
padding: 8px;
padding: 4px;
}}
QListWidget#navigationList::item {{
min-height: 36px;
padding: 0 10px;
min-height: 32px;
padding: 0 8px;
border-radius: 6px;
color: {tokens.text_secondary};
}}
@@ -229,12 +261,12 @@ def _stylesheet(tokens: ThemeTokens) -> str:
}}
QPushButton, QToolButton, QComboBox, QSpinBox, QDoubleSpinBox,
QLineEdit {{
min-height: 30px;
min-height: 26px;
border: 1px solid {tokens.border};
border-radius: 6px;
background: {tokens.surface};
color: {tokens.text_primary};
padding: 0 10px;
padding: 0 7px;
}}
QPushButton:hover, QToolButton:hover, QComboBox:hover {{
background: {tokens.surface_hover};
@@ -260,12 +292,12 @@ def _stylesheet(tokens: ThemeTokens) -> str:
background: {tokens.surface};
}}
QPushButton#segmentButton {{
min-height: 30px;
min-height: 26px;
border: none;
border-right: 1px solid {tokens.border};
border-radius: 0;
background: transparent;
padding: 0 8px;
padding: 0 5px;
}}
QPushButton#segmentButton:checked {{
background: {tokens.accent};
@@ -281,6 +313,22 @@ def _stylesheet(tokens: ThemeTokens) -> str:
max-width: 30px;
padding: 0;
}}
QToolButton#panelToggle {{
min-width: 66px;
max-width: 66px;
padding: 0 7px;
text-align: center;
}}
QToolButton#toolbarMore {{
min-width: 26px;
max-width: 16777000px;
padding: 0;
}}
QToolButton#toolbarMore::menu-indicator {{
image: none;
width: 0px;
height: 0px;
}}
QFrame#statusStrip {{
background: {tokens.surface};
border-top: 1px solid {tokens.border};
+49 -8
View File
@@ -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)
+23
View File
@@ -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"),
]
+170 -24
View File
@@ -1,31 +1,177 @@
from pathlib import Path
import shutil
import subprocess
import pytest
from dx_productivity.bridge.startup_assets import generate_startup_assets
def test_generate_startup_assets_lists_all_feature_actions() -> None:
from dx_productivity.bridge.startup_assets import generate_startup_assets
@pytest.fixture
def portable_root(tmp_path):
root = tmp_path / "一叶知秋 工具"
integration = Path(__file__).parents[2] / "integration" / "dxdesigner795"
root.mkdir()
(root / "DxDesignerTools.exe").write_bytes(b"fixture")
for name in ("MenuAdd.vbs", "DesignBridge.vbs", "CompatibilityProbe.vbs", "LoadMenu.vbs"):
source = integration / name
if source.exists():
shutil.copy2(source, root / name)
runtime = root / "_runtime" / "vbs"
runtime.mkdir(parents=True)
shutil.copy2(integration / "BridgeCommon.vbs", runtime)
for source in (integration / "core").glob("*.vbs"):
shutil.copy2(source, runtime)
return root
assets = generate_startup_assets(Path("C:/portable/DxDesignerTools"))
def test_generated_menu_loads_without_host_script_path_metadata(portable_root, tmp_path):
assets = generate_startup_assets(portable_root, tmp_path / "用户 profile")
# Run the real VBS without DxDesigner script-path globals: the reported bug.
fixture = Path(__file__).parents[1] / "vbs" / "test_menu_add.vbs"
fake_host = fixture.read_text(encoding="ascii").split('Set Fso = CreateObject')[0]
fake_host = fake_host.replace("Const cmdControlPopup = 1", "")
collection = fake_host.split("Class FakeControlsCollection", 1)[1].split("End Class", 1)[0]
popup_collection = "Class FakePopupControlsCollection" + collection.replace(
"Public Function Add()",
'Public Function Add(controlType)\n If CStr(controlType) <> "1" Then WScript.Quit 5',
) + "End Class\n"
harness = tmp_path / "host.vbs"
harness.write_text(
fake_host + popup_collection
+ '\nSet Fso = CreateObject("Scripting.FileSystemObject")\n'
+ 'Set FakeMenuBar = New FakeControl\n'
+ 'Set FakeMenuBar.Controls = New FakePopupControlsCollection\n'
+ 'Set FakeMainMenuBar = New FakeControl\n'
+ 'Set FakeMainMenuBar.Controls = New FakePopupControlsCollection\n'
+ 'MenuText = Fso.OpenTextFile(WScript.Arguments(0), 1).ReadAll\n'
+ 'ExecuteGlobal MenuText\n'
+ 'If FakeMenuBar.Controls.Count <> 1 Then WScript.Quit 1\n'
+ 'If FakeMainMenuBar.Controls.Count <> 1 Then WScript.Quit 6\n'
+ 'If FakeMenuBar.Controls.Item(1).Controls.Count <> 8 Then WScript.Quit 2\n'
+ 'For Each SourceMenu In Array(1, 2, 3, 4, 5, 6, 7, 8)\n'
+ ' If Left(FakeMenuBar.Controls.Item(1).Controls.Item(SourceMenu).OnAction, 5) <> "run """ Then WScript.Quit 3\n'
+ 'Next\n'
+ 'Call DxToolsInstallMenu()\n'
+ 'If FakeMenuBar.Controls.Count <> 1 Then WScript.Quit 4\n'
+ '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(
["cscript", "//nologo", str(harness), str(assets.menu_script)],
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",
"bom",
"compatibility",
"guide",
"refdes", "property-change", "property-visibility", "inspection",
"bom", "pdf-export", "compatibility", "guide",
}
assert assets.action_scripts["refdes"] == "DxToolsOpenRefDes"
assert (
assets.action_scripts["property-change"]
== "DxToolsOpenPropertyChange"
)
assert assets.action_scripts["bom"] == "DxToolsOpenBom"
assert assets.action_scripts["compatibility"] == "DxToolsOpenCompatibility"
assert assets.action_scripts["guide"] == "DxToolsOpenGuide"
assert all(
"D:\\NET_CHECK" not in value for value in assets.action_scripts.values()
)
assert not any(
value.startswith("run ") for value in assets.action_scripts.values()
)
for script in assets.action_scripts.values():
assert script.read_bytes().isascii()
compiler = tmp_path / "compile-action.vbs"
compiler.write_text(
'Dim text\ntext = CreateObject("Scripting.FileSystemObject").OpenTextFile(WScript.Arguments(0), 1).ReadAll\n'
'ExecuteGlobal Split(text, "\' DXTOOLS_ENTRY")(0)\n',
encoding="ascii",
)
result = subprocess.run(["cscript", "//nologo", str(compiler), str(script)], capture_output=True, timeout=10)
assert result.returncode == 0, result.stderr.decode(errors="replace")
def test_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"
viewdraw = install / "wv" / "win32" / "bin" / "viewdraw.exe"
viewdraw.parent.mkdir(parents=True)
viewdraw.write_bytes(b"fixture")
standard = install / "standard"
standard.mkdir()
vendor = standard / "scripts.ini"
original = b"[LibraryStudio]\r\nScript#0=library.vbs\r\n[ViewDraw]\r\nScript#0=company.vbs\r\n"
vendor.write_bytes(original)
(standard / "vllib.vmb").write_bytes(b"vendor message catalog")
environment = {"LOCALAPPDATA": str(tmp_path / "profile"), "WDIR": str(standard)}
configuration = prepare_startup(portable_root, viewdraw, environment)
configuration_again = prepare_startup(portable_root, viewdraw, environment)
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(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):
from dx_productivity.bridge.startup import StartupError, prepare_startup
(portable_root / "_runtime" / "vbs" / "Snapshot.vbs").unlink()
profile = tmp_path / "untouched"
with pytest.raises(StartupError, match="Snapshot.vbs"):
prepare_startup(portable_root, tmp_path / "viewdraw.exe", {"LOCALAPPDATA": str(profile)})
assert not profile.exists()
def test_start_never_reports_success_from_a_stale_host_receipt(portable_root, tmp_path, monkeypatch):
from dx_productivity.bridge.startup import StartupError, start_dxdesigner
install = tmp_path / "SDD_HOME"
viewdraw = install / "wv/win32/bin/viewdraw.exe"
viewdraw.parent.mkdir(parents=True)
viewdraw.write_bytes(b"fixture")
standard = install / "standard"
standard.mkdir()
(standard / "vllib.vmb").write_bytes(b"catalog")
profile = tmp_path / "profile"
ready = profile / "DxProductivity/startup-refactored/menu-ready.txt"
ready.parent.mkdir(parents=True)
ready.write_text("old-token", encoding="utf-16")
monkeypatch.setattr(subprocess, "run", lambda *args, **kwargs: subprocess.CompletedProcess(args[0], 0, b"", b""))
with pytest.raises(StartupError, match="菜单加载回执"):
start_dxdesigner(portable_root, viewdraw=viewdraw, environment={"LOCALAPPDATA": str(profile), "WDIR": str(standard)}, timeout=0.01)
def test_start_launches_absent_host_with_private_configuration(portable_root, tmp_path, monkeypatch):
import re
from dx_productivity.bridge.startup import start_dxdesigner
install = tmp_path / "SDD_HOME"
viewdraw = install / "wv/win32/bin/viewdraw.exe"
viewdraw.parent.mkdir(parents=True)
viewdraw.write_bytes(b"fixture")
standard = install / "standard"
standard.mkdir()
(standard / "vllib.vmb").write_bytes(b"catalog")
profile = tmp_path / "profile"
environment = {"LOCALAPPDATA": str(profile), "WDIR": str(standard)}
launched = []
monkeypatch.setattr(subprocess, "run", lambda *args, **kwargs: subprocess.CompletedProcess(args[0], 3, b"", b""))
def launch(command, *, cwd, env):
launched.append((command, cwd, env))
private = profile / "DxProductivity/startup-refactored"
token = re.search(r'stream.WriteLine "([0-9a-f]+)"', (private / "MenuAdd.vbs").read_text(encoding="ascii"))[1]
(private / "menu-ready.txt").write_text(token, encoding="utf-16")
monkeypatch.setattr(subprocess, "Popen", launch)
assert "已启动" in start_dxdesigner(portable_root, viewdraw=viewdraw, environment=environment, timeout=0.1)
assert len(launched) == 1
command, cwd, child = launched[0]
assert command == [str(viewdraw.resolve())]
assert cwd == viewdraw.parent.resolve()
assert child["WDIR"].split(";")[0] == str(standard)
assert child["DXTOOLS_HOME"] == str(portable_root.resolve())
assert environment == {"LOCALAPPDATA": str(profile), "WDIR": str(standard)}
+123
View File
@@ -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?"
+28
View File
@@ -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
+73 -1
View File
@@ -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
+260
View File
@@ -0,0 +1,260 @@
from pathlib import Path
import os
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, **_kwargs):
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, **_kwargs):
_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, **_kwargs):
_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, **_kwargs):
_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()
def test_exporter_applies_reference_colors_only_to_child(project, tmp_path, monkeypatch):
engine = tmp_path / 'sch2pdf.exe'
engine.touch()
original_config = project.parent / 'DxDesigner.xml'
original_config.write_bytes(b'original project colors')
monkeypatch.setenv('WDIR', 'D:/Mentor/standard')
before = dict(os.environ)
settings = PdfExportSettings(project, ExportScope.PROJECT, '', tmp_path / 'output', engine_path=engine)
def native_engine(command, *_args, env=None):
assert env is not None
assert env['WDIR'].endswith(';D:/Mentor/standard')
assert Path(env['WDIR'].split(';')[0], 'DxDesigner.xml').is_file()
assert original_config.read_bytes() == b'original project colors'
_write_pdf(Path(command[command.index('-a') + 1]), (('Main Sheet Analog', 'CONTENT'),))
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 == 'success', result.message
assert dict(os.environ) == before
assert original_config.read_bytes() == b'original project colors'
@@ -0,0 +1,75 @@
from pathlib import Path
import json
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, print_theme='original')
save_settings(settings, config_path=config)
observed = {}
def export(settings, cancel, **kwargs):
assert settings.print_theme == 'original'
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'
def test_old_settings_use_reference_palette_and_explicit_palette_roundtrips(tmp_path):
config = tmp_path / 'config.json'
settings = PdfExportSettings(tmp_path / 'Demo.prj', ExportScope.PROJECT, '', tmp_path / 'output')
save_settings(settings, config_path=config)
data = json.loads(config.read_text(encoding='utf-8'))
data.pop('print_theme', None)
config.write_text(json.dumps(data), encoding='utf-8')
assert load_settings(settings.project_path, config_path=config).print_theme == 'reference'
data['print_theme'] = 'original'
config.write_text(json.dumps(data), encoding='utf-8')
native = load_settings(settings.project_path, config_path=config)
assert native.print_theme == 'original'
save_settings(native, config_path=config)
assert load_settings(settings.project_path, config_path=config) == native
data['print_theme'] = 'unknown'
config.write_text(json.dumps(data), encoding='utf-8')
assert load_settings(settings.project_path, config_path=config).print_theme == 'reference'
+49
View File
@@ -0,0 +1,49 @@
import os
from pathlib import Path
import sys
import threading
import xml.etree.ElementTree as ET
import pytest
from dx_productivity.features.pdf_export.engine import run_engine
def test_reference_palette_preserves_parent_environment_and_native_search_path(tmp_path, monkeypatch):
from dx_productivity.features.pdf_export.native_profile import prepare_environment
monkeypatch.setenv('WDIR', 'D:/Mentor/standard;D:/Library')
before = dict(os.environ)
environment = prepare_environment(tmp_path / '中文 run', 'reference')
assert dict(os.environ) == before
profile, inherited = environment['WDIR'].split(';', 1)
assert inherited == before['WDIR']
assert Path(profile).is_relative_to(tmp_path)
tree = ET.parse(Path(profile) / 'DxDesigner.xml')
expected = {'NET': '0xff0000', 'COMPONENT': '0x800080', 'PIN': '0x008080',
'LINE': '0x0000ff', 'BOX': '0x800080', 'CIRCLE': '0x008000',
'ARC': '0x0000ff', 'TEXT': '0x0000ff', 'LABEL': '0x008000',
'ATTRIBUTE': '0x388e8e'}
actual = {item.get('name'): item.find("key[@name='COLOR']").get('value')
for item in tree.findall('./DxDesigner/OBJECTS/object')}
assert actual == expected
assert tree.find("./DxDesigner/LAYERS/layer[@name='BORDER_LAYER']/key").get('value') == '0x0000ff'
assert prepare_environment(tmp_path / 'native', 'original') is None
assert not (tmp_path / 'native').exists()
def test_reference_palette_rejects_wdir_separator_in_run_path(tmp_path):
from dx_productivity.features.pdf_export.native_profile import prepare_environment
with pytest.raises(ValueError, match='分号'):
prepare_environment(tmp_path / 'bad;path', 'reference')
def test_engine_uses_child_environment_without_changing_parent(tmp_path, monkeypatch):
monkeypatch.setenv('DXTOOLS_PALETTE_TEST', 'parent')
environment = dict(os.environ, DXTOOLS_PALETTE_TEST='child')
result = run_engine([sys.executable, '-c', "import os; print(os.environ['DXTOOLS_PALETTE_TEST'])"],
tmp_path, tmp_path / 'logs', threading.Event(), 10, env=environment)
assert result == 0
assert (tmp_path / 'logs/stdout.log').read_text().strip() == 'child'
assert os.environ['DXTOOLS_PALETTE_TEST'] == 'parent'
+64
View File
@@ -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 == []
+103
View File
@@ -0,0 +1,103 @@
from pathlib import Path
import threading
import pytest
from pypdf import PdfReader, PdfWriter
from pypdf.generic import ArrayObject, ByteStringObject, ContentStream, DictionaryObject, FloatObject, NameObject, NumberObject
from dx_productivity.features.pdf_export import exporter
from dx_productivity.features.pdf_export.models import ExportScope, PdfExportSettings
def legacy_pdf(path, text='输入网络 输出网络 Ω μ ± ×', *, raw=None, compound=False):
writer = PdfWriter()
page = writer.add_blank_page(640, 240)
font = DictionaryObject({NameObject('/Type'): NameObject('/Font'), NameObject('/Subtype'): NameObject('/Type1'),
NameObject('/BaseFont'): NameObject('/Courier'), NameObject('/Encoding'): NameObject('/WinAnsiEncoding')})
page[NameObject('/Resources')] = DictionaryObject({NameObject('/Font'): DictionaryObject({NameObject('/F1'): writer._add_object(font)})})
stream = ContentStream(None, writer)
value = ByteStringObject(raw if raw is not None else text.encode('gbk'))
stream.operations = [([NumberObject(1), NumberObject(0), NumberObject(0)], b'RG'),
([NumberObject(10), NumberObject(20)], b'm'), ([NumberObject(600), NumberObject(20)], b'l'), ([], b'S'),
([], b'BT'), ([NameObject('/F1'), NumberObject(14)], b'Tf'),
([FloatObject(80)], b'Tz'), ([NumberObject(20), NumberObject(120)], b'Td'),
([ArrayObject([value])], b'TJ') if compound else ([value], b'Tj'), ([], b'ET')]
page[NameObject('/Contents')] = writer._add_object(stream)
writer.add_outline_item('Main Sheet Analog', 0)
with Path(path).open('wb') as output:
writer.write(output)
def test_chinese_repair_embeds_unicode_and_keeps_native_vectors_and_bookmark(tmp_path):
from dx_productivity.features.pdf_export.text_repair import repair_text
file = tmp_path / 'native.pdf'
legacy_pdf(file)
before = PdfReader(file)
geometry = [(a, o) for a, o in ContentStream(before.pages[0].get_contents(), before).operations if o in (b'RG', b'rg', b'm', b'l', b'S', b'Td')]
result = repair_text(file, 'chinese', threading.Event())
after = PdfReader(file, strict=True)
assert '输入网络 输出网络 Ω μ ± ×' in after.pages[0].extract_text()
assert after.outline[0].title == 'Main Sheet Analog'
assert geometry == [(a, o) for a, o in ContentStream(after.pages[0].get_contents(), after).operations if o in (b'RG', b'rg', b'm', b'l', b'S', b'Td')]
assert list(before.pages[0].mediabox) == list(after.pages[0].mediabox)
assert result['repaired_strings'] == 1
for font in after.pages[0]['/Resources']['/Font'].values():
font = font.get_object()
if font.get('/Subtype') == '/Type0':
assert font['/ToUnicode'].get_data()
assert font['/DescendantFonts'][0]['/FontDescriptor']['/FontFile2'].get_data()
def test_western_mode_keeps_engineering_symbols_without_gbk_guess(tmp_path):
from dx_productivity.features.pdf_export.text_repair import repair_text
file = tmp_path / 'symbols.pdf'
legacy_pdf(file, raw='±× µ± ÉÉ'.encode('cp1252'))
repair_text(file, 'western', threading.Event())
assert '±× µ± ÉÉ' in PdfReader(file).pages[0].extract_text()
def test_unsupported_text_and_cancellation_preserve_staging_bytes(tmp_path):
from dx_productivity.features.pdf_export.text_repair import repair_text
file = tmp_path / 'compound.pdf'
legacy_pdf(file, compound=True)
before = file.read_bytes()
with pytest.raises(ValueError, match='TJ'):
repair_text(file, 'chinese', threading.Event())
assert file.read_bytes() == before
cancel = threading.Event()
cancel.set()
with pytest.raises(InterruptedError):
repair_text(file, 'chinese', cancel)
assert file.read_bytes() == before
def test_native_mode_preserves_bytes_and_uses_original_mapping(tmp_path):
from dx_productivity.features.pdf_export.text_repair import repair_text
file = tmp_path / 'native.pdf'
legacy_pdf(file)
before = file.read_bytes()
repair_text(file, 'original', threading.Event())
assert file.read_bytes() == before
assert '-udx' not in exporter.build_command(Path('sch2pdf.exe'), Path('Demo.prj'), file, ExportScope.PROJECT)
assert '-udx' in exporter.build_command(Path('sch2pdf.exe'), Path('Demo.prj'), file, ExportScope.PROJECT, text_mode='original')
def test_exporter_repairs_text_before_publishing(tmp_path, monkeypatch):
source = tmp_path / 'source'
(source / 'database').mkdir(parents=True)
project = source / 'Demo.prj'
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir ".\\database"\n')
engine = tmp_path / 'sch2pdf.exe'
engine.touch()
settings = PdfExportSettings(project, ExportScope.CURRENT_PAGE, 'Main', tmp_path / 'output', engine_path=engine)
def native(command, *_args, **_kwargs):
assert '-udx' not in command
legacy_pdf(Path(command[command.index('-a') + 1]))
return 0
monkeypatch.setattr(exporter, 'run_engine', native)
result = exporter.export_project(settings, threading.Event(), active_block_name='Main', active_sheet_name='Analog', local_app_data=tmp_path / 'state')
assert result.state == 'success', result.message
assert '输入网络' in PdfReader(result.output_path).pages[0].extract_text()
assert (result.run_dir / 'text-check.json').is_file()
@@ -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
+2 -1
View File
@@ -8,7 +8,8 @@ INTEGRATION_ROOT = Path("integration/dxdesigner795")
def test_menu_is_ascii_portable_and_uses_795_menu_bar() -> None:
text = (INTEGRATION_ROOT / "MenuAdd.vbs").read_text(encoding="ascii")
assert 'CommandBars("Sheet Menu Bar")' in text
assert 'DxToolsInstallMenuBar("Sheet Menu Bar")' in text
assert 'DxToolsInstallMenuBar("Main Menu Bar")' in text
assert "DxToolsResolveRoot" in text
assert "WScript.ScriptFullName" in text
assert "Scripting.CurrentScriptFullName" in text
+3 -3
View File
@@ -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
+37 -4
View File
@@ -5,9 +5,11 @@ from pathlib import Path
import shutil
import subprocess
import pytest
REPO_ROOT = Path(__file__).resolve().parents[2]
RELEASE_ROOT = REPO_ROOT / "release" / "DxDesigner效率工具"
RELEASE_ROOT = Path(os.environ.get("DXTOOLS_RELEASE_ROOT", str(REPO_ROOT / "release" / "DxDesigner效率工具")))
def _sanitized_environment() -> dict[str, str]:
@@ -35,6 +37,8 @@ def test_release_contains_portable_runtime_and_root_scripts() -> None:
"MenuAdd.vbs",
"DesignBridge.vbs",
"CompatibilityProbe.vbs",
"PdfSaveListener.vbs",
"LoadMenu.vbs",
"templates/BOM模板.xls",
"expedition/ExpeditionBridge.vbs",
"docs/DxDesigner_7.9.5_自动位号工具使用说明.docx",
@@ -77,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",
],
@@ -137,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")
+16
View File
@@ -0,0 +1,16 @@
"""Explicit application shutdown: closing the feature panel only hides it."""
import pytest
from PySide6.QtWidgets import QApplication
from dx_productivity.ui.main_window import MainWindow
@pytest.fixture(autouse=True)
def shutdown_productivity_windows(qtbot):
yield
for window in QApplication.topLevelWidgets():
if isinstance(window, MainWindow):
startup = getattr(window, 'startup_controller', None)
if startup is not None and startup.is_running():
qtbot.waitUntil(lambda: not startup.is_running(), timeout=10000)
window.request_exit()
+154
View File
@@ -0,0 +1,154 @@
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_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
):
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|"]
+216
View File
@@ -0,0 +1,216 @@
from PySide6.QtCore import QCoreApplication, QEvent, QPoint, QPointF, QTimer, Qt
from PySide6.QtGui import QMouseEvent
from dx_productivity.ui.app import FEATURE_PAGE_INDEX, create_main_window
from dx_productivity.ui.floating_toolbar import PRIMARY_PAGES
from dx_productivity.ui.pdf_export_page import PdfExportPage
from dx_productivity.ui.settings_page import SettingsPage
def make_window(qtbot, monkeypatch, tmp_path):
monkeypatch.setenv('LOCALAPPDATA', str(tmp_path))
window = create_main_window()
qtbot.addWidget(window)
window.show_toolbar()
return window
def test_pdf_is_primary_before_settings_and_all_routes_are_accessible(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
assert tuple(window.toolbar.page_buttons) == PRIMARY_PAGES
for index in range(window.pages.count()):
window.toolbar.page_requested.emit(index)
assert window.isVisible() and window.pages.currentIndex() == index
for feature, page_type in (('pdf-export', PdfExportPage), ('settings', SettingsPage)):
window.show_panel(FEATURE_PAGE_INDEX[feature])
assert isinstance(window.pages.currentWidget(), page_type)
def test_floating_restore_retains_page_form_and_background_work(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
window.show_panel(FEATURE_PAGE_INDEX['pdf-export'])
page = window.pages.currentWidget()
page.output_input.setText('pending-user-folder')
ticks = []
timer = QTimer(window)
timer.setInterval(10)
timer.timeout.connect(lambda: ticks.append(1))
timer.start()
qtbot.mouseClick(window.collapse_button, Qt.MouseButton.LeftButton)
assert not window.isVisible() and window.toolbar.isVisible()
assert window.toolbar.windowFlags() & Qt.WindowType.WindowStaysOnTopHint
qtbot.waitUntil(lambda: len(ticks) >= 2)
qtbot.mouseClick(window.toolbar.toggle_button, Qt.MouseButton.LeftButton)
assert window.isVisible() and window.toolbar.isVisible()
assert window.pages.currentWidget() is page
assert page.output_input.text() == 'pending-user-folder'
def test_native_minimize_becomes_toolbar_and_can_repeat(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
window.show_panel(0)
for _ in range(2):
window.showMinimized()
qtbot.waitUntil(lambda: window.toolbar.isVisible() and not window.isVisible())
qtbot.mouseClick(window.toolbar.toggle_button, Qt.MouseButton.LeftButton)
assert window.isVisible() and not window.isMinimized()
def test_drag_only_handle_moves_toolbar_and_panel_without_switching(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
window.show_panel(0)
floating = window.toolbar
floating.move_within_screen(QPoint(10, 40))
panel_position = window.pos()
handle = floating.drag_handle
start = QPointF(handle.mapToGlobal(QPoint(10, 10)))
for kind, local, global_pos, button, buttons in (
(QEvent.Type.MouseButtonPress, QPointF(10, 10), start, Qt.MouseButton.LeftButton, Qt.MouseButton.LeftButton),
(QEvent.Type.MouseMove, QPointF(20, 30), start + QPointF(10, 20), Qt.MouseButton.NoButton, Qt.MouseButton.LeftButton),
(QEvent.Type.MouseButtonRelease, QPointF(10, 10), start + QPointF(10, 20), Qt.MouseButton.LeftButton, Qt.MouseButton.NoButton),
):
event = QMouseEvent(kind, local, global_pos, button, buttons, Qt.KeyboardModifier.NoModifier)
QCoreApplication.sendEvent(handle, event)
# A wider menu button can reach the edge of the offscreen test monitor.
bounds = floating.screen().availableGeometry()
assert floating.pos() == QPoint(min(20, bounds.right() - floating.width() + 1), 60)
assert window.pos().y() == panel_position.y() + 20
assert window.pages.currentIndex() == 0
def test_close_hides_but_explicit_exit_closes_toolbar_and_stops_timers(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
timer = QTimer(window)
timer.start(100)
window.show_panel(0)
window.close()
assert not window.isVisible() and window.toolbar.isVisible() and timer.isActive()
with qtbot.waitSignal(window.window_closed):
window.request_exit()
assert not window.toolbar.isVisible() and not timer.isActive()
def test_narrow_screen_keeps_priority_buttons_and_overflow_routes(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
toolbar = window.toolbar
toolbar.fit_available_width(520)
assert toolbar.width() <= 520
assert toolbar.height() == 44
for index in (0, 1, 7):
assert toolbar.page_buttons[index].isVisible()
for index in (2, 3, 4, 5):
if not toolbar.page_buttons[index].isVisible():
assert toolbar.page_actions[index].isVisible()
toolbar.page_actions[index].trigger()
assert window.pages.currentIndex() == index
def test_page_size_and_toolbar_position_restore_without_overwriting_settings(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
window.show_panel(0)
window.resize(750, 470)
window.show_panel(7)
window.resize(700, 410)
window.show_panel(0)
assert window.size().width() == 750 and window.size().height() == 470
window.toolbar.move_within_screen(QPoint(20, 50))
saved_position = window.toolbar.pos()
path = window.layout_preferences.path
window.request_exit()
from dx_productivity.ui.main_window import MainWindow
restored = MainWindow(layout_path=path)
qtbot.addWidget(restored)
restored.show_panel(7)
assert restored.size().width() == 700 and restored.size().height() == 410
assert restored.toolbar.pos() == saved_position
def test_menu_registration_blocks_exit_but_not_panel_hide(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
from types import SimpleNamespace
window.startup_controller = SimpleNamespace(is_running=lambda: True)
window.show_panel(0)
window.close()
assert not window.isVisible() and window.toolbar.isVisible()
assert not window.request_exit()
assert not window._closing
window.startup_controller = None
def test_saved_offscreen_position_and_bottom_anchor_are_clamped(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
screen = window.toolbar.screen()
bounds = screen.availableGeometry()
window.toolbar.move_within_screen(QPoint(99999, 99999), screen)
assert bounds.contains(window.toolbar.frameGeometry())
window.show_panel(0)
assert bounds.contains(window.frameGeometry())
assert window.frameGeometry().bottom() < window.toolbar.frameGeometry().top()
def test_screen_clamp_preserves_preferred_sizes_through_hide_switch_and_restore(qtbot, monkeypatch, tmp_path):
from types import SimpleNamespace
from PySide6.QtCore import QRect, QSize
from PySide6.QtWidgets import QApplication
from dx_productivity.ui.main_window import MainWindow
bounds = [QRect(0, 0, 1800, 1000)]
screen = SimpleNamespace(availableGeometry=lambda: bounds[0], name=lambda: 'test-monitor')
monkeypatch.setattr(QApplication, 'screenAt', lambda _point: screen)
window = MainWindow(layout_path=tmp_path / 'ui-layout.json')
qtbot.addWidget(window)
window.show_panel(0)
window.resize(1000, 700)
assert window.layout_preferences.page_sizes[0] == QSize(1000, 700)
bounds[0] = QRect(0, 0, 800, 600)
window._screens_changed()
assert window.width() < 1000 and window.height() < 700
window.hide_panel()
assert window.layout_preferences.page_sizes[0] == QSize(1000, 700)
from dx_productivity.ui.layout_preferences import LayoutPreferences
assert LayoutPreferences(window.layout_preferences.path).page_sizes[0] == QSize(1000, 700)
window.show_panel(7)
window.show_panel(0)
assert window.layout_preferences.page_sizes[0] == QSize(1000, 700)
bounds[0] = QRect(0, 0, 1800, 1000)
window._screens_changed()
assert window.size() == QSize(1000, 700)
window.resize(900, 650)
window.hide_panel()
assert window.layout_preferences.page_sizes[0] == QSize(900, 650)
def test_extremely_narrow_toolbar_keeps_children_in_bounds_and_routes_accessible(qtbot, monkeypatch, tmp_path):
from dx_productivity.ui.main_window import MainWindow
from PySide6.QtWidgets import QAbstractButton
window = MainWindow(layout_path=tmp_path / 'ui-layout.json')
qtbot.addWidget(window)
window.show_toolbar()
toolbar = window.toolbar
for width in (340, 240, 180, 120, 96):
toolbar.fit_available_width(width)
toolbar.layout().activate()
assert toolbar.width() <= width and toolbar.height() == 44
for child in toolbar.findChildren(QAbstractButton):
if child.isVisibleTo(toolbar):
assert toolbar.rect().contains(child.geometry()), (width, child.accessibleName(), child.geometry())
visible = [toolbar.layout().itemAt(i).widget() for i in range(toolbar.layout().count())
if not toolbar.layout().itemAt(i).widget().isHidden()]
for left, right in zip(visible, visible[1:]):
assert left.geometry().right() < right.geometry().left(), (width, left.geometry(), right.geometry())
assert toolbar.start_button.isVisible() and toolbar.page_buttons[7].isVisible()
assert toolbar.more_button.isVisible()
for index in range(window.pages.count()):
assert index in toolbar.page_buttons and toolbar.page_buttons[index].isVisible() or toolbar.page_actions[index].isVisible()
with qtbot.waitSignal(toolbar.page_requested) as received:
toolbar.page_actions[0].trigger()
assert received.args == [0]
for width in (80, 48, 34):
toolbar.fit_available_width(width)
for child in toolbar.findChildren(QAbstractButton):
if child.isVisibleTo(toolbar):
assert toolbar.rect().contains(child.geometry())
assert toolbar.more_button.isVisible()
assert toolbar.start_action.isVisible() or toolbar.start_button.isVisible()
assert toolbar.page_actions[7].isVisible() or toolbar.page_buttons[7].isVisible()
with qtbot.waitSignal(toolbar.start_requested):
toolbar.start_action.trigger()
+32
View File
@@ -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
+77
View File
@@ -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()
+13
View File
@@ -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()
+195
View File
@@ -0,0 +1,195 @@
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QToolButton
from dx_productivity.ui.main_window import MainWindow
def test_toolbar_routes_toggle_and_explicit_exit(qtbot, tmp_path, monkeypatch):
monkeypatch.setenv('LOCALAPPDATA', str(tmp_path))
window = MainWindow()
qtbot.addWidget(window)
window.show_toolbar()
assert window.toolbar.isVisible() and not window.isVisible()
assert window.toolbar.windowTitle() == '一叶知秋悬浮工具栏'
for index, button in window.toolbar.page_buttons.items():
qtbot.mouseClick(button, Qt.MouseButton.LeftButton)
assert window.isVisible() and window.pages.currentIndex() == index
assert button.isChecked()
qtbot.mouseClick(button, Qt.MouseButton.LeftButton)
assert not window.isVisible() and window.toolbar.isVisible()
window.show_panel(0)
window.close()
assert not window.isVisible() and window.toolbar.isVisible()
with qtbot.waitSignal(window.window_closed):
assert window.request_exit()
assert not window.toolbar.isVisible()
def test_status_setters_update_hidden_toolbar_without_showing_panel(qtbot, tmp_path, monkeypatch):
monkeypatch.setenv('LOCALAPPDATA', str(tmp_path))
window = MainWindow()
qtbot.addWidget(window)
window.show_toolbar()
window.set_project_status('design.prj', 'C:/design.prj')
window.set_bridge_status('桥接已连接')
window.set_selection_status('已选 C18', '当前页:ROOT / 1\n选中器件:C18')
assert 'C18' in window.toolbar.status_label.text()
assert 'C18' in window.toolbar.status_label.accessibleName()
assert 'ROOT / 1' in window.toolbar.status_label.toolTip()
from PySide6.QtGui import QAccessible
long_reference = 'C18_' + 'LONG_REFERENCE_' * 15
window.set_selection_status('已选 ' + long_reference, '选中器件:' + long_reference)
label = window.toolbar.status_label
assert long_reference not in label.text()
assert long_reference in QAccessible.queryAccessibleInterface(label).text(QAccessible.Text.Name)
assert long_reference in label.accessibleDescription()
window.set_operation_status('PDF 导出中')
assert 'PDF 导出中' in window.toolbar.status_label.text()
assert 'C18' in window.toolbar.status_label.toolTip()
assert not window.isVisible()
def test_panel_toggle_has_explicit_direction_and_text(qtbot):
window = MainWindow()
qtbot.addWidget(window)
toggle = window.toolbar.toggle_button
assert isinstance(toggle, QToolButton)
assert toggle.text() == '展开'
assert toggle.arrowType() == Qt.ArrowType.DownArrow
assert toggle.accessibleName() == '展开面板'
window.show_panel(0)
assert toggle.text() == '收起'
assert toggle.arrowType() == Qt.ArrowType.UpArrow
assert toggle.accessibleName() == '收起面板'
def test_expanded_panel_is_a_frameless_tool_card(qtbot):
window = MainWindow()
qtbot.addWidget(window)
flags = window.windowFlags()
assert flags & Qt.WindowType.FramelessWindowHint
assert flags & Qt.WindowType.Tool
assert window.centralWidget().objectName() == 'appRoot'
def test_more_button_reserves_room_for_text_and_arrow_in_both_themes(qtbot, qapp, tmp_path):
from PySide6.QtWidgets import QStyle
from dx_productivity.ui.app import create_application
from dx_productivity.ui.theme import Theme, apply_theme
create_application([])
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.show_toolbar()
toolbar = window.toolbar
button = toolbar.more_button
for theme in (Theme.LIGHT, Theme.DARK):
apply_theme(qapp, theme)
toolbar.refresh_theme(theme)
toolbar.fit_available_width(1100)
qapp.processEvents()
text_width = button.fontMetrics().horizontalAdvance('更多')
arrow_width = button.style().pixelMetric(QStyle.PixelMetric.PM_MenuButtonIndicator)
assert button.width() >= text_width + arrow_width + 14
assert button.text() == '更多'
assert toolbar.rect().contains(button.geometry())
toolbar.fit_available_width(96)
qapp.processEvents()
assert toolbar.rect().contains(button.geometry())
assert button.menu() is toolbar.more_menu
toolbar.fit_available_width(1100)
qapp.processEvents()
assert button.text() == '更多'
assert button.width() >= text_width + arrow_width + 14
def test_passive_status_keeps_host_focus_and_tracks_background_task(qtbot, qapp, tmp_path, monkeypatch):
from types import SimpleNamespace
from PySide6.QtWidgets import QWidget
monkeypatch.setenv('LOCALAPPDATA', str(tmp_path))
window = MainWindow()
qtbot.addWidget(window)
window.show_toolbar()
host = QWidget()
qtbot.addWidget(host)
host.show()
host.activateWindow()
qapp.processEvents()
active = qapp.activeWindow()
window.set_bridge_status('桥接已连接')
window.set_selection_status('已选 C1', '选中器件:C1')
window.refdes_controller = SimpleNamespace(_apply_in_flight=True)
window._sync_status()
assert window.operation_status.text() == '位号应用中'
assert '位号应用中' in window.toolbar.status_label.text()
assert 'C1' in window.toolbar.status_label.toolTip()
assert qapp.activeWindow() is active and not window.isVisible()
window.refdes_controller._apply_in_flight = False
window.set_operation_status('位号已应用')
assert 'C1' in window.toolbar.status_label.text()
window.set_bridge_status('桥接已断开')
assert 'C1' not in window.toolbar.status_label.text()
assert 'C1' not in window.selection_status.text()
def test_toolbar_clamps_negative_monitor_coordinates(qtbot, tmp_path, monkeypatch):
from PySide6.QtCore import QPoint, QRect
from types import SimpleNamespace
monkeypatch.setenv('LOCALAPPDATA', str(tmp_path))
window = MainWindow()
qtbot.addWidget(window)
bounds = QRect(-1400, -100, 1400, 900)
screen = SimpleNamespace(availableGeometry=lambda: bounds)
window.toolbar.move_within_screen(QPoint(-1600, -300), screen)
assert window.toolbar.pos() == bounds.topLeft()
assert bounds.contains(window.toolbar.frameGeometry())
def test_advanced_section_title_fits_natural_button_geometry(qtbot, qapp):
from dx_productivity.ui.app import create_application
from dx_productivity.ui.collapsible_section import CollapsibleSection
from dx_productivity.ui.theme import apply_theme, Theme
create_application([])
section = CollapsibleSection('高级 PDF 导出与兼容选项')
qtbot.addWidget(section)
section.resize(350, 80)
section.show()
for theme in (Theme.LIGHT, Theme.DARK):
apply_theme(qapp, theme)
qapp.processEvents()
button = section.toggle_button
assert button.width() >= button.fontMetrics().horizontalAdvance(button.text()) + 14
assert button.height() >= 28
assert section.rect().contains(button.geometry())
assert button.text() == '高级 PDF 导出与兼容选项'
assert button.arrowType() == Qt.ArrowType.RightArrow
section.set_expanded(True)
assert button.arrowType() == Qt.ArrowType.DownArrow
section.set_expanded(False)
def test_compact_page_check_and_radio_hit_targets_fit(qtbot, qapp):
from PySide6.QtWidgets import QCheckBox, QRadioButton, QAbstractButton
from dx_productivity.ui.app import create_application
from dx_productivity.ui.pdf_export_page import PdfExportPage
from dx_productivity.ui.settings_page import SettingsPage
from dx_productivity.ui.bom_page import BomPage
from dx_productivity.ui.theme import apply_theme, Theme
create_application([])
apply_theme(qapp, Theme.LIGHT)
for page, width, height in ((PdfExportPage(), 660, 390), (SettingsPage(current_version='0.1.0'), 660, 390), (BomPage(), 780, 480)):
qtbot.addWidget(page)
page.resize(width, height)
page.show()
qapp.processEvents()
assert page.width() <= width and page.height() <= height
targets = [child for child in page.findChildren(QAbstractButton)
if isinstance(child, (QCheckBox, QRadioButton)) and child.isVisibleTo(page)]
assert targets
for child in targets:
assert child.height() >= 28, (type(page).__name__, child.text(), child.geometry())
assert page.rect().contains(child.mapTo(page, child.rect().bottomRight()))
+204
View File
@@ -0,0 +1,204 @@
import json
from types import SimpleNamespace
import pytest
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QLineEdit, QWidget
from dx_productivity.ui.main_window import MainWindow
@pytest.mark.parametrize('expanded', (False, True))
def test_host_minimize_hides_both_windows_and_restores_previous_panel(qtbot, tmp_path, expanded):
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
page = QLineEdit('unfinished input')
window.set_page(1, page, '属性批改')
window.show_panel(1) if expanded else window.show_toolbar()
ticks = []
timer = QTimer(window)
timer.timeout.connect(lambda: ticks.append(1))
timer.start(10)
window.set_host_minimized(True)
assert not window.toolbar.isVisible() and not window.isVisible()
qtbot.waitUntil(lambda: len(ticks) >= 2)
window.set_host_minimized(True)
window.set_host_minimized(False)
assert window.toolbar.isVisible()
assert window.isVisible() is expanded
assert page.text() == 'unfinished input'
if expanded:
assert window.pages.currentIndex() == 1
def test_initial_minimized_host_defers_requested_page_until_restore(qtbot, tmp_path):
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.set_host_minimized(True)
window.show_panel(7)
window.show_toolbar()
assert not window.isVisible() and not window.toolbar.isVisible()
window.set_host_minimized(False)
assert window.isVisible() and window.toolbar.isVisible()
assert window.pages.currentIndex() == 7
def test_collapse_during_host_minimize_remains_collapsed_after_restore(qtbot, tmp_path):
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.show_panel(0)
window.set_host_minimized(True)
window.hide_panel()
assert not window.toolbar.isVisible()
window.set_host_minimized(False)
assert window.toolbar.isVisible() and not window.isVisible()
def test_host_restore_does_not_activate_feature_panel(qtbot, qapp, tmp_path):
if qapp.platformName() == 'offscreen':
pytest.skip('Offscreen activates every shown window; focus requires the native window backend')
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.show_panel(0)
window.set_host_minimized(True)
host = QWidget()
qtbot.addWidget(host)
host.show()
host.activateWindow()
qapp.processEvents()
active = qapp.activeWindow()
window.set_host_minimized(False)
qapp.processEvents()
assert window.isVisible() and qapp.activeWindow() is active
def test_explicit_exit_while_host_minimized_cannot_restore_windows(qtbot, tmp_path):
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.show_panel(0)
window.set_host_minimized(True)
window.request_exit()
window.set_host_minimized(False)
assert not window.isVisible() and not window.toolbar.isVisible()
def test_host_minimize_closes_more_popup(qtbot, qapp, tmp_path):
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.show_toolbar()
window.toolbar.more_menu.popup(window.toolbar.more_button.mapToGlobal(window.toolbar.more_button.rect().bottomLeft()))
qapp.processEvents()
assert window.toolbar.more_menu.isVisible()
window.set_host_minimized(True)
assert not window.toolbar.more_menu.isVisible()
assert not window.toolbar.isVisible()
class FakeHostWindows:
def __init__(self):
self.minimized = {100: False, 200: False}
def resolve(self, view_handle):
return view_handle if view_handle in self.minimized else None
def is_minimized(self, handle):
return self.minimized.get(handle)
def test_watcher_follows_exact_bridge_host_even_during_transaction(qtbot, tmp_path):
from dx_productivity.ui.host_window_watcher import HostWindowWatcher
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.refdes_controller = SimpleNamespace(snapshot=SimpleNamespace(run_id='run-1', design_path='C:/demo.prj'), _apply_in_flight=True)
request = tmp_path / 'request.json'
request.write_text(json.dumps({'run_id': 'run-1', 'design_path': 'C:/demo.prj', 'host_view_handle': 100}), encoding='utf-8')
backend = FakeHostWindows()
watcher = HostWindowWatcher(window, request, backend=backend)
window.show_panel(0)
backend.minimized[200] = True
watcher._check()
assert window.toolbar.isVisible() and window.isVisible()
backend.minimized[100] = True
watcher._check()
assert not window.toolbar.isVisible() and not window.isVisible()
backend.minimized[100] = False
watcher._check()
assert window.toolbar.isVisible() and window.isVisible()
window.request_exit()
assert not watcher.timer.isActive()
@pytest.mark.parametrize('expanded', (False, True))
@pytest.mark.parametrize('minimized', (False, True))
def test_watcher_exits_tool_when_owned_dx_window_disappears(qtbot, tmp_path, expanded, minimized):
from dx_productivity.ui.host_window_watcher import HostWindowWatcher
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.refdes_controller = SimpleNamespace(snapshot=SimpleNamespace(run_id='run-1', design_path='C:/demo.prj'))
request = tmp_path / 'request.json'
request.write_text(json.dumps({'run_id': 'run-1', 'design_path': 'C:/demo.prj', 'host_view_handle': 100}), encoding='utf-8')
backend = FakeHostWindows()
watcher = HostWindowWatcher(window, request, backend=backend)
window.show_panel(0) if expanded else window.show_toolbar()
backend.minimized.pop(200)
watcher._check()
assert not window._closing and watcher.timer.isActive()
assert window.toolbar.isVisible() and window.isVisible() is expanded
backend.minimized[100] = minimized
watcher._check()
backend.minimized.pop(100)
watcher._check()
assert window._closing
assert not window.toolbar.isVisible() and not window.isVisible()
assert not watcher.timer.isActive()
def test_watcher_retries_host_close_after_menu_registration_finishes(qtbot, tmp_path):
from dx_productivity.ui.host_window_watcher import HostWindowWatcher
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.refdes_controller = SimpleNamespace(snapshot=SimpleNamespace(run_id='run-1', design_path='C:/demo.prj'))
request = tmp_path / 'request.json'
request.write_text(json.dumps({'run_id': 'run-1', 'design_path': 'C:/demo.prj', 'host_view_handle': 100}), encoding='utf-8')
backend = FakeHostWindows()
watcher = HostWindowWatcher(window, request, backend=backend)
window.show_toolbar()
registering = [True]
window.startup_controller = SimpleNamespace(is_running=lambda: registering[0])
backend.minimized.pop(100)
watcher._check()
assert not window._closing and watcher.timer.isActive()
registering[0] = False
qtbot.waitUntil(lambda: window._closing)
assert not window.toolbar.isVisible() and not watcher.timer.isActive()
def test_watcher_can_bind_later_from_selection_without_using_foreign_run(qtbot, tmp_path):
from dx_productivity.ui.host_window_watcher import HostWindowWatcher
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.refdes_controller = SimpleNamespace(snapshot=SimpleNamespace(run_id='run-1', design_path='C:/demo.prj'))
request = tmp_path / 'request.json'
request.write_text(json.dumps({'run_id': 'run-1', 'design_path': 'C:/demo.prj', 'host_view_handle': 0}), encoding='utf-8')
backend = FakeHostWindows()
backend.minimized[100] = True
watcher = HostWindowWatcher(window, request, backend=backend)
window.show_toolbar()
selection = tmp_path / 'selection.json'
for run_id, design_path in (('other-run', 'C:/demo.prj'), ('run-1', 'C:/other.prj')):
selection.write_text(json.dumps({'run_id': run_id, 'design_path': design_path, 'host_view_handle': 100}), encoding='utf-8')
watcher._check()
assert window.toolbar.isVisible()
selection.write_text(json.dumps({'run_id': 'run-1', 'design_path': 'C:/demo.prj', 'host_view_handle': 100}), encoding='utf-8')
watcher._check()
assert not window.toolbar.isVisible()
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more