feat: add current-project PDF export
This commit is contained in:
1 parent
771d8efb87
commit
c8caaf8daf
22 files changed
+1959
-1
No files matched your search
@@ -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,15 @@
|
||||
# PDF 导出
|
||||
|
||||
在 DxDesigner 的“Dx 效率工具”菜单中打开“PDF 导出”,工具会按当前桥接工程执行导出。
|
||||
|
||||
范围有三种:
|
||||
|
||||
- **整工程**:导出当前工程中的全部原理图页。
|
||||
- **当前页**:导出打开工具时 DxDesigner 活动视图对应的 Block。
|
||||
- **指定原理图或 Block**:输入本机 DxDesigner 工程中的实际 Block 名称。
|
||||
|
||||
默认输出到 `%LOCALAPPDATA%\DxProductivity\pdf-output` 下按工程区分的目录。可在页面选择其他输出目录,但不能选择源工程目录或其子目录。覆盖现有 PDF 前,手动导出会先询问;自动导出只在新 PDF 验证成功后替换原文件。
|
||||
|
||||
“保存工程后自动导出”默认关闭。开启后,DxDesigner 7.9.5 的保存完成事件会触发后台导出;关闭后监听器会自行退出。导出状态显示在 DxDesigner 状态栏,详细记录位于 `%LOCALAPPDATA%\DxProductivity\pdf-runs`。
|
||||
|
||||
PDF 使用本机 `sch2pdf.exe`、DxDesigner 配置和许可。原生出图可能更新工程数据库或运行记录;发布 PDF 前工具会检查工程文件变化,未确认的变化会阻止发布。
|
||||
@@ -61,6 +61,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"
|
||||
@@ -68,6 +72,10 @@ Sub DxToolsInstallMenu()
|
||||
Set button = DxToolsMenu.Controls.Add
|
||||
button.Caption = DxToolsGuideCaption()
|
||||
button.OnAction = "DxToolsOpenGuide"
|
||||
On Error Resume Next
|
||||
Call DxToolsMaybeStartPdfListener()
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
End Sub
|
||||
|
||||
Sub DxToolsOpenRefDes()
|
||||
@@ -90,6 +98,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 +144,59 @@ 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
|
||||
|
||||
listenerPath = fso.BuildPath(DxToolsHome, "PdfSaveListener.vbs")
|
||||
executablePath = fso.BuildPath(DxToolsHome, "DxDesignerTools.exe")
|
||||
hostPath = shell.ExpandEnvironmentStrings( _
|
||||
"%WINDIR%\SysWOW64\wscript.exe")
|
||||
If Not fso.FileExists(listenerPath) Then Exit Sub
|
||||
If Not fso.FileExists(executablePath) Then Exit Sub
|
||||
If Not fso.FileExists(hostPath) Then Exit Sub
|
||||
commandLine = DxToolsQuote(hostPath) & " //B //NoLogo " & _
|
||||
DxToolsQuote(listenerPath) & " " & DxToolsQuote(settingsPath) & " " & _
|
||||
DxToolsQuote(executablePath) & " exe " & DxToolsQuote(DxToolsHome)
|
||||
shell.Run commandLine, 0, False
|
||||
End Sub
|
||||
|
||||
Function DxToolsEnsureRoot()
|
||||
If DxToolsHome = "" Then DxToolsHome = DxToolsResolveRoot()
|
||||
DxToolsEnsureRoot = (DxToolsHome <> "")
|
||||
@@ -256,6 +321,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.ProjectPath)
|
||||
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.ProjectPath)
|
||||
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
|
||||
@@ -45,6 +45,8 @@ Function DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _
|
||||
Dim netsText
|
||||
Dim selectedNetsText
|
||||
Dim snapshotSequence
|
||||
Dim activeBlockName
|
||||
Dim currentSheetNumberJson
|
||||
|
||||
DxRefreshSnapshot = False
|
||||
Set selectedKeys = CreateObject("Scripting.Dictionary")
|
||||
@@ -71,6 +73,8 @@ Function DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _
|
||||
designId = CStr(designs.GetItem(1))
|
||||
topBlock = projectData.GetiCDBDesignRootBlock(designId)
|
||||
designPath = DxBridgeDesignPath()
|
||||
activeBlockName = DxBridgeCurrentBlockName()
|
||||
currentSheetNumberJson = DxBridgeCurrentSheetNumberJson()
|
||||
componentCount = 0
|
||||
componentText = ""
|
||||
|
||||
@@ -141,6 +145,9 @@ Function DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _
|
||||
" ""snapshot_id"": """ & DxToolsJson(snapshotId) & """," & vbCrLf & _
|
||||
" ""design_id"": """ & DxToolsJson(designId) & """," & vbCrLf & _
|
||||
" ""design_path"": """ & DxToolsJson(designPath) & """," & vbCrLf & _
|
||||
" ""active_block_name"": """ & _
|
||||
DxToolsJson(activeBlockName) & """," & vbCrLf & _
|
||||
" ""current_sheet_number"": " & currentSheetNumberJson & "," & vbCrLf & _
|
||||
" ""nets"": " & netsText & "," & vbCrLf & _
|
||||
" ""selected_nets"": " & selectedNetsText & "," & vbCrLf & _
|
||||
" ""components"": [" & vbCrLf & componentText & vbCrLf & _
|
||||
@@ -383,6 +390,25 @@ Function DxBridgeCurrentSheetNumber()
|
||||
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()
|
||||
DxBridgeCurrentSheetNumberJson = "null"
|
||||
On Error Resume Next
|
||||
DxBridgeCurrentSheetNumberJson = CStr(CLng(ActiveView.Block.SheetNum))
|
||||
If Err.Number <> 0 Then
|
||||
DxBridgeCurrentSheetNumberJson = "null"
|
||||
Err.Clear
|
||||
End If
|
||||
On Error GoTo 0
|
||||
End Function
|
||||
|
||||
Function DxBridgeCoordinate(component, readX)
|
||||
Dim value
|
||||
value = 0
|
||||
|
||||
@@ -10,6 +10,8 @@ hiddenimports = (
|
||||
collect_submodules("dx_productivity")
|
||||
+ collect_submodules("qtawesome")
|
||||
+ collect_submodules("cryptography")
|
||||
+ collect_submodules("pypdf")
|
||||
+ ["pypdf", "win32job", "win32con", "win32process", "pywintypes"]
|
||||
)
|
||||
datas = collect_data_files("qtawesome")
|
||||
|
||||
|
||||
@@ -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,7 @@ 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")
|
||||
|
||||
$runtimeVbs = Join-Path $releaseRoot "_runtime\vbs"
|
||||
New-Item -ItemType Directory -Path $runtimeVbs -Force | Out-Null
|
||||
@@ -103,6 +104,8 @@ 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
|
||||
|
||||
$env:PYTHONPATH = Join-Path $repoRoot "src"
|
||||
$productVersion = (& $pythonExe -c "import dx_productivity; print(dx_productivity.__version__)").Trim()
|
||||
@@ -135,6 +138,7 @@ $expected = @(
|
||||
(Join-Path $releaseRoot "MenuAdd.vbs"),
|
||||
(Join-Path $releaseRoot "DesignBridge.vbs"),
|
||||
(Join-Path $releaseRoot "CompatibilityProbe.vbs"),
|
||||
(Join-Path $releaseRoot "PdfSaveListener.vbs"),
|
||||
(Join-Path $releaseRoot "_runtime\vbs\BridgeCommon.vbs"),
|
||||
(Join-Path $releaseRoot "_runtime\vbs\Snapshot.vbs"),
|
||||
(Join-Path $releaseRoot "_runtime\vbs\Transaction.vbs"),
|
||||
@@ -143,6 +147,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
|
||||
)
|
||||
|
||||
@@ -11,6 +11,8 @@ dependencies = [
|
||||
"PySide6-Essentials>=6.7,<7",
|
||||
"qtawesome>=1.3,<2",
|
||||
"cryptography>=42,<46",
|
||||
"pypdf>=5,<7",
|
||||
"pywin32>=306,<312; sys_platform == 'win32'",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
|
||||
@@ -34,6 +34,11 @@ 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] == "ui":
|
||||
arguments = arguments[1:]
|
||||
|
||||
|
||||
@@ -49,6 +49,12 @@ 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")
|
||||
|
||||
return DesignSnapshot(
|
||||
format_version=FORMAT_VERSION,
|
||||
@@ -59,6 +65,8 @@ 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,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -194,6 +194,8 @@ class DesignSnapshot:
|
||||
components: tuple[ComponentRecord, ...]
|
||||
nets: tuple[NetRecord, ...] = ()
|
||||
selected_nets: tuple[str, ...] = ()
|
||||
active_block_name: str = ""
|
||||
current_sheet_number: int | None = None
|
||||
|
||||
@property
|
||||
def component_count(self) -> int:
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Single-project PDF export for DxDesigner."""
|
||||
@@ -0,0 +1,41 @@
|
||||
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("--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,
|
||||
overwrite=True,
|
||||
)
|
||||
_write_status(options.status_file, result.message)
|
||||
return 0 if result.state == "success" else 1
|
||||
@@ -0,0 +1,243 @@
|
||||
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
|
||||
):
|
||||
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,
|
||||
None,
|
||||
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,
|
||||
) -> 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)
|
||||
else:
|
||||
process = subprocess.Popen(
|
||||
args,
|
||||
cwd=cwd,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=stdout,
|
||||
stderr=stderr,
|
||||
)
|
||||
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,446 @@
|
||||
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
|
||||
|
||||
from .engine import discover_engine, run_engine
|
||||
from .models import ExportScope, PdfExportResult, PdfExportSettings
|
||||
|
||||
|
||||
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 _fingerprint(root: Path, cancel: threading.Event) -> dict[str, str]:
|
||||
digest_map: dict[str, str] = {}
|
||||
for path in _source_files(root):
|
||||
if cancel.is_set():
|
||||
raise InterruptedError("导出已取消")
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
while chunk := stream.read(1024 * 1024):
|
||||
if cancel.is_set():
|
||||
raise InterruptedError("导出已取消")
|
||||
digest.update(chunk)
|
||||
digest_map[path.relative_to(root).as_posix()] = digest.hexdigest()
|
||||
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 = "") -> 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 名称,请刷新设计快照")
|
||||
digest = hashlib.sha256(name.casefold().encode("utf-8")).hexdigest()[:6]
|
||||
suffix = f"current-page-{_safe_name(name)}-{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 build_command(
|
||||
engine: Path,
|
||||
project: Path,
|
||||
output: Path,
|
||||
scope: ExportScope,
|
||||
block_name: str = "",
|
||||
) -> list[str]:
|
||||
command = [
|
||||
str(engine),
|
||||
"-project",
|
||||
str(project),
|
||||
"-a",
|
||||
str(output),
|
||||
"-c",
|
||||
"4",
|
||||
"-p",
|
||||
"-e",
|
||||
"-i2s",
|
||||
"-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 = "",
|
||||
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
|
||||
|
||||
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)
|
||||
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)
|
||||
_write_json(
|
||||
run_dir / "request.json",
|
||||
{
|
||||
"project": str(project),
|
||||
"scope": settings.scope.value,
|
||||
"block_name": block_name,
|
||||
"output": str(final_path),
|
||||
"engine": str(engine),
|
||||
"command": command,
|
||||
},
|
||||
)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
emit("核验当前工程和输出目录")
|
||||
before = _fingerprint(source_root, cancel)
|
||||
_write_json(run_dir / "source-before.json", before)
|
||||
emit("直接调用本机 sch2pdf.exe;读取当前工程配置")
|
||||
return_code = run_engine(command, source_root, run_dir, cancel, timeout, emit)
|
||||
if return_code != 0:
|
||||
raise RuntimeError(f"原生引擎退出码 {return_code};请检查工程、许可和运行日志")
|
||||
if cancel.is_set():
|
||||
raise InterruptedError("导出已取消")
|
||||
pages, size, sha256 = _validate_pdf(stage)
|
||||
_write_json(
|
||||
run_dir / "pdf-check.json",
|
||||
{"pages": pages, "size": size, "sha256": sha256},
|
||||
)
|
||||
after = _fingerprint(source_root, cancel)
|
||||
_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})
|
||||
state = "uncertain"
|
||||
message = "导出期间工程文件发生变化,未发布 PDF;请检查运行记录中的 source-assessment.json"
|
||||
return PdfExportResult(project, state, message, final_path, pages, run_dir)
|
||||
if any(accepted.values()):
|
||||
warnings.append("原生数据库或运行记录发生变化;这不代表源工程只读")
|
||||
_write_json(run_dir / "source-assessment.json", {"accepted": accepted, "blocked": blocked})
|
||||
if 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 += "。" + warnings[0]
|
||||
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())
|
||||
_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})
|
||||
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,49 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def ensure_listener(config_path: Path, tool_root: Path) -> str | None:
|
||||
windows_root = Path(os.environ.get("WINDIR", r"C:\Windows"))
|
||||
script_path = Path(tool_root) / "PdfSaveListener.vbs"
|
||||
host = windows_root / "SysWOW64" / "wscript.exe"
|
||||
if not host.is_file():
|
||||
if os.environ.get("PROCESSOR_ARCHITEW6432"):
|
||||
return "未找到 32 位 Windows Script Host,自动导出监听未启动"
|
||||
host = windows_root / "System32" / "wscript.exe"
|
||||
if not host.is_file() or not script_path.is_file():
|
||||
return "找不到 DxDesigner 保存事件监听脚本,自动导出监听未启动"
|
||||
if getattr(sys, "frozen", False):
|
||||
executable = Path(sys.executable)
|
||||
mode = "exe"
|
||||
working_root = executable.parent
|
||||
else:
|
||||
executable = Path(sys.executable)
|
||||
mode = "module"
|
||||
working_root = Path(__file__).resolve().parents[4]
|
||||
command = [
|
||||
str(host),
|
||||
"//B",
|
||||
"//NoLogo",
|
||||
str(script_path),
|
||||
str(Path(config_path).resolve()),
|
||||
str(executable),
|
||||
mode,
|
||||
str(working_root),
|
||||
]
|
||||
try:
|
||||
subprocess.Popen(
|
||||
command,
|
||||
cwd=working_root,
|
||||
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,38 @@
|
||||
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
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
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,125 @@
|
||||
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", "")
|
||||
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,
|
||||
)
|
||||
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),
|
||||
"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
|
||||
@@ -29,6 +29,8 @@ 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
|
||||
@@ -76,6 +78,7 @@ FEATURE_PAGE_INDEX = {
|
||||
"bom": 5,
|
||||
"history": 6,
|
||||
"settings": 7,
|
||||
"pdf-export": 8,
|
||||
}
|
||||
|
||||
STATUS_TEXT = {
|
||||
@@ -249,6 +252,15 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
|
||||
window.set_page(7, 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.operation_status.setText)
|
||||
window.set_page(8, pdf_export_page, "PDF 导出")
|
||||
window.pdf_export_controller = pdf_export_controller
|
||||
if settings_controller.auto_check_due(persisted_settings):
|
||||
QTimer.singleShot(
|
||||
0,
|
||||
@@ -270,12 +282,15 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
|
||||
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:
|
||||
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()
|
||||
)
|
||||
if watcher is not None:
|
||||
watcher.snapshot_reloaded.connect(pdf_export_controller.load_snapshot)
|
||||
window.navigation.setCurrentRow(0)
|
||||
window.pages.setCurrentIndex(0)
|
||||
window.page_title.setText("自动位号")
|
||||
|
||||
@@ -31,6 +31,7 @@ NAVIGATION = (
|
||||
("BOM 工具", "fa6s.table"),
|
||||
("操作历史", "fa6s.clock-rotate-left"),
|
||||
("设置", "fa6s.gear"),
|
||||
("PDF 导出", "fa6s.file-pdf"),
|
||||
)
|
||||
|
||||
|
||||
@@ -74,6 +75,7 @@ class MainWindow(QMainWindow):
|
||||
getattr(self, "settings_controller", None),
|
||||
getattr(self, "refdes_controller", None),
|
||||
getattr(self, "history_controller", None),
|
||||
getattr(self, "pdf_export_controller", None),
|
||||
):
|
||||
shutdown = getattr(controller, "shutdown", None)
|
||||
if callable(shutdown):
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
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,
|
||||
overwrite: bool,
|
||||
cancel: threading.Event,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.settings = settings
|
||||
self.active_block_name = active_block_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,
|
||||
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 _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)
|
||||
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,
|
||||
overwrite,
|
||||
self._cancel,
|
||||
)
|
||||
self._worker.moveToThread(self._thread)
|
||||
self._thread.started.connect(self._worker.run)
|
||||
self._worker.progress.connect(self.page.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.page.set_status("正在调用原生 PDF 引擎…")
|
||||
self._thread.start()
|
||||
|
||||
@Slot(object)
|
||||
def _on_finished(self, result: PdfExportResult) -> None:
|
||||
self.page.set_status(result.message)
|
||||
self.status_changed.emit(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.page.set_status("正在取消导出…")
|
||||
|
||||
def shutdown(self) -> None:
|
||||
self.cancel()
|
||||
if self._thread is not None and self._thread.isRunning():
|
||||
self._thread.quit()
|
||||
self._thread.wait()
|
||||
@@ -0,0 +1,255 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import QSize, Signal
|
||||
from PySide6.QtWidgets import (
|
||||
QCheckBox,
|
||||
QComboBox,
|
||||
QFileDialog,
|
||||
QFormLayout,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QMessageBox,
|
||||
QPushButton,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from dx_productivity.domain.models import DesignSnapshot
|
||||
from dx_productivity.features.pdf_export.models import ExportScope, PdfExportSettings
|
||||
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._theme = Theme.LIGHT
|
||||
self._build_ui()
|
||||
|
||||
def _build_ui(self) -> None:
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(20, 16, 20, 16)
|
||||
layout.setSpacing(12)
|
||||
|
||||
form = QFormLayout()
|
||||
form.setHorizontalSpacing(14)
|
||||
form.setVerticalSpacing(12)
|
||||
|
||||
self.project_input = QLineEdit()
|
||||
self.project_input.setReadOnly(True)
|
||||
self.project_input.setPlaceholderText("未连接 DxDesigner 工程")
|
||||
form.addRow("当前工程", self.project_input)
|
||||
|
||||
self.scope_combo = QComboBox()
|
||||
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)
|
||||
|
||||
block_row = QHBoxLayout()
|
||||
self.block_input = QLineEdit()
|
||||
self.block_input.setPlaceholderText("DxDesigner 原理图或 Block 名称")
|
||||
block_row.addWidget(self.block_input, 1)
|
||||
self.active_block_label = QLabel("")
|
||||
self.active_block_label.setMinimumWidth(160)
|
||||
block_row.addWidget(self.active_block_label)
|
||||
form.addRow("Block", block_row)
|
||||
|
||||
output_row = QHBoxLayout()
|
||||
self.output_input = QLineEdit()
|
||||
self.output_button = QPushButton("浏览…")
|
||||
self.output_button.setIconSize(QSize(16, 16))
|
||||
self.output_button.clicked.connect(self._choose_output)
|
||||
output_row.addWidget(self.output_input, 1)
|
||||
output_row.addWidget(self.output_button)
|
||||
form.addRow("输出目录", output_row)
|
||||
|
||||
engine_row = QHBoxLayout()
|
||||
self.engine_input = QLineEdit()
|
||||
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)
|
||||
form.addRow("原生引擎", engine_row)
|
||||
layout.addLayout(form)
|
||||
|
||||
self.auto_export_checkbox = QCheckBox("保存工程后自动导出")
|
||||
self.auto_export_checkbox.setEnabled(False)
|
||||
layout.addWidget(self.auto_export_checkbox)
|
||||
|
||||
self.warning_label = QLabel(
|
||||
"原生出图直接读取当前工程;DxDesigner 可能更新数据库或运行记录。"
|
||||
)
|
||||
self.warning_label.setWordWrap(True)
|
||||
self.warning_label.setObjectName("secondaryLabel")
|
||||
layout.addWidget(self.warning_label)
|
||||
|
||||
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.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.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)
|
||||
|
||||
def bind(self, snapshot: DesignSnapshot | None, settings: PdfExportSettings) -> None:
|
||||
self._loading = True
|
||||
self.snapshot = snapshot
|
||||
self.project_input.setText(snapshot.design_path if snapshot else "")
|
||||
scope_index = self.scope_combo.findData(settings.scope.value)
|
||||
self.scope_combo.setCurrentIndex(max(scope_index, 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._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,
|
||||
)
|
||||
|
||||
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())
|
||||
)
|
||||
self.export_button.setEnabled(enabled and valid_scope)
|
||||
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.export_button.setEnabled(not busy and self.snapshot is not None)
|
||||
self.cancel_button.setEnabled(busy)
|
||||
self.scope_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
|
||||
)
|
||||
|
||||
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.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)
|
||||
self.active_block_label.setText(
|
||||
f"活动页:{self.snapshot.active_block_name}"
|
||||
if current and self.snapshot and self.snapshot.active_block_name
|
||||
else ("活动 Block 不可用" if current else "")
|
||||
)
|
||||
self.active_block_label.setVisible(current)
|
||||
if not self._loading:
|
||||
self.set_can_export(self.snapshot is not None)
|
||||
self._emit_settings()
|
||||
|
||||
def _emit_settings(self, *_args) -> None:
|
||||
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 _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()
|
||||
Reference in new issue
Block a user