release: ship validated Mentor PDF exporter v1.0.0

This commit is contained in:
阿白叔 committed 2026-10-10 16:28:18 +08:00
1 parent d4928af5b6
commit 0334f2b85b
50 files changed
+3998 -219

No files matched your search

+5
View File
@@ -15,3 +15,8 @@ __pycache__/
*.prj *.prj
*.pdf *.pdf
*.zip *.zip
# Local engineering references and evidence are never published.
/PDF参考/
*.lmc
*.log
+16
View File
@@ -0,0 +1,16 @@
# 更新记录
## 1.0.0 — 2026-10-10
首个正式版,延续已验收的直接导出、参考配色和中文修复行为。
- 原工程名输出;同名版本使用自然子目录,不添加摘要后缀。
- 修复安全 ASCII 笔画隐藏检索层被误拦截的问题,保留原有矢量内容。
- 精简界面说明,统一控件对齐,扩大工程队列,执行时支持滚动。
- 简化可见日志,保留完整运行记录和失败重试。
- 统一正式产品名称、版本号、窗口 / 任务栏 / EXE 图标及 Windows 文件属性。
- 添加可重复构建、包校验与组织仓库发行流程。
## 0.3.x — 内部验证阶段
完成原生引擎、源保护、编码、配色、批量扫描和成品验证。历史内部测试记录不作为所有工程、平台或 Mentor 版本的兼容性保证。
+55 -37
View File
@@ -1,58 +1,76 @@
# Mentor 工程批量导出 PDF 测试工具 # Mentor PDF 批量导出
独立 Windows 简易界面,扫描 DxDesigner 原理图工程,通过本机原生 `sch2pdf.exe` 串行导出 PDF。每个任务在独立工程副本中执行,不保存或改写源工程,不修改源工程的 `dxpdf.ini`。这是 v0.1.0 测试版,不是无需 Mentor 的独立转换器。 **v1.0.0 正式版 · Windows x64**
## 使用便携版 扫描 Mentor / DxDesigner 原理图工程,调用本机原生 `sch2pdf.exe` 串行导出 PDF。提供工程队列、参考配色、中文字体处理、失败重试和运行记录。
解压整个发行目录,双击 `MentorPDFExporter.exe`。不能只复制 exe,必须保留 `_internal` 文件夹。用户不需要安装 Python,但本机必须安装 Mentor、拥有有效许可证,工程引用的库必须可访问。 ## 下载与启动
1. 选择包含一个或多个工程的目录,点击“扫描工程”。排除 PCB、备份、输出、运行目录;会完整递归而不是根目录发现工程后提前结束。 从组织仓库的 **Releases / 发行版** 下载 `MentorPDFExporter-1.0.0-win64.zip`,解压整个文件夹,双击 `MentorPDFExporter.exe`。不能单独复制 EXE,必须保留 `_internal` 文件夹。
2. 选择源工程外部的 PDF 输出目录。工程名相同的项目通过路径摘要区分,不会互相覆盖。
3. 检查自动发现的 `sch2pdf.exe`,必要时手动选择。
4. 网络中心库不可达时,显式选择对应本地 `.lmc`。工具只修改工作副本的 `CentralLibrary`,不改源工程;不会自动选择可能不匹配的库。
5. 勾选工程,确认配置,然后开始导出。默认不覆盖已有 PDF。失败项可通过“选中失败项重试”重新执行。
6. 可以停止当前任务及后续队列;仅结束工具启动的引擎进程树,不关闭用户的 DxDesigner。
## 配置与安全 - 用户无需安装 Python。
- 本机必须安装 Mentor、拥有有效许可证,工程引用的中心库 / 依赖库必须可访问。
- 已验收环境:Windows 11 x64、Mentor EE 7.9.5。其他系统或 Mentor 版本需要另行验证。
- 源码目录中的 `Start-MentorPDF.cmd` 优先启动 v1.0.0 便携版,否则启动本项目开发环境。
- 默认白底彩色并保留彩色文字(`-c 4`)、器件弹出菜单开启、可见超链接关闭、URL-valued 清空、ICT 转原理图开启、线宽 1。 ## 使用
- `Use exclusion info` 按截图保持勾选,它不等于“去掉文字掩盖”。不要为了掩盖问题直接关闭排除信息。
- 整工程范围可能包含非顶层 Block;如只需要截图中的 Block 范围,选择“指定原理图 / Block”并填真实名称,例如 `PON`,不是 `Board1`。
- 现有字体映射保留;笔画字体提供对照方式。不同工程的中文、特殊字符和背景掩盖效果仍须查看样张。PDF 结构成功不代表排版、中文及图页范围全部验收完成。
- 源数据库必须在工程内部,含外部数据库路径或链接的工程不执行,以免副本反而写回原数据库。
- 工作副本中排除 PCB、CES、ICXPro、Integration、备份与历史日志;不依赖这些目录的标准原理图工程已做验证,特殊外部依赖需要人工检查。
- 已有输出只有显式勾选覆盖后才替换。引擎正常退出且 PDF 解析成功、至少一页、源内容指纹一致后,才发布新文件。
## 日志 1. 选择工程目录,点击 **扫描工程**。工具会递归识别原理图工程并排除 PCB、备份、输出和运行目录。
2. 选择位于源工程之外的 PDF 输出目录。
3. 确认自动发现的导出引擎;必要时手动选择本机 `sch2pdf.exe`。
4. 勾选工程并确认配色、字体和导出范围,点击 **开始批量导出**。
5. 完成后打开输出目录;失败项目可选中重试。运行中队列仍可滚动查看。
默认保存到 `%LOCALAPPDATA%\MentorPDFExporter\runs`。每次记录源工程指纹、实际命令、副本配置、stdout/stderr、PDF 页数/摘要以及结果 JSON,失败输出不会成为正式 PDF。发布前以原子写入并刷盘方式持久化提交预记录;覆盖前保留旧 PDF 备份。若提交后结果记录写入失败,会返回“待核验”并保留真实输出路径,不能当作完整成功。工作副本包含工程数据,请按公司要求保存;测试版不自动删除运行记录。 PDF 与原 `.prj` 文件同名,不加随机 / 摘要后缀。同名不同版本放入自然子目录,例如 `Work/PON.pdf` 和 `Cert/PON.pdf`。子集重试保留扫描时规划的目录。
## 已确认的真实测试 依赖库沿用各原工程现有配置,不需要在本工具另选。中心库不是待导出的工程集合;库路径失效时,应先在 Mentor 中修复原工程配置。
本机 EE 7.9.5;PON 示例工程原引用 `192.168.0.252` 的网络中心库,首次默认路径导出超时且只产生空 PDF;在副本中显式使用本地对应库后正常导出 24 页。源工程参与复制的文件内容指纹一致。样张外部 URL 数为零。 ## 默认出图设置
默认样张部分中文批注存在乱码、浅色原理图对象对白底对比度较低,因此该版本只标为测试版,不把 PDF 结构验证当作最终出图质量验收。 - 工程参考配色,白底彩色,保留显式文字属性颜色与原有线宽。
- Arial 字体映射及中文宋体回退,修复 CP936 / GBK 旧工程文字。
- 整工程导出;也可指定真实原理图 / Block 名称。
- 不覆盖已有 PDF;只有主动勾选允许覆盖才会替换旧文件。
- 原生高级参数折叠显示,界面只保留操作控件与简短状态。
## 额外安全保护 **普通 WinAnsi 工程请关闭 GBK 修复。** 不能将编码修复用于所有项目,也不能只凭“成功”状态代替最终 PDF 检查。安全可识别的英文笔画隐藏检索层会保留;无法安全处理的字体仍会明确失败。
- 队列开始前统一检查全部源工程,防止 A 的输出目录误选到 B 的数据库中。 ## 源工程与覆盖策略
- CLI 报告仅允许 `.json`,拒绝写入源工程/运行证据目录或覆盖非本工具的 JSON;自动测试截图也不能写入源目录。
- 最后一次源内容核验在发布之前完成,不在覆盖旧 PDF 后才否决结果。
- 批量队列预记录写入失败时不启动引擎;末尾记录更新失败仍保留计数、内存结果和逐工程提交预记录。
- 打包排除构建机 PATH 中误发现的第三方 ICU DLL,使用与本机 Qt 轮子配套的 Windows 系统依赖。
- 当前真实验收环境为 Windows 11;尚未对其他 Windows 版本做兼容性验收。
## 开发 工具直接读取原工程,**不创建工程工作副本、不备份旧 PDF**,不改工程字体 INI、全局 Mentor 配色、Windows 字体或父进程环境。独立打印配色只在本次导出子进程生效。
Python 3.12。安装依赖后: **直接导出不是只读保证。** Mentor 原生引擎可能更新数据库、运行记录,旧工程可能触发原生升级并产生引擎自身的升级备份。工具不擅自删除或回滚这些更新。
默认将已分类的数据库 / 运行记录更新记录为提示,不仅因此阻止有效 PDF 发布;图纸、配置、未知文件等变化仍会阻止发布。严格源检查会阻止任何受保护源变化后的发布,但不能撤销引擎已经写回的数据。路径分类也不能证明所有设计语义完全不变。
成功覆盖后工具不提供旧 PDF 恢复。停止任务不能回滚已发生的原生写回;成功出图后会等待原生后台写回完成,不强杀后台数据库服务。
## 运行记录
默认保存在 `%LOCALAPPDATA%\MentorPDFExporter\runs`。界面显示简短进度、结果与错误;完整命令、引擎输出、PDF 检查和源变化记录可通过 **打开运行记录** 查看。日志可能包含工程路径或敏感文字,请按所在组织的要求保存,不要随源码上传。
## 正式版交付
- 窗口、任务栏和 EXE 使用统一的原创 PDF 导出图标;不使用 Mentor / Adobe 商标图标。
- Windows 文件属性包含正式产品名称与 1.0.0 版本信息。
- 发布包附带使用说明、发布说明、第三方声明和 SHA-256 校验文件。
- 不分发 Mentor 二进制、许可证、工程、中心库、参考 PDF 或 Windows 字体文件。
- 验证范围和变更说明见 `CHANGELOG.md` 与 `docs/releases/1.0.0.md`。
## 源码开发与构建
使用 Python 3.12 x64:
```powershell ```powershell
$env:PYTHONPATH = "$(Get-Location)\src" python -m venv .venv
.\.venv\Scripts\python.exe -m mentor_pdf_export .\.venv\Scripts\python.exe -m pip install -r packaging/requirements-release.txt
.\.venv\Scripts\python.exe -m pip install -e ".[dev]"
.\.venv\Scripts\python.exe -m pytest -q .\.venv\Scripts\python.exe -m pytest -q
.\.venv\Scripts\python.exe -m PyInstaller packaging\MentorPDFExporter.spec --distpath release --workpath build\pyinstaller --noconfirm .\.venv\Scripts\python.exe packaging/build_release.py
``` ```
CLI:`--self-check --report FILE`;批量命令行:`--export A.prj B.prj --output DIR --library LOCAL.lmc --report FILE`;UI 自动测试:`--project-root DIR --output DIR --library LOCAL.lmc --ui-smoke SCREENSHOT.png --ui-export-smoke --report FILE`。 构建结果位于 `release/MentorPDFExporter-1.0.0` 和 `release/MentorPDFExporter-1.0.0-win64.zip`。开发命令行支持 `python -m mentor_pdf_export --help`。
源码、测试和说明纳入 Git。原始文档、Mentor 工程、PDF、运行数据和发行产物不入 Git。无自动上传、联网更新或用户环境变量修改。 ### 发布维护
构建后运行 `python packaging/verify_release.py` 验收 EXE 与最终 ZIP。`packaging/publish_release.py` 默认只检查 `git.simgreek.com` 登录和组织可达性;加 `--publish` 后才会创建私有仓库、推送源码及正式标签、上传已验收的 ZIP 和校验文件。发布前需要完整回归记录、干净源码提交与匹配的版本标签。凭据只从现有 Git 凭据管理器读取,不写入源码、远端 URL 或发行包。
+2 -2
View File
@@ -1,8 +1,8 @@
@echo off @echo off
setlocal setlocal
cd /d "%~dp0" cd /d "%~dp0"
if exist "%~dp0release\MentorPDFExporter\MentorPDFExporter.exe" ( if exist "%~dp0release\MentorPDFExporter-1.0.0\MentorPDFExporter.exe" (
start "" "%~dp0release\MentorPDFExporter\MentorPDFExporter.exe" start "" "%~dp0release\MentorPDFExporter-1.0.0\MentorPDFExporter.exe"
exit /b 0 exit /b 0
) )
if exist "%~dp0.venv\Scripts\pythonw.exe" ( if exist "%~dp0.venv\Scripts\pythonw.exe" (
+28
View File
@@ -0,0 +1,28 @@
# Mentor PDF 批量导出 v1.0.0
发布日期:2026-10-10。渠道:正式版,Windows x64。
## 交付内容
- 完整便携目录与 ZIP,不需要另装 Python。
- 原创 PDF 导出图标:EXE、窗口与任务栏统一,多分辨率 16 / 24 / 32 / 48 / 64 / 128 / 256 px。
- Windows 产品属性、使用说明、第三方声明、SHA-256 文件。
## 已验证基础
v0.3.4 的 236 项回归通过。实际失败批次的 4 个原工程重新导出成功;成品已渲染,中文可读,同次绘图、颜色、线宽和定位检查一致。交付 EXE 已实际完成其中一个原失败工程的导出。正式化改动不调整导出参数、参考配色或字体修复规则。
正式版新增身份、图标、资源与发布流程回归;发布前重新执行完整回归、EXE 属性 / 图标核对、普通默认 UI 扫描、仅系统 PATH 启动和 ZIP CRC 校验。本机完整记录保留在忽略的 artifacts 目录,不随仓库或安装包分发。
## 使用边界
本机需要 Mentor 与有效许可证;已验收 Windows 11 x64 / EE 7.9.5。工程及库可达性由用户原有配置决定。直接导出可能引发原生数据库写回或升级,不保证源数据库只读、所有历史版本兼容或全部设计语义不变。详见 README 中的源工程策略。
## 正式交付验证结果
- 完整回归:279 项通过。
- 冻结 EXE 的 17 个应用模块与交付源码逐一匹配。
- EXE 大小图标可由 Windows Shell 提取;应用资源图标与源 ICO 完全一致。
- 普通默认界面在仅系统 PATH 环境下启动并完成 3 个合成工程扫描;应用 / 窗口图标有效,稳定任务栏 AppID 已设置。
- Windows 文件属性版本为 1.0.0;完整 ZIP 文件集合、逐文件 SHA-256 与 CRC 校验通过。
- 构建 runtime 和第三方许可文件使用批准来源清单;私有工程、许可证、字体、运行产物及额外 ZIP 成员均有拒绝回归。
@@ -0,0 +1,34 @@
# Mentor PDF UI Dependency Font Color Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox syntax for tracking.
**Goal:** Make dependency selection clearly optional, refresh the UI to blue/gray, and add evidence-backed native font/print-color profiles.
**Architecture:** Keep isolated project export and pre-publication safety intact. Add per-run private configuration and process-only environment overrides, never global/user environment or installed Mentor config edits. Native behavior must be verified before claiming Chinese correctness.
**Tech Stack:** Existing Python 3.12 / PySide6 / pywin32 / pypdf / local EE7.9.5.
**Spec:** Approved preceding chat design: rename/hide optional project dependency library, blue-gray interface, high-contrast print palette, Arial font mapping comparison; no library-content export.
## Global Constraints
- Empty library_override means preserve original .prj CentralLibrary, never require manual selection or silently pick another library.
- All native adjustments occur in copied project or run-owned config; source CAD, installed Mentor files and user environment unchanged.
- Preserve Job-before-resume, whole-queue path guards, source fingerprints, commit pre-records, no-overwrite default and traceable failure results.
- Do not promise Arial fixes Chinese without actual rendered evidence. Distinguish font mapping from UI typography and from byte encoding.
- Native/private config feasibility first. If native color/font settings are ignored or unsupported, record it and use a verified approach or expose a clearly labelled experimental option; never ship a no-op as a working feature.
### Task 1: Native probe and profile semantics
Files: tests/test_profiles.py, tests/test_workspace.py, src/mentor_pdf_export/{models,profiles,workspace,engine}.py; throwaway probes under artifacts/v02.
- [ ] Establish baseline/Arial/Chinese-font comparison on isolated PON data and inspect PDF resources/text/rendering.
- [ ] Test private colors.def PRINT_COLOR scope; distinguish screen/display from output palette.
- [ ] Write failing tests for empty library preservation, font profiles, print palette, process-only config and original-file safety.
- [ ] Implement the smallest verified configuration route; run red/green tests.
### Task 2: UI clarity and blue-gray styling
Files: tests/test_ui.py, src/mentor_pdf_export/ui.py.
- [ ] Red tests: optional dependency section hidden by default, explicit selection reveals it, empty dependency exports unchanged, font/color controls flow to options, no scroll reset.
- [ ] Implement advanced dependency wording/help, blue-gray style and profile controls with accurate warnings.
- [ ] Verify UI tests and capture native-window screenshot.
### Task 3: Delivery
Files: README.md, docs/testing, version/packaging metadata; release v0.2.0.
- [ ] Run full suite, scoped safety review, real final exe native batch and rendered PDF comparison.
- [ ] Package versioned portable directory/ZIP without deleting v0.1.0 release; test extracted runtime and confirm source/global configuration hashes unchanged.
- [ ] Commit source on feat/pdf-export and report exact remaining limitations.
@@ -0,0 +1,50 @@
# 0.3.0 配色与直接导出界面验证(2026-10-10)
## 本轮确认的设计
- 默认原始配色(参考风格·推荐),白底高对比改为可选;默认仍为原生 color=4。
- 字体映射/CP936 编码修复独立,不自动触发重配色。
- 不创建工程副本,不备份旧 PDF,不替换依赖库;没有跳过源指纹保护。
- 原生引擎可能更新数据库/日志的风险在主界面中常驻提示。
## 回归验证
全量命令:`.venv\Scripts\python.exe -m pytest -q --junitxml=artifacts/pytest-v03-reference.xml`。
结果:**151 passed,82.67 秒,退出码 0**。
本轮新增/更新验证:
1. 默认推荐原始配色,高对比不再标推荐。
2. Arial+GBK 修复仍使用原始配色、color=4,不隐式重配色。
3. 直接模式风险提示可见,明确数据库变化时待核验、不发布。
4. Arial、宋体、微软雅黑三种 font-only 修复均保留测试中全部 RGB 颜色指令、hairline/强调线宽、矢量路径、文字原点和页面框;中文正确提取。
5. 既有西文符号/编码保护、取消/失败保护、源指纹、无副本/无旧 PDF 备份测试均通过。
证据:`artifacts/pytest-v03-reference.log`、`artifacts/pytest-v03-reference.xml`。
## 源码界面测试
只扫描已有测试工程 A/B,**不执行原生导出**。字体 Arial+中文回退,显式启用已确认 GBK,配色 original。
结果:退出码 0;发现 2 个工程,截图成功,`ui_export_requested=false`,无导出结果。
证据:`artifacts/ui-v03-reference.json`、`artifacts/ui-v03-reference.png`。已人工查看截图,中文和风险提示可见,无明显控件遮挡。
## 原生直接模式仍未完成无损验收
既有 2026-10-10 直接试验使用的是已有测试工程,不是公司重要原工程。原生输出后受保护 `database/icdb.dat` 的内容变化,结果 `uncertain`,未发布正式 PDF。主数据库变化的语义尚未查明,不能称为仅更新日志或缓存;文件内容检查不能回滚源变化。
本轮仅实施已批准的配色/界面方案及回归验证,不重新试跑重要原工程,也不把用户对配色的确认视为允许忽略数据库变化。便携版定位为界面/功能预览,不是原工程无损导出正式版。旧版副本流程的成功记录不能替代当前直接模式验收。
## 便携预览版验证
- 使用全新 PyInstaller workpath 构建 0.3.0,构建退出码 0;未改写或删除旧发行版。
- 从 EXE 的 PYZ 提取并逐一比较代码对象,**14 个运行模块全部匹配当前源码**。冻结入口为 packaging/entrypoint.py,不使用 python -m 的 __main__.py。
- ZIP 共 255 个文件,57298592 字节;CRC 检查通过,解压后 EXE 哈希匹配。
- 清除 Python/Qt 搜索环境,PATH 仅保留 Windows System32;解压版环境自检和 UI-only 扫描均退出码 0。
- 打包版扫描 2 个测试工程,截图成功,未请求原生导出、无导出结果。已人工查看最终截图,布局与中文提示可读。
- 未分发 Windows 字体、Mentor 工程/库/PDF 或第三方错误 ICU DLL;保留第三方许可证。
- 发行文件:release/MentorPDFExporter-0.3.0-win64.zip;启动目录:release/MentorPDFExporter-0.3.0。
- 证据:artifacts/build-v03-reference.log、artifacts/v03-bundle-source-check.json、artifacts/v03-package-report.json、artifacts/v03-zip-check-report.json、artifacts/v03-bundle-ui-report.json、artifacts/ui-v03-bundle.png。
- 本轮只读审查未发现阻塞问题;这不改变上文原生数据库变化风险。
+50
View File
@@ -0,0 +1,50 @@
# 0.3.1 执行中队列浏览与源变化诊断(2026-10-10)
## 用户问题与根因
1. 右上角“已找到 Mentor 原生引擎”不需要展示:移除 badge,仍保留引擎路径输入及导出前环境验证。
2. 执行中队列无法上下浏览:旧 _set_busy 把整个 QTableWidget 禁用,滚动条和视图事件一并失效。
3. “源工程在任务期间发生变化”是文件内容指纹不同,不等于用户手动修改图纸。只读分析用户已有运行记录 20261010-093135 至 20261010-093217:六个工程均出现 database/icdb.dat 的内容变化,并伴有事件/日志变化;部分工程新增数据库升级记录。Audio_D2128_SURGE_ESD 的原生升级日志明确记录约束定义升级、保存 DxD/Board1 等快照。该次 pdf-check.json 显示已生成 1 页原生 PDF,但最后源指纹不同,未正式发布。
这些证据说明不能把全部变化当作无害日志或缓存;尚未对设计语义/电路进行前后比较。本轮没有再次调用原生导出,没有改写/恢复用户工程,也没有删除原生引擎自身生成的 cdbback 升级备份。
## 修复范围
- 表格保持启用,执行或扫描时仅锁定勾选项的 ItemIsUserCheckable 和配置/全选/清除/重试按钮。队列状态、结果、路径和滚动条可浏览;结束后恢复勾选。
- 新扫描行也根据 busy 状态锁定,防止 scan found 与 finished 之间可以修改队列。
- 清除日志占位、执行状态、单工程状态中的过时副本文案;仍不创建工程副本。
- 源不一致时保留 uncertain、不发布、不覆盖旧 PDF,且写 source-diff.json,分 modified/added/removed;结果及日志列出部分路径,完整列表保存在运行证据中。不擅自忽略主数据库或其他变化。
- 独立发布 0.3.1,保留先前发行版,启动脚本指向新版。
## TDD 与自动验证
先运行新增测试:7 项失败,分别复现 badge 仍存在、scan/batch 全表禁用、真实等待 worker 时表格禁用、源变化没有具体文件信息、尚无 compare_fingerprints。
修复后新增测试 7 项通过,覆盖:
- badge 移除但引擎输入保留。
- 45 行队列在 scan/batch busy 中,滚动条实际键盘 End/Home 事件可以上下浏览;鼠标点击和空格键不改变已锁定勾选,结束后空格可正常改选。
- 30 行队列真实 BatchWorker 运行(测试 runner 阻塞,不调用 Mentor)期间可浏览,停止后正常恢复,执行文案为直接模式。
- 原生返回 0 或 9 且源文件发生修改/新增/删除时,结果仍 uncertain、旧 PDF 字节不变,source-diff.json 精确列出文件。
- fingerprint 差异比较正确区分三类变化并排序,未修改的哈希不误报。
全量命令:.venv/Scripts/python.exe -m pytest -q --junitxml=artifacts/pytest-v031-ui-fix.xml。
结果:**158 passed,73.03 秒,退出码 0**。证据:artifacts/pytest-v031-ui-fix.log、artifacts/pytest-v031-ui-fix.xml。
已有原生记录只读分析:artifacts/v031-native-existing-run-analysis.json。
## 未解决边界
源变化的精确诊断已改进,但主数据库升级/更新问题没有通过关闭检查来“解决”。当前直接模式仍可能由原生引擎写回工程,指纹保护只能阻止发布,不能撤销这些源写入;不能把本次 UI 修复认定为原工程只读/无损导出验收。
## 便携修复版验证
- 使用全新 workpath 构建 0.3.1,构建退出码 0。
- EXE 内 14 个运行模块逐一与当前源码比较,全部一致。
- ZIP 255 个文件、57300568 字节,CRC 和解压后 EXE 哈希检查通过。
- 清理 Python/Qt 环境路径后,解压版环境自检及 UI-only 扫描均返回 0;扫描两个已有测试工程,没有请求原生导出、没有导出结果。
- 已查看 artifacts/ui-v031-bundle.png:右上角无引擎 badge,界面中文可读,无明显控件遮挡。
- 保留 0.3.0 等既有发行目录。新版路径 release/MentorPDFExporter-0.3.1;启动脚本 Start-MentorPDF.cmd 指向新版。
- 本轮独立只读代码审查未发现阻塞问题。
- 证据:artifacts/build-v031-ui-fix.log、artifacts/v031-bundle-source-check.json、artifacts/v031-package-report.json、artifacts/v031-zip-check-report.json、artifacts/v031-bundle-ui-report.json。
@@ -0,0 +1,66 @@
# 0.3.2 原生数据库更新不阻塞策略与实测(2026-10-10)
## 用户授权与策略
用户明确要求不要仅因数据库/日志变化阻塞有效 PDF,并要求检查实际影响。默认采用 native_updates_warn:声明的数据库目录中 icdb.dat 仅内容修改、cdbsvr 的 events/log/plog/dbcheck/dbupgrade 子目录与 sAddress.adr 变化、新增 cdbback ZIP,只记录成功提示。不能据此证明变更来源或无害。主数据库新增/删除、配置/图纸/未知文件变化仍阻止发布。严格检查可选且默认关闭。
完整源指纹和 source-diff.json 保留;source-assessment.json 记录允许及阻止的变化。源变化时 commit.json 的 source_verified_before_publish 和 source_content_identical 均为 false,不伪称字节不变。有效 PDF 发布状态为 success,warnings 单列;UI 显示成功(有提示),批量统计计入成功内提示。原生失败、超时、取消或无效 PDF 不会被允许的数据库变化掩盖,也不会覆盖旧输出。不创建工程副本或旧 PDF 备份。
## 自动测试
新增策略分类、配置/未知变更拦截、声明数据库目录与大小写、主数据库新增/删除、严格模式、无效 PDF、原生退出失败/取消/超时、CLI 退出码与 GUI 严格参数传递、成功提示显示、完整双工程队列统计测试。
完整最终命令:.venv/Scripts/python.exe -m pytest -q --junitxml=artifacts/pytest-v032-final.xml。
**197 passed,118.59 秒,退出码 0。** 初始回归测试记录保存在 artifacts/pytest-v032-red.log;修复前缺失策略/警告/可选严格模式的测试失败,不用事后单次绿色代替回归验证。
## 原生实际测试方法
使用本机 EE7.9.5 sch2pdf.exe 与安装自带 icdb2ascii.exe(先核对 -help)。CBB 选现有 Audio_D2128_SURGE_ESD 原工程;PON 使用早已存在的工程A测试工程。本轮不新建工程工作副本、不恢复/降级数据库、不删除原生升级备份。
每个工程:
1. -snap=DxD -t -c -h -offline 生成连接及文本属性报告。
2. 真实导出两次到不同输出目录,保留原生 PDF 作 QA 对照。QA 保留原生暂存 PDF,不是生产旧输出备份,也不是工程副本。
3. 每次导出后再次生成报告。只去除报告日期/选项头,逐字节比较全部 Block 开始的设计正文;包括连接、符号/引脚属性、空值和同名多值,未排序或删除设计字段。
4. 比较页面框、矢量坐标、颜色与线宽、文字、书签、注释和链接。字体处理前后分别比较,不把修复乱码时预期发生的字体变化当作源 CAD 变化。
5. 全部页按 2 倍分辨率渲染,两次原生输出与两次最终输出分别逐像素比较;不只抽检首页。
6. 打包 EXE 另外实际导出 CBB 一页。清除 Python/Qt 搜索覆盖但保留安装所需 Mentor 环境,验证 CLI 返回 0、文件实际发布、源更新有 warnings;再次对比设计报告及页面像素。
注意 icdb2ascii 查询本身也会更新 icdb.dat/日志,所以测试记录明确区分源字节变化和设计报告正文变化,不能把原生报告查询称为只读保证。
## 真实结果
| 样本 | 原生页数 | 网络 | 符号(含引脚/注释等类型) | 连接项 | 报告属性项 | 导出前后报告正文 | 重复输出逐页渲染 |
|---|---:|---:|---:|---:|---:|---|---|
| CBB_Audio | 1 × 2 | 22 | 56 | 229 | 577 | 一致 | 2 组,均一致 |
| PON_17pages | 17 × 2 | 465 | 1018 | 5260 | 14054 | 一致 | 34 组,均一致 |
四次原生导出全部成功(有源更新提示),总计 36 页;打包 EXE 额外成功发布 1 页,总计 5 次、37 页。便携版设计报告正文与基线相同,页面像素相同,CLI 返回 0。
两个样本的整体源差异均限定在数据库目录,没有观察到源 .prj/INI/其他配置文件变化。数据库字节实际变了,不宣称整个工程完全没变。设计报告和可见出图未发现连接/报告属性/重复页面改变。
## 严格检查发现的差异及限制(未隐藏)
### 原生颜色指令顺序
CBB 重复输出的部分冗余颜色设置指令顺序不同,不能用 PDF 二进制或流指令列表完全相同作为视觉一致性的唯一依据。已验证指令多重集合相同,全部实际渲染像素相同;工具字体处理前后仍严格保持各次原始矢量、颜色、线宽和注释等结构。
### 原生弹出菜单字段
PON 共 1975 个注释,重复导出只有一个可观测语义差异:第 12 页 CG16 弹出菜单的 Part Label 从空值变为 100NF/16V。源设计报告在导出前后均包含同名的 100NF/16V 与空值项,报告正文没有改变;这与原生导出取用同名/覆盖属性的差异相符,但未确认原生实现内部原因。
这条差异完整保存在 artifacts/v032-annotation-differences.json 和原生报告中。没有把它删除后宣称所有 PDF 内部对象一致:report.strict_all_pdf_objects_equal=false。两次可见页面、其他注释字段、导航目标与位置保持一致;各次字体处理没有改变该次原生菜单数据。需要可靠菜单属性时应另外核对;只需查看/打印图纸可关闭器件弹出菜单。
### 编码与排版
CBB 用原映射的效果测试保留原生乱码,并不是中文质量通过。追加针对已确认 CP936 旧样本的 PDF-only Arial+中文回退验证:855 段映射、58 段编码修复、607 个中文字符;音频及注意事项正确提取,已查看修复渲染。颜色操作变更数 0,矢量/颜色/线宽/注释/书签保持。未为这个测试再次操作 CAD。
PON Arial+确认 GBK:29061 段字体处理、154 段编码修复、140 段中文回退,提取 1116 个中文字符;注意事项、输入网络、输出网络均存在。PON 第8页原生样张本身已有文字拥挤/重叠与浅色图元;这次保持原布局/配色,没有伪称自动修好了源排版。原生注释有历史 W/S/8 转义解析警告,前后语义比较保留这些数据,不宣称原生格式无警告。FontTools 的非字形 MERG/meta 子集警告也保留在日志。
## 结论范围
验证对象是当前/已升级样本的 DxD 报告和 PDF,不能推广为所有旧版迁移、全部 PCB/约束或任意并发源编辑都无影响。生产不会每次运行额外 ASCII 报告,也不声称 source_design_semantics_verified=true;路径分类只能分流提示与发布阻止,严格模式仍可选。
## 打包检查
全新 PyInstaller workpath 构建退出码 0;15 个运行模块全部与当前源码一致。ZIP CRC、解压 EXE 哈希、清除 Python/Qt 搜索环境且 System32-only PATH 的自检和 UI-only 扫描通过。原生运行测试保留 Mentor 必需的环境,不把系统原生依赖当作缺失 Python 来处理。旧版本保留,无 Windows 字体/私有工程/样张随包分发。已检查打包界面,严格检查默认关闭,右上角无引擎 badge。
证据:artifacts/pytest-v032-final.log、artifacts/v032-native-qa/report.json、artifacts/v032-frozen-native-qa.json、artifacts/v032-native-qa/CBB_Audio/Arial-GBK-sample-check.json、artifacts/v032-bundle-source-check.json、artifacts/v032-package-report.json。
@@ -0,0 +1,59 @@
# v0.3.3 成品配色与中文验收(2026-10-10)
## 验收目标与纠正
不把原生进程退出码 0、PDF 结构正确或重复渲染一致当作参考配色/中文正确的证据。前版普通 UI 默认 preserve + original + GBK 关闭,实际不会自动修复中文;旧原生参数 -udx 在 Audio 工程上触发淡色笔画与不可见检索文字。之前的“原始配色(参考风格)”标签也没有实施对象角色配色。
本版 UI 和 CLI 的普通启动均默认 Arial+宋体中文回退、CP936/GBK 修复、reference 配色;程序化 ExportOptions() 的保守原映射默认保留,避免破坏明确需要无处理的调用方。
## 参考参数与实测证据
只读分析 PDF参考 中的七份 PDF。它们有旧编码乱码,因此用于颜色/图形参考而不是照抄其错误文字。当前本机可直接对应的项目为 Audio_D2128_SURGE_ESD。
通过原生配置的对象颜色键实现:NET 红色 #FF0000;LINE/ARC/TEXT 蓝色 #0000FF;PIN 青绿色 #008080;BOX/COMPONENT 紫色 #800080;CIRCLE/LABEL 绿色 #008000;继承参数文字默认深青色 #388E8E,同时保留原生显式对象颜色(部分参数 #008080)。XML 颜色值为 RGB,不混用 colors.def 的 BGR 整数。
原生参数对照显示:原始青色混合了多个角色,不能全局把所有青色换成蓝色。配色通过运行记录目录内仅含颜色键的 native-profile/DxDesigner.xml 及子进程 WDIR 前置读取,实现原生对象角色分离。不改父进程环境、工程 dxpdf.ini/.prj 或全局 Mentor 配置,不创建工程副本。
Audio 成品验收(普通 UI 已成功出图;最终参数色精校使用已捕获的原生 PDF,无再次调用异常原工程):
- 1 页,724 项矢量路径;路径坐标、描边颜色、填充和线宽的多重集合与参考全部一致。
- 重复路径分别按描边/填充分组匹配,未用会覆盖重复路径的单值字典掩盖差异。
- 追加可见文字颜色检查:与参考共有的 84 个 ASCII 文本项(位号、参数、引脚和网络名)颜色全部一致。对照发现默认参数应为 #388E8E 而非引脚色 #008080;最终样张依据两份原生 PDF 的原始文字及文字起点,精确识别继承 ATTRIBUTE 后校正,不替换所有青绿色文字。工具的原生 ATTRIBUTE 配置同步修正。
- 恢复 607 个中文字符,“注意事项/音频/输入/输出”均可提取并已渲染目视确认。
- Arial 和中文宋体以 Unicode Type0/Identity-H 与 ToUnicode 子集嵌入;不添加白色遮罩、不栅格化、不强制加粗。
- 与另一独立原生运行的比较存在注释对象差异,不能宣称全部 PDF 对象完全相同。颜色/几何验收并不依赖注释完全相同。
## 真实多页验证
使用之前已存在的自有 PON 测试工程,没有新建工程工作副本。直接获取未修改 UI 的默认选项实际导出;默认整工程包含 24 页,旧测试选择指定 PON Block 时为 17 页,这两种范围不同。
实测:24 页,2418 个中文字符。每页均渲染;同次原生出图前后通过仅记录 JSON 的 QA 快照比较,页框、绘图与颜色操作、线宽、文字定位、注释和书签相同。字体处理 color_ops=0,原生角色配色不被高对比分支再次换色。不复制原生 PDF,也不备份旧输出。
PON 的部分原生字体是没有显式 Widths 的 Helvetica/Times:使用 pypdf 所带 Adobe Core14 AFM 精确字宽,而不是用 Arial 近似字宽。未知字体仍拒绝转换。许可与版权通知随发行包保留。
## 追加测试发现的数据库异常与处理边界
旧 Windows Job 清理会在原生主进程返回成功后,继续通过 KILL_ON_JOB_CLOSE 强杀本次后台子进程。已用独立 Python 父子进程复现,可能中断 iCDB 异步整理/写回。
Audio 追加测试日志在 2026-10-10 11:46:18 开始原生数据库整理,11:50:56 尝试恢复到整理前状态并报告 DatabaseLoadError。这个现象与强杀机制一致,但不能断定是唯一原因。已停止对该原工程继续原生测试;原生恢复点内容 SHA-256 与追加测试前指纹不一致,因此没有自动恢复或覆盖原数据库。**此原工程需先在 Mentor 核查/修复;不能宣称当前数据库已经恢复或所有原工程均已验收。**已成功生成并验收的 Audio PDF 保留。
本版修正:
- 成功出图后解除强杀,等待本次 Job 中后台服务结束,再开始字体处理和发布校验。
- 父进程已完成后的停止/后台等待超时:不发布 PDF,保留后台服务完成写回。
- 出图仍在执行时停止/超时:仍仅结束本工具启动的进程树;无法回滚原生写回。
- 成功后停止的竞态也已加入进程级回归。
- exact database/cdbsvr/backup.lck 原生备份协调记录默认列为提示;未知锁文件仍阻塞,严格模式全部阻塞。**没有把既有备份 ZIP 的删除列为提示**。
## 自动回归与交付检查
- 完整回归:214 passed;最终参数色修正后再次全量运行,日志 artifacts/pytest-v033-final-attribute.log 与 XML。
- 新增默认界面中文修复、对象角色配置、子进程环境隔离、标准字体精确字宽、CLI 隐式 GBK 归一化及笔画拒绝测试。
- 实际执行到的 Form XObject 笔画/旧编码文字不能绕过验证;未支持的转换安全失败。
- Windows 生命周期审查的整组进程测试 22 passed;另外验证父进程完成后的超时/取消仍允许后台写回。
- PyInstaller 使用独立全新 workpath;冻结包全部 15 个应用模块的代码对象与当前源代码匹配,不仅检查构建退出码。
- 交付 EXE 已再次通过普通 UI 默认设置实际导出 PON 整工程 24 页,2418 个中文字符;最终参数色 #388E8E 存在,全部 24 页均渲染,图形路径/颜色/填充/线宽与已验证实现的输出一致。工程 .prj、dxpdf.ini 与全局 Mentor 配置 SHA-256 前后相同。
- 参数文字色是有意修正,不把新旧版本的逐像素差异当作相同;没有宣称旧新 PDF 每个对象均相同。
- 发行包不带 Windows 字体文件、Mentor 可执行文件、许可证或私人工程。
## 已知限制
其他编码的工程请关闭 GBK 修复;GBK 与 WinAnsi 本质上有歧义,不靠试解码猜测。源图原有重叠文字(例如 PON 的公式区域)仍可能重叠,字体修复保持原定位,不自动重新排版。旧参考与当前工程内容可能来自不同修订,不承诺逐字/逐像素相同。数据库/运行记录写回默认提示并非只读或设计语义不变保证。
@@ -0,0 +1,46 @@
# v0.3.4 失败修复、原名输出与紧凑界面(2026-10-10)
## 最新失败原因
用户最新批次 15 个工程:11 成功,4 失败。失败项目为 1GPHY_RTL8211F、1GPHY_RTL8211F_A、1GPHY_YT8511C、2G5PHY_GPY211,原生进程均完成出图,被工具的混合笔画字体检查拒绝;不是缺依赖库或本次数据库加载失败。
工程 dxpdf.ini 使用了混合映射:新宋体的正常文字与 STROKE:GOTHIC 等英文笔画同时存在。GPY211 真实原生输出中 1783 段 fstroke5 文字全为 ASCII,且 Tr=3:这是可见英文笔画的隐藏检索层。前版不加区分地拒绝全部 fstroke,误判这类合法输出。
本版只允许原生 WinAnsi Type1/TrueType fstroke 的 ASCII 隐藏 Tj 保留,不更换该检索层字体,也不重画或遮盖原有英文笔画。正常文字仍转换为 Arial/中文宋体并修复 GBK。非 ASCII、可见笔画或不能安全转换的复合文字仍失败。即使同一 ASCII 字串同时用于正常字体与笔画层,也不会因字串匹配而转换隐藏层。
## 四个真实工程复测
全部直接导出原工程,无新工程副本、无旧 PDF 备份、无工程字体 INI 修改。原生输出前后仅生成 JSON 快照,不复制原生 PDF 作为备份。
| 工程 | 页数 | 中文字符 | 保留 ASCII 笔画检索段 |
|---|---:|---:|---:|
| 2G5PHY_GPY211 | 1 | 89 | 1783 |
| 1GPHY_YT8511C | 1 | 309 | 397 |
| 1GPHY_RTL8211F_A | 1 | 143 | 6 |
| 1GPHY_RTL8211F | 1 | 143 | 6 |
四项均成功发布,成品均已渲染;同次绘图路径、颜色、线宽、文字定位、注释与书签快照相同,工程 .prj 与 dxpdf.ini SHA-256 不变,字体处理 color_ops=0。原生仍可能更新数据库/运行记录,保持之前的提示策略,不宣称源数据库只读或所有设计语义不变。
最新用户记录中 Audio_D2128_SURGE_ESD 于 2026-10-10 13:31 已成功导出,因此前一次的数据库异常不作为这四项失败的原因,也没有自动恢复或覆盖原工程。
## 原名输出
PON.prj 输出 PON.pdf,不再附加 __xxxxxxxx 摘要。同名不同版本使用自然子目录,例如 Work/PON.pdf 与 Cert/PON.pdf,不改 PDF 名字、不互相覆盖。界面重试子集依据完整扫描列表规划,因此 Work/Cert 的位置保持稳定;CLI 多工程使用同一规划逻辑。
所有派生目录在启动第一个引擎前针对全部源目录核验。输出目录先解析到实际路径,Windows 联接/符号链接把两个版本导向同一文件时直接拒绝,而不是两个成功结果覆盖同一 PDF。已存在的旧后缀 PDF 不自动删除或重命名。
## 界面
删除所有说明段落,只保留功能标签、按钮和简短状态;详细使用提示放在悬停提示及 README。路径行、按钮、选项列对齐,原生高级选项折叠。默认 1200×820 的 Windows Qt 实测工程表格约 335px,日志约 69px;忙时仍可滚动队列,选择与设置锁定。日志只显示扫描、项目开始、简短结果、错误及队列汇总;完整原生输出、源差异和错误仍保存在运行记录。
## 验证
完整回归和便携版结果以 artifacts/pytest-v034-release.log、artifacts/v034-recovered/report.json、artifacts/v034-package-report.json 和 artifacts/v034-frozen-quality.json 为准。命名包含真实 Windows junction 冲突回归;界面包含可见标签、对齐坐标、队列高度、滚动锁定和精简日志回归。
## 最终交付检查结果
- 完整回归:236 passed。
- 冻结包 16 个应用模块的代码对象均匹配当前源码。
- 交付 EXE 使用普通界面默认值,实际重新导出原失败 GPY211 工程:1 页、89 个中文字符、1783 段 ASCII 检索层保留,输出名 2G5PHY_GPY211.pdf。
- 交付成品与已验证源码实现的输出渲染像素一致;工程 .prj、dxpdf.ini 和全局配置哈希不变。
- 便携包在不依赖 Python/Qt 外部环境的 PATH 下通过普通默认界面扫描测试,ZIP CRC 检查通过。
+7
View File
@@ -0,0 +1,7 @@
# Application icon
The blue document / red PDF / export arrow artwork is original to this project.
No Mentor, Siemens, Adobe, or third-party application logo is used.
The editable SVG and multi-resolution ICO are stored in the application assets package.
Regenerate with `python packaging/generate_icon.py` using the release PySide6 environment.
Copyright © 2026 simgreek.
+22 -3
View File
@@ -1,14 +1,33 @@
# Portable onedir bundle: no Mentor binaries, licenses or private projects. # Portable onedir bundle: no Mentor binaries, licenses or private projects.
from pathlib import Path from pathlib import Path
import sys import sys
import tomllib
from PyInstaller.utils.win32.versioninfo import VSVersionInfo, FixedFileInfo, StringFileInfo, StringTable, StringStruct, VarFileInfo, VarStruct
sys.path.insert(0, SPECPATH) sys.path.insert(0, SPECPATH)
from bundle_policy import filter_binaries from bundle_policy import filter_binaries
root = Path(SPECPATH).parent root = Path(SPECPATH).parent
version = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))["project"]["version"]
assets = root / "src/mentor_pdf_export/assets"
version_tuple = tuple(int(part) for part in version.split(".")) + (0,)
version_info = VSVersionInfo(
ffi=FixedFileInfo(filevers=version_tuple, prodvers=version_tuple, mask=0x3f,
flags=0, OS=0x40004, fileType=1, subtype=0, date=(0, 0)),
kids=[StringFileInfo([StringTable("040904B0", [
StringStruct("CompanyName", "simgreek"),
StringStruct("FileDescription", "Mentor PDF Batch Exporter"),
StringStruct("FileVersion", version),
StringStruct("InternalName", "MentorPDFExporter"),
StringStruct("OriginalFilename", "MentorPDFExporter.exe"),
StringStruct("ProductName", "Mentor PDF Batch Exporter"),
StringStruct("ProductVersion", version),
StringStruct("LegalCopyright", "Copyright (c) 2026 simgreek"),
])]), VarFileInfo([VarStruct("Translation", [1033, 1200])])],
)
analysis = Analysis( analysis = Analysis(
[str(root / "packaging" / "entrypoint.py")], [str(root / "packaging" / "entrypoint.py")],
pathex=[str(root / "src")], pathex=[str(root / "src")],
binaries=[], binaries=[],
datas=[], datas=[(str(assets), "mentor_pdf_export/assets")],
hiddenimports=["win32job", "win32api", "win32con"], hiddenimports=["win32job", "win32api", "win32con"],
hookspath=[], hookspath=[],
hooksconfig={}, hooksconfig={},
@@ -20,7 +39,7 @@ analysis = Analysis(
analysis.binaries = filter_binaries(analysis.binaries) analysis.binaries = filter_binaries(analysis.binaries)
pyz = PYZ(analysis.pure) pyz = PYZ(analysis.pure)
exe = EXE(pyz, analysis.scripts, [], exclude_binaries=True, exe = EXE(pyz, analysis.scripts, [], exclude_binaries=True,
name="MentorPDFExporter", debug=False, bootloader_ignore_signals=False, name="MentorPDFExporter", icon=str(assets / "app.ico"), version=version_info, debug=False, bootloader_ignore_signals=False,
strip=False, upx=False, console=False, disable_windowed_traceback=False) strip=False, upx=False, console=False, disable_windowed_traceback=False)
coll = COLLECT(exe, analysis.binaries, analysis.datas, strip=False, upx=False, coll = COLLECT(exe, analysis.binaries, analysis.datas, strip=False, upx=False,
name="MentorPDFExporter") name=f"MentorPDFExporter-{version}")
+223
View File
@@ -0,0 +1,223 @@
"""Build and assemble the formal Windows portable release from this checkout."""
from __future__ import annotations
import argparse
import ast
import hashlib
from importlib import metadata
import json
from pathlib import Path, PurePosixPath
import re
import shutil
import struct
import subprocess
import sys
import tomllib
import zipfile
ROOT = Path(__file__).resolve().parents[1]
def project_version() -> str:
version = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf8"))["project"]["version"]
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version):
raise ValueError("Formal releases require a stable major.minor.patch version")
return version
def sha256(path: Path) -> str:
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def validate_bundle(bundle: Path, *, runtime_files=None, license_files=None) -> None:
if not (bundle / "MentorPDFExporter.exe").is_file():
raise ValueError("Missing application executable")
if not (bundle / "_internal/mentor_pdf_export/assets/app.ico").is_file():
raise ValueError("Missing packaged window icon")
forbidden = {".prj", ".lmc", ".pdf", ".ttf", ".ttc", ".otf", ".woff", ".woff2", ".doc", ".docx", ".lic", ".dat", ".log"}
top_level = {"MentorPDFExporter.exe", "README.md", "CHANGELOG.md", "使用说明.txt", "发布说明.txt", "ThirdPartyNotices.txt", "SHA256SUMS.txt", "manifest.json"}
forbidden_dirs = {".git", "database", "projectbackup", "pcb", "sch", "runs", "logs", "output", "artifacts", "pdf参考"}
runtime_suffixes = {".dll", ".pyd", ".qm", ".zip", ".ico", ".svg", ".png", ".txt", ".md", ".apache", ".bsd", ""}
for file in bundle.rglob("*"):
relative = file.relative_to(bundle)
parts = relative.parts
if file.is_symlink() or file.is_junction():
raise ValueError(f"Linked bundle entry: {file.name}")
if any(part.casefold() in forbidden_dirs for part in parts):
raise ValueError(f"Private source/runtime directory: {relative}")
if len(parts) == 1 and parts[0] not in top_level | {"_internal", "licenses"}:
raise ValueError(f"Unapproved top-level bundle entry: {relative}")
if not file.is_file():
continue
if file.suffix.lower() in forbidden or file.name.lower() == "sch2pdf.exe":
raise ValueError(f"Private engineering data, font or Mentor binary: {file.name}")
if file.name.lower() in {"icuuc.dll", "icuin.dll"}:
raise ValueError(f"Foreign ICU library: {file.name}")
key = relative.as_posix()
if parts[0] == "_internal":
if file.suffix.lower() not in runtime_suffixes:
raise ValueError(f"Unapproved runtime file type: {relative}")
if runtime_files is not None and (key not in runtime_files or sha256(file) != runtime_files[key]):
raise ValueError(f"Runtime file differs from the build allowlist: {relative}")
if parts[0] == "licenses" and license_files is not None:
if key not in license_files or sha256(file) != license_files[key]:
raise ValueError(f"License file has no approved distribution source: {relative}")
if key == "MentorPDFExporter.exe" and runtime_files is not None:
if key not in runtime_files or sha256(file) != runtime_files[key]:
raise ValueError("Application executable differs from the build allowlist")
if runtime_files is not None:
for relative, expected in runtime_files.items():
file = (bundle / relative).resolve()
if not file.is_relative_to(bundle.resolve()) or not file.is_file() or sha256(file) != expected:
raise ValueError("A required build runtime file is missing or modified")
def validate_archive(archive: Path, bundle: Path) -> None:
"""Independently compare every ZIP member with the verified directory."""
expected = {bundle.name + "/" + p.relative_to(bundle).as_posix(): p for p in bundle.rglob("*") if p.is_file()}
with zipfile.ZipFile(archive) as zipped:
entries = zipped.infolist()
names = [entry.filename for entry in entries]
if len(set(names)) != len(names):
raise ValueError("Duplicate release ZIP member")
for entry in entries:
name = entry.filename
path = PurePosixPath(name)
if entry.is_dir() or name != path.as_posix() or "\\" in name or ":" in name or path.is_absolute() or ".." in path.parts:
raise ValueError("Unsafe release ZIP member path")
if set(names) != set(expected):
raise ValueError("Release ZIP members do not match the verified file set")
for name, source in expected.items():
with zipped.open(name) as stream:
digest = hashlib.file_digest(stream, "sha256").hexdigest()
if digest != sha256(source):
raise ValueError(f"Release ZIP member differs from the verified file: {name}")
def record_runtime_allowlist(bundle: Path, version: str) -> None:
"""Use PyInstaller's collected file list, never a wildcard of the bundle."""
work = ROOT / "build" / f"pyinstaller-{version}"
toc = ast.literal_eval((work / "MentorPDFExporter/COLLECT-00.toc").read_text(encoding="utf8"))
files = {}
for destination, source, kind in toc[0]:
relative = Path(destination) if kind == "EXECUTABLE" else Path("_internal") / destination
file = (bundle / relative).resolve()
if not file.is_relative_to(bundle.resolve()) or not file.is_file():
raise ValueError("Collected runtime file missing from bundle")
files[relative.as_posix()] = sha256(file)
(work / "runtime-files.json").write_text(json.dumps({"version": version, "files": files}, indent=2), encoding="utf8")
def collect_licenses(bundle: Path) -> tuple[dict[str, str], dict[str, str]]:
licenses = bundle / "licenses"
licenses.mkdir(exist_ok=True)
python_license = Path(sys.base_prefix) / "LICENSE.txt"
if not python_license.is_file():
raise FileNotFoundError("Python runtime license not found")
shutil.copyfile(python_license, licenses / "Python-LICENSE.txt")
versions = {}
approved = {"licenses/Python-LICENSE.txt": sha256(licenses / "Python-LICENSE.txt")}
names = ("pyside6", "pyside6_addons", "pyside6_essentials", "shiboken6", "pypdf", "pywin32", "cryptography", "cffi", "fonttools")
for name in names:
distribution = metadata.distribution(name)
versions[name] = distribution.version
copied = 0
for relative in distribution.files or ():
parts = relative.parts
if len(parts) < 3 or not parts[0].endswith(".dist-info") or parts[1] != "licenses":
continue
source = Path(distribution.locate_file(relative))
if source.is_file():
destination = licenses / Path(*parts)
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, destination)
approved[destination.relative_to(bundle).as_posix()] = sha256(source)
copied += 1
if not copied:
raise FileNotFoundError(f"No distributed license texts found for {name}")
metrics = Path(metadata.distribution("pypdf").locate_file("pypdf/_codecs/core_font_metrics.py"))
destination = licenses / "pypdf/Adobe-Core14-metrics-and-notices.py"
destination.parent.mkdir(exist_ok=True)
shutil.copyfile(metrics, destination)
shutil.copyfile(ROOT / "packaging/ICON-NOTICE.md", licenses / "Application-Icon.txt")
approved[destination.relative_to(bundle).as_posix()] = sha256(metrics)
approved["licenses/Application-Icon.txt"] = sha256(ROOT / "packaging/ICON-NOTICE.md")
return versions, approved
def assemble_release(bundle: Path, version: str) -> Path:
trusted = json.loads((ROOT / "build" / f"pyinstaller-{version}" / "runtime-files.json").read_text(encoding="utf8"))
if trusted["version"] != version:
raise ValueError("Runtime allowlist version mismatch")
runtime_files = trusted["files"]
validate_bundle(bundle, runtime_files=runtime_files)
versions, license_files = collect_licenses(bundle)
shutil.copyfile(ROOT / "README.md", bundle / "README.md")
shutil.copyfile(ROOT / "CHANGELOG.md", bundle / "CHANGELOG.md")
shutil.copyfile(ROOT / "docs/releases" / f"{version}.md", bundle / "发布说明.txt")
(bundle / "使用说明.txt").write_text(
f"Mentor PDF 批量导出 v{version} 正式版\n\n"
"双击 MentorPDFExporter.exe;请保留整个文件夹及 _internal。\n"
"本机需要 Mentor、有效许可证以及可访问的原工程依赖库。\n"
"选择工程目录 → 扫描工程 → 选择输出目录 → 勾选工程 → 开始批量导出。\n"
"PDF 使用原工程名,同名版本通过自然子目录区分。\n"
"默认参考配色、Arial 中文回退与 GBK 修复;普通 WinAnsi 工程请关闭 GBK 修复。\n"
"直接导出,不创建工程副本,不备份旧 PDF。原生引擎可能更新数据库或升级旧工程。\n"
"更多说明与边界见 README.md 和发布说明.txt。\n",
encoding="utf-8-sig",
)
(bundle / "ThirdPartyNotices.txt").write_text(
"This bundle includes Python, PySide6/Qt, shiboken6, pypdf, pywin32, cryptography, CFFI and FontTools. "
"Their license texts as distributed by the installed packages are retained in licenses/. "
"These notices do not replace the original terms.\n\n"
"Adobe Core14 AFM-derived metrics and all embedded permission/copyright notices from pypdf "
"are retained in licenses/pypdf/Adobe-Core14-metrics-and-notices.py.\n\n"
"The application icon is original project artwork, not a Mentor/Siemens/Adobe logo.\n\n"
"Mentor binaries/licenses, CAD projects, central libraries, PDFs and Windows font files are not shipped. "
"Fonts are read from the user system; restricted embedding/subsetting is rejected.\n",
encoding="utf8",
)
validate_bundle(bundle, runtime_files=runtime_files, license_files=license_files)
files = sorted((p for p in bundle.rglob("*") if p.is_file()), key=lambda p: p.relative_to(bundle).as_posix())
manifest = {
"product": "MentorPDFExporter", "version": version, "channel": "stable",
"platform": "windows-x64", "python": sys.version.split()[0],
"runtime_components": versions, "runtime_files": runtime_files, "license_files": license_files, "exe_sha256": sha256(bundle / "MentorPDFExporter.exe"),
"icon_sha256": sha256(bundle / "_internal/mentor_pdf_export/assets/app.ico"),
}
(bundle / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf8")
files = [p for p in files if p.name != "SHA256SUMS.txt" and p.name != "manifest.json"] + [bundle / "manifest.json"]
(bundle / "SHA256SUMS.txt").write_text("".join(f"{sha256(p)} {p.relative_to(bundle).as_posix()}\n" for p in files), encoding="utf8")
archive = bundle.parent / f"MentorPDFExporter-{version}-win64.zip"
with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED, compresslevel=6) as output:
for file in sorted(p for p in bundle.rglob("*") if p.is_file()):
output.write(file, file.relative_to(bundle.parent).as_posix())
validate_archive(archive, bundle)
archive.with_suffix(".zip.sha256").write_text(f"{sha256(archive)} {archive.name}\n", encoding="ascii")
print(json.dumps({"archive": str(archive), "bytes": archive.stat().st_size, "sha256": sha256(archive), **manifest}, indent=2))
return archive
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description="Build the formal Windows portable release")
parser.add_argument("--skip-build", action="store_true", help="Reassemble an already built, verified bundle")
args = parser.parse_args(argv)
if sys.platform != "win32" or struct.calcsize("P") != 8:
parser.error("Build on Windows using 64-bit Python")
version = project_version()
bundle = ROOT / "release" / f"MentorPDFExporter-{version}"
if not args.skip_build:
subprocess.run([sys.executable, str(ROOT / "packaging/generate_icon.py")], cwd=ROOT, check=True)
subprocess.run([
sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean",
"--distpath", str(ROOT / "release"), "--workpath", str(ROOT / "build" / f"pyinstaller-{version}"),
str(ROOT / "packaging/MentorPDFExporter.spec"),
], cwd=ROOT, check=True)
record_runtime_allowlist(bundle, version)
assemble_release(bundle, version)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+46
View File
@@ -0,0 +1,46 @@
"""Render the project's original SVG into a multi-resolution Windows ICO."""
from pathlib import Path
import struct
from PySide6.QtCore import QByteArray, QBuffer, QIODevice, QRectF
from PySide6.QtGui import QGuiApplication, QImage, QPainter
from PySide6.QtSvg import QSvgRenderer
ROOT = Path(__file__).resolve().parents[1]
def main():
app = QGuiApplication.instance() or QGuiApplication([])
assets = ROOT / "src/mentor_pdf_export/assets"
renderer = QSvgRenderer(str(assets / "app.svg"))
if not renderer.isValid():
raise ValueError("Invalid application icon SVG")
sizes = (16, 24, 32, 48, 64, 128, 256)
entries = []
payloads = []
offset = 6 + 16 * len(sizes)
for size in sizes:
image = QImage(size, size, QImage.Format.Format_ARGB32)
image.fill(0)
painter = QPainter(image)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
renderer.render(painter, QRectF(0, 0, size, size))
painter.end()
data = QByteArray()
buffer = QBuffer(data)
buffer.open(QIODevice.OpenModeFlag.WriteOnly)
if not image.save(buffer, "PNG"):
raise RuntimeError("Cannot encode application icon")
buffer.close()
png = bytes(data)
entries.append(struct.pack("<BBBBHHII", size % 256, size % 256, 0, 0, 1, 32, len(png), offset))
payloads.append(png)
offset += len(png)
if size == 256:
image.save(str(assets / "app.png"))
(assets / "app.ico").write_bytes(struct.pack("<HHH", 0, 1, len(sizes)) + b"".join(entries) + b"".join(payloads))
print("Generated original application icon: 16/24/32/48/64/128/256 px")
if __name__ == "__main__":
main()
+214
View File
@@ -0,0 +1,214 @@
"""Publish a verified stable release to the user's simgreek Gitea organization.
Credentials are read from Git Credential Manager into memory only. No secret is
accepted on the command line, written to a report, or embedded in remote URLs.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import time
import tomllib
import urllib.error
import urllib.parse
import urllib.request
import uuid
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[1]
SERVER = "https://git.simgreek.com"
HOST = "git.simgreek.com"
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
# Never forward authentication to an attachment redirect or another host.
return None
def validate_name(value: str) -> str:
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", value):
raise ValueError("Invalid organization or repository name")
return value
def multipart_attachment(file: Path, boundary: str) -> tuple[bytes, str]:
name = file.name
if not re.fullmatch(r"[A-Za-z0-9_.-]+", name):
raise ValueError("Unsafe release attachment filename")
header = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{name}"\r\n'
'Content-Type: application/octet-stream\r\n\r\n').encode("ascii")
return header + file.read_bytes() + f"\r\n--{boundary}--\r\n".encode("ascii"), f"multipart/form-data; boundary={boundary}"
def git(*args: str) -> str:
env = dict(os.environ, GIT_TERMINAL_PROMPT="0", GCM_INTERACTIVE="Never")
result = subprocess.run(["git", *args], cwd=ROOT, env=env, capture_output=True, text=True, check=True, timeout=240)
return result.stdout.strip()
def credentials() -> str:
env = dict(os.environ, GIT_TERMINAL_PROMPT="0", GCM_INTERACTIVE="Never")
result = subprocess.run(["git", "credential", "fill"], cwd=ROOT, env=env,
input=f"protocol=https\nhost={HOST}\n\n", capture_output=True, text=True, timeout=30)
fields = dict(line.split("=", 1) for line in result.stdout.splitlines() if "=" in line)
if result.returncode or not fields.get("username") or not fields.get("password"):
raise RuntimeError("No stored Git credential for git.simgreek.com; sign in using your normal Git client first")
return "Basic " + base64.b64encode((fields["username"] + ":" + fields["password"]).encode("utf8")).decode("ascii")
class Client:
def __init__(self, authorization: str):
self.authorization = authorization
# The existing Git configuration explicitly disables a proxy for this host.
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
def request(self, path: str, method="GET", data=None, attachment=None, missing_ok=False):
headers = {"Authorization": self.authorization, "Accept": "application/json", "User-Agent": "MentorPDFExporter-release"}
body = None
if attachment:
body, headers["Content-Type"] = multipart_attachment(attachment, "mentor-release-" + uuid.uuid4().hex)
elif data is not None:
body = json.dumps(data).encode("utf8")
headers["Content-Type"] = "application/json"
url = SERVER + "/api/v1" + path
for attempt in range(3):
try:
request = urllib.request.Request(url, data=body, headers=headers, method=method)
with self.opener.open(request, timeout=180 if attachment else 30) as response:
content = response.read()
return json.loads(content) if content else None
except urllib.error.HTTPError as error:
if error.code == 404 and missing_ok:
return None
if method == "GET" and error.code in (502, 503, 504) and attempt < 2:
time.sleep(2 * (attempt + 1))
continue
raise RuntimeError(f"git.simgreek.com returned HTTP {error.code} for {path}; nothing is claimed uploaded") from None
raise RuntimeError("Server unavailable")
def attachment_hash(self, url: str) -> str:
parsed = urllib.parse.urlsplit(url)
if parsed.scheme != "https" or parsed.hostname != HOST or parsed.username or parsed.password or parsed.port not in (None, 443):
raise ValueError("Attachment download URL does not belong to the trusted Git host")
request = urllib.request.Request(url, headers={"Authorization": self.authorization, "User-Agent": "MentorPDFExporter-release"})
digest = hashlib.sha256()
with self.opener.open(request, timeout=180) as response:
while data := response.read(1024 * 1024):
digest.update(data)
return digest.hexdigest()
def file_hash(file: Path) -> str:
with file.open("rb") as source:
return hashlib.file_digest(source, "sha256").hexdigest()
def verified_artifacts(version: str) -> tuple[Path, Path]:
report = ROOT / "artifacts" / f"release-{version}" / "verification.json"
data = json.loads(report.read_text(encoding="utf8"))
archive = ROOT / "release" / f"MentorPDFExporter-{version}-win64.zip"
checksum = archive.with_suffix(".zip.sha256")
if not data.get("passed") or data.get("version") != version or data.get("zip_sha256") != file_hash(archive):
raise ValueError("Release archive does not match its passed verification report")
if checksum.read_text(encoding="ascii").split()[0] != file_hash(archive):
raise ValueError("Release ZIP checksum differs")
tree = ET.parse(ROOT / "artifacts" / "pytest-v100-final.xml")
suites = tree.getroot().iter("testsuite")
counts = [(int(s.get("tests", "0")), int(s.get("failures", "0")), int(s.get("errors", "0"))) for s in suites]
if not counts or sum(x[0] for x in counts) < 236 or any(x[1] or x[2] for x in counts):
raise ValueError("A passing complete release regression run is required")
# Re-check current application code rather than trusting stale build metadata.
sys.path.insert(0, str(ROOT / "packaging"))
from verify_release import verify_source
verify_source(ROOT / "release" / f"MentorPDFExporter-{version}" / "MentorPDFExporter.exe")
return archive, checksum
def publish(client: Client, org: str, repo: str, version: str) -> dict:
archive, checksum = verified_artifacts(version)
if git("status", "--porcelain"):
raise ValueError("Commit release source before publishing; the working tree must be clean")
commit = git("rev-parse", "HEAD")
tag = "v" + version
if git("rev-parse", tag + "^{commit}") != commit:
raise ValueError("Release tag must identify the current source commit")
remote_url = f"{SERVER}/{org}/{repo}.git"
remotes = git("remote").splitlines()
original_remote = git("remote", "get-url", "origin") if "origin" in remotes else None
if original_remote is not None and original_remote != remote_url:
raise ValueError("Existing origin differs from requested organization repository")
existing = client.request(f"/repos/{org}/{repo}", missing_ok=True)
if existing is not None and not existing.get("empty", False) and original_remote is None:
raise ValueError("Repository already contains unrelated history; refusing to overwrite it")
if existing is None:
existing = client.request(f"/orgs/{org}/repos", method="POST", data={
"name": repo, "description": "Mentor / DxDesigner PDF batch exporter for Windows",
"private": True, "auto_init": False, "default_branch": "main",
})
if original_remote is None:
git("remote", "add", "origin", remote_url)
# No force push; branch and tag are published together or not at all.
git("push", "--atomic", "-u", "origin", "HEAD:refs/heads/main", "refs/tags/" + tag)
refs = git("ls-remote", "origin", "refs/heads/main", "refs/tags/" + tag + "^{}")
refmap = dict(line.split()[::-1] for line in refs.splitlines())
if refmap.get("refs/heads/main") != commit or refmap.get("refs/tags/" + tag + "^{}") != commit:
raise ValueError("Remote branch/tag does not match the release source commit")
release = client.request(f"/repos/{org}/{repo}/releases/tags/{tag}", missing_ok=True)
if release is None:
release = client.request(f"/repos/{org}/{repo}/releases", method="POST", data={
"tag_name": tag, "target_commitish": commit, "name": f"Mentor PDF 批量导出 {tag}",
"body": (ROOT / "docs/releases" / f"{version}.md").read_text(encoding="utf8"),
"draft": False, "prerelease": False,
})
if release.get("draft") or release.get("prerelease"):
raise ValueError("Existing release is not a formal stable release; refusing implicit changes")
release_id = release["id"]
assets = {asset["name"]: asset for asset in release.get("assets", [])}
uploaded = []
for file in (archive, checksum):
asset = assets.get(file.name)
if asset is None:
asset = client.request(f"/repos/{org}/{repo}/releases/{release_id}/assets?name={urllib.parse.quote(file.name)}", method="POST", attachment=file)
if client.attachment_hash(asset["browser_download_url"]) != file_hash(file):
raise ValueError("Remote attachment hash mismatch; existing attachments are never silently replaced")
uploaded.append({"name": file.name, "sha256": file_hash(file), "url": asset["browser_download_url"]})
return {"published": True, "repository": existing["html_url"], "release": release["html_url"],
"version": version, "commit": commit, "tag": tag, "assets": uploaded}
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description="Publish a verified stable release to simgreek Gitea")
parser.add_argument("--org", default="simgreek")
parser.add_argument("--repo", default="mentor-pdf-exporter")
parser.add_argument("--publish", action="store_true", help="Create the private repository if needed, push source/tag and upload the verified release")
args = parser.parse_args(argv)
org, repo = validate_name(args.org), validate_name(args.repo)
version = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf8"))["project"]["version"]
try:
client = Client(credentials())
server = client.request("/version")
user = client.request("/user")
organization = client.request(f"/orgs/{org}")
print(json.dumps({"server": server, "authenticated_user": user.get("login"), "organization": organization.get("username", org)}, ensure_ascii=True))
if args.publish:
result = publish(client, org, repo, version)
evidence = ROOT / "artifacts" / f"release-{version}"
evidence.mkdir(parents=True, exist_ok=True)
(evidence / "published.json").write_text(json.dumps(result, indent=2), encoding="utf8")
print(json.dumps(result, ensure_ascii=True, indent=2))
return 0
except (RuntimeError, ValueError, OSError, subprocess.CalledProcessError, urllib.error.URLError) as error:
print(f"Release not completed: {type(error).__name__}: {error}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())
+4 -1
View File
@@ -1,5 +1,8 @@
# Exact runtime/build versions used for the 2026-10-09 Windows release. # Exact runtime/build versions used for the 2026-10-10 Windows release.
PySide6==6.11.2 PySide6==6.11.2
pypdf==6.20.0 pypdf==6.20.0
pywin32==312 pywin32==312
PyInstaller==6.22.3 PyInstaller==6.22.3
fonttools==4.66.1
cryptography==45.0.7
cffi==2.1.1
+134
View File
@@ -0,0 +1,134 @@
"""Verify the delivered EXE, icons, source match, clean-PATH UI and ZIP."""
from __future__ import annotations
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import types
import zipfile
from build_release import ROOT, project_version, sha256, validate_bundle, validate_archive
def verify_source(exe: Path) -> int:
from PyInstaller.archive.readers import CArchiveReader
archive = CArchiveReader(str(exe)).open_embedded_archive("PYZ.pyz")
def normalized(code):
return code.replace(co_filename="", co_consts=tuple(normalized(c) if isinstance(c, types.CodeType) else c for c in code.co_consts))
package = ROOT / "src/mentor_pdf_export"
expected = {"mentor_pdf_export" if p.name == "__init__.py" else "mentor_pdf_export." + p.stem for p in package.glob("*.py") if p.name != "__main__.py"}
found = {n for n in archive.toc if n == "mentor_pdf_export" or n.startswith("mentor_pdf_export.")}
if found != expected:
raise ValueError("Frozen application module list differs from source")
for name in sorted(found):
source = package / ("__init__.py" if name == "mentor_pdf_export" else name.rsplit(".", 1)[1] + ".py")
code = compile(source.read_bytes(), str(source), "exec", dont_inherit=True, optimize=0)
if normalized(code) != normalized(archive.extract(name)):
raise ValueError(f"Frozen application module differs from current source: {name}")
return len(found)
def verify_shell_icon(exe: Path, output: Path) -> None:
import win32api
import win32con
import win32gui
import win32ui
from PySide6.QtGui import QImage
count = win32gui.ExtractIconEx(str(exe), -1)
if count < 1:
raise ValueError("Executable has no Windows shell icon resource")
large, small = win32gui.ExtractIconEx(str(exe), 0)
if not large or not small:
raise ValueError("Executable shell icons cannot be extracted")
desktop = win32gui.GetDC(0)
dc = win32ui.CreateDCFromHandle(desktop)
memory = dc.CreateCompatibleDC()
bitmap = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(dc, 64, 64)
previous = memory.SelectObject(bitmap)
try:
memory.FillSolidRect((0, 0, 64, 64), win32api.RGB(255, 255, 255))
win32gui.DrawIconEx(memory.GetSafeHdc(), 0, 0, large[0], 64, 64, 0, None, win32con.DI_NORMAL)
image = QImage(bitmap.GetBitmapBits(True), 64, 64, QImage.Format.Format_RGB32).copy()
if not image.save(str(output)):
raise ValueError("Cannot save shell icon evidence")
finally:
memory.SelectObject(previous)
win32gui.DeleteObject(bitmap.GetHandle())
memory.DeleteDC()
dc.DeleteDC()
win32gui.ReleaseDC(0, desktop)
for handle in large + small:
win32gui.DestroyIcon(handle)
def main() -> int:
import win32api
version = project_version()
bundle = ROOT / "release" / f"MentorPDFExporter-{version}"
exe = bundle / "MentorPDFExporter.exe"
archive = bundle.parent / f"MentorPDFExporter-{version}-win64.zip"
evidence = ROOT / "artifacts" / f"release-{version}"
evidence.mkdir(parents=True, exist_ok=True)
validate_bundle(bundle)
frozen_modules = verify_source(exe)
metadata = {}
for key in ("CompanyName", "FileDescription", "FileVersion", "ProductName", "ProductVersion", "OriginalFilename"):
metadata[key] = win32api.GetFileVersionInfo(str(exe), "\\StringFileInfo\\040904B0\\" + key)
assert metadata["FileVersion"] == metadata["ProductVersion"] == version
assert metadata["CompanyName"] == "simgreek"
verify_shell_icon(exe, evidence / "exe-icon.png")
packaged_icon = bundle / "_internal/mentor_pdf_export/assets/app.ico"
assert packaged_icon.read_bytes() == (ROOT / "src/mentor_pdf_export/assets/app.ico").read_bytes()
manifest = json.loads((bundle / "manifest.json").read_text(encoding="utf8"))
assert manifest["version"] == version and manifest["channel"] == "stable"
validate_bundle(bundle, runtime_files=manifest["runtime_files"], license_files=manifest["license_files"])
assert manifest["exe_sha256"] == sha256(exe) and manifest["icon_sha256"] == sha256(packaged_icon)
for line in (bundle / "SHA256SUMS.txt").read_text(encoding="utf8").splitlines():
expected, relative = line.split(" ", 1)
file = (bundle / relative).resolve()
assert file.is_relative_to(bundle.resolve()) and sha256(file) == expected
assert archive.with_suffix(".zip.sha256").read_text(encoding="ascii").split()[0] == sha256(archive)
validate_archive(archive, bundle)
with zipfile.ZipFile(archive) as zipped:
assert zipped.testzip() is None
assert hashlib.sha256(zipped.read(bundle.name + "/MentorPDFExporter.exe")).hexdigest() == sha256(exe)
assert zipped.read(bundle.name + "/_internal/mentor_pdf_export/assets/app.ico") == packaged_icon.read_bytes()
assert zipped.read(bundle.name + "/发布说明.txt") == (ROOT / "docs/releases" / f"{version}.md").read_bytes()
source = evidence / "smoke-projects"
for name in ("Example-A", "Example-B", "Example-C"):
directory = source / name
directory.mkdir(parents=True, exist_ok=True)
(directory / (name + ".prj")).write_text('SECTION DesignInfo\nKEY FrontEndSnapshot "DxD"\nENDSECTION\nSECTION iCDB\nKEY iCDBDir ".\\database"\nENDSECTION\n', encoding="utf8")
env = dict(os.environ)
for key in ("PYTHONPATH", "PYTHONHOME", "QT_PLUGIN_PATH", "QT_QPA_PLATFORM_PLUGIN_PATH", "QT_QPA_PLATFORM"):
env.pop(key, None)
env["PATH"] = str(Path(os.environ.get("WINDIR", "C:/Windows")) / "System32")
check = evidence / "self-check.json"
subprocess.run([str(exe), "--self-check", "--report", str(check)], cwd=bundle, env=env, timeout=60, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
self_check = json.loads(check.read_text(encoding="utf8"))
assert self_check["version"] == version and self_check["frozen"] and self_check["ui_import_ok"]
report = evidence / "ui.json"
shot = evidence / "ui.png"
subprocess.run([str(exe), "--project-root", str(source), "--output", str(evidence / "output"), "--ui-smoke", str(shot), "--report", str(report)], cwd=bundle, env=env, timeout=90, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
ui = json.loads(report.read_text(encoding="utf8"))
assert ui["version"] == version and ui["projects"] == 3 and ui["screenshot_saved"]
assert ui["application_icon"] and ui["window_icon"] and ui["app_id_set"]
assert ui["app_id"] == "simgreek.MentorPDFExporter" and not ui["ui_export_requested"]
result = {
"passed": True, "version": version, "channel": "stable", "frozen_source_modules_match": frozen_modules,
"exe_sha256": sha256(exe), "zip_sha256": sha256(archive), "zip_bytes": archive.stat().st_size,
"windows_metadata": metadata, "exe_shell_icon": True, "packaged_window_icon_matches": True,
"stable_taskbar_app_id": ui["app_id"], "clean_path_default_ui": True, "scanned_projects": ui["projects"],
"zip_crc_ok": True, "private_projects_or_fonts_shipped": False,
}
(evidence / "verification.json").write_text(json.dumps(result, indent=2), encoding="utf8")
print(json.dumps(result, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+5 -2
View File
@@ -4,10 +4,10 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "mentor-pdf-export" name = "mentor-pdf-export"
version = "0.1.0" version = "1.0.0"
description = "Safe native Mentor DxDesigner batch PDF exporter" description = "Safe native Mentor DxDesigner batch PDF exporter"
requires-python = ">=3.12,<3.13" requires-python = ">=3.12,<3.13"
dependencies = ["PySide6>=6.7,<7", "pypdf>=5,<7", "pywin32>=306"] dependencies = ["PySide6>=6.7,<7", "pypdf>=6.20,<7", "pywin32>=306", "fonttools>=4.60,<5"]
[project.scripts] [project.scripts]
mentor-pdf-export = "mentor_pdf_export.cli:main" mentor-pdf-export = "mentor_pdf_export.cli:main"
@@ -23,3 +23,6 @@ testpaths = ["tests"]
pythonpath = ["src"] pythonpath = ["src"]
addopts = "-ra" addopts = "-ra"
cache_dir = "build/pytest-cache" cache_dir = "build/pytest-cache"
[tool.setuptools.package-data]
mentor_pdf_export = ["assets/*.ico", "assets/*.svg", "assets/*.png"]
+1 -1
View File
@@ -1,2 +1,2 @@
"""Mentor native batch PDF exporter.""" """Mentor native batch PDF exporter."""
__version__ = "0.1.0" __version__ = "1.0.0"
Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

+15
View File
@@ -0,0 +1,15 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256">
<defs><linearGradient id="bg" x1="0" y1="0" x2="1" y2="1"><stop stop-color="#2563eb"/><stop offset="1" stop-color="#1e3a8a"/></linearGradient></defs>
<rect x="8" y="8" width="240" height="240" rx="52" fill="url(#bg)"/>
<path d="M64 38H137L179 80V210H64Q53 210 53 199V49Q53 38 64 38Z" fill="#ffffff"/>
<path d="M137 38V69Q137 80 148 80H179Z" fill="#bfdbfe"/>
<rect x="38" y="94" width="136" height="54" rx="10" fill="#dc2626"/>
<g fill="#ffffff">
<path fill-rule="evenodd" d="M56 105H70Q82 105 82 117Q82 129 70 129H63V138H56ZM63 111V123H70Q75 123 75 117Q75 111 70 111Z"/>
<path fill-rule="evenodd" d="M90 105H103Q119 105 119 121Q119 138 103 138H90ZM97 111V132H103Q112 132 112 121Q112 111 103 111Z"/>
<path d="M128 105H151V112H135V118H149V125H135V138H128Z"/>
</g>
<path d="M72 164H127M72 180H116" stroke="#93c5fd" stroke-width="8" stroke-linecap="round"/>
<circle cx="184" cy="185" r="43" fill="#1d4ed8" stroke="#ffffff" stroke-width="7"/>
<path d="M162 185H207M191 169L207 185L191 201" fill="none" stroke="#ffffff" stroke-width="12" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

+48
View File
@@ -0,0 +1,48 @@
"""Application identity and packaged icon; no Mentor configuration changes."""
from __future__ import annotations
import ctypes
from pathlib import Path
import sys
from PySide6.QtGui import QIcon
from . import __version__
APP_ID = "simgreek.MentorPDFExporter"
APP_NAME = "MentorPDFExporter"
DISPLAY_NAME = "Mentor PDF 批量导出"
def icon_path() -> Path:
# PyInstaller places package data alongside the frozen package __file__.
return Path(__file__).resolve().parent / "assets" / "app.ico"
def application_icon() -> QIcon:
return QIcon(str(icon_path()))
def _shell32():
return ctypes.WinDLL("shell32", use_last_error=True)
def set_windows_app_id() -> bool:
"""Set a stable taskbar identity before QApplication or windows are created."""
if sys.platform != "win32":
return False
try:
setter = _shell32().SetCurrentProcessExplicitAppUserModelID
setter.argtypes = [ctypes.c_wchar_p]
setter.restype = ctypes.c_long
return setter(APP_ID) >= 0
except (OSError, AttributeError):
return False
def configure_application(app) -> None:
app.setApplicationName(APP_NAME)
app.setApplicationDisplayName(DISPLAY_NAME)
app.setApplicationVersion(__version__)
app.setOrganizationName("simgreek")
app.setWindowIcon(application_icon())
+25 -9
View File
@@ -12,6 +12,7 @@ from .exporter import Exporter, write_json
from .models import ExportOptions from .models import ExportOptions
from .scanner import read_project from .scanner import read_project
from .path_policy import validate_artifact_path, validate_queue_paths from .path_policy import validate_artifact_path, validate_queue_paths
from .naming import plan_output_directories
def _print(value): def _print(value):
@@ -20,21 +21,30 @@ def _print(value):
def main(argv=None) -> int: def main(argv=None) -> int:
parser=argparse.ArgumentParser(description="Mentor 原生 PDF 批量导出测试工具") parser=argparse.ArgumentParser(description="Mentor 原生 PDF 批量导出工具")
parser.add_argument("--self-check",action="store_true") parser.add_argument("--self-check",action="store_true")
parser.add_argument("--report",type=Path) parser.add_argument("--report",type=Path)
parser.add_argument("--engine",type=Path) parser.add_argument("--engine",type=Path)
parser.add_argument("--library",type=Path,help="可选本地 .lmc 路径,仅改变工作副本") parser.add_argument("--library",type=Path,help="已停用:直接导出不支持替换库路径,请先配置原工程")
parser.add_argument("--project-root",type=Path) parser.add_argument("--project-root",type=Path)
parser.add_argument("--output",type=Path) parser.add_argument("--output",type=Path)
parser.add_argument("--runs-root",type=Path) parser.add_argument("--runs-root",type=Path)
parser.add_argument("--export",nargs="+",type=Path,metavar="PROJECT") parser.add_argument("--export",nargs="+",type=Path,metavar="PROJECT")
parser.add_argument("--timeout",type=float,default=300) parser.add_argument("--timeout",type=float,default=300)
parser.add_argument("--overwrite",action="store_true") parser.add_argument("--overwrite",action="store_true")
parser.add_argument("--strict-source",action="store_true",help="源文件任何变化均阻止 PDF 发布;默认数据库/运行日志更新只记录提示")
parser.add_argument("--schematic",default="") parser.add_argument("--schematic",default="")
parser.add_argument("--font-mapping",choices=("preserve","arial","simsun","msyh"),default="arial")
parser.add_argument("--legacy-gbk",action=argparse.BooleanOptionalAction,default=None,help="默认修复中文旧工程 CP936 / GBK;正常 WinAnsi 工程请用 --no-legacy-gbk")
parser.add_argument("--print-theme",choices=("reference","original","high_contrast","mono"),default="reference")
parser.add_argument("--ui-smoke",type=Path,metavar="SCREENSHOT") parser.add_argument("--ui-smoke",type=Path,metavar="SCREENSHOT")
parser.add_argument("--ui-export-smoke",action="store_true",help="自动在 UI 内扫描并实际导出;需要 --ui-smoke、--project-root、--output") parser.add_argument("--ui-export-smoke",action="store_true",help="自动在 UI 内扫描并实际导出;需要 --ui-smoke、--project-root、--output")
args=parser.parse_args(argv) args=parser.parse_args(argv)
if args.legacy_gbk is None:
args.legacy_gbk = args.font_mapping != "preserve"
if args.library:
_print("直接导出不支持 --library;请先在 Mentor 配置原工程的依赖库路径")
return 2
# Validate every user-supplied report/screenshot BEFORE any branch writes, # Validate every user-supplied report/screenshot BEFORE any branch writes,
# including self-check and exception handling. # including self-check and exception handling.
protected_dirs=[project.resolve().parent for project in (args.export or [])] protected_dirs=[project.resolve().parent for project in (args.export or [])]
@@ -76,12 +86,12 @@ def main(argv=None) -> int:
info=read_project(project) info=read_project(project)
if not info:raise ValueError(f"不是 DxDesigner 原理图工程:{project}") if not info:raise ValueError(f"不是 DxDesigner 原理图工程:{project}")
infos.append(info) infos.append(info)
validate_queue_paths(infos,args.output,runs_root) directories=plan_output_directories(infos,args.output,runs_root)
preflight_ok=True preflight_ok=True
engine=discover_engine(args.engine) engine=discover_engine(args.engine)
exporter=Exporter(engine,runs_root) exporter=Exporter(engine,runs_root)
options=ExportOptions(timeout=args.timeout,overwrite=args.overwrite,schematic=args.schematic,library_override=str(args.library) if args.library else "") options=ExportOptions(strict_source=args.strict_source,legacy_gbk=args.legacy_gbk,font_mapping=args.font_mapping,print_theme=args.print_theme,timeout=args.timeout,overwrite=args.overwrite,schematic=args.schematic,library_override=str(args.library) if args.library else "")
results=[exporter.export(info,args.output,options,threading.Event(),_print) for info in infos] results=[exporter.export(info,directory,options,threading.Event(),_print) for info,directory in zip(infos,directories)]
data={"tool":"MentorPDFExporter","results":[asdict(result) for result in results]} data={"tool":"MentorPDFExporter","results":[asdict(result) for result in results]}
if args.report: if args.report:
args.report.parent.mkdir(parents=True,exist_ok=True);write_json(args.report,data) args.report.parent.mkdir(parents=True,exist_ok=True);write_json(args.report,data)
@@ -100,9 +110,14 @@ def main(argv=None) -> int:
from PySide6.QtCore import QTimer from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QApplication from PySide6.QtWidgets import QApplication
from .ui import MainWindow from .ui import MainWindow
from .branding import configure_application, set_windows_app_id, APP_ID
app_id_set = set_windows_app_id()
app=QApplication.instance() or QApplication([sys.argv[0]]) app=QApplication.instance() or QApplication([sys.argv[0]])
app.setApplicationName("MentorPDFExporter");app.setOrganizationName("MentorTools") configure_application(app)
window=MainWindow(root=args.project_root,output=args.output,engine=args.engine,library=args.library,runs_root=args.runs_root) window=MainWindow(root=args.project_root,output=args.output,engine=args.engine,library=args.library,runs_root=args.runs_root,strict_source=args.strict_source)
window.legacy_gbk_check.setChecked(args.legacy_gbk)
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData(args.font_mapping))
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData(args.print_theme))
window.timeout_spin.setValue(int(args.timeout));window.overwrite_check.setChecked(args.overwrite) window.timeout_spin.setValue(int(args.timeout));window.overwrite_check.setChecked(args.overwrite)
if args.schematic: if args.schematic:
window.scope_combo.setCurrentIndex(1);window.schematic_edit.setText(args.schematic) window.scope_combo.setCurrentIndex(1);window.schematic_edit.setText(args.schematic)
@@ -115,10 +130,11 @@ def main(argv=None) -> int:
args.ui_smoke.parent.mkdir(parents=True,exist_ok=True) args.ui_smoke.parent.mkdir(parents=True,exist_ok=True)
saved=window.grab().save(str(args.ui_smoke)) saved=window.grab().save(str(args.ui_smoke))
results=[asdict(result) for result in window.worker.results] if window.worker else [] results=[asdict(result) for result in window.worker.results] if window.worker else []
data={"tool":"MentorPDFExporter","screenshot":str(args.ui_smoke.resolve()),"screenshot_saved":saved,"projects":len(window.projects),"ui_export_requested":args.ui_export_smoke,"results":results,"status":window.status_label.text()} data={"tool":"MentorPDFExporter","screenshot":str(args.ui_smoke.resolve()),"screenshot_saved":saved,"version":__version__,"application_icon":not app.windowIcon().isNull(),"window_icon":not window.windowIcon().isNull(),"app_id":APP_ID,"app_id_set":app_id_set,"projects":len(window.projects),"ui_export_requested":args.ui_export_smoke,"results":results,"status":window.status_label.text()}
if args.report: if args.report:
args.report.parent.mkdir(parents=True,exist_ok=True);write_json(args.report,data) args.report.parent.mkdir(parents=True,exist_ok=True);write_json(args.report,data)
ok=saved and (not args.ui_export_smoke or (bool(results) and all(result["status"]=="success" for result in results))) identity_ok = not app.windowIcon().isNull() and not window.windowIcon().isNull() and (sys.platform != "win32" or app_id_set)
ok=saved and identity_ok and (not args.ui_export_smoke or (bool(results) and all(result["status"]=="success" for result in results)))
timer.stop();app.exit(0 if ok else 1) timer.stop();app.exit(0 if ok else 1)
def tick(): def tick():
nonlocal smoke_phase nonlocal smoke_phase
+31 -5
View File
@@ -76,7 +76,7 @@ def _create_job(process):
return job return job
def _start_windows_process(args, cwd, stdout, stderr, cancel): def _start_windows_process(args, cwd, stdout, stderr, cancel, env=None):
import _winapi import _winapi
import msvcrt import msvcrt
import subprocess import subprocess
@@ -106,7 +106,7 @@ def _start_windows_process(args, cwd, stdout, stderr, cancel):
None, subprocess.list2cmdline([os.fspath(arg) for arg in args]), None, subprocess.list2cmdline([os.fspath(arg) for arg in args]),
None, None, True, None, None, True,
win32con.CREATE_SUSPENDED | subprocess.CREATE_NO_WINDOW, win32con.CREATE_SUSPENDED | subprocess.CREATE_NO_WINDOW,
None, os.fspath(cwd), startup, env, os.fspath(cwd), startup,
) )
process = _WindowsProcess(args, handle, pid) process = _WindowsProcess(args, handle, pid)
job = _create_job(process) job = _create_job(process)
@@ -116,6 +116,8 @@ def _start_windows_process(args, cwd, stdout, stderr, cancel):
except BaseException: except BaseException:
try: try:
if job is not None: if job is not None:
if process is not None and process.poll() is not None:
_preserve_completed_job_children(job)
job.Close() job.Close()
finally: finally:
if process is not None: if process is not None:
@@ -135,7 +137,15 @@ def _start_windows_process(args, cwd, stdout, stderr, cancel):
_winapi.CloseHandle(handle) _winapi.CloseHandle(handle)
def run_engine(args, cwd, log_dir, cancel, timeout, on_event=None) -> int:
def _preserve_completed_job_children(job):
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, cwd, log_dir, cancel, timeout, on_event=None, *, env=None) -> int:
import subprocess import subprocess
import time import time
from .workspace import check_cancel from .workspace import check_cancel
@@ -149,9 +159,9 @@ def run_engine(args, cwd, log_dir, cancel, timeout, on_event=None) -> int:
with (log_dir / "stdout.log").open("wb") as stdout, (log_dir / "stderr.log").open("wb") as stderr: with (log_dir / "stdout.log").open("wb") as stdout, (log_dir / "stderr.log").open("wb") as stderr:
try: try:
if os.name == "nt": if os.name == "nt":
process, job = _start_windows_process(args, cwd, stdout, stderr, cancel) process, job = _start_windows_process(args, cwd, stdout, stderr, cancel, env=env)
else: else:
process = subprocess.Popen(args, cwd=cwd, stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr) process = subprocess.Popen(args, cwd=cwd, stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr, env=env)
emit(f"原生引擎已启动,PID={process.pid}") emit(f"原生引擎已启动,PID={process.pid}")
last_heartbeat = started last_heartbeat = started
while process.poll() is None: while process.poll() is None:
@@ -163,11 +173,27 @@ def run_engine(args, cwd, log_dir, cancel, timeout, on_event=None) -> int:
emit(f"等待原生引擎,已用时 {now-started:.0f} 秒") emit(f"等待原生引擎,已用时 {now-started:.0f} 秒")
last_heartbeat = now last_heartbeat = now
time.sleep(.05) time.sleep(.05)
if job is not None and process.returncode == 0:
# sch2pdf can leave iCDB flushing/defragmenting after its own
# successful exit. Never abort this work through Job close.
import win32job
_preserve_completed_job_children(job)
announced = False
while win32job.QueryInformationJobObject(job, win32job.JobObjectBasicAccountingInformation)["ActiveProcesses"]:
if not announced:
emit("原生出图完成,等待本次后台数据库服务完成写回;不强制结束后台服务")
announced = True
check_cancel(cancel)
if time.monotonic() - started > timeout:
raise TimeoutError("原生出图已完成,但后台数据库服务未在限时内结束;未发布 PDF,保留后台服务完成写回")
time.sleep(.05)
check_cancel(cancel) check_cancel(cancel)
return process.returncode return process.returncode
finally: finally:
try: try:
if job is not None: if job is not None:
if process is not None and process.poll() is not None:
_preserve_completed_job_children(job)
job.Close() job.Close()
finally: finally:
if process is not None: if process is not None:
+72 -29
View File
@@ -5,21 +5,21 @@ import hashlib
import json import json
import os import os
from pathlib import Path from pathlib import Path
import shutil
import threading import threading
import time import time
import uuid import uuid
from .engine import run_engine from .engine import run_engine
from .models import ExportOptions, ExportResult, ProjectInfo from .models import ExportOptions, ExportResult, ProjectInfo
from .path_policy import validate_queue_paths from .path_policy import validate_queue_paths
from .profiles import build_command from .profiles import build_command, prepare_native_environment
from .validation import validate_pdf from .validation import validate_pdf
from .workspace import check_cancel, fingerprint, prepare_workspace from .pdf_styles import apply_pdf_style
from .source_policy import classify_source_changes
from .workspace import check_cancel, compare_fingerprints, fingerprint, validate_project_database
def output_path(project: ProjectInfo, output_root: Path) -> Path: def output_path(project: ProjectInfo, output_root: Path) -> Path:
identity = hashlib.sha256(os.path.normcase(str(project.path.resolve())).encode("utf-8")).hexdigest()[:8] return Path(output_root) / (Path(project.path).stem + ".pdf")
return Path(output_root) / f"{project.name}__{identity}.pdf"
def write_json(path: Path, data) -> None: def write_json(path: Path, data) -> None:
@@ -40,6 +40,28 @@ def write_json(path: Path, data) -> None:
pass pass
def record_source_change(run: Path, before: dict[str, str], after: dict[str, str], database_relative: str, *, strict_source=False):
changes = compare_fingerprints(before, after)
accepted, blocked = classify_source_changes(changes, database_relative, strict=strict_source)
write_json(run / "source-diff.json", changes)
write_json(run / "source-assessment.json", {
"policy": "strict" if strict_source else "native_updates_warn",
"source_content_identical": before == after,
"native_updates": accepted, "blocked_changes": blocked,
"source_design_semantics_verified": False,
})
details = []
for key, label in (("modified", "内容变化"), ("added", "新增"), ("removed", "删除")):
paths = changes[key]
if paths:
sample = "、".join(paths[:3])
details.append(f"{label}:{sample}" + (f" 等 {len(paths)} 个文件" if len(paths) > 3 else ""))
blocking = any(blocked.values())
prefix = ("源工程文件内容发生变化,未发布 PDF,待人工核验。" if blocking else
"源数据库/运行记录发生变化,按直接导出策略仅记录提示;不是只读保证,也不能仅凭路径证明设计语义未变。")
return blocking, prefix + ";".join(details) + "。可能是原生引擎更新或外部修改;完整明细见 source-diff.json。"
class Exporter: class Exporter:
def __init__(self, engine: Path, runs_root: Path, *, runner=run_engine): def __init__(self, engine: Path, runs_root: Path, *, runner=run_engine):
self.engine = Path(engine) self.engine = Path(engine)
@@ -59,7 +81,9 @@ class Exporter:
start = time.monotonic() start = time.monotonic()
run = stage = before = final = None run = stage = before = final = None
published = False published = False
source_verified = False source_checked = False
source_identical = False
warnings = []
status, message, pages = "failed", "", 0 status, message, pages = "failed", "", 0
external = on_event or (lambda message: None) external = on_event or (lambda message: None)
def notify(message): def notify(message):
@@ -75,7 +99,12 @@ class Exporter:
log.write(datetime.now().isoformat(timespec="seconds") + " " + message + "\n") log.write(datetime.now().isoformat(timespec="seconds") + " " + message + "\n")
try: try:
check_cancel(cancel) check_cancel(cancel)
source_root = project.path.parent.resolve() if options.library_override:
raise ValueError("直接导出不支持替换依赖库;请先在 Mentor 配置原工程的库路径")
database = validate_project_database(project.path)
original_project = project.path.resolve()
source_root = original_project.parent
database_relative = database.resolve().relative_to(source_root).as_posix()
output_root = Path(output_root).resolve() output_root = Path(output_root).resolve()
runs_root = self.runs_root.resolve() runs_root = self.runs_root.resolve()
validate_queue_paths([project], output_root, runs_root) validate_queue_paths([project], output_root, runs_root)
@@ -86,18 +115,19 @@ class Exporter:
run = runs_root / (datetime.now().strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8]) run = runs_root / (datetime.now().strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8])
run.mkdir(parents=True, exist_ok=False) run.mkdir(parents=True, exist_ok=False)
write_json(run / "request.json", {"project": str(project.path), "options": asdict(options), "output": str(final), "engine": str(self.engine)}) write_json(run / "request.json", {"project": str(project.path), "options": asdict(options), "output": str(final), "engine": str(self.engine)})
emit("核验源工程并创建独立工作副本") emit("核验原工程;直接读取,不创建工程副本或备份")
before = fingerprint(source_root, cancel) before = fingerprint(source_root, cancel)
write_json(run / "source-before.json", before) write_json(run / "source-before.json", before)
copied = prepare_workspace(project.path, run, options, cancel)
if before != fingerprint(source_root, cancel):
raise RuntimeError("复制期间源工程发生变化,停止导出")
output_root.mkdir(parents=True, exist_ok=True) output_root.mkdir(parents=True, exist_ok=True)
stage = output_root / f".{final.stem}.{uuid.uuid4().hex[:8]}.partial.pdf" stage = output_root / f".{final.stem}.{uuid.uuid4().hex[:8]}.partial.pdf"
args = build_command(self.engine, copied, stage, options) args = build_command(self.engine, original_project, stage, options)
write_json(run / "command.json", args) write_json(run / "command.json", args)
emit("导出仅操作工作副本;源工程不保存、不修改") env = prepare_native_environment(run, options)
rc = self.runner(args, copied.parent, run, cancel, options.timeout, emit) emit("直接读取原工程;参考配色仅覆盖导出子进程配置,字体修复仅处理输出 PDF")
if env is not None:
write_json(run / "native-profile.json", {"theme": "reference", "config": str(run / "native-profile" / "DxDesigner.xml"), "WDIR": env["WDIR"], "scope": "child_process_only"})
kwargs = {"env": env} if env is not None else {}
rc = self.runner(args, source_root, run, cancel, options.timeout, emit, **kwargs)
check_cancel(cancel) check_cancel(cancel)
if rc != 0: if rc != 0:
details = [] details = []
@@ -109,22 +139,30 @@ class Exporter:
details.append(stream.read().decode("gb18030", errors="replace").strip()) details.append(stream.read().decode("gb18030", errors="replace").strip())
tail = " / ".join(text for text in details if text) tail = " / ".join(text for text in details if text)
raise RuntimeError(f"原生引擎退出码 {rc}。{tail or '请检查工程、许可证及运行日志。'}") raise RuntimeError(f"原生引擎退出码 {rc}。{tail or '请检查工程、许可证及运行日志。'}")
if options.font_mapping!="preserve" or options.print_theme!="original":
emit("发布前处理文字编码、字体回退与矢量打印配色;不增加白色遮罩")
validate_pdf(stage)
style=apply_pdf_style(stage,options,cancel)
write_json(run / "pdf-style.json",asdict(style))
emit(f"字体/配色完成:转换 {style.font_strings} 段文字,修复 {style.repaired_strings} 段编码,中文回退 {style.fallback_strings} 段")
emit("发布前验证 PDF 结构、页数与源工程内容指纹") emit("发布前验证 PDF 结构、页数与源工程内容指纹")
check = validate_pdf(stage) check = validate_pdf(stage)
write_json(run / "pdf-check.json", asdict(check)) write_json(run / "pdf-check.json", asdict(check))
after = fingerprint(source_root, cancel) after = fingerprint(source_root, cancel)
write_json(run / "source-after.json", after) write_json(run / "source-after.json", after)
if before != after: source_identical = before == after
status, message = "uncertain", "源工程在任务期间发生变化,未发布 PDF;请检查并重新导出" blocked = False
else: if not source_identical:
source_verified = True blocked, detail = record_source_change(run, before, after, database_relative, strict_source=options.strict_source)
if blocked:
status, message = "uncertain", detail
else:
warnings.append(detail)
if not blocked:
source_checked = True
check_cancel(cancel) check_cancel(cancel)
backup = None
if options.overwrite and final.exists():
backup = run / "previous-output.pdf"
shutil.copyfile(final, backup)
prepared = ExportResult(str(project.path), "publishing", "发布前校验通过,提交中;若中断请核对 commit.json", str(final), check.pages, str(run), time.monotonic()-start) prepared = ExportResult(str(project.path), "publishing", "发布前校验通过,提交中;若中断请核对 commit.json", str(final), check.pages, str(run), time.monotonic()-start)
write_json(run / "commit.json", {"phase":"prepared", "target":str(final), "new_sha256":check.sha256, "previous_backup":str(backup) if backup else "", "source_verified_before_publish":True}) write_json(run / "commit.json", {"phase":"prepared", "target":str(final), "new_sha256":check.sha256, "backup_created":False,"working_copy_created":False,"source_project":str(original_project), "source_verified_before_publish":source_identical, "source_content_identical":source_identical, "source_change_policy":"strict" if options.strict_source else "native_updates_warn", "warnings":warnings})
# If this write fails, the old output has not been touched. # If this write fails, the old output has not been touched.
write_json(run / "result.json", asdict(prepared)) write_json(run / "result.json", asdict(prepared))
check_cancel(cancel) check_cancel(cancel)
@@ -136,7 +174,7 @@ class Exporter:
os.link(stage, final) os.link(stage, final)
stage.unlink() stage.unlink()
published, stage, pages, status = True, None, check.pages, "success" published, stage, pages, status = True, None, check.pages, "success"
message = f"已导出 {pages} 页;发布前源内容指纹一致。图页完整性及字体效果请人工复核。" message = f"已导出 {pages} 页;PDF 结构与发布前检查通过。" + ("源内容指纹一致。" if source_identical else "存在源数据库/运行记录更新提示。") + "图页完整性及字体效果请人工复核。"
except InterruptedError as error: except InterruptedError as error:
status, message = "cancelled", str(error) status, message = "cancelled", str(error)
except TimeoutError as error: except TimeoutError as error:
@@ -147,26 +185,31 @@ class Exporter:
# Failure-path checks never happen AFTER irrevocable publication. # Failure-path checks never happen AFTER irrevocable publication.
# A source edit after the final pre-commit observation is a new # A source edit after the final pre-commit observation is a new
# source version, not a reason to silently retract the old result. # source version, not a reason to silently retract the old result.
if not published and not source_verified and before is not None and run is not None: if not published and not source_checked and before is not None and run is not None:
try: try:
after = fingerprint(project.path.parent.resolve()) after = fingerprint(project.path.parent.resolve())
write_json(run / "source-after.json", after) write_json(run / "source-after.json", after)
if after != before: if after != before:
status, message = "uncertain", "源工程在任务期间发生变化,未发布 PDF,结果待人工核验" blocked, detail = record_source_change(run, before, after, database_relative, strict_source=options.strict_source)
if blocked:
status, message = "uncertain", detail
elif detail not in warnings:
warnings.append(detail)
except Exception as error: except Exception as error:
status, message = "uncertain", f"无法完成源工程核验,未发布 PDF:{error}" status, message = "uncertain", f"无法完成源工程核验,未发布 PDF:{error}"
if stage is not None: if stage is not None:
try: try:
if stage.exists(): if stage.exists():
shutil.copyfile(stage, run / "unpublished.pdf")
stage.unlink() stage.unlink()
except OSError: except OSError:
message += ";暂存输出清理失败,请检查运行记录" message += ";暂存输出清理失败,请检查运行记录"
result = ExportResult(str(project.path), status, message, str(final) if published else "", pages, str(run) if run else "", time.monotonic()-start) if warnings:
message += " 提示:" + " ".join(warnings)
result = ExportResult(str(project.path), status, message, str(final) if published else "", pages, str(run) if run else "", time.monotonic()-start, warnings=tuple(warnings))
if run: if run:
try: try:
write_json(run / "result.json", asdict(result)) write_json(run / "result.json", asdict(result))
except Exception as error: except Exception as error:
result = replace(result, status="uncertain" if published else result.status, message=result.message+f";结果记录写入失败:{error}"+ ("。PDF 已发布,commit.json 与提交预记录保留,旧输出备份在运行目录。" if published else "。未发布正式 PDF。")) result = replace(result, status="uncertain" if published else result.status, message=result.message+f";结果记录写入失败:{error}"+ ("。PDF 已发布,commit.json 与提交预记录保留;未保留旧 PDF 备份。" if published else "。未发布正式 PDF。"))
notify(result.message) notify(result.message)
return result return result
+13
View File
@@ -11,6 +11,9 @@ class ProjectInfo:
@dataclass(frozen=True) @dataclass(frozen=True)
class ExportOptions: class ExportOptions:
library_override: str = "" library_override: str = ""
font_mapping: str = "preserve"
print_theme: str = "original"
legacy_gbk: bool = False
color: int = 4 color: int = 4
popup: bool = True popup: bool = True
use_exclusion: bool = True use_exclusion: bool = True
@@ -22,8 +25,17 @@ class ExportOptions:
stroke_width: int = 1 stroke_width: int = 1
timeout: float = 180.0 timeout: float = 180.0
overwrite: bool = False overwrite: bool = False
strict_source: bool = False
def __post_init__(self): def __post_init__(self):
if self.font_mapping not in {"preserve","arial","simsun","msyh"}:
raise ValueError("无效字体映射方案")
if self.stroke_fonts and self.font_mapping != "preserve":
raise ValueError("笔画字体不能与 Unicode 字体修复同时启用,请关闭笔画字体")
if self.legacy_gbk and self.font_mapping == "preserve":
raise ValueError("CP936 / GBK 修复必须显式选择 Arial、宋体或微软雅黑字体映射")
if self.print_theme not in {"reference","original","high_contrast","mono"}:
raise ValueError("无效打印配色方案")
if self.color not in (0, 1, 2, 3, 4): if self.color not in (0, 1, 2, 3, 4):
raise ValueError("无效颜色模式") raise ValueError("无效颜色模式")
if self.timeout <= 0 or self.line_width < 1 or self.stroke_width < 1: if self.timeout <= 0 or self.line_width < 1 or self.stroke_width < 1:
@@ -40,3 +52,4 @@ class ExportResult:
pages: int = 0 pages: int = 0
run_dir: str = "" run_dir: str = ""
duration: float = 0.0 duration: float = 0.0
warnings: tuple[str, ...] = ()
+45
View File
@@ -0,0 +1,45 @@
"""Keep PDF basenames unchanged; isolate only colliding source versions."""
from __future__ import annotations
from collections import defaultdict
import os
from pathlib import Path
from .path_policy import validate_queue_paths
def plan_output_directories(projects, output_root: Path, runs_root: Path) -> list[Path]:
projects = list(projects)
output = Path(output_root).resolve()
validate_queue_paths(projects, output, runs_root)
destinations = [output] * len(projects)
groups = defaultdict(list)
for index, project in enumerate(projects):
groups[Path(project.path).stem.casefold()].append(index)
for indexes in groups.values():
if len(indexes) < 2:
continue
parents = [Path(projects[index].path).resolve().parent for index in indexes]
try:
common = Path(os.path.commonpath(parents))
except ValueError: # different Windows drives / UNC shares
common = None
for index, parent in zip(indexes, parents):
if common is not None:
relative = parent.relative_to(common)
else:
anchor = parent.anchor.replace(':', '').strip('\\/').replace('\\', '/')
relative = Path(anchor).joinpath(*parent.parts[1:])
destinations[index] = output / relative
# Canonical paths must match the exporter; junction aliases cannot merge
# separate versions into a shared same.pdf when overwrite is enabled.
destinations = [directory.resolve() for directory in destinations]
# Derived folders must protect the ENTIRE queue, not just their own source.
for directory in dict.fromkeys(destinations):
validate_queue_paths(projects, directory, runs_root)
targets = {}
for project, directory in zip(projects, destinations):
source = os.path.normcase(str(Path(project.path).resolve()))
target = os.path.normcase(str(directory / (Path(project.path).stem + '.pdf')))
previous = targets.setdefault(target, source)
if previous != source:
raise ValueError('同名工程输出路径冲突,请按不同工程目录分批导出')
return destinations
+119
View File
@@ -0,0 +1,119 @@
"""Subset installed TrueType fonts into explicit Unicode PDF resources.
Font files are read from Windows, never distributed with the application.
Only text resources change; no white rectangle or raster overlay is added.
"""
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,FloatObject,NameObject,NumberObject,TextStringObject)
FONT_FILES={"arial":"arial.ttf","simsun":"simsun.ttc","msyh":"msyh.ttc"}
@dataclass
class EmbeddedFont:
name: str
reference: object
glyphs: dict[int,int]
widths: dict[int,float]
fallback: bool = False
def encode(self,text):
return b"".join(self.glyphs[ord(character)].to_bytes(2,"big") for character in text)
def width(self,text,size):
return sum(self.widths[ord(character)] for character in text)*size/1000
def font_path(mode):
path=Path(os.environ.get("WINDIR",r"C:\Windows"))/"Fonts"/FONT_FILES[mode]
if not path.is_file():
raise ValueError(f"本机缺少 {FONT_FILES[mode]} 字体,无法完成选定字体方案")
return path
def _load(mode):
from fontTools.ttLib import TTFont
path=font_path(mode)
return TTFont(path,fontNumber=0,lazy=False,recalcTimestamp=False)
def _embedded(writer,mode,font,characters,fallback=False):
from fontTools import subset
cmap=font.getBestCmap() or {}
codepoints={ord(c) for c in characters}
missing=codepoints-cmap.keys()
if missing:
raise ValueError(f"字体 {mode} 缺少字符:"+" ".join(f"U+{c:04X}" for c in sorted(missing)[:12]))
flags=getattr(font.get("OS/2"),"fsType",0)
if flags & (0x0002|0x0100|0x0200):
raise ValueError(f"字体 {mode} 的嵌入限制不支持此子集处理")
options=subset.Options()
options.recalc_timestamp=False
options.layout_features=[]
worker=subset.Subsetter(options=options);worker.populate(unicodes=codepoints);worker.subset(font)
font.flavor=None
buffer=BytesIO();font.save(buffer,reorderTables=True);payload=buffer.getvalue()
cmap=font.getBestCmap()
units=font['head'].unitsPerEm
glyphs={cp:font.getGlyphID(cmap[cp]) for cp in codepoints}
widths={cp:font['hmtx'][cmap[cp]][0]*1000/units for cp in codepoints}
order=font.getGlyphOrder()
all_widths=[round(font['hmtx'][name][0]*1000/units) for name in order]
tag={"arial":"MNARAL","simsun":"MNSMSN","msyh":"MNMSYH"}[mode]
family={"arial":"Arial","simsun":"SimSun","msyh":"MicrosoftYaHei"}[mode]
base=f"/{tag}+{family}"
font_file=DecodedStreamObject();font_file.set_data(payload);font_file[NameObject('/Length1')]=NumberObject(len(payload))
font_file_ref=writer._add_object(font_file.flate_encode())
head=font['head'];hhea=font['hhea'];os2=font.get('OS/2')
metric=lambda value:NumberObject(round(value*1000/units))
descriptor=DictionaryObject({
NameObject('/Type'):NameObject('/FontDescriptor'),NameObject('/FontName'):NameObject(base),
NameObject('/Flags'):NumberObject(32),NameObject('/FontBBox'):ArrayObject([metric(v) for v 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'):font_file_ref,
})
cid=DictionaryObject({NameObject('/Type'):NameObject('/Font'),NameObject('/Subtype'):NameObject('/CIDFontType2'),NameObject('/BaseFont'):NameObject(base),
NameObject('/CIDSystemInfo'):DictionaryObject({NameObject('/Registry'):TextStringObject('Adobe'),NameObject('/Ordering'):TextStringObject('Identity'),NameObject('/Supplement'):NumberObject(0)}),
NameObject('/FontDescriptor'):writer._add_object(descriptor),NameObject('/CIDToGIDMap'):NameObject('/Identity'),
NameObject('/DW'):NumberObject(1000),NameObject('/W'):ArrayObject([NumberObject(0),ArrayObject([NumberObject(v) for v in all_widths])]),
})
# CID == subset glyph ID; map each used CID to its original Unicode scalar.
mappings={}
for cp,gid in sorted(glyphs.items()):mappings.setdefault(gid,cp)
rows=["/CIDInit /ProcSet findresource begin","12 dict begin","begincmap","/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def","/CMapName /MentorUnicode def","/CMapType 2 def","1 begincodespacerange","<0000> <FFFF>","endcodespacerange"]
pairs=list(mappings.items())
for offset in range(0,len(pairs),100):
chunk=pairs[offset:offset+100];rows.append(f"{len(chunk)} beginbfchar")
rows.extend(f"<{gid:04X}> <{chr(cp).encode('utf-16-be').hex().upper()}>" for gid,cp in chunk)
rows.append("endbfchar")
rows.extend(["endcmap","CMapName currentdict /CMap defineresource pop","end","end"])
unicode_map=DecodedStreamObject();unicode_map.set_data("\n".join(rows).encode('ascii'))
resource=DictionaryObject({NameObject('/Type'):NameObject('/Font'),NameObject('/Subtype'):NameObject('/Type0'),NameObject('/BaseFont'):NameObject(base),NameObject('/Encoding'):NameObject('/Identity-H'),NameObject('/DescendantFonts'):ArrayObject([writer._add_object(cid)]),NameObject('/ToUnicode'):writer._add_object(unicode_map.flate_encode())})
return EmbeddedFont(f"/Mentor{family}",writer._add_object(resource),glyphs,widths,fallback)
def build_fonts(writer,mode,texts):
"""Select a primary font and whole-string Chinese fallback explicitly."""
primary=_load(mode)
fallback_font=None
try:
cmap=primary.getBestCmap() or {}
groups={False:set(),True:set()}
use_fallback=[]
for text in texts:
fallback=any(ord(c) not in cmap for c in text)
groups[fallback].update(text);use_fallback.append(fallback)
result={}
if groups[False]:result[False]=_embedded(writer,mode,primary,groups[False],False)
if groups[True]:
fallback_mode='simsun' if mode!='simsun' else 'msyh'
fallback_font=_load(fallback_mode)
result[True]=_embedded(writer,fallback_mode,fallback_font,groups[True],True)
return result,use_fallback
finally:
primary.close()
if fallback_font is not None:fallback_font.close()
+350
View File
@@ -0,0 +1,350 @@
"""Verified, vector-preserving styling of native Mentor PDF staging files."""
from __future__ import annotations
from dataclasses import dataclass
import colorsys
import math
import os
from pathlib import Path
import uuid
from pypdf import PdfReader,PdfWriter
from pypdf.generic import (ArrayObject,ByteStringObject,ContentStream,DictionaryObject,FloatObject,NameObject,NumberObject)
from .models import ExportOptions
from .workspace import check_cancel
@dataclass(frozen=True)
class StyleReport:
modified: bool = False
color_ops: int = 0
font_strings: int = 0
repaired_strings: int = 0
fallback_strings: int = 0
font_mapping: str = "preserve"
print_theme: str = "original"
legacy_gbk: bool = False
preserved_ascii_stroke_strings: int = 0
def decode_legacy_text(raw, *, legacy_gbk=False):
"""Respect declared WinAnsi unless the caller explicitly confirms CP936.
GBK and WinAnsi are inherently ambiguous: B1D7 is either 弊 or ±×.
Never infer engineering text encoding from successful byte round-trips.
Native output can mix standalone WinAnsi engineering symbols with GBK.
Invalid GBK retains the declared encoding; unknown CP1252 bytes fail.
"""
if not legacy_gbk:
return raw.decode('cp1252', errors='strict'), False
try:
decoded = raw.decode('gbk', errors='strict')
except UnicodeDecodeError:
return raw.decode('cp1252', errors='strict'), False
return decoded, any(byte >= 128 for byte in raw)
PALETTE=((139,30,45),(146,90,16),(31,41,55),(23,107,58),(11,95,106),(36,86,166),(107,33,168))
def contrast_rgb(rgb,*,text=True,mono=False):
rgb=tuple(float(value) for value in rgb)
if min(rgb)>.97:return (1,1,1)
if max(rgb)<.08:return (0,0,0)
if mono:
return (0,0,0) if text else (.92,.92,.92)
# Make palette application idempotent for its own foreground/tinted fills.
for item in PALETTE+((75,85,99),):
target=tuple(v/255 for v in item)
tint=tuple(.84+.16*v for v in target)
if all(abs(a-b)<.00001 for a,b in zip(rgb,tint)):
return target if text else tint
if all(abs(a-b)<.004 for a,b in zip(rgb,target)):
dark=target;break
else:
hue,saturation,_=colorsys.rgb_to_hsv(*rgb)
if saturation<.13:dark=tuple(v/255 for v in (75,85,99))
else:
index=0 if hue<.04 or hue>=.96 else 1 if hue<.14 else 2 if hue<.25 else 3 if hue<.45 else 4 if hue<.60 else 5 if hue<.78 else 6
dark=tuple(v/255 for v in PALETTE[index])
return dark if text else tuple(.84+.16*v for v in dark)
def _raw(value):
if isinstance(value,ByteStringObject):return bytes(value)
if hasattr(value,'original_bytes'):return value.original_bytes
return str(value).encode('cp1252')
def _is_stroke_font(font):
return str(font.get('/BaseFont', '')).lstrip('/').split('+')[-1].casefold().startswith('fstroke')
def _preservable_ascii_stroke(font, raw, rendering_mode):
# Native English stroke geometry is already visible; Tr=3 text is ONLY its
# search layer. Preserve both without claiming a font/Chinese conversion.
return (_is_stroke_font(font) and rendering_mode == 3 and raw.isascii()
and font.get('/Encoding') == '/WinAnsiEncoding'
and font.get('/Subtype') in ('/Type1', '/TrueType'))
def _validate_form_text(form, reader, inherited_resources, current_font=None, active=None, rendering_mode=0):
"""Never claim repair for text in a reachable form that we cannot rewrite."""
active = set() if active is None else active
if id(form) in active:
raise ValueError('Form XObject 存在循环引用,不能安全验证文字')
active.add(id(form))
try:
resources = form.get('/Resources', inherited_resources).get_object()
fonts = resources.get('/Font', DictionaryObject()).get_object()
xobjects = resources.get('/XObject', DictionaryObject()).get_object()
stack = []
for operands, operator in ContentStream(form, reader).operations:
if operator == b'q': stack.append((current_font, rendering_mode))
elif operator == b'Q' and stack: current_font, rendering_mode = stack.pop()
elif operator == b'Tf': current_font = fonts.get(operands[0])
elif operator == b'Tr': rendering_mode = int(operands[0])
elif operator == b'Do':
child = xobjects.get(operands[0])
if child and child.get_object().get('/Subtype') == '/Form':
_validate_form_text(child.get_object(), reader, resources, current_font, active, rendering_mode=rendering_mode)
elif operator in (b'Tj', b'TJ', b"'", b'"'):
if not current_font:
raise ValueError('Form XObject 文字缺少字体状态,不能保证字体修复')
font = current_font.get_object()
if _is_stroke_font(font):
if operator == b'Tj' and _preservable_ascii_stroke(font, _raw(operands[0]), rendering_mode):
continue
raise ValueError('Form XObject 使用非 ASCII 或可见笔画文字,不能冒充中文修复')
if font.get('/Encoding') == '/WinAnsiEncoding' and font.get('/Subtype') in ('/Type1', '/TrueType'):
raise ValueError('暂不支持 Form XObject 内的旧编码文字转换,未修改正式输出')
finally:
active.remove(id(form))
def _texts(reader, *, legacy_gbk=False):
"""Only rewrite simple WinAnsi native fonts; proper CID input is untouched."""
found=[]
for page in reader.pages:
resources=page.get('/Resources',DictionaryObject()).get_object()
fonts=resources.get('/Font',DictionaryObject()).get_object()
current=None; rendering_mode=0; stack=[]
for operands,operator in ContentStream(page.get_contents(),reader).operations:
if operator==b'q':stack.append((current,rendering_mode))
elif operator==b'Q' and stack:current,rendering_mode=stack.pop()
elif operator==b'Tf':current=fonts.get(operands[0])
elif operator==b'Tr':rendering_mode=int(operands[0])
elif operator==b'Do':
xobjects=resources.get('/XObject',DictionaryObject()).get_object()
form=xobjects.get(operands[0])
if form and form.get_object().get('/Subtype')=='/Form':
_validate_form_text(form.get_object(),reader,resources,current,rendering_mode=rendering_mode)
elif operator in (b'Tj',b'TJ',b"'",b'"') and current:
font=current.get_object()
if _is_stroke_font(font):
if operator==b'Tj' and _preservable_ascii_stroke(font,_raw(operands[0]),rendering_mode):
continue
raise ValueError('原生输出含非 ASCII 或可见笔画文字,无法安全修复;请检查该字体映射')
if font.get('/Encoding')!='/WinAnsiEncoding' or font.get('/Subtype') not in ('/Type1','/TrueType'):continue
if operator!=b'Tj':
raise ValueError(f'字体转换尚不支持 {operator.decode()} 复合文字操作,未修改正式输出')
items=[operands[0]]
for value in items:
raw=_raw(value)
if not raw:continue
decoded,repaired=decode_legacy_text(raw, legacy_gbk=legacy_gbk)
decoded=''.join(c for c in decoded if ord(c)>=32)
if not decoded:continue
found.append((raw,decoded,repaired))
return found
def _old_width(font,raw,size):
raw=bytes(byte for byte in raw if byte>=32)
widths=font.get('/Widths')
if widths:
widths=widths.get_object();first=int(font.get('/FirstChar',0))
values=[float(widths[byte-first]) if 0<=byte-first<len(widths) else 500 for byte in raw]
elif 'Courier' in str(font.get('/BaseFont','')):
values=[600]*len(raw)
elif font.get('/Subtype') == '/Type1':
# Exact Adobe Core-14 AFM metrics already shipped by pypdf; never
# substitute Windows Arial widths for a native Helvetica/Times font.
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:
return None
widths = metrics.character_widths
values=[widths.get(_win_encoding[byte], widths['default']) for byte in raw]
else:
# Native mapped TrueType fonts provide Widths; unsupported base-font
# advance estimates are not used to stretch legitimate geometry.
return None
return sum(values)*size/1000
def _numbers(values):return [FloatObject(value) for value in values]
def _point(matrix,x,y):
a,b,c,d,e,f=matrix
return (a*x+c*y+e,b*x+d*y+f)
def _matrix(left,right):
a,b,c,d,e,f=left; A,B,C,D,E,F=right
return (a*A+c*B,b*A+d*B,a*C+c*D,b*C+d*D,a*E+c*F+e,b*E+d*F+f)
def _minimum_width(matrix,width):
a,b,c,d,_,_=matrix
determinant=abs(a*d-b*c)
trace=a*a+b*b+c*c+d*d
largest=math.sqrt((trace+math.sqrt(max(0,trace*trace-4*determinant*determinant)))/2)
smallest=determinant/largest if largest else 0
if smallest<=1e-10:
raise ValueError('打印配色不支持退化的坐标变换,未修改正式输出')
return max(width,.35/smallest)
def _panel(points,complex_path):
"""Only tint large simple rectangles, never filled stroke-font glyphs."""
if complex_path:return False
if len(points)==5 and points[0]==points[-1]:points=points[:-1]
if len(points)!=4:return False
xs={p[0] for p in points};ys={p[1] for p in points}
if len(xs)!=2 or len(ys)!=2:return False
return max(xs)-min(xs)>=6 and max(ys)-min(ys)>=6 and len(set(points))==4 and all(p[0]==q[0] or p[1]==q[1] for p,q in zip(points,points[1:]+points[:1]))
def apply_pdf_style(path:Path,options:ExportOptions,cancel=None)->StyleReport:
check_cancel(cancel)
style_colors = options.print_theme in {"high_contrast", "mono"}
if options.font_mapping=='preserve' and not style_colors:
return StyleReport(print_theme=options.print_theme)
path=Path(path)
reader=PdfReader(path,strict=True)
writer=PdfWriter();writer.clone_document_from_reader(reader)
entries=_texts(reader, legacy_gbk=options.legacy_gbk) if options.font_mapping!='preserve' else []
font_choices={}
fonts={}
if entries:
from .pdf_fonts import build_fonts
fonts,flags=build_fonts(writer,options.font_mapping,[text for _,text,_ in entries])
for entry,fallback in zip(entries,flags):font_choices[entry[0]]=(entry[1],entry[2],fonts[fallback])
color_ops=font_strings=repaired_strings=fallback_strings=preserved_ascii_stroke_strings=0
for page in writer.pages:
check_cancel(cancel)
resources=page.get('/Resources',DictionaryObject()).get_object()
# Own this page's resource dictionary: do not mutate a shared inherited
# dictionary while another page/form still depends on its old names.
resources=DictionaryObject(dict(resources));page[NameObject('/Resources')]=resources
old_fonts=resources.get('/Font',DictionaryObject()).get_object()
font_dict=DictionaryObject(dict(old_fonts));resources[NameObject('/Font')]=font_dict
for font in fonts.values():
if font.name in font_dict:raise ValueError('新字体资源名与原 PDF 冲突')
font_dict[NameObject(font.name)]=font.reference
stream=ContentStream(page.get_contents(),writer)
rebuilt=[([FloatObject(.35)],b"w")] if style_colors else []
raw_fill=(0,0,0);rendering_mode=0;inside_text=False;current_font=None;size=12.0;scale=100.0;char_space=word_space=0.0;stack=[]
matrix=(1,0,0,1,0,0);line_width=1.0;path_points=[];complex_path=False
mono=options.print_theme=='mono'
for operands,operator in stream.operations:
if operator==b'q':stack.append((raw_fill,current_font,size,scale,char_space,word_space,matrix,line_width,rendering_mode))
elif operator==b'Q' and stack:raw_fill,current_font,size,scale,char_space,word_space,matrix,line_width,rendering_mode=stack.pop()
elif operator==b'Tf':current_font=operands[0];size=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_mode=int(operands[0])
if operator==b'cm':matrix=_matrix(matrix,tuple(float(v) for v in operands))
if operator==b'm':
complex_path=complex_path or bool(path_points)
path_points.append(_point(matrix,*map(float,operands)))
elif operator==b'l':path_points.append(_point(matrix,*map(float,operands)))
elif operator==b're':
complex_path=complex_path or bool(path_points)
x,y,w,h=map(float,operands)
path_points.extend(_point(matrix,X,Y) for X,Y in [(x,y),(x+w,y),(x+w,y+h),(x,y+h)])
elif operator in (b'c',b'v',b'y'):complex_path=True
if operator==b'w':line_width=float(operands[0])
if style_colors and operator in (b'S',b's',b'B',b'B*',b'b',b'b*',b'Tj'):
rebuilt.append(([FloatObject(_minimum_width(matrix,line_width))],b'w'))
if operator in (b'f',b'f*',b'B',b'B*',b'b',b'b*') and style_colors:
foreground=not _panel(path_points,complex_path)
rebuilt.append((_numbers(contrast_rgb(raw_fill,text=foreground,mono=mono)),b'rg'))
rebuilt.append((operands,operator))
rebuilt.append((_numbers(contrast_rgb(raw_fill,text=inside_text,mono=mono)),b'rg'))
color_ops+=2;path_points=[];complex_path=False
continue
if operator in (b'S',b's',b'n',b'f',b'f*',b'B',b'B*',b'b',b'b*'):
path_points=[];complex_path=False
if operator==b'w' and style_colors and operands:
operands=[FloatObject(_minimum_width(matrix,line_width))]
if operator==b'BT':
inside_text=True;rebuilt.append((operands,operator))
if style_colors:rebuilt.append((_numbers(contrast_rgb(raw_fill,text=True,mono=mono)),b'rg'));color_ops+=1
continue
if operator==b'ET':
inside_text=False;rebuilt.append((operands,operator))
if style_colors:rebuilt.append((_numbers(contrast_rgb(raw_fill,text=False,mono=mono)),b'rg'));color_ops+=1
continue
if style_colors and operator in (b'cs',b'CS',b'sc',b'SC',b'scn',b'SCN'):
raise ValueError('打印配色暂不支持自定义颜色空间,未修改正式输出')
if operator in (b'g',b'G') and style_colors:
operands = _numbers([float(operands[0])] * 3)
operator = b'rg' if operator == b'g' else b'RG'
elif operator in (b'k',b'K') and style_colors:
c,m,y,k = (float(value) for value in operands)
operands = _numbers([1-min(1,component+k) for component in (c,m,y)])
operator = b'rg' if operator == b'k' else b'RG'
if operator==b'rg' and len(operands)==3:
raw_fill=tuple(float(v) for v in operands)
if style_colors:operands=_numbers(contrast_rgb(raw_fill,text=inside_text,mono=mono));color_ops+=1
elif operator==b'RG' and len(operands)==3 and style_colors:
operands=_numbers(contrast_rgb(tuple(float(v) for v in operands),text=True,mono=mono));color_ops+=1
if operator==b'Tj' and options.font_mapping!='preserve' and current_font in old_fonts:
original_font=old_fonts[current_font].get_object()
if _preservable_ascii_stroke(original_font,_raw(operands[0]),rendering_mode):
preserved_ascii_stroke_strings+=1
rebuilt.append((operands,operator))
continue
if operator==b'Tj' and font_choices and current_font in old_fonts:
original_font=old_fonts[current_font].get_object()
if original_font.get('/Encoding')=='/WinAnsiEncoding' and original_font.get('/Subtype') in ('/Type1','/TrueType'):
raw=_raw(operands[0])
selected=font_choices.get(raw)
if selected:
if char_space != 0 or word_space != 0:
raise ValueError('字体转换暂不支持非零字符间距或词间距,未修改正式输出')
text,repaired,font=selected
previous_width=_old_width(original_font,raw,size)
if previous_width is None:
raise ValueError(f'原字体 {original_font.get("/BaseFont")} 缺少可靠字宽信息,不能保证文字推进量;未修改正式输出')
new_width=font.width(text,size)
new_scale=scale*previous_width/new_width if previous_width is not None and previous_width>0 and new_width>0 else scale
rebuilt.extend([([NameObject(font.name),FloatObject(size)],b'Tf'),([FloatObject(new_scale)],b'Tz'),([ByteStringObject(font.encode(text))],b'Tj'),([current_font,FloatObject(size)],b'Tf'),([FloatObject(scale)],b'Tz')])
font_strings+=1;repaired_strings+=int(repaired);fallback_strings+=int(font.fallback)
continue
# Native output was verified to use Tj. Do not falsely claim a
# compound TJ/shorthand operator was converted by this version.
rebuilt.append((operands,operator))
stream.operations=rebuilt
stream.get_data() # materialize operations before flate_encode uses _data
page[NameObject('/Contents')]=writer._add_object(stream.flate_encode())
temporary=path.with_name('.'+path.name+'.'+uuid.uuid4().hex[:8]+'.style.tmp')
try:
check_cancel(cancel)
with temporary.open('xb') as output:
writer.write(output);output.flush();os.fsync(output.fileno())
check_cancel(cancel)
# Structural verification happens before replacement, and again in the
# enclosing exporter before any formal publication.
result=PdfReader(temporary,strict=True)
if len(result.pages)!=len(reader.pages):raise ValueError('配色/字体处理改变了 PDF 页数')
os.replace(temporary,path)
finally:
try:
if temporary.exists():temporary.unlink()
except OSError:pass
return StyleReport(True,color_ops,font_strings,repaired_strings,fallback_strings,options.font_mapping,options.print_theme,options.legacy_gbk,preserved_ascii_stroke_strings)
+53 -3
View File
@@ -1,8 +1,14 @@
from __future__ import annotations from __future__ import annotations
from pathlib import Path from pathlib import Path
import os
import xml.etree.ElementTree as ET
from .models import ExportOptions from .models import ExportOptions
def effective_color(options: ExportOptions) -> int:
return 4 if options.print_theme in {"reference", "high_contrast"} else 3 if options.print_theme=="mono" else options.color
def write_profile(path: Path, options: ExportOptions) -> None: def write_profile(path: Path, options: ExportOptions) -> None:
original = path.read_bytes() if path.exists() else b"" original = path.read_bytes() if path.exists() else b""
encoding = "utf-8" encoding = "utf-8"
@@ -16,7 +22,7 @@ def write_profile(path: Path, options: ExportOptions) -> None:
values = { values = {
"AddPopup": str(int(options.popup)), "AddPopup": str(int(options.popup)),
"ChangeIct2Sch": str(int(options.change_ict)), "ChangeIct2Sch": str(int(options.change_ict)),
"Color": str(options.color), "Color": str(effective_color(options)),
"VisibleHLs": "0", "VisibleHLs": "0",
"StartAcrobat": "0", "StartAcrobat": "0",
"UrlProperties": "", "UrlProperties": "",
@@ -27,6 +33,10 @@ def write_profile(path: Path, options: ExportOptions) -> None:
"SheetOrder": "", "SheetOrder": "",
"HorizontalScale": "100", "HorizontalScale": "100",
} }
if options.font_mapping != "preserve":
family={"arial":"Arial","simsun":"SimSun","msyh":"Microsoft YaHei"}[options.font_mapping]
values["FONT_CUSTOM_FONTS"]=family
values.update({f"Font_{i}":family for i in range(14)})
aliases = {key.casefold(): key for key in values} aliases = {key.casefold(): key for key in values}
lines = [] lines = []
seen = set() seen = set()
@@ -44,7 +54,7 @@ def write_profile(path: Path, options: ExportOptions) -> None:
def build_command(engine: Path, project: Path, output: Path, options: ExportOptions) -> list[str]: def build_command(engine: Path, project: Path, output: Path, options: ExportOptions) -> list[str]:
args = [str(engine), "-project", str(project), "-a", str(output), "-c", str(options.color)] args = [str(engine), "-project", str(project), "-a", str(output), "-c", str(effective_color(options))]
if options.popup: if options.popup:
args.append("-p") args.append("-p")
if options.use_exclusion: if options.use_exclusion:
@@ -53,10 +63,50 @@ def build_command(engine: Path, project: Path, output: Path, options: ExportOpti
args.append("-i2s") args.append("-i2s")
if options.stroke_fonts: if options.stroke_fonts:
args.append("-uAll") # Verified on EE 7.9.5; separated -u All fails. args.append("-uAll") # Verified on EE 7.9.5; separated -u All fails.
else: elif options.font_mapping == "preserve":
args.append("-udx") args.append("-udx")
if options.stop_at: if options.stop_at:
args.extend(["-l", options.stop_at]) args.extend(["-l", options.stop_at])
if options.schematic: if options.schematic:
args.extend(["-schematic", options.schematic]) args.extend(["-schematic", options.schematic])
return args return args
# Evidence: aligned Audio reference paths separate NET, PIN, primitives and BOX.
# These XML values are RGB, not the legacy colors.def Windows BGR integers.
REFERENCE_OBJECT_COLORS = {
"NET": "0xff0000", "COMPONENT": "0x800080", "PIN": "0x008080",
"LINE": "0x0000ff", "BOX": "0x800080", "CIRCLE": "0x008000",
"ARC": "0x0000ff", "TEXT": "0x0000ff", "LABEL": "0x008000",
"ATTRIBUTE": "0x388e8e",
}
def prepare_native_environment(run: Path, options: ExportOptions) -> dict[str, str] | None:
"""Supply a minimal native palette to THIS child; never change os.environ.
WDIR is an ordered semicolon-separated native configuration search path.
The original project and its dependencies stay in place. This directory
contains only our color keys, not a CAD project, database or global config.
Native explicit property colors still take precedence over role defaults.
"""
if options.print_theme != "reference":
return None
config = Path(run).resolve() / "native-profile"
if ";" in str(config):
raise ValueError("运行记录路径含分号,不能安全加入 Mentor 配置搜索路径")
config.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_OBJECT_COLORS.items():
obj = ET.SubElement(objects, "object", name=name)
ET.SubElement(obj, "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(config / "DxDesigner.xml", encoding="utf-8", xml_declaration=True)
env = dict(os.environ)
inherited = env.get("WDIR", "")
env["WDIR"] = str(config) + (";" + inherited if inherited else "")
return env
+33
View File
@@ -0,0 +1,33 @@
from __future__ import annotations
KINDS = ('modified', 'added', 'removed')
RUNTIME_DIRS = frozenset({'events', 'log', 'plog', 'dbcheck', 'dbupgrade'})
def classify_source_changes(changes: dict[str, list[str]], database_relative: str, *, strict: bool = False):
"""Classify observed native writes, NOT proof of harmlessness or origin.
Main database modifications are explicitly accepted by the direct-export
policy. Its creation/deletion and all unknown/config/design paths block.
"""
accepted = {kind: [] for kind in KINDS}
blocked = {kind: [] for kind in KINDS}
prefix = tuple(part.casefold() for part in database_relative.strip('/').split('/') if part and part != '.')
for kind in KINDS:
for name in changes[kind]:
parts = tuple(part.casefold() for part in name.split('/'))
safe = not strict and '\\' not in name and not any(p in ('', '.', '..') for p in parts)
safe = safe and not any(p == '..' for p in prefix) and parts[:len(prefix)] == prefix
relative = parts[len(prefix):] if safe else ()
native = False
if safe:
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
+328 -112
View File
@@ -8,9 +8,10 @@ from PySide6.QtWidgets import (
QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout, QLabel, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout, QLabel,
QLineEdit, QPushButton, QGroupBox, QComboBox, QCheckBox, QSpinBox, QLineEdit, QPushButton, QGroupBox, QComboBox, QCheckBox, QSpinBox,
QTableWidget, QTableWidgetItem, QHeaderView, QAbstractItemView, QTableWidget, QTableWidgetItem, QHeaderView, QAbstractItemView,
QPlainTextEdit, QProgressBar, QFileDialog, QMessageBox, QSplitter, QPlainTextEdit, QProgressBar, QFileDialog, QMessageBox, QSplitter, QToolButton, QSizePolicy,
) )
from . import __version__ from . import __version__
from .branding import application_icon
from .engine import discover_engine from .engine import discover_engine
from .exporter import Exporter from .exporter import Exporter
from .models import ExportOptions from .models import ExportOptions
@@ -25,9 +26,13 @@ def default_data_root() -> Path:
class MainWindow(QMainWindow): class MainWindow(QMainWindow):
def __init__(self, root=None, output=None, engine=None, library=None, runs_root=None, exporter_factory=None): def __init__(self, root=None, output=None, engine=None, library=None, runs_root=None, exporter_factory=None, font_mapping="arial", print_theme="reference", strict_source=False, legacy_gbk=True):
super().__init__() super().__init__()
self.setWindowTitle(f"Mentor PDF 批量导出 · 测试版 {__version__}") if library:
raise ValueError("直接导出不支持替换依赖库;请先在 Mentor 配置原工程的库路径")
initial_options = ExportOptions(font_mapping=font_mapping, print_theme=print_theme, strict_source=strict_source, legacy_gbk=legacy_gbk and font_mapping != "preserve")
self.setWindowTitle(f"Mentor PDF 批量导出 · v{__version__}")
self.setWindowIcon(application_icon())
self.resize(1200, 820) self.resize(1200, 820)
self.setMinimumSize(940, 660) self.setMinimumSize(940, 660)
self.runs_root = Path(runs_root) if runs_root else default_data_root() / "runs" self.runs_root = Path(runs_root) if runs_root else default_data_root() / "runs"
@@ -40,8 +45,10 @@ class MainWindow(QMainWindow):
self._done = 0 self._done = 0
self._queue_rows = [] self._queue_rows = []
self._build() self._build()
if library: self.font_mapping_combo.setCurrentIndex(self.font_mapping_combo.findData(initial_options.font_mapping))
self.library_edit.setText(str(library)) self.print_theme_combo.setCurrentIndex(self.print_theme_combo.findData(initial_options.print_theme))
self.legacy_gbk_check.setChecked(initial_options.legacy_gbk)
self.strict_source_check.setChecked(initial_options.strict_source)
if root: if root:
self.root_edit.setText(str(root)) self.root_edit.setText(str(root))
if output: if output:
@@ -51,112 +58,248 @@ class MainWindow(QMainWindow):
self.output_edit.setText(str(path.parent / (path.name + "_PDF"))) self.output_edit.setText(str(path.parent / (path.name + "_PDF")))
try: try:
self.engine_edit.setText(str(discover_engine(engine))) self.engine_edit.setText(str(discover_engine(engine)))
self.environment_label.setText("● 已找到 Mentor 原生引擎")
except Exception: except Exception:
if engine: if engine:
self.engine_edit.setText(str(engine)) self.engine_edit.setText(str(engine))
self.environment_label.setText("● 请指定本机 sch2pdf.exe")
self._update_selection() self._update_selection()
def _build(self): def _build(self):
central = QWidget(); self.setCentralWidget(central) central = QWidget()
layout = QVBoxLayout(central); layout.setContentsMargins(20,16,20,16); layout.setSpacing(10) self.setCentralWidget(central)
heading = QHBoxLayout() layout = QVBoxLayout(central)
title = QLabel("Mentor 工程批量导出 PDF"); title.setObjectName("title") layout.setContentsMargins(18, 10, 18, 10)
heading.addWidget(title); heading.addStretch() layout.setSpacing(5)
self.environment_label = QLabel(); self.environment_label.setObjectName("badge"); heading.addWidget(self.environment_label) title = QLabel("Mentor 工程批量导出 PDF")
layout.addLayout(heading) title.setObjectName("title")
subtitle = QLabel("原生导出引擎 · 独立工程副本 · 串行队列 · PDF 结构校验"); subtitle.setObjectName("muted"); layout.addWidget(subtitle) layout.addWidget(title)
self.paths_group = QGroupBox("1 工程与输出位置") self.paths_group = QGroupBox("1 工程与输出位置")
grid = QGridLayout(self.paths_group);grid.setColumnStretch(1,1) grid = QGridLayout(self.paths_group)
self.root_edit = QLineEdit();self.root_edit.setPlaceholderText("选择包含多个原理图工程的目录,自动排除 PCB 与备份") grid.setContentsMargins(10, 6, 10, 6)
self.output_edit = QLineEdit();self.output_edit.setPlaceholderText("选择源工程外部的 PDF 输出目录") grid.setColumnStretch(1, 1)
self.engine_edit = QLineEdit();self.engine_edit.setPlaceholderText("本机 Mentor 安装目录中的 sch2pdf.exe") grid.setVerticalSpacing(5)
choose_root = QPushButton("选择目录");choose_root.clicked.connect(self.choose_root) self.root_edit = QLineEdit()
self.scan_button = QPushButton("扫描工程");self.scan_button.clicked.connect(self.scan_projects) self.root_edit.setPlaceholderText("工程根目录")
choose_output = QPushButton("选择目录");choose_output.clicked.connect(self.choose_output) self.root_edit.setToolTip("依赖库沿用原工程设置,无需选择;路径有误请在 Mentor 配置。工具不替换库、不改工程配色。扫描时排除 PCB 与备份目录。")
open_output = QPushButton("打开输出");open_output.clicked.connect(lambda:self.open_folder(self.output_edit.text())) self.output_edit = QLineEdit()
choose_engine = QPushButton("选择引擎");choose_engine.clicked.connect(self.choose_engine) self.output_edit.setPlaceholderText("PDF 输出目录")
for row, (label,edit,button) in enumerate((("工程目录",self.root_edit,choose_root),("输出目录",self.output_edit,choose_output),("导出引擎",self.engine_edit,choose_engine))): self.output_edit.setToolTip("输出目录必须位于源工程外部;默认不覆盖已有 PDF。")
grid.addWidget(QLabel(label),row,0);grid.addWidget(edit,row,1);grid.addWidget(button,row,2) self.engine_edit = QLineEdit()
grid.addWidget(self.scan_button,0,3);grid.addWidget(open_output,1,3) self.engine_edit.setPlaceholderText("sch2pdf.exe")
self.library_edit = QLineEdit();self.library_edit.setPlaceholderText("可选:网络库不可达时选择对应本地 .lmc,仅修改工作副本") self.engine_edit.setToolTip("选择本机 Mentor 安装目录中的 sch2pdf.exe;需要有效许可证。")
choose_library = QPushButton("选择中心库");choose_library.clicked.connect(self.choose_library) choose_root = QPushButton("选择目录")
grid.addWidget(QLabel("本地中心库"),3,0);grid.addWidget(self.library_edit,3,1);grid.addWidget(choose_library,3,2) choose_root.clicked.connect(self.choose_root)
library_note=QLabel("可留空");library_note.setObjectName("muted");grid.addWidget(library_note,3,3) self.scan_button = QPushButton("扫描工程")
self.scan_button.clicked.connect(self.scan_projects)
choose_output = QPushButton("选择目录")
choose_output.clicked.connect(self.choose_output)
open_output = QPushButton("打开输出")
open_output.clicked.connect(lambda: self.open_folder(self.output_edit.text()))
choose_engine = QPushButton("选择引擎")
choose_engine.clicked.connect(self.choose_engine)
for row, (label, edit, button) in enumerate((
("工程目录", self.root_edit, choose_root),
("输出目录", self.output_edit, choose_output),
("导出引擎", self.engine_edit, choose_engine),
)):
grid.addWidget(QLabel(label), row, 0)
grid.addWidget(edit, row, 1)
grid.addWidget(button, row, 2)
grid.addWidget(self.scan_button, 0, 3)
grid.addWidget(open_output, 1, 3)
layout.addWidget(self.paths_group) layout.addWidget(self.paths_group)
self.options_group = QGroupBox("2 统一导出设置") self.options_group = QGroupBox("2 统一导出设置")
options = QGridLayout(self.options_group) options = QGridLayout(self.options_group)
options.setContentsMargins(10, 6, 10, 6)
options.setVerticalSpacing(5)
for column in (1, 3, 5):
options.setColumnStretch(column, 1)
self.color_combo = QComboBox() self.color_combo = QComboBox()
for label, value in (("白底彩色 · 保留彩色文字(推荐)",4),("白底黑白 · 保留黑色文字",3),("白底彩色",1),("黑底彩色",2)): for label, value in (("白底彩色 · 保留彩色文字(推荐)", 4), ("白底黑白 · 保留黑色文字", 3), ("白底彩色", 1), ("黑底彩色", 2)):
self.color_combo.addItem(label,value) self.color_combo.addItem(label, value)
self.scope_combo = QComboBox();self.scope_combo.addItems(["整工程", "指定原理图 / Block"]) self.color_combo.setToolTip("仅原生配色可选择此模式;白底高对比固定白底彩色,黑白打印固定黑白模式。切回原生配色会保留之前的选择。")
self.schematic_edit = QLineEdit();self.schematic_edit.setPlaceholderText("填真实原理图名称,不是 Board1");self.schematic_edit.setEnabled(False) self.scope_combo = QComboBox()
self.scope_combo.currentIndexChanged.connect(lambda value:self.schematic_edit.setEnabled(value==1)) self.scope_combo.addItems(["整工程", "指定原理图 / Block"])
self.timeout_spin = QSpinBox();self.timeout_spin.setRange(30,3600);self.timeout_spin.setValue(300);self.timeout_spin.setSuffix(" 秒 / 工程") self.schematic_edit = QLineEdit()
options.addWidget(QLabel("颜色"),0,0);options.addWidget(self.color_combo,0,1) self.schematic_edit.setPlaceholderText("原理图名称")
options.addWidget(QLabel("范围"),0,2);options.addWidget(self.scope_combo,0,3);options.addWidget(self.schematic_edit,0,4) self.schematic_edit.setToolTip("填写真实原理图名称,不是 Board1。")
options.addWidget(QLabel("超时"),0,5);options.addWidget(self.timeout_spin,0,6) self.schematic_edit.setEnabled(False)
self.popup_check=QCheckBox("器件弹出菜单");self.popup_check.setChecked(True) self.scope_combo.currentIndexChanged.connect(lambda value: self.schematic_edit.setEnabled(value == 1))
self.exclusion_check=QCheckBox("使用排除信息(按截图)");self.exclusion_check.setChecked(True) scope = QHBoxLayout()
self.ict_check=QCheckBox("ICT 转原理图");self.ict_check.setChecked(True) scope.setContentsMargins(0, 0, 0, 0)
self.stroke_check=QCheckBox("笔画字体原样");self.stroke_check.setToolTip("适合字体映射异常时对照测试;文字检索可能受限") scope.addWidget(self.scope_combo)
self.overwrite_check=QCheckBox("允许覆盖已有 PDF");self.overwrite_check.setObjectName("warning") scope.addWidget(self.schematic_edit, 1)
checks=QHBoxLayout() self.timeout_spin = QSpinBox()
for check in (self.popup_check,self.exclusion_check,self.ict_check,self.stroke_check,self.overwrite_check):checks.addWidget(check) self.timeout_spin.setRange(30, 3600)
checks.addStretch();options.addLayout(checks,1,0,1,7) self.timeout_spin.setValue(300)
note=QLabel("固定设置:清空 URL-valued,隐藏可见超链接,线宽 1;批量导出不打开阅读器。字体与掩盖效果请核对样张。") self.timeout_spin.setSuffix(" 秒 / 工程")
note.setObjectName("muted");note.setWordWrap(True);options.addWidget(note,2,0,1,7) self.font_mapping_combo = QComboBox()
for label, value in (("原映射", "preserve"), ("Arial+中文回退(推荐)", "arial"), ("宋体(中文对照)", "simsun"), ("微软雅黑(中文对照)", "msyh")):
self.font_mapping_combo.addItem(label, value)
self.font_mapping_combo.setCurrentIndex(self.font_mapping_combo.findData("arial"))
self.print_theme_combo = QComboBox()
for label, value in (("工程参考配色(推荐)", "reference"), ("原生配色(不匹配参考)", "original"), ("白底高对比(可选)", "high_contrast"), ("黑白打印", "mono")):
self.print_theme_combo.addItem(label, value)
self.legacy_gbk_check = QCheckBox("CP936 / GBK 修复")
self.legacy_gbk_check.setChecked(True)
self.legacy_gbk_check.setToolTip('仅在已确认工程中文使用 CP936 / GBK 旧编码时启用;不适用于正常 WinAnsi 工程符号(如 ±、×)。仅更换 Arial 等字体不等于编码修复;启用时须选择 Arial、宋体(SimSun)或微软雅黑(YaHei),不能使用原映射。')
self._font_help = '发布前映射字体;Arial 缺失中文字符时回退宋体,不改变界面字体。仅更换 Arial 等字体不等于编码修复;当前中文 CBB 工程默认勾选 CP936 / GBK 修复;其他编码工程可取消。样本结论不代表所有工程。'
self._theme_help = '参考配色:红色连线/节点、蓝色图形/说明、青绿色引脚、紫色方框、绿色网络名称,保留原生线宽。仅导出子进程生效,不改原工程和全局设置;显式对象颜色保留。界面蓝灰主题与 PDF 配色独立,字体修复也独立。白底高对比强制 color=4,黑白打印强制 color=3;仅原生配色沿用上方颜色模式。高对比在 PDF 发布前调整深色前景、浅色填充和最小线宽 0.35pt。'
self._profile_help = '所选方案在原生 PDF 生成后、发布前处理;在支持范围内保留矢量、坐标、书签和注释,不添加白色遮罩、不栅格化。仅更换字体不等于文字编码修复,当前中文 CBB 工程默认启用 CP936 / GBK 修复;正常 WinAnsi 工程请取消勾选。当前 17 页旧工程样本的 Arial+宋体回退及高对比已验证;样本结论不代表所有 PDF、字体、文字结构或复杂图元均兼容,其他工程请核对样张。'
for row, column, label, widget in (
(0, 0, "打印配色", self.print_theme_combo),
(0, 2, "字体映射", self.font_mapping_combo),
(0, 4, "编码", self.legacy_gbk_check),
(1, 0, "颜色", self.color_combo),
(1, 4, "超时", self.timeout_spin),
):
options.addWidget(QLabel(label), row, column)
options.addWidget(widget, row, column + 1)
options.addWidget(QLabel("范围"), 1, 2)
options.addLayout(scope, 1, 3)
self.overwrite_check = QCheckBox("允许覆盖已有 PDF")
self.overwrite_check.setObjectName("warning")
self.advanced_button = QToolButton()
self.advanced_button.setText("高级选项")
self.advanced_button.setCheckable(True)
self.advanced_button.setArrowType(Qt.RightArrow)
self.advanced_button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
option_tools = QHBoxLayout()
option_tools.addWidget(self.overwrite_check)
option_tools.addStretch()
option_tools.addWidget(self.advanced_button)
options.addLayout(option_tools, 2, 0, 1, 6)
self.advanced_panel = QWidget()
advanced = QHBoxLayout(self.advanced_panel)
advanced.setContentsMargins(0, 0, 0, 0)
self.popup_check = QCheckBox("器件弹出菜单")
self.popup_check.setChecked(True)
self.exclusion_check = QCheckBox("使用排除信息")
self.exclusion_check.setChecked(True)
self.ict_check = QCheckBox("ICT 转原理图")
self.ict_check.setChecked(True)
self.stroke_check = QCheckBox("笔画字体原样")
self.stroke_check.setToolTip("适合字体映射异常时对照测试;文字检索可能受限。")
self.strict_source_check = QCheckBox("严格源文件检查")
self.strict_source_check.toggled.connect(self._update_source_warning)
for check in (self.popup_check, self.exclusion_check, self.ict_check, self.stroke_check, self.strict_source_check):
advanced.addWidget(check)
advanced.addStretch()
options.addWidget(self.advanced_panel, 3, 0, 1, 6)
self.advanced_panel.hide()
self.advanced_button.toggled.connect(self._toggle_advanced)
self._update_source_warning()
self.font_mapping_combo.currentIndexChanged.connect(self._font_mapping_changed)
self.print_theme_combo.currentIndexChanged.connect(self._update_profile_warning)
self.legacy_gbk_check.toggled.connect(self._update_profile_warning)
self._update_profile_warning()
layout.addWidget(self.options_group) layout.addWidget(self.options_group)
splitter=QSplitter(Qt.Vertical)
list_panel=QWidget();list_layout=QVBoxLayout(list_panel);list_layout.setContentsMargins(0,0,0,0) splitter = QSplitter(Qt.Vertical)
tools=QHBoxLayout() splitter.setChildrenCollapsible(False)
self.selection_label=QLabel("3 工程队列");tools.addWidget(self.selection_label);tools.addStretch() list_panel = QWidget()
self.select_all_button=QPushButton("全选");self.select_all_button.clicked.connect(self.select_all) list_layout = QVBoxLayout(list_panel)
self.clear_button=QPushButton("清除选择");self.clear_button.clicked.connect(lambda:self._select(lambda row:False)) list_layout.setContentsMargins(0, 0, 0, 0)
self.select_failed_button=QPushButton("选中失败项重试");self.select_failed_button.clicked.connect(self.select_failed) list_layout.setSpacing(5)
for button in (self.select_all_button,self.clear_button,self.select_failed_button):tools.addWidget(button) tools = QHBoxLayout()
self.selection_label = QLabel("3 工程队列")
tools.addWidget(self.selection_label)
tools.addStretch()
self.select_all_button = QPushButton("全选")
self.select_all_button.clicked.connect(self.select_all)
self.clear_button = QPushButton("清除选择")
self.clear_button.clicked.connect(lambda: self._select(lambda row: False))
self.select_failed_button = QPushButton("选中失败项重试")
self.select_failed_button.clicked.connect(self.select_failed)
for button in (self.select_all_button, self.clear_button, self.select_failed_button):
tools.addWidget(button)
list_layout.addLayout(tools) list_layout.addLayout(tools)
self.table=QTableWidget(0,6);self.table.setHorizontalHeaderLabels(["选择","工程","工程路径","状态","结果","PDF 输出 / 日志"]) self.table = QTableWidget(0, 6)
self.table.setEditTriggers(QAbstractItemView.NoEditTriggers);self.table.setAlternatingRowColors(True) self.table.setHorizontalHeaderLabels(["选择", "工程", "工程路径", "状态", "结果", "PDF 输出 / 日志"])
self.table.setSelectionBehavior(QAbstractItemView.SelectRows);self.table.verticalHeader().setVisible(False) self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.table.setAlternatingRowColors(True)
self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.table.verticalHeader().setVisible(False)
self.table.setWordWrap(False) self.table.setWordWrap(False)
header=self.table.horizontalHeader();header.setSectionResizeMode(QHeaderView.Interactive) self.table.setMinimumHeight(180)
self.table.setColumnWidth(0,48);self.table.setColumnWidth(1,140);self.table.setColumnWidth(2,290) header = self.table.horizontalHeader()
self.table.setColumnWidth(3,76);self.table.setColumnWidth(4,150);header.setStretchLastSection(True) header.setSectionResizeMode(QHeaderView.Interactive)
self.table.itemChanged.connect(self._update_selection);list_layout.addWidget(self.table) for column, width in enumerate((48, 140, 290, 110, 150)):
self.table.setColumnWidth(column, width)
header.setStretchLastSection(True)
self.table.itemChanged.connect(self._update_selection)
list_layout.addWidget(self.table, 1)
splitter.addWidget(list_panel) splitter.addWidget(list_panel)
log_panel=QWidget();log_layout=QVBoxLayout(log_panel);log_layout.setContentsMargins(0,0,0,0) log_panel = QWidget()
log_tools=QHBoxLayout();log_tools.addWidget(QLabel("运行日志"));log_tools.addStretch() log_layout = QVBoxLayout(log_panel)
log_button=QPushButton("打开运行记录");log_button.clicked.connect(lambda:self.open_folder(str(self.runs_root)));log_tools.addWidget(log_button) log_layout.setContentsMargins(0, 0, 0, 0)
log_layout.setSpacing(4)
log_tools = QHBoxLayout()
log_tools.addWidget(QLabel("运行日志"))
log_tools.addStretch()
log_button = QPushButton("打开运行记录")
log_button.clicked.connect(lambda: self.open_folder(str(self.runs_root)))
log_tools.addWidget(log_button)
log_layout.addLayout(log_tools) log_layout.addLayout(log_tools)
self.log=QPlainTextEdit();self.log.setReadOnly(True);self.log.setMaximumBlockCount(2000) self.log = QPlainTextEdit()
self.log.setPlaceholderText("先扫描工程,再勾选并开始导出。日志会记录副本、原生引擎、校验及错误。") self.log.setReadOnly(True)
log_layout.addWidget(self.log);splitter.addWidget(log_panel);splitter.setSizes([330,135]);layout.addWidget(splitter,1) self.log.setMaximumBlockCount(500)
self.progress=QProgressBar();self.progress.setRange(0,1);self.progress.setValue(0);self.progress.setFormat("%v / %m 工程") self.log.setMinimumHeight(60)
footer=QHBoxLayout();footer.addWidget(self.progress,1) self.log.setMaximumHeight(100)
self.stop_button=QPushButton("停止任务");self.stop_button.setEnabled(False);self.stop_button.clicked.connect(self.stop_export) self.log.setPlaceholderText("扫描与导出结果")
self.start_button=QPushButton("开始批量导出");self.start_button.setObjectName("primary");self.start_button.clicked.connect(self.start_export) self.log.setToolTip("完整证据与原生进程明细保存在运行记录中。")
footer.addWidget(self.stop_button);footer.addWidget(self.start_button);layout.addLayout(footer) log_layout.addWidget(self.log)
self.status_label=QLabel("就绪。测试版需要本机 Mentor 及有效许可证;默认不覆盖已有 PDF。");self.status_label.setWordWrap(True);self.status_label.setObjectName("muted");layout.addWidget(self.status_label) log_panel.setMaximumHeight(140)
splitter.addWidget(log_panel)
splitter.setStretchFactor(0, 1)
splitter.setStretchFactor(1, 0)
splitter.setSizes([700, 100])
layout.addWidget(splitter, 1)
self.progress = QProgressBar()
self.progress.setRange(0, 1)
self.progress.setValue(0)
self.progress.setFormat("%v / %m 工程")
footer = QHBoxLayout()
footer.addWidget(self.progress, 1)
self.stop_button = QPushButton("停止任务")
self.stop_button.setEnabled(False)
self.stop_button.clicked.connect(self.stop_export)
self.start_button = QPushButton("开始批量导出")
self.start_button.setObjectName("primary")
self.start_button.clicked.connect(self.start_export)
footer.addWidget(self.stop_button)
footer.addWidget(self.start_button)
layout.addLayout(footer)
self.status_label = QLabel("就绪")
self.status_label.setObjectName("muted")
self.status_label.setMinimumWidth(0)
self.status_label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)
layout.addWidget(self.status_label)
self.setStyleSheet(""" self.setStyleSheet("""
QWidget {font-family:'Microsoft YaHei UI';font-size:12px;color:#243443;} QWidget {font-family:'Microsoft YaHei UI';font-size:12px;color:#334155;}
QMainWindow {background:#f4f7fa;} QLabel#title {font-size:23px;font-weight:600;color:#102e3c;} QMainWindow {background:#f1f5f9;} QLabel#title {font-size:23px;font-weight:600;color:#0f172a;}
QLabel#muted {color:#647585;} QLabel#badge {color:#087c72;background:#e1f2ee;padding:7px 10px;border-radius:5px;} QLabel#muted {color:#64748b;}
QGroupBox {background:white;border:1px solid #dce4eb;border-radius:7px;margin-top:10px;padding-top:10px;font-weight:600;} QGroupBox {background:white;border:1px solid #dce4eb;border-radius:7px;margin-top:8px;padding-top:0;font-weight:600;}
QGroupBox::title {subcontrol-origin:margin;left:12px;padding:0 4px;} QGroupBox::title {subcontrol-origin:margin;left:12px;padding:0 4px;}
QLineEdit,QComboBox,QSpinBox {background:white;border:1px solid #ccd7e1;border-radius:4px;padding:5px;min-height:19px;} QLineEdit,QComboBox,QSpinBox {background:white;border:1px solid #ccd7e1;border-radius:4px;padding:3px;min-height:17px;}
QPushButton {background:white;border:1px solid #ccd7e1;border-radius:4px;padding:6px 12px;min-height:19px;} QPushButton {background:white;border:1px solid #ccd7e1;border-radius:4px;padding:4px 12px;min-height:17px;}
QPushButton:hover {background:#eaf3f5;border-color:#80b8b7;} QPushButton:disabled {color:#a0aeb8;background:#f1f4f7;} QPushButton:hover {background:#eff6ff;border-color:#93c5fd;} QPushButton:disabled {color:#a0aeb8;background:#f1f4f7;}
QPushButton#primary {background:#087f78;color:white;border:0;padding:8px 23px;font-weight:600;} QPushButton#primary {background:#2563EB;color:white;border:0;padding:8px 23px;font-weight:600;}
QPushButton#primary:disabled {background:#a8c8c6;} QCheckBox#warning {color:#9d5d14;} QPushButton#primary:disabled {background:#93c5fd;} QCheckBox#warning {color:#d97706;}
QTableWidget {background:white;alternate-background-color:#f6f9fc;border:1px solid #dce4eb;border-radius:4px;gridline-color:#edf1f5;} QTableWidget {background:white;alternate-background-color:#f6f9fc;border:1px solid #dce4eb;border-radius:4px;gridline-color:#edf1f5;}
QHeaderView::section {background:#eaf0f5;border:0;border-bottom:1px solid #dce4eb;padding:7px;font-weight:600;} QHeaderView::section {background:#eaf0f5;border:0;border-bottom:1px solid #dce4eb;padding:7px;font-weight:600;}
QPlainTextEdit {background:#fcfdff;border:1px solid #dce4eb;border-radius:4px;font-family:'Consolas','Microsoft YaHei UI';font-size:11px;} QPlainTextEdit {background:#fcfdff;border:1px solid #dce4eb;border-radius:4px;font-family:'Consolas','Microsoft YaHei UI';font-size:11px;}
QProgressBar {border:1px solid #dce4eb;border-radius:4px;background:white;text-align:center;min-height:23px;} QProgressBar {border:1px solid #dce4eb;border-radius:4px;background:white;text-align:center;min-height:23px;}
QProgressBar::chunk {background:#80c9bd;border-radius:3px;} QProgressBar::chunk {background:#2563EB;border-radius:3px;}
""") """)
def _toggle_advanced(self, expanded):
self.advanced_panel.setVisible(expanded)
self.advanced_button.setArrowType(Qt.DownArrow if expanded else Qt.RightArrow)
def choose_root(self): def choose_root(self):
path=QFileDialog.getExistingDirectory(self,"选择工程根目录",self.root_edit.text()) path=QFileDialog.getExistingDirectory(self,"选择工程根目录",self.root_edit.text())
if path: if path:
@@ -173,29 +316,55 @@ class MainWindow(QMainWindow):
path,_=QFileDialog.getOpenFileName(self,"选择 Mentor 原生 sch2pdf.exe",self.engine_edit.text(),"导出引擎 (sch2pdf.exe)") path,_=QFileDialog.getOpenFileName(self,"选择 Mentor 原生 sch2pdf.exe",self.engine_edit.text(),"导出引擎 (sch2pdf.exe)")
if path:self.engine_edit.setText(path) if path:self.engine_edit.setText(path)
def choose_library(self):
path,_=QFileDialog.getOpenFileName(self,"选择对应的本地中心库,仅在副本中使用",self.library_edit.text(),"Mentor 中心库 (*.lmc)")
if path:self.library_edit.setText(path)
def open_folder(self,value): def open_folder(self,value):
path=Path(value.strip()) if value.strip() else None path=Path(value.strip()) if value.strip() else None
if path and path.is_dir():QDesktopServices.openUrl(QUrl.fromLocalFile(str(path.resolve()))) if path and path.is_dir():QDesktopServices.openUrl(QUrl.fromLocalFile(str(path.resolve())))
else:self.append_log("目录尚不存在;完成一次导出后再打开。") else:self.append_log("目录尚不存在;完成一次导出后再打开。")
def append_log(self,message): @staticmethod
self.log.appendPlainText(datetime.now().strftime("%H:%M:%S")+" "+message) def _compact_text(message, limit=160):
text = " ".join(str(message).split())
return text if len(text) <= limit else text[:limit - 1] + "…"
def append_log(self, message):
self.log.appendPlainText(datetime.now().strftime("%H:%M:%S") + " " + self._compact_text(message))
def _set_status(self, message, detail=None):
self.status_label.setText(self._compact_text(message))
self.status_label.setToolTip(message if detail is None else detail)
def _worker_message(self, message):
# The exporter persists full evidence; only actionable worker errors
# belong in the compact UI log. Project lifecycle comes from signals.
if message.startswith("批量报告:"):
return
if any(word in message.casefold() for word in (
"失败", "异常", "错误", "超时", "停止", "取消", "警告", "无法", "未能", "待核验",
"error", "failed", "failure", "timeout", "cancelled", "canceled", "warning", "unable",
)):
self.append_log(message)
def _set_busy(self,busy,kind="batch"): def _set_busy(self,busy,kind="batch"):
self.busy=busy self.busy=busy
for widget in (self.paths_group,self.options_group,self.table,self.select_all_button,self.clear_button,self.select_failed_button):widget.setEnabled(not busy) for widget in (self.paths_group,self.options_group,self.select_all_button,self.clear_button,self.select_failed_button):widget.setEnabled(not busy)
# Keep the view and scrollbars active; lock only queue membership.
blocked = self.table.blockSignals(True)
try:
for row in range(self.table.rowCount()):
item = self.table.item(row,0)
if item is not None:
flags = item.flags()
item.setFlags(flags & ~Qt.ItemIsUserCheckable if busy else flags | Qt.ItemIsUserCheckable)
finally:
self.table.blockSignals(blocked)
self.start_button.setEnabled(not busy and bool(self.projects));self.stop_button.setEnabled(busy and kind=="batch") self.start_button.setEnabled(not busy and bool(self.projects));self.stop_button.setEnabled(busy and kind=="batch")
def scan_projects(self): def scan_projects(self):
if self.busy:return if self.busy:return
root=self.root_edit.text().strip() root=self.root_edit.text().strip()
if not root or not Path(root).is_dir(): if not root or not Path(root).is_dir():
self.append_log("请选择存在的工程根目录。");self.status_label.setText("工程目录无效。");return self.append_log("请选择存在的工程根目录。");self._set_status("工程目录无效。");return
self._set_busy(True,"scan");self.status_label.setText("正在扫描原理图工程,排除 PCB、备份和输出目录……") self._set_busy(True,"scan");self._set_status("正在扫描工程…");self.append_log("开始扫描工程")
excluded=[self.runs_root] excluded=[self.runs_root]
if self.output_edit.text().strip():excluded.append(Path(self.output_edit.text().strip())) if self.output_edit.text().strip():excluded.append(Path(self.output_edit.text().strip()))
self.scan_worker=ScanWorker(root,excluded,self) self.scan_worker=ScanWorker(root,excluded,self)
@@ -206,15 +375,18 @@ class MainWindow(QMainWindow):
previous={info.path:self.table.item(row,0).checkState() for row,info in enumerate(self.projects)} previous={info.path:self.table.item(row,0).checkState() for row,info in enumerate(self.projects)}
self.projects=projects;self.table.blockSignals(True);self.table.setRowCount(len(projects)) self.projects=projects;self.table.blockSignals(True);self.table.setRowCount(len(projects))
for row,info in enumerate(projects): for row,info in enumerate(projects):
check=QTableWidgetItem();check.setFlags(Qt.ItemIsUserCheckable|Qt.ItemIsEnabled|Qt.ItemIsSelectable);check.setCheckState(previous.get(info.path,Qt.Checked));self.table.setItem(row,0,check) check=QTableWidgetItem()
flags=Qt.ItemIsEnabled|Qt.ItemIsSelectable
if not self.busy:flags|=Qt.ItemIsUserCheckable
check.setFlags(flags);check.setCheckState(previous.get(info.path,Qt.Checked));self.table.setItem(row,0,check)
for col,text in enumerate((info.name,str(info.path),"待处理","—","—"),start=1): for col,text in enumerate((info.name,str(info.path),"待处理","—","—"),start=1):
item=QTableWidgetItem(text);item.setToolTip(text);self.table.setItem(row,col,item) item=QTableWidgetItem(text);item.setToolTip(text);self.table.setItem(row,col,item)
self.table.blockSignals(False);self._update_selection() self.table.blockSignals(False);self._update_selection()
self.append_log(f"发现 {len(projects)} 个原理图工程。PCB 与备份目录已排除。") self.append_log(f"扫描完成:{len(projects)} 个工程")
self.status_label.setText(f"扫描完成:{len(projects)} 个工程。勾选后开始导出。") self._set_status(f"扫描完成:{len(projects)} 个工程")
def _scan_failed(self,message): def _scan_failed(self,message):
self.append_log("扫描失败:"+message);self.status_label.setText("扫描失败,请检查目录权限。") self.append_log("扫描失败:"+message);self._set_status("扫描失败:" + message, detail=message)
def _scan_finished(self): def _scan_finished(self):
self._set_busy(False) self._set_busy(False)
@@ -235,10 +407,51 @@ class MainWindow(QMainWindow):
def select_all(self):self._select(lambda row:True) def select_all(self):self._select(lambda row:True)
def select_failed(self):self._select(lambda row:self.table.item(row,3).text() in {"失败","超时","待核验","已停止","未执行"}) def select_failed(self):self._select(lambda row:self.table.item(row,3).text() in {"失败","超时","待核验","已停止","未执行"})
def _font_mapping_changed(self,*args):
if self.font_mapping_combo.currentData() == "preserve":
self.legacy_gbk_check.setChecked(False)
self._update_profile_warning()
def _update_profile_warning(self,*args):
mapping = self.font_mapping_combo.currentData()
theme = self.print_theme_combo.currentData()
self.color_combo.setEnabled(theme == "original")
details = []
legacy_gbk = self.legacy_gbk_check.isChecked()
if mapping != "preserve":
font = {"arial":"Arial+宋体回退", "simsun":"宋体映射", "msyh":"微软雅黑映射"}[mapping]
details.append(f"发布前映射字体、{font}。" if legacy_gbk else f"发布前映射字体、{font};不自动修复编码。")
if legacy_gbk:
details.append("按已确认 CP936 / GBK 修复中文。" if mapping != "preserve" else "CP936 / GBK 修复需选择 Arial/宋体/微软雅黑。")
if theme == "reference":
details.append("工程参考配色:红色连线、蓝色图形、青绿色引脚;子进程配置,不改原工程,保留原生线宽。")
elif theme == "high_contrast":
details.append("发布前调整深色前景/浅色填充、最小线宽 0.35pt。")
elif theme == "mono":
details.append("黑白打印。")
elif details:
details.append("原始配色不额外换色,保留原生线宽。")
summary = "".join(details) + "仅作用于输出 PDF,不改变工程配色;样本兼容范围有限,其他工程请核对样张。" if details else ""
self.font_mapping_combo.setToolTip(self._font_help + summary + self._profile_help)
self.print_theme_combo.setToolTip(self._theme_help + summary + self._profile_help)
def _update_source_warning(self,*args):
if self.strict_source_check.isChecked():
text = "严格检查:原生引擎也可能更新数据库/日志;受保护源文件变化时待核验、不发布 PDF。检查不能撤销源更新。"
else:
text = "原生引擎可能更新数据库/日志:不阻止有效 PDF 发布,记录成功提示;配置/其他源文件变化仍待核验、不发布。非只读保证。"
self.strict_source_check.setToolTip(text)
def options(self): def options(self):
schematic=self.schematic_edit.text().strip() if self.scope_combo.currentIndex()==1 else "" schematic=self.schematic_edit.text().strip() if self.scope_combo.currentIndex()==1 else ""
if self.scope_combo.currentIndex()==1 and not schematic:raise ValueError("指定范围时必须填写真实原理图名称") if self.scope_combo.currentIndex()==1 and not schematic:raise ValueError("指定范围时必须填写真实原理图名称")
return ExportOptions(library_override=self.library_edit.text().strip(),color=self.color_combo.currentData(),popup=self.popup_check.isChecked(),use_exclusion=self.exclusion_check.isChecked(),change_ict=self.ict_check.isChecked(),stroke_fonts=self.stroke_check.isChecked(),schematic=schematic,timeout=self.timeout_spin.value(),overwrite=self.overwrite_check.isChecked()) font_mapping=self.font_mapping_combo.currentData()
legacy_gbk=self.legacy_gbk_check.isChecked()
if legacy_gbk and font_mapping=="preserve":
raise ValueError("修复 CP936 / GBK 旧工程中文时,请选择 Arial、宋体(SimSun)或微软雅黑(YaHei)字体映射,不能使用原映射。")
print_theme=self.print_theme_combo.currentData()
color={"reference":4,"high_contrast":4,"mono":3}.get(print_theme,self.color_combo.currentData())
return ExportOptions(font_mapping=font_mapping,legacy_gbk=legacy_gbk,print_theme=print_theme,color=color,popup=self.popup_check.isChecked(),use_exclusion=self.exclusion_check.isChecked(),change_ict=self.ict_check.isChecked(),stroke_fonts=self.stroke_check.isChecked(),schematic=schematic,timeout=self.timeout_spin.value(),overwrite=self.overwrite_check.isChecked(),strict_source=self.strict_source_check.isChecked())
def start_export(self): def start_export(self):
if self.busy:return if self.busy:return
@@ -250,33 +463,36 @@ class MainWindow(QMainWindow):
validate_queue_paths([info for _,info in items],Path(self.output_edit.text().strip()),self.runs_root) validate_queue_paths([info for _,info in items],Path(self.output_edit.text().strip()),self.runs_root)
exporter=self.exporter_factory(engine,self.runs_root) exporter=self.exporter_factory(engine,self.runs_root)
except Exception as error: except Exception as error:
self.append_log(str(error));self.status_label.setText(str(error));return self.append_log(str(error));self._set_status(str(error));return
self._done=0;self._queue_rows=[row for row,_ in items] self._done=0;self._queue_rows=[row for row,_ in items]
for row,_ in items: for row,_ in items:
self.table.item(row,3).setText("排队中");self.table.item(row,4).setText("等待原生导出") self.table.item(row,3).setText("排队中");self.table.item(row,4).setText("等待原生导出")
self.progress.setRange(0,len(items));self.progress.setValue(0);self._set_busy(True) self.progress.setRange(0,len(items));self.progress.setValue(0);self._set_busy(True)
self.status_label.setText("执行中:仅在副本操作。请勿编辑源工程;可随时请求停止。") self._set_status("执行中 · 直接导出")
self.append_log(f"开始队列:{len(items)} 个工程,单工程超时 {options.timeout:g} 秒。") self.append_log(f"开始队列:{len(items)} 个工程,单工程超时 {options.timeout:g} 秒。")
self.worker=BatchWorker(items,self.output_edit.text().strip(),options,exporter,self) self.worker=BatchWorker(items,self.output_edit.text().strip(),options,exporter,self,all_projects=self.projects)
self.worker.current.connect(self._item_started);self.worker.result.connect(self._item_result) self.worker.current.connect(self._item_started);self.worker.result.connect(self._item_result)
self.worker.message.connect(self.append_log);self.worker.completed.connect(self._batch_completed) self.worker.message.connect(self._worker_message);self.worker.completed.connect(self._batch_completed)
self.worker.finished.connect(self._batch_finished);self.worker.start() self.worker.finished.connect(self._batch_finished);self.worker.start()
def _item_started(self,row,name): def _item_started(self,row,name):
self.table.item(row,3).setText("导出中");self.table.item(row,4).setText("创建副本 / 原生导出") self.table.item(row,3).setText("导出中");self.table.item(row,4).setText("处理中")
self.append_log(f"正在处理:{name}") self.append_log(f"正在处理:{name}")
def _item_result(self,row,result): def _item_result(self,row,result):
self._done+=1;self.progress.setValue(self._done) self._done+=1;self.progress.setValue(self._done)
item=self.table.item(row,3);item.setText(STATUS.get(result.status,result.status)) warned = result.status == "success" and bool(result.warnings)
item.setForeground(QColor("#087f78" if result.status=="success" else "#9d5d14" if result.status=="skipped" else "#b64343")) item=self.table.item(row,3);item.setText("成功(有提示)" if warned else STATUS.get(result.status,result.status))
text=f"{result.pages} 页 · {result.duration:.1f} 秒" if result.status=="success" else result.message item.setForeground(QColor("#16a34a" if result.status=="success" and not warned else "#d97706" if warned or result.status in {"skipped","uncertain","cancelled"} else "#dc2626"))
text=f"{result.pages} 页 · {result.duration:.1f} 秒" if result.status=="success" else self._compact_text(result.message)
self.table.item(row,4).setText(text);self.table.item(row,4).setToolTip(result.message) self.table.item(row,4).setText(text);self.table.item(row,4).setToolTip(result.message)
destination=result.output or result.run_dir or "—" destination=result.output or result.run_dir or "—"
self.table.item(row,5).setText(destination);self.table.item(row,5).setToolTip(destination) self.table.item(row,5).setText(destination);self.table.item(row,5).setToolTip(destination)
name = self.table.item(row,1).text()
self.append_log(f"{name}:{item.text()} · {text}")
def _batch_completed(self,message): def _batch_completed(self,message):
self.status_label.setText(message);self.append_log("队列结束:"+message) self._set_status(message);self.append_log("队列结束:"+message)
for row in self._queue_rows: for row in self._queue_rows:
if self.table.item(row,3).text() in {"排队中","导出中"}: if self.table.item(row,3).text() in {"排队中","导出中"}:
self.table.item(row,3).setText("未执行");self.table.item(row,4).setText("队列停止,可重新勾选") self.table.item(row,3).setText("未执行");self.table.item(row,4).setText("队列停止,可重新勾选")
@@ -288,8 +504,8 @@ class MainWindow(QMainWindow):
def stop_export(self): def stop_export(self):
if self.worker and self.worker.isRunning(): if self.worker and self.worker.isRunning():
self.worker.cancel_event.set();self.stop_button.setEnabled(False) self.worker.cancel_event.set();self.stop_button.setEnabled(False)
self.status_label.setText("正在安全停止:仅终止本工具启动的原生进程树,不关闭用户 CAD。") self._set_status("正在停止…", detail="仅终止本工具启动的原生进程树,不关闭用户 CAD。")
self.append_log("已请求停止当前任务及后续队列。") self.append_log("已请求停止队列")
def closeEvent(self,event): def closeEvent(self,event):
if self.busy: if self.busy:
+14 -5
View File
@@ -9,6 +9,7 @@ from PySide6.QtCore import QThread, Signal
from .scanner import scan_projects from .scanner import scan_projects
from .exporter import write_json from .exporter import write_json
from .path_policy import validate_queue_paths from .path_policy import validate_queue_paths
from .naming import plan_output_directories
class ScanWorker(QThread): class ScanWorker(QThread):
@@ -29,9 +30,10 @@ class BatchWorker(QThread):
result = Signal(int, object) result = Signal(int, object)
message = Signal(str) message = Signal(str)
completed = Signal(str) completed = Signal(str)
def __init__(self, items, output, options, exporter, parent=None): def __init__(self, items, output, options, exporter, parent=None, *, all_projects=None):
super().__init__(parent) super().__init__(parent)
self.items, self.output, self.options, self.exporter = items, Path(output), options, exporter self.items, self.output, self.options, self.exporter = items, Path(output), options, exporter
self.all_projects = list(all_projects) if all_projects is not None else [project for _,project in items]
self.cancel_event = threading.Event() self.cancel_event = threading.Event()
self.results = [] self.results = []
self.summary_path = "" self.summary_path = ""
@@ -40,18 +42,24 @@ class BatchWorker(QThread):
error_text = "" error_text = ""
record_error = "" record_error = ""
try: try:
validate_queue_paths([project for _,project in self.items],self.output,self.exporter.runs_root) contexts = list(self.all_projects)
for _, project in self.items:
if project not in contexts:
contexts.append(project)
planned = plan_output_directories(contexts,self.output,self.exporter.runs_root)
by_source = {project.path.resolve():directory for project,directory in zip(contexts,planned)}
directories = [by_source[project.path.resolve()] for _,project in self.items]
self.exporter.runs_root.mkdir(parents=True, exist_ok=True) self.exporter.runs_root.mkdir(parents=True, exist_ok=True)
report = self.exporter.runs_root / ("batch-" + datetime.now().strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8] + ".json") report = self.exporter.runs_root / ("batch-" + datetime.now().strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8] + ".json")
# No engine starts unless a durable queue pre-record exists. # No engine starts unless a durable queue pre-record exists.
write_json(report, {"phase":"running", "requested":[str(project.path) for _,project in self.items], "output":str(self.output.resolve()), "options":asdict(self.options), "results":[]}) write_json(report, {"phase":"running", "requested":[str(project.path) for _,project in self.items], "output":str(self.output.resolve()), "options":asdict(self.options), "results":[]})
self.summary_path = str(report) self.summary_path = str(report)
for row, project in self.items: for (row, project), directory in zip(self.items, directories):
if self.cancel_event.is_set(): if self.cancel_event.is_set():
break break
self.current.emit(row, project.name) self.current.emit(row, project.name)
try: try:
result = self.exporter.export(project, self.output, self.options, self.cancel_event, self.message.emit) result = self.exporter.export(project, directory, self.options, self.cancel_event, self.message.emit)
except Exception as error: except Exception as error:
from .models import ExportResult from .models import ExportResult
result = ExportResult(str(project.path),"uncertain",f"执行器异常,结果待核验:{error}") result = ExportResult(str(project.path),"uncertain",f"执行器异常,结果待核验:{error}")
@@ -70,8 +78,9 @@ class BatchWorker(QThread):
self.message.emit(f"队列执行异常:{error}") self.message.emit(f"队列执行异常:{error}")
finally: finally:
counts = Counter(r.status for r in self.results) counts = Counter(r.status for r in self.results)
warned = sum(r.status == "success" and bool(r.warnings) for r in self.results)
not_run = len(self.items) - len(self.results) not_run = len(self.items) - len(self.results)
text = f"成功 {counts['success']} / 失败 {counts['failed']+counts['timeout']} / 跳过 {counts['skipped']} / 待核验 {counts['uncertain']} / 停止 {counts['cancelled']} / 未执行 {not_run}" text = f"成功 {counts['success']}(有提示 {warned}) / 失败 {counts['failed']+counts['timeout']} / 跳过 {counts['skipped']} / 待核验 {counts['uncertain']} / 停止 {counts['cancelled']} / 未执行 {not_run}"
if report is not None and self.summary_path: if report is not None and self.summary_path:
try: try:
write_json(report, {"phase":"completed", "summary":text, "error":error_text, "not_run":not_run, "results":[asdict(r) for r in self.results]}) write_json(report, {"phase":"completed", "summary":text, "error":error_text, "not_run":not_run, "results":[asdict(r) for r in self.results]})
+11 -1
View File
@@ -23,7 +23,7 @@ def source_files(root: Path):
if path.is_dir() and path.name.casefold() in COPY_PRUNED: if path.is_dir() and path.name.casefold() in COPY_PRUNED:
continue continue
if is_link(path): if is_link(path):
raise ValueError(f"工程含链接/重解析点,不复制:{path}") raise ValueError(f"工程含链接/重解析点,无法安全核验:{path}")
if path.is_dir(): if path.is_dir():
yield from walk(path) yield from walk(path)
elif path.is_file(): elif path.is_file():
@@ -44,6 +44,16 @@ def fingerprint(root: Path, cancel: threading.Event | None = None) -> dict[str,
return result return result
def compare_fingerprints(before: dict[str, str], after: dict[str, str]) -> dict[str, list[str]]:
"""Report content differences without treating database writes as harmless."""
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 validate_project_database(project: Path) -> Path: def validate_project_database(project: Path) -> Path:
with project.open("rb") as stream: with project.open("rb") as stream:
match = _DATABASE.search(stream.read(HEADER_LIMIT)) match = _DATABASE.search(stream.read(HEADER_LIMIT))
+63 -3
View File
@@ -1,4 +1,5 @@
import json import json
import pytest
from pathlib import Path from pathlib import Path
from mentor_pdf_export.cli import main from mentor_pdf_export.cli import main
@@ -7,7 +8,8 @@ def test_self_check_writes_machine_readable_report(tmp_path):
report=tmp_path / "check.json" report=tmp_path / "check.json"
assert main(["--self-check","--report",str(report)]) == 0 assert main(["--self-check","--report",str(report)]) == 0
data=json.loads(report.read_text(encoding="utf-8")) data=json.loads(report.read_text(encoding="utf-8"))
assert data["version"] == "0.1.0" from mentor_pdf_export import __version__
assert data["version"] == __version__
assert "engine_available" in data assert "engine_available" in data
@@ -29,7 +31,7 @@ def test_report_inside_source_is_rejected_before_export(project_factory,tmp_path
project=project_factory() project=project_factory()
protected=project.parent/"settings.json";protected.write_text("original") protected=project.parent/"settings.json";protected.write_text("original")
engine=tmp_path/"sch2pdf.exe";engine.write_bytes(b"fake") engine=tmp_path/"sch2pdf.exe";engine.write_bytes(b"fake")
def runner(args,*rest): def runner(args,*rest,env=None):
writer=PdfWriter();writer.add_blank_page(width=500,height=400) writer=PdfWriter();writer.add_blank_page(width=500,height=400)
with Path(args[args.index("-a")+1]).open("wb") as out:writer.write(out) with Path(args[args.index("-a")+1]).open("wb") as out:writer.write(out)
return 0 return 0
@@ -48,7 +50,7 @@ def test_queue_destinations_protect_every_source_before_first_export(project_fac
a=project_factory("a");b=project_factory("b") a=project_factory("a");b=project_factory("b")
engine=tmp_path/"sch2pdf.exe";engine.write_bytes(b"fake") engine=tmp_path/"sch2pdf.exe";engine.write_bytes(b"fake")
before=fingerprint(b.parent) before=fingerprint(b.parent)
def runner(args,*rest): def runner(args,*rest,env=None):
writer=PdfWriter();writer.add_blank_page(width=500,height=400) writer=PdfWriter();writer.add_blank_page(width=500,height=400)
with Path(args[args.index("-a")+1]).open("wb") as out:writer.write(out) with Path(args[args.index("-a")+1]).open("wb") as out:writer.write(out)
return 0 return 0
@@ -70,3 +72,61 @@ def test_self_check_can_refresh_its_own_report(tmp_path):
report=tmp_path/"self-check.json" report=tmp_path/"self-check.json"
assert main(["--self-check","--report",str(report)]) == 0 assert main(["--self-check","--report",str(report)]) == 0
assert main(["--self-check","--report",str(report)]) == 0 assert main(["--self-check","--report",str(report)]) == 0
def test_cli_accepts_explicit_print_and_font_profiles(tmp_path):
report=tmp_path/"style-check.json"
assert main(["--self-check","--font-mapping","arial","--print-theme","high_contrast","--report",str(report)])==0
def test_cli_rejects_library_replacement_in_direct_mode(tmp_path):
assert main(["--self-check","--library",str(tmp_path/"matching.lmc")])==2
@pytest.mark.parametrize('strict',[False,True])
def test_cli_native_update_warning_exit_and_strict_fallback(project_factory,tmp_path,monkeypatch,strict):
from mentor_pdf_export import cli
from mentor_pdf_export.exporter import Exporter
from pypdf import PdfWriter
project=project_factory();engine=tmp_path/'sch2pdf.exe';engine.write_bytes(b'fake')
def runner(args,*rest,env=None):
writer=PdfWriter();writer.add_blank_page(width=500,height=400)
with Path(args[args.index('-a')+1]).open('wb') as out:writer.write(out)
(project.parent/'database/icdb.dat').write_bytes(b'native update');return 0
monkeypatch.setattr(cli,'Exporter',lambda engine,runs:Exporter(engine,runs,runner=runner))
report=tmp_path/'report.json'
args=['--export',str(project),'--engine',str(engine),'--output',str(tmp_path/'pdfs'),'--runs-root',str(tmp_path/'runs'),'--report',str(report)]
if strict:args.append('--strict-source')
assert main(args)==(1 if strict else 0)
result=json.loads(report.read_text(encoding='utf-8'))['results'][0]
assert result['status']==('uncertain' if strict else 'success')
if not strict:assert result['warnings'] and Path(result['output']).is_file()
def test_cli_strict_source_flag_reaches_ui(qtbot,tmp_path,monkeypatch):
from mentor_pdf_export import ui
original=ui.MainWindow;windows=[]
def capture(*args,**kwargs):
window=original(*args,**kwargs);qtbot.addWidget(window);windows.append(window);return window
monkeypatch.setattr(ui,'MainWindow',capture)
assert main(['--strict-source','--ui-smoke',str(tmp_path/'ui.png')])==0
assert windows[0].strict_source_check.isChecked()
@pytest.mark.parametrize('flags,exit_code',[
(['--font-mapping','preserve'],0),
(['--font-mapping','preserve','--no-legacy-gbk'],0),
(['--font-mapping','preserve','--legacy-gbk'],2),
])
def test_cli_preserve_normalizes_implicit_not_explicit_gbk(project_factory,tmp_path,monkeypatch,flags,exit_code):
from mentor_pdf_export import cli
from mentor_pdf_export.exporter import Exporter
from pypdf import PdfWriter
project=project_factory();engine=tmp_path/'sch2pdf.exe';engine.write_bytes(b'fake')
def runner(args,*rest,env=None):
writer=PdfWriter();writer.add_blank_page(width=500,height=400)
with Path(args[args.index('-a')+1]).open('wb') as out:writer.write(out)
return 0
monkeypatch.setattr(cli,'Exporter',lambda e,r:Exporter(e,r,runner=runner))
rc=main(['--export',str(project),'--engine',str(engine),'--output',str(tmp_path/'out'),'--runs-root',str(tmp_path/'runs'),*flags])
assert rc==exit_code
+39
View File
@@ -323,3 +323,42 @@ def test_callback_error_stops_owned_tree_but_not_other_process(tmp_path, monkeyp
if other.poll() is None: if other.poll() is None:
other.kill() other.kill()
other.wait(timeout=10) other.wait(timeout=10)
def test_success_does_not_kill_background_database_flush(tmp_path,owned_process_handles):
import subprocess
import win32event
marker=tmp_path/'flush-complete.txt';pid_file=tmp_path/'flush.pid'
child=f"import time,pathlib;time.sleep(.6);pathlib.Path({str(marker)!r}).write_text('flushed')"
parent=("import subprocess,pathlib;"
f"p=subprocess.Popen([{sys.executable!r},'-B','-c',{child!r}],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL);"
f"pathlib.Path({str(pid_file)!r}).write_text(str(p.pid))")
children=[]
def started(message):
if 'PID=' in message:children.append(capture_child(pid_file,owned_process_handles))
assert run_engine([sys.executable,'-B','-c',parent],tmp_path,tmp_path/'logs',threading.Event(),10,started)==0
assert win32event.WaitForSingleObject(children[0],5000)==win32event.WAIT_OBJECT_0
assert marker.read_text()=='flushed'
def test_cancel_after_parent_success_does_not_abort_completed_native_writeback(tmp_path,monkeypatch,owned_process_handles):
import win32event
from mentor_pdf_export import engine
marker=tmp_path/'flush-late-stop.txt';pid_file=tmp_path/'late-stop.pid'
child=f"import time,pathlib;time.sleep(.6);pathlib.Path({str(marker)!r}).write_text('flushed')"
parent=("import subprocess,pathlib;"
f"p=subprocess.Popen([{sys.executable!r},'-B','-c',{child!r}],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL);"
f"pathlib.Path({str(pid_file)!r}).write_text(str(p.pid))")
children=[];parents=[];original=engine._create_job;cancel=threading.Event()
def bind(process):
parents.append(owned_process_handles(process.pid));return original(process)
def started(message):
if 'PID=' in message:
children.append(capture_child(pid_file,owned_process_handles))
assert win32event.WaitForSingleObject(parents[0],5000)==win32event.WAIT_OBJECT_0
cancel.set()
monkeypatch.setattr(engine,'_create_job',bind)
with pytest.raises(InterruptedError):
run_engine([sys.executable,'-B','-c',parent],tmp_path,tmp_path/'logs',cancel,10,started)
assert win32event.WaitForSingleObject(children[0],5000)==win32event.WAIT_OBJECT_0
assert marker.read_text()=='flushed'
+138 -2
View File
@@ -76,7 +76,7 @@ def test_source_change_never_claims_success(project_factory, tmp_path):
project = project_factory(); info = read_project(project) project = project_factory(); info = read_project(project)
def changing(args, *rest): def changing(args, *rest):
pdf(args[args.index("-a") + 1]) pdf(args[args.index("-a") + 1])
(project.parent / "database/icdb.dat").write_bytes(b"edited elsewhere") project.write_bytes(project.read_bytes() + b"\nKEY ExternalEdit 1\n")
return 0 return 0
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=changing).export(info, tmp_path / "pdfs", ExportOptions(), threading.Event()) result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=changing).export(info, tmp_path / "pdfs", ExportOptions(), threading.Event())
assert result.status == "uncertain" assert result.status == "uncertain"
@@ -85,7 +85,10 @@ def test_source_change_never_claims_success(project_factory, tmp_path):
def test_duplicate_project_names_have_distinct_outputs(project_factory, tmp_path): def test_duplicate_project_names_have_distinct_outputs(project_factory, tmp_path):
a = read_project(project_factory("a", "same")); b = read_project(project_factory("b", "same")) a = read_project(project_factory("a", "same")); b = read_project(project_factory("b", "same"))
assert output_path(a, tmp_path / "out") != output_path(b, tmp_path / "out") from mentor_pdf_export.naming import plan_output_directories
directories=plan_output_directories([a,b],tmp_path/"out",tmp_path/"runs")
assert output_path(a,directories[0]) != output_path(b,directories[1])
assert output_path(a,directories[0]).name == output_path(b,directories[1]).name == "same.pdf"
def test_cannot_output_inside_source(project_factory, tmp_path): def test_cannot_output_inside_source(project_factory, tmp_path):
@@ -162,3 +165,136 @@ def test_staging_stat_failure_still_returns_and_records_result(project_factory,t
assert result.status=="failed" assert result.status=="failed"
assert (Path(result.run_dir)/"result.json").is_file() assert (Path(result.run_dir)/"result.json").is_file()
assert "暂存" in result.message assert "暂存" in result.message
def test_style_failure_never_replaces_old_output(project_factory,tmp_path,monkeypatch):
import mentor_pdf_export.exporter as module
info=read_project(project_factory())
output=output_path(info,tmp_path/"pdfs");output.parent.mkdir();output.write_bytes(b"previous")
def broken(*args):raise ValueError("unsupported font glyph")
monkeypatch.setattr(module,"apply_pdf_style",broken)
result=Exporter(Path("fake.exe"),tmp_path/"runs",runner=fake_runner).export(info,output.parent,ExportOptions(overwrite=True,font_mapping="arial"),threading.Event())
assert result.status=="failed" and output.read_bytes()==b"previous"
def test_direct_export_uses_original_project_without_creating_copy_or_ini(project_factory,tmp_path):
project=project_factory();info=read_project(project)
ini=project.parent/'dxpdf.ini';ini.write_bytes(b'Color 2\nFONT_CUSTOM_FONTS Courier-Bold\n')
before={p.relative_to(project.parent):p.read_bytes() for p in project.parent.rglob('*') if p.is_file()}
def direct(args,cwd,log_dir,*rest):
assert Path(args[args.index('-project')+1])==project.resolve()
assert Path(cwd)==project.parent.resolve()
assert not (Path(log_dir)/'project').exists()
return fake_runner(args,cwd,log_dir,*rest)
result=Exporter(Path('fake.exe'),tmp_path/'runs',runner=direct).export(info,tmp_path/'pdfs',ExportOptions(),threading.Event())
assert result.status=='success',result.message
assert before=={p.relative_to(project.parent):p.read_bytes() for p in project.parent.rglob('*') if p.is_file()}
assert not list(Path(result.run_dir).rglob('*.prj'))
def test_overwrite_has_no_previous_pdf_backup(project_factory,tmp_path):
info=read_project(project_factory());output=output_path(info,tmp_path/'pdfs');output.parent.mkdir();output.write_bytes(b'previous')
result=Exporter(Path('fake.exe'),tmp_path/'runs',runner=fake_runner).export(info,output.parent,ExportOptions(overwrite=True),threading.Event())
assert result.status=='success'
assert not (Path(result.run_dir)/'previous-output.pdf').exists()
assert not list(Path(result.run_dir).rglob('*.pdf'))
def test_failed_export_does_not_keep_unpublished_pdf_copy(project_factory,tmp_path):
info=read_project(project_factory())
def failed(args,*rest):pdf(args[args.index('-a')+1]);return 7
result=Exporter(Path('fake.exe'),tmp_path/'runs',runner=failed).export(info,tmp_path/'pdfs',ExportOptions(),threading.Event())
assert result.status=='failed'
assert not list(Path(result.run_dir).rglob('*.pdf'))
assert not list((tmp_path/'pdfs').glob('*.partial.pdf'))
def test_direct_mode_rejects_library_override_without_touching_original(project_factory,tmp_path):
project=project_factory();before=project.read_bytes()
result=Exporter(Path('fake.exe'),tmp_path/'runs',runner=fake_runner).export(read_project(project),tmp_path/'pdfs',ExportOptions(library_override=str(tmp_path/'library.lmc')),threading.Event())
assert result.status=='failed' and '依赖库' in result.message
assert project.read_bytes()==before
assert not (tmp_path/'runs').exists()
@pytest.mark.parametrize("native_rc", [0, 9])
def test_source_change_explains_files_and_records_diff_without_publication(project_factory, tmp_path, native_rc):
import json
project = project_factory()
info = read_project(project)
old = project.parent / "database" / "obsolete.txt"
old.write_bytes(b"old native record")
output = output_path(info, tmp_path / "pdfs")
output.parent.mkdir()
output.write_bytes(b"previous PDF")
def changing(args, *rest):
pdf(args[args.index("-a") + 1])
(project.parent / "database" / "icdb.dat").write_bytes(b"updated by native engine")
(project.parent / "database" / "new.txt").write_bytes(b"new native record")
old.unlink()
return native_rc
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=changing).export(info, output.parent, ExportOptions(overwrite=True), threading.Event())
assert result.status == "uncertain" and not result.output
assert output.read_bytes() == b"previous PDF"
for detail in ("database/icdb.dat", "新增", "删除", "原生引擎", "source-diff.json"):
assert detail in result.message
changes = json.loads((Path(result.run_dir) / "source-diff.json").read_text(encoding="utf-8"))
assert changes == {"modified": ["database/icdb.dat"], "added": ["database/new.txt"], "removed": ["database/obsolete.txt"]}
@pytest.mark.parametrize('custom_database', ['database', 'DATA'])
def test_native_database_updates_publish_pdf_with_explicit_warning(project_factory,tmp_path,custom_database):
import json
project=project_factory(); info=read_project(project)
if custom_database!='database':
(project.parent/'database').rename(project.parent/custom_database)
project.write_text(project.read_text().replace('database',custom_database))
def updating(args,*rest):
pdf(args[args.index('-a')+1])
(project.parent/custom_database/'icdb.dat').write_bytes(b'native updated database')
logs=project.parent/custom_database/'cdbsvr'/'log'/'run';logs.mkdir(parents=True)
(logs/'native.txt').write_bytes(b'native log')
return 0
result=Exporter(Path('fake.exe'),tmp_path/'runs',runner=updating).export(info,tmp_path/'pdfs',ExportOptions(),threading.Event())
assert result.status=='success' and result.pages==1 and Path(result.output).is_file()
assert result.warnings and '只读' in result.message
commit=json.loads((Path(result.run_dir)/'commit.json').read_text(encoding='utf-8'))
assert commit['source_verified_before_publish'] is False
assert commit['source_content_identical'] is False
assert commit['source_change_policy']=='native_updates_warn'
assert not commit['backup_created'] and not commit['working_copy_created']
assessment=json.loads((Path(result.run_dir)/'source-assessment.json').read_text(encoding='utf-8'))
assert not any(assessment['blocked_changes'].values())
assert assessment['native_updates']['modified']==[custom_database+'/icdb.dat']
def test_strict_source_mode_still_blocks_native_database_update(project_factory,tmp_path):
project=project_factory();info=read_project(project)
def updating(args,*rest):
pdf(args[args.index('-a')+1]);(project.parent/'database/icdb.dat').write_bytes(b'native update');return 0
result=Exporter(Path('fake.exe'),tmp_path/'runs',runner=updating).export(info,tmp_path/'pdfs',ExportOptions(strict_source=True),threading.Event())
assert result.status=='uncertain' and not result.output
assert not output_path(info,tmp_path/'pdfs').exists()
@pytest.mark.parametrize('outcome', ['failed','cancelled','timeout'])
def test_native_updates_do_not_hide_real_failures_or_cancellation(project_factory,tmp_path,outcome):
project=project_factory();info=read_project(project)
target=output_path(info,tmp_path/'pdfs');target.parent.mkdir();target.write_bytes(b'previous')
def updating(args,*rest):
pdf(args[args.index('-a')+1]);(project.parent/'database/icdb.dat').write_bytes(b'native update')
if outcome=='cancelled':raise InterruptedError('stop requested')
if outcome=='timeout':raise TimeoutError('timeout')
return 9
result=Exporter(Path('fake.exe'),tmp_path/'runs',runner=updating).export(info,target.parent,ExportOptions(overwrite=True),threading.Event())
assert result.status==outcome and not result.output and result.warnings
assert target.read_bytes()==b'previous'
def test_invalid_pdf_is_not_published_even_when_changes_are_native(project_factory,tmp_path):
project=project_factory();info=read_project(project)
def invalid(args,*rest):
Path(args[args.index('-a')+1]).write_bytes(b'not a PDF')
(project.parent/'database/icdb.dat').write_bytes(b'native update');return 0
result=Exporter(Path('fake.exe'),tmp_path/'runs',runner=invalid).export(info,tmp_path/'pdfs',ExportOptions(),threading.Event())
assert result.status=='failed' and not result.output
+72
View File
@@ -0,0 +1,72 @@
import threading
from pathlib import Path
from pypdf import PdfWriter
from mentor_pdf_export.exporter import Exporter,output_path
from mentor_pdf_export.models import ExportOptions
from mentor_pdf_export.scanner import read_project
from mentor_pdf_export.workers import BatchWorker
def test_pdf_uses_original_project_basename_without_hash(project_factory,tmp_path):
project=read_project(project_factory('input','音频_Test'))
assert output_path(project,tmp_path/'out').name=='音频_Test.pdf'
def test_duplicate_names_export_to_natural_subfolders_without_overwrite(qapp,project_factory,tmp_path):
a=read_project(project_factory('design/Work','same'))
b=read_project(project_factory('design/Cert','same'))
def runner(args,*rest):
writer=PdfWriter();writer.add_blank_page(width=500,height=400)
with Path(args[args.index('-a')+1]).open('wb') as f:writer.write(f)
return 0
worker=BatchWorker([(0,a),(1,b)],tmp_path/'out',ExportOptions(overwrite=True),Exporter(Path('fake.exe'),tmp_path/'runs',runner=runner))
worker.run()
assert [r.status for r in worker.results]==['success','success']
assert [Path(r.output).relative_to(tmp_path/'out').as_posix() for r in worker.results]==['Work/same.pdf','Cert/same.pdf']
def test_unique_names_keep_flat_output(qapp,project_factory,tmp_path):
from mentor_pdf_export.naming import plan_output_directories
a=read_project(project_factory('a','One'));b=read_project(project_factory('b','Two'))
assert plan_output_directories([a,b],tmp_path/'out',tmp_path/'runs')==[tmp_path/'out',tmp_path/'out']
def test_derived_subfolder_cannot_enter_any_source_before_first_native_call(qapp,project_factory,tmp_path):
a=read_project(project_factory('design/root/Work','same'))
b=read_project(project_factory('design/root/Cert','same'))
# root is an allowed ancestor, but derived Work/Cert outputs would hit sources.
calls=[]
worker=BatchWorker([(0,a),(1,b)],tmp_path/'design/root',ExportOptions(),Exporter(Path('fake.exe'),tmp_path/'runs',runner=lambda *args:calls.append(args)))
worker.run()
assert not calls and not worker.results
def test_retry_subset_preserves_collision_folders(qapp,project_factory,tmp_path):
a=read_project(project_factory('design/Work','same'));b=read_project(project_factory('design/Cert','same'))
def runner(args,*rest):
writer=PdfWriter();writer.add_blank_page(width=500,height=400)
with Path(args[args.index('-a')+1]).open('wb') as f:writer.write(f)
return 0
worker=BatchWorker([(0,a)],tmp_path/'out',ExportOptions(),Exporter(Path('fake.exe'),tmp_path/'runs',runner=runner),all_projects=[a,b])
worker.run()
assert Path(worker.results[0].output).relative_to(tmp_path/'out').as_posix()=='Work/same.pdf'
def test_junction_aliases_cannot_merge_same_name_outputs(qapp,project_factory,tmp_path):
import os,pytest
if os.name!='nt':pytest.skip('Windows junction regression')
import _winapi
a=read_project(project_factory('design/Work','same'));b=read_project(project_factory('design/Cert','same'))
output=tmp_path/'out';output.mkdir();shared=tmp_path/'shared';shared.mkdir()
_winapi.CreateJunction(str(shared),str(output/'Work'))
_winapi.CreateJunction(str(shared),str(output/'Cert'))
assert (output/'Work').resolve()==(output/'Cert').resolve()==shared
calls=[]
def runner(args,*rest):
calls.append(args);writer=PdfWriter();writer.add_blank_page(width=500,height=400)
with Path(args[args.index('-a')+1]).open('wb') as f:writer.write(f)
return 0
worker=BatchWorker([(0,a),(1,b)],output,ExportOptions(overwrite=True),Exporter(Path('fake.exe'),tmp_path/'runs',runner=runner))
worker.run()
assert not calls and not worker.results
assert not (shared/'same.pdf').exists()
+330
View File
@@ -0,0 +1,330 @@
from pathlib import Path
import threading
import pytest
from pypdf import PdfReader, PdfWriter
from pypdf.generic import (DictionaryObject,NameObject,NumberObject,ArrayObject,FloatObject,TextStringObject,ByteStringObject,DecodedStreamObject,ContentStream)
from mentor_pdf_export.models import ExportOptions
from mentor_pdf_export.pdf_styles import apply_pdf_style, decode_legacy_text, contrast_rgb
def legacy_pdf(path,text="注意事项 输入网络 Ω μ ± ×"):
writer=PdfWriter();page=writer.add_blank_page(width=640,height=220)
font=DictionaryObject({NameObject("/Type"):NameObject("/Font"),NameObject("/Subtype"):NameObject("/Type1"),NameObject("/BaseFont"):NameObject("/Courier-Bold"),NameObject("/Encoding"):NameObject("/WinAnsiEncoding")})
page[NameObject("/Resources")]=DictionaryObject({NameObject("/Font"):DictionaryObject({NameObject("/F1"):writer._add_object(font)})})
stream=ContentStream(None,writer)
stream.operations=[
([FloatObject(1),FloatObject(1),FloatObject(1)],b"rg"),
([NumberObject(0),NumberObject(0),NumberObject(640),NumberObject(220)],b"re"),([],b"f"),
([FloatObject(0),FloatObject(1),FloatObject(1)],b"RG"),
([NumberObject(20),NumberObject(25)],b"m"),([NumberObject(600),NumberObject(25)],b"l"),([],b"S"),
([FloatObject(1),FloatObject(1),FloatObject(0)],b"rg"),
([],b"BT"),([NameObject("/F1"),NumberObject(14)],b"Tf"),
([NumberObject(1),NumberObject(0),NumberObject(0),NumberObject(1),NumberObject(20),NumberObject(120)],b"Tm"),
([ByteStringObject(text.encode("gbk"))],b"Tj"),([],b"ET"),
]
page[NameObject("/Contents")]=writer._add_object(stream)
annotation=DictionaryObject({NameObject("/Type"):NameObject("/Annot"),NameObject("/Subtype"):NameObject("/Link"),NameObject("/Rect"):ArrayObject([NumberObject(10),NumberObject(10),NumberObject(30),NumberObject(20)]),NameObject("/A"):DictionaryObject({NameObject("/S"):NameObject("/URI"),NameObject("/URI"):TextStringObject("https://example.invalid")})})
page[NameObject("/Annots")]=ArrayObject([writer._add_object(annotation)])
writer.add_outline_item("Power",0)
with Path(path).open("wb") as out:writer.write(out)
def test_legacy_gbk_bytes_decode_without_guessing_ascii():
text="注意事项 Ω μ ± ×"
assert decode_legacy_text(text.encode("gbk"), legacy_gbk=True)==(text,True)
assert decode_legacy_text(b"R1 10K")==("R1 10K",False)
def test_palette_preserves_white_and_darkens_cyan_and_yellow():
assert contrast_rgb((1,1,1),text=True)==(1,1,1)
assert max(contrast_rgb((1,1,0),text=True))<.4
cyan=contrast_rgb((0,1,1),text=True)
assert max(cyan)<.5
tinted=contrast_rgb((0,1,0),text=False)
assert min(tinted)>.8
def test_original_mode_does_not_touch_bytes(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file);before=file.read_bytes()
report=apply_pdf_style(file,ExportOptions())
assert file.read_bytes()==before and not report.modified
def test_high_contrast_preserves_vectors_page_box_annotations_outline(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file)
before=PdfReader(file);box=list(before.pages[0].mediabox)
report=apply_pdf_style(file,ExportOptions(print_theme="high_contrast"))
after=PdfReader(file)
assert report.modified and report.color_ops>0
assert list(after.pages[0].mediabox)==box
assert after.outline[0].title=="Power"
assert after.pages[0]['/Annots'][0].get_object()['/A']['/URI']=="https://example.invalid"
operators=[op for _,op in ContentStream(after.pages[0].get_contents(),after).operations]
assert b"m" in operators and b"l" in operators and b"S" in operators
assert len(after.pages[0].get('/Resources',{}).get('/XObject',{}))==0
def test_arial_with_cjk_fallback_recovers_real_chinese(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file)
report=apply_pdf_style(file,ExportOptions(font_mapping="arial",legacy_gbk=True))
reader=PdfReader(file,strict=True);text=reader.pages[0].extract_text()
assert "注意事项" in text and "输入网络" in text
assert "Ω" in text and "μ" in text and "±" in text and "×" in text
assert report.repaired_strings==1 and report.fallback_strings==1
assert reader.outline[0].title=="Power"
assert reader.pages[0]['/Annots'][0].get_object()['/A']['/URI']=="https://example.invalid"
def test_pre_cancel_never_modifies_pdf(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file);before=file.read_bytes()
cancel=threading.Event();cancel.set()
with pytest.raises(InterruptedError):
apply_pdf_style(file,ExportOptions(font_mapping="arial",legacy_gbk=True),cancel)
assert file.read_bytes()==before
def test_normal_western_accent_is_not_guessed_as_chinese():
assert decode_legacy_text("école".encode("cp1252"))==("école",False)
def test_compound_text_requires_explicit_support_not_silent_success(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file)
r=PdfReader(file);w=PdfWriter();w.clone_document_from_reader(r)
page=w.pages[0];stream=ContentStream(page.get_contents(),w)
stream.operations=[([ArrayObject([operands[0]])],b'TJ') if op==b'Tj' else (operands,op) for operands,op in stream.operations]
page[NameObject('/Contents')]=w._add_object(stream)
with file.open('wb') as out:w.write(out)
before=file.read_bytes()
with pytest.raises(ValueError,match="TJ"):
apply_pdf_style(file,ExportOptions(font_mapping="arial",legacy_gbk=True))
assert file.read_bytes()==before
def test_nonprinting_native_control_does_not_require_missing_font_glyph(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file,"A\r注意事项")
report=apply_pdf_style(file,ExportOptions(font_mapping="arial",legacy_gbk=True))
assert "注意事项" in PdfReader(file).pages[0].extract_text()
assert report.repaired_strings==1
def test_high_contrast_sets_readable_minimum_stroke_without_moving_path(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file)
r=PdfReader(file);w=PdfWriter();w.clone_document_from_reader(r)
page=w.pages[0];stream=ContentStream(page.get_contents(),w)
stream.operations.insert(0,([FloatObject(.01)],b'w'))
page[NameObject('/Contents')]=w._add_object(stream)
with file.open('wb') as out:w.write(out)
apply_pdf_style(file,ExportOptions(print_theme="high_contrast"))
after=PdfReader(file);ops=ContentStream(after.pages[0].get_contents(),after).operations
widths=[float(a[0]) for a,o in ops if o==b'w']
assert widths and min(widths)>=.35
assert ([NumberObject(20),NumberObject(25)],b'm') in ops
assert ([NumberObject(600),NumberObject(25)],b'l') in ops
def rewrite_operations(file, transform):
reader=PdfReader(file); writer=PdfWriter(); writer.clone_document_from_reader(reader)
page=writer.pages[0]; stream=ContentStream(page.get_contents(),writer)
stream.operations=transform(stream.operations)
page[NameObject('/Contents')]=writer._add_object(stream)
with file.open('wb') as output: writer.write(output)
@pytest.mark.parametrize("raw,text",[(b"\xb1\xd7","±×"),(b"\xb5\xb1","µ±"),(b"\xc9\xc9","ÉÉ")])
def test_declared_winansi_never_guessed_as_gbk(raw,text):
assert decode_legacy_text(raw)==(text,False)
def test_gbk_repair_requires_explicit_font_mapping():
with pytest.raises(ValueError,match="字体"):
ExportOptions(legacy_gbk=True)
@pytest.mark.parametrize("color,operator",[([0],b'g'),([0,0,0,1],b'k')])
def test_high_contrast_tracks_gray_and_cmyk_text_after_white_fill(tmp_path,color,operator):
file=tmp_path/'native.pdf'; legacy_pdf(file,'LABEL')
rewrite_operations(file,lambda ops: [([NumberObject(v) for v in color],operator) if o==b'rg' and a==[1,1,0] else (a,o) for a,o in ops])
apply_pdf_style(file,ExportOptions(print_theme='high_contrast'))
r=PdfReader(file); ops=ContentStream(r.pages[0].get_contents(),r).operations
begin=next(i for i,(_,o) in enumerate(ops) if o==b'BT')
assert ops[begin+1][1]==b'rg'
assert max(float(v) for v in ops[begin+1][0])<.4
@pytest.mark.parametrize("operator",[b'Tc',b'Tw'])
def test_nonzero_text_spacing_fails_before_staging_replacement(tmp_path,operator):
file=tmp_path/'native.pdf'; legacy_pdf(file,'A A')
rewrite_operations(file,lambda ops: [(a,o) for a,o in ops] + [])
rewrite_operations(file,lambda ops: [(a,o) for a,o in ops[:1]]+[( [NumberObject(5)],operator)]+ops[1:])
before=file.read_bytes()
with pytest.raises(ValueError,match='间距'):
apply_pdf_style(file,ExportOptions(font_mapping='arial'))
assert file.read_bytes()==before
def test_tinted_palette_is_idempotent():
color=contrast_rgb((0,1,1),text=False)
assert contrast_rgb(color,text=False)==color
def test_font_mapping_keeps_declared_winansi_symbols(tmp_path):
file=tmp_path/'native.pdf';legacy_pdf(file,'ASCII')
raw='±× µ±'.encode('cp1252')
rewrite_operations(file,lambda ops:[([ByteStringObject(raw)],o) if o==b'Tj' else (a,o) for a,o in ops])
report=apply_pdf_style(file,ExportOptions(font_mapping='arial'))
assert '±× µ±' in PdfReader(file).pages[0].extract_text()
assert report.repaired_strings==0
def test_unknown_original_font_advance_fails_safe(tmp_path):
file=tmp_path/'native.pdf';legacy_pdf(file,'LABEL')
r=PdfReader(file);w=PdfWriter();w.clone_document_from_reader(r)
w.pages[0]['/Resources']['/Font']['/F1'].get_object()[NameObject('/BaseFont')]=NameObject('/UnknownNoMetrics')
with file.open('wb') as out:w.write(out)
before=file.read_bytes()
with pytest.raises(ValueError,match='字宽'):
apply_pdf_style(file,ExportOptions(font_mapping='arial'))
assert file.read_bytes()==before
def test_explicit_gbk_retains_standalone_declared_winansi_symbol():
assert decode_legacy_text(b"\xa3",legacy_gbk=True)==("£",False)
@pytest.mark.parametrize('width,height,panel',[(.2,12,False),(70,40,True)])
def test_high_contrast_distinguishes_stroke_glyph_fills_from_panels(tmp_path,width,height,panel):
file=tmp_path/'native.pdf';legacy_pdf(file,'LABEL')
path_ops=[([NumberObject(0),NumberObject(1),NumberObject(1)],b'rg'),([NumberObject(30),NumberObject(40),FloatObject(width),FloatObject(height)],b're'),([],b'f')]
rewrite_operations(file,lambda ops:path_ops+ops)
apply_pdf_style(file,ExportOptions(print_theme='high_contrast'))
r=PdfReader(file);color=None
for args,op in ContentStream(r.pages[0].get_contents(),r).operations:
if op==b'rg':color=tuple(float(x) for x in args)
if op==b'f':break
assert (min(color)>.8) if panel else (max(color)<.5)
def test_scaled_rectangle_glyph_is_not_mistaken_for_large_panel(tmp_path):
file=tmp_path/'native.pdf';legacy_pdf(file,'LABEL')
path_ops=[([FloatObject(.01),NumberObject(0),NumberObject(0),FloatObject(.01),NumberObject(0),NumberObject(0)],b'cm'),([NumberObject(0),NumberObject(1),NumberObject(1)],b'rg'),([NumberObject(30),NumberObject(40),NumberObject(70),NumberObject(400)],b're'),([],b'f')]
rewrite_operations(file,lambda ops:path_ops+ops)
apply_pdf_style(file,ExportOptions(print_theme='high_contrast'))
r=PdfReader(file);color=None
for args,op in ContentStream(r.pages[0].get_contents(),r).operations:
if op==b'rg':color=tuple(float(x) for x in args)
if op==b'f':break
assert max(color)<.5
def test_minimum_stroke_is_in_physical_points_after_scaled_transform(tmp_path):
file=tmp_path/'native.pdf';legacy_pdf(file,'LABEL')
prefix=[([FloatObject(.01),NumberObject(0),NumberObject(0),FloatObject(.01),NumberObject(0),NumberObject(0)],b'cm'),([FloatObject(.1)],b'w')]
rewrite_operations(file,lambda ops:prefix+ops)
apply_pdf_style(file,ExportOptions(print_theme='high_contrast'))
r=PdfReader(file);width=None
for args,op in ContentStream(r.pages[0].get_contents(),r).operations:
if op==b'w':width=float(args[0])
if op==b'S':break
assert width*.01>=.35
@pytest.mark.parametrize("mapping", ["arial", "simsun", "msyh"])
def test_font_only_repair_preserves_reference_colors_widths_and_geometry(tmp_path, mapping):
file = tmp_path / "native.pdf"
legacy_pdf(file)
writer = PdfWriter(clone_from=file)
page = writer.pages[0]
stream = ContentStream(page.get_contents(), writer)
# Explicit hairline, a thicker emphasis stroke, and red/blue/teal/green
# reference colors must survive even when Chinese text is repaired.
additions = [([NumberObject(0)], b"w")]
for color in ((1,0,0), (0,0,1), (0,.5,.5), (0,.5,0), (0,0,.5), (.5,0,.5)):
additions += [([FloatObject(v) for v in color], b"RG"),
([NumberObject(20), NumberObject(50)], b"m"),
([NumberObject(600), NumberObject(50)], b"l"), ([], b"S")]
additions += [([FloatObject(1.2)], b"w")]
stream.operations = additions + stream.operations
page[NameObject("/Contents")] = writer._add_object(stream)
with file.open("wb") as out:
writer.write(out)
tracked = {b"rg", b"RG", b"g", b"G", b"k", b"K", b"w", b"cm", b"m", b"l", b"re", b"S", b"f", b"Tm"}
def graphics(reader):
return [(tuple(operands), op) for operands, op in ContentStream(reader.pages[0].get_contents(), reader).operations if op in tracked]
before = PdfReader(file)
expected = graphics(before)
box = list(before.pages[0].mediabox)
report = apply_pdf_style(file, ExportOptions(font_mapping=mapping, legacy_gbk=True, print_theme="original"))
after = PdfReader(file)
assert report.modified and report.repaired_strings == 1
assert report.color_ops == 0
assert graphics(after) == expected
assert list(after.pages[0].mediabox) == box
assert "注意事项" in after.pages[0].extract_text()
def test_stroke_search_text_is_not_reported_as_visible_font_repair(tmp_path):
file=tmp_path/'stroke.pdf';legacy_pdf(file,'注意事项')
writer=PdfWriter();writer.clone_document_from_reader(PdfReader(file))
font=writer.pages[0]['/Resources']['/Font']['/F1'].get_object()
font[NameObject('/BaseFont')]=NameObject('/fstroke0')
font[NameObject('/Widths')]=ArrayObject([NumberObject(600)]*256)
font[NameObject('/FirstChar')]=NumberObject(0)
with file.open('wb') as stream:writer.write(stream)
before=file.read_bytes()
with pytest.raises(ValueError,match='笔画'):
apply_pdf_style(file,ExportOptions(font_mapping='arial',legacy_gbk=True))
assert file.read_bytes()==before
def test_used_form_stroke_font_cannot_bypass_repair_validation(tmp_path):
file=tmp_path/'form-stroke.pdf';legacy_pdf(file,'注意事项')
writer=PdfWriter();writer.clone_document_from_reader(PdfReader(file));page=writer.pages[0]
font=page['/Resources']['/Font']['/F1'].get_object()
font[NameObject('/BaseFont')]=NameObject('/fstroke0')
font[NameObject('/Widths')]=ArrayObject([NumberObject(600)]*256)
font[NameObject('/FirstChar')]=NumberObject(0)
form=DecodedStreamObject();form.set_data(page.get_contents().get_data())
form.update({NameObject('/Type'):NameObject('/XObject'),NameObject('/Subtype'):NameObject('/Form'),NameObject('/BBox'):ArrayObject([NumberObject(0),NumberObject(0),NumberObject(640),NumberObject(220)]),NameObject('/Resources'):page['/Resources']})
page[NameObject('/Resources')]=DictionaryObject({NameObject('/XObject'):DictionaryObject({NameObject('/X1'):writer._add_object(form)})})
content=DecodedStreamObject();content.set_data(b'/X1 Do');page[NameObject('/Contents')]=writer._add_object(content)
with file.open('wb') as out:writer.write(out)
before=file.read_bytes()
with pytest.raises(ValueError,match='笔画'):
apply_pdf_style(file,ExportOptions(font_mapping='arial',legacy_gbk=True))
assert file.read_bytes()==before
@pytest.mark.parametrize('family,advance',[
('Helvetica',31.892),('Courier-Bold',33.6),
])
def test_standard14_fonts_use_exact_afm_advance_without_guessing(family,advance):
from mentor_pdf_export.pdf_styles import _old_width
font=DictionaryObject({NameObject('/BaseFont'):NameObject('/'+family),NameObject('/Subtype'):NameObject('/Type1'),NameObject('/Encoding'):NameObject('/WinAnsiEncoding')})
assert _old_width(font,b'Wi12',14)==pytest.approx(advance)
def test_unknown_font_without_metrics_is_still_rejected():
from mentor_pdf_export.pdf_styles import _old_width
assert _old_width(DictionaryObject({NameObject('/BaseFont'):NameObject('/UnknownNoMetrics')}),b'Wi12',14) is None
def test_hidden_ascii_strokes_survive_mixed_chinese_repair_without_overlay(tmp_path):
file=tmp_path/'mixed.pdf';legacy_pdf(file,'注意事项')
writer=PdfWriter();writer.clone_document_from_reader(PdfReader(file));page=writer.pages[0]
font=DictionaryObject({NameObject('/Type'):NameObject('/Font'),NameObject('/Subtype'):NameObject('/TrueType'),NameObject('/BaseFont'):NameObject('/fstroke5'),NameObject('/Encoding'):NameObject('/WinAnsiEncoding'),NameObject('/FirstChar'):NumberObject(0),NameObject('/Widths'):ArrayObject([NumberObject(600)]*256)})
page['/Resources']['/Font'][NameObject('/F2')]=writer._add_object(font)
stream=ContentStream(page.get_contents(),writer)
stream.operations.extend([
([],b'BT'),([NameObject('/F1'),NumberObject(14)],b'Tf'),([ByteStringObject(b'POWER')],b'Tj'),([],b'ET'),
([],b'BT'),([NumberObject(3)],b'Tr'),([NameObject('/F2'),NumberObject(14)],b'Tf'),([ByteStringObject(b'POWER')],b'Tj'),([],b'ET'),([NumberObject(0)],b'Tr'),
])
stream.get_data();page[NameObject('/Contents')]=writer._add_object(stream)
with file.open('wb') as out:writer.write(out)
before=PdfReader(file);old=[(a,op) for a,op in ContentStream(before.pages[0].get_contents(),before).operations if op in (b'm',b'l',b're',b'RG',b'rg',b'Tr')]
report=apply_pdf_style(file,ExportOptions(font_mapping='arial',legacy_gbk=True,print_theme='reference'))
result=PdfReader(file)
assert '注意事项' in result.pages[0].extract_text()
assert report.font_strings==2 and report.preserved_ascii_stroke_strings==1
ops=ContentStream(result.pages[0].get_contents(),result).operations
assert old==[(a,op) for a,op in ops if op in (b'm',b'l',b're',b'RG',b'rg',b'Tr')]
assert any(op==b'Tj' and (a[0].original_bytes if hasattr(a[0],'original_bytes') else bytes(a[0]))==b'POWER' for a,op in ops)
+28
View File
@@ -31,3 +31,31 @@ def test_stroke_mode_uses_native_verified_attached_switch():
args=build_command(Path("engine.exe"),Path("a.prj"),Path("a.pdf"),ExportOptions(stroke_fonts=True)) args=build_command(Path("engine.exe"),Path("a.prj"),Path("a.pdf"),ExportOptions(stroke_fonts=True))
assert "-uAll" in args assert "-uAll" in args
assert "-u" not in args and "-udx" not in args assert "-u" not in args and "-udx" not in args
def test_explicit_font_and_print_profile_modes():
options=ExportOptions(font_mapping="arial",print_theme="high_contrast")
assert options.font_mapping=="arial" and options.print_theme=="high_contrast"
def test_profile_modes_reject_unknown_names():
import pytest
with pytest.raises(ValueError,match="字体"):
ExportOptions(font_mapping="arail\nInjected value")
with pytest.raises(ValueError,match="配色"):
ExportOptions(print_theme="unknown")
def test_arial_profile_changes_only_copy_font_configuration(tmp_path):
ini=tmp_path/"dxpdf.ini";ini.write_text("FONT_CUSTOM_FONTS Courier-Bold\nFont_1 Courier-Bold\n")
write_profile(ini,ExportOptions(font_mapping="arial"))
lines=ini.read_text().splitlines()
assert "FONT_CUSTOM_FONTS Arial" in lines
assert "Font_1 Arial" in lines
def test_print_theme_controls_effective_background_mode():
args=build_command(Path("engine.exe"),Path("p.prj"),Path("p.pdf"),ExportOptions(color=2,print_theme="high_contrast"))
assert args[args.index("-c")+1]=="4"
args=build_command(Path("engine.exe"),Path("p.prj"),Path("p.pdf"),ExportOptions(print_theme="mono"))
assert args[args.index("-c")+1]=="3"
+68
View File
@@ -0,0 +1,68 @@
"""Regression: ordinary UI defaults must generate readable reference-style output."""
import os
import sys
import threading
import xml.etree.ElementTree as ET
from pathlib import Path
from pypdf import PdfReader
from pypdf.generic import ContentStream
from mentor_pdf_export.models import ExportOptions
from mentor_pdf_export.profiles import build_command
from mentor_pdf_export.pdf_styles import apply_pdf_style
from mentor_pdf_export.engine import run_engine
from mentor_pdf_export.ui import MainWindow
from test_pdf_styles import legacy_pdf
def test_font_repair_uses_native_mapped_text_not_dxd_stroke_fallback():
cmd=build_command(Path('sch2pdf.exe'),Path('demo.prj'),Path('demo.pdf'),ExportOptions(font_mapping='arial',legacy_gbk=True))
assert '-udx' not in cmd and '-uAll' not in cmd
def test_reference_palette_is_child_only_and_role_specific(tmp_path,monkeypatch):
from mentor_pdf_export.profiles import prepare_native_environment
monkeypatch.setenv('WDIR',r'D:\Mentor\standard')
monkeypatch.setenv('MENTOR_TEST_LICENSE','inherited')
before=dict(os.environ)
env=prepare_native_environment(tmp_path,ExportOptions(print_theme='reference'))
assert dict(os.environ)==before
cfg=Path(env['WDIR'].split(';')[0])
assert cfg.is_relative_to(tmp_path)
tree=ET.parse(cfg/'DxDesigner.xml')
def color(name):return tree.find(f"./DxDesigner/OBJECTS/object[@name='{name}']/key[@name='COLOR']").get('value')
assert color('NET')=='0xff0000'
assert color('PIN')=='0x008080'
assert color('LINE')=='0x0000ff'
assert color('BOX')=='0x800080'
assert color('CIRCLE')=='0x008000'
assert color('LABEL')=='0x008000'
assert color('ATTRIBUTE')=='0x388e8e' # Reference's inherited component values; pins remain #008080.
assert env['WDIR'].endswith(r';D:\Mentor\standard')
assert env['MENTOR_TEST_LICENSE']=='inherited'
assert prepare_native_environment(tmp_path,ExportOptions(print_theme='original')) is None
def test_engine_passes_environment_to_owned_child_only(tmp_path,monkeypatch):
monkeypatch.setenv('MENTOR_PDF_ENV_TEST','parent')
env=dict(os.environ);env['MENTOR_PDF_ENV_TEST']='child'
rc=run_engine([sys.executable,'-c',"import os;print(os.environ['MENTOR_PDF_ENV_TEST'])"],tmp_path,tmp_path/'logs',threading.Event(),10,env=env)
assert rc==0
assert (tmp_path/'logs/stdout.log').read_text().strip()=='child'
assert os.environ['MENTOR_PDF_ENV_TEST']=='parent'
def test_plain_ui_defaults_repair_chinese_without_recoloring_or_thickening(qtbot,tmp_path):
window=MainWindow();qtbot.addWidget(window)
opts=window.options()
assert opts.print_theme=='reference'
cmd=build_command(Path('sch2pdf.exe'),Path('工程.prj'),Path('工程.pdf'),opts)
assert '-udx' not in cmd
file=tmp_path/'native.pdf';legacy_pdf(file,'注意事项 音频 Ω μ ± ×')
before=PdfReader(file);ops=ContentStream(before.pages[0].get_contents(),before).operations
geometry=[(a,b) for a,b in ops if b in (b'm',b'l',b're',b'w',b'rg',b'RG')]
report=apply_pdf_style(file,opts)
reader=PdfReader(file);text=reader.pages[0].extract_text()
assert '注意事项' in text and '音频' in text
assert all(s in text for s in ('Ω','μ','±','×'))
assert report.repaired_strings==1 and report.fallback_strings==1
assert geometry==[(a,b) for a,b in ContentStream(reader.pages[0].get_contents(),reader).operations if b in (b'm',b'l',b're',b'w',b'rg',b'RG')]
+124
View File
@@ -0,0 +1,124 @@
from pathlib import Path
import struct
import tomllib
from PySide6.QtCore import QSize
from PySide6.QtGui import QIcon
ROOT = Path(__file__).parents[1]
def test_official_version_and_user_facing_title(qtbot):
from mentor_pdf_export import __version__
from mentor_pdf_export.ui import MainWindow
assert __version__ == "1.0.0"
assert tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf8"))["project"]["version"] == __version__
window = MainWindow()
qtbot.addWidget(window)
assert window.windowTitle() == "Mentor PDF 批量导出 · v1.0.0"
assert not window.windowIcon().isNull()
def test_icon_contains_all_shell_and_taskbar_sizes(qapp):
from mentor_pdf_export.branding import icon_path, application_icon
data = icon_path().read_bytes()
reserved, kind, count = struct.unpack_from("<HHH", data)
assert (reserved, kind) == (0, 1)
sizes = set()
for index in range(count):
width, height, _, _, _, bits, length, offset = struct.unpack_from("<BBBBHHII", data, 6 + 16 * index)
assert bits == 32 and width == height
assert offset + length <= len(data)
assert data[offset:offset + 8] == b"\x89PNG\r\n\x1a\n"
sizes.add(width or 256)
assert sizes == {16, 24, 32, 48, 64, 128, 256}
icon = application_icon()
assert not icon.isNull()
for size in sizes:
assert not icon.pixmap(QSize(size, size)).isNull()
def test_application_metadata_and_global_icon(qapp):
from mentor_pdf_export.branding import configure_application, APP_ID
configure_application(qapp)
assert qapp.applicationVersion() == "1.0.0"
assert qapp.applicationDisplayName() == "Mentor PDF 批量导出"
assert qapp.applicationName() == "MentorPDFExporter"
assert not qapp.windowIcon().isNull()
assert APP_ID == "simgreek.MentorPDFExporter"
def test_windows_app_id_is_explicit_and_stable(monkeypatch):
from mentor_pdf_export import branding
calls = []
class Function:
def __call__(self, app_id):
calls.append(app_id)
return 0
class Shell:
SetCurrentProcessExplicitAppUserModelID = Function()
monkeypatch.setattr(branding.sys, "platform", "win32")
monkeypatch.setattr(branding, "_shell32", lambda: Shell())
assert branding.set_windows_app_id()
assert calls == [branding.APP_ID]
def test_app_id_skips_non_windows(monkeypatch):
from mentor_pdf_export import branding
monkeypatch.setattr(branding.sys, "platform", "linux")
monkeypatch.setattr(branding, "_shell32", lambda: (_ for _ in ()).throw(AssertionError("Windows API called")))
assert not branding.set_windows_app_id()
def test_pyinstaller_includes_application_icon_and_windows_metadata():
spec = (ROOT / "packaging/MentorPDFExporter.spec").read_text(encoding="utf8")
assert "mentor_pdf_export/assets" in spec
assert "icon=" in spec and "version=version_info" in spec
config = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf8"))
assert "assets/*.ico" in config["tool"]["setuptools"]["package-data"]["mentor_pdf_export"]
def test_cli_uses_release_wording(capsys):
import pytest
from mentor_pdf_export.cli import main
with pytest.raises(SystemExit) as exit_info:
main(["--help"])
assert exit_info.value.code == 0
output = capsys.readouterr().out
assert "批量导出工具" in output and "测试工具" not in output
def test_windows_app_id_failure_is_nonfatal(monkeypatch):
from mentor_pdf_export import branding
class Function:
def __call__(self, app_id):
return -1
class Shell:
SetCurrentProcessExplicitAppUserModelID = Function()
monkeypatch.setattr(branding.sys, "platform", "win32")
monkeypatch.setattr(branding, "_shell32", lambda: Shell())
assert not branding.set_windows_app_id()
def test_ui_smoke_fails_when_application_icon_is_missing(qapp, tmp_path, monkeypatch):
import json
from mentor_pdf_export import branding, ui
from mentor_pdf_export.cli import main
monkeypatch.setattr(branding, "application_icon", lambda: QIcon())
monkeypatch.setattr(ui, "application_icon", lambda: QIcon())
report = tmp_path / "smoke.json"
rc = main(["--ui-smoke", str(tmp_path / "ui.png"), "--report", str(report)])
data = json.loads(report.read_text(encoding="utf8"))
assert data["screenshot_saved"] and not data["application_icon"] and not data["window_icon"]
assert rc != 0
def test_windows_ui_smoke_requires_taskbar_identity(qapp, tmp_path, monkeypatch):
import sys
import pytest
from mentor_pdf_export import branding
from mentor_pdf_export.cli import main
if sys.platform != "win32":
pytest.skip("Windows taskbar identity")
monkeypatch.setattr(branding, "set_windows_app_id", lambda: False)
assert main(["--ui-smoke", str(tmp_path / "ui.png")]) != 0
+111
View File
@@ -0,0 +1,111 @@
from pathlib import Path
import importlib.util
import pytest
ROOT = Path(__file__).parents[1]
def release_module():
spec = importlib.util.spec_from_file_location("build_release", ROOT / "packaging/build_release.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def skeleton(tmp_path):
(tmp_path / "MentorPDFExporter.exe").write_bytes(b"stub")
assets = tmp_path / "_internal/mentor_pdf_export/assets"
assets.mkdir(parents=True)
(assets / "app.ico").write_bytes(b"icon")
return tmp_path
def test_release_version_matches_official_metadata():
assert release_module().project_version() == "1.0.0"
requirements = (ROOT / "packaging/requirements-release.txt").read_text(encoding="utf8")
assert "cryptography==45.0.7" in requirements and "cffi==2.1.1" in requirements
@pytest.mark.parametrize("name", ["private.prj", "library.lmc", "output.pdf", "Arial.ttf", "SimSun.ttc", "font.otf", "sch2pdf.exe"])
def test_release_rejects_engineering_data_fonts_and_mentor(tmp_path, name):
bundle = skeleton(tmp_path)
(bundle / name).write_bytes(b"private")
with pytest.raises(ValueError):
release_module().validate_bundle(bundle)
def test_release_requires_packaged_window_icon(tmp_path):
bundle = skeleton(tmp_path)
(bundle / "_internal/mentor_pdf_export/assets/app.ico").unlink()
with pytest.raises(ValueError, match="icon"):
release_module().validate_bundle(bundle)
def test_release_allows_runtime_library_archive(tmp_path):
bundle = skeleton(tmp_path)
(bundle / "_internal/base_library.zip").write_bytes(b"runtime")
release_module().validate_bundle(bundle)
@pytest.mark.parametrize("relative", ["license.lic", "license.dat", "database/icdb.dat", "runs/report.json", ".git/config", "_internal/runs/report.json", "_internal/private.dat", "unexpected.txt"])
def test_release_rejects_private_license_database_logs_and_git(tmp_path, relative):
bundle = skeleton(tmp_path)
private = bundle / relative
private.parent.mkdir(parents=True, exist_ok=True)
private.write_bytes(b"private")
with pytest.raises(ValueError):
release_module().validate_bundle(bundle)
def test_release_runtime_must_match_build_allowlist(tmp_path):
bundle = skeleton(tmp_path)
module = release_module()
allowed = {p.relative_to(bundle).as_posix(): module.sha256(p) for p in bundle.rglob("*") if p.is_file()}
(bundle / "_internal/unknown.dll").write_bytes(b"not collected by PyInstaller")
with pytest.raises(ValueError):
module.validate_bundle(bundle, runtime_files=allowed)
def make_archive(path, bundle, *, omit=None, extra=None, duplicate=None, changed=None):
import zipfile
with zipfile.ZipFile(path, "w") as archive:
for file in bundle.rglob("*"):
if not file.is_file() or file.name == omit:
continue
name = bundle.name + "/" + file.relative_to(bundle).as_posix()
archive.writestr(name, b"tampered" if file.name == changed else file.read_bytes())
if file.name == duplicate:
archive.writestr(name, file.read_bytes())
if extra:
archive.writestr(extra, b"private")
def test_archive_matches_complete_verified_directory(tmp_path):
bundle = tmp_path / "release"
bundle.mkdir()
skeleton(bundle)
archive = tmp_path / "release.zip"
make_archive(archive, bundle)
release_module().validate_archive(archive, bundle)
@pytest.mark.parametrize("case", ["missing", "extra", "duplicate", "traversal", "modified"])
def test_archive_rejects_incomplete_extra_duplicate_unsafe_or_changed_members(tmp_path, case):
import warnings
bundle = tmp_path / "release"
bundle.mkdir()
skeleton(bundle)
archive = tmp_path / "release.zip"
options = {
"missing": {"omit": "app.ico"},
"extra": {"extra": "release/license.lic"},
"duplicate": {"duplicate": "MentorPDFExporter.exe"},
"traversal": {"extra": "release/../private.txt"},
"modified": {"changed": "app.ico"},
}[case]
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
make_archive(archive, bundle, **options)
with pytest.raises(ValueError):
release_module().validate_archive(archive, bundle)
+37
View File
@@ -0,0 +1,37 @@
from pathlib import Path
import importlib.util
import pytest
ROOT = Path(__file__).parents[1]
def publisher():
spec = importlib.util.spec_from_file_location("publish_release", ROOT / "packaging/publish_release.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.mark.parametrize("value", ["../other", "org/name", "org?token=x", "", "name with spaces"])
def test_repository_names_cannot_change_request_paths(value):
with pytest.raises(ValueError):
publisher().validate_name(value)
def test_expected_organization_name_is_valid():
assert publisher().validate_name("simgreek") == "simgreek"
def test_attachment_uses_gitea_multipart_field(tmp_path):
file = tmp_path / "release.zip"
file.write_bytes(b"ZIP-CONTENT")
body, content_type = publisher().multipart_attachment(file, "safe-boundary")
assert 'boundary=safe-boundary' in content_type
assert b'name="attachment"; filename="release.zip"' in body
assert b"ZIP-CONTENT" in body and body.endswith(b"--safe-boundary--\r\n")
def test_server_redirect_never_forwards_credentials():
handler = publisher().NoRedirect()
assert handler.redirect_request(None, None, 302, "redirect", {}, "https://other-host.invalid") is None
+61
View File
@@ -0,0 +1,61 @@
from mentor_pdf_export.source_policy import classify_source_changes
import pytest
@pytest.mark.parametrize('kind, name', [
('modified','database/icdb.dat'),
('modified','database/cdbsvr/events/events.dat'),
('added','database/cdbsvr/events/events.idx'),
('removed','database/cdbsvr/events/events.idx'),
('modified','database/cdbsvr/sAddress.adr'),
('added','database/cdbsvr/sAddress.adr'),
('removed','database/cdbsvr/sAddress.adr'),
('added','database/cdbsvr/log/new/run.txt'),
('removed','database/cdbsvr/log/old/run.txt'),
('added','database/cdbsvr/dbcheck/new/check.txt'),
('added','database/cdbsvr/dbupgrade/new/upgrade.txt'),
('added','database/cdbsvr/plog/run.txt'),
('added','database/cdbback/native.zip'),
])
def test_observed_native_updates_are_nonblocking_but_recorded(kind, name):
from mentor_pdf_export.source_policy import classify_source_changes
changes={'modified':[], 'added':[], 'removed':[]}; changes[kind]=[name]
accepted, blocked=classify_source_changes(changes,'database')
assert accepted==changes and not any(blocked.values())
accepted, blocked=classify_source_changes(changes,'database',strict=True)
assert not any(accepted.values()) and blocked==changes
@pytest.mark.parametrize('kind, name', [
('modified','board.prj'), ('modified','dxpdf.ini'),
('modified','colors.def'), ('modified','sheet.sch'),
('added','database/icdb.dat'), ('removed','database/icdb.dat'),
('modified','database/cdbback/old.zip'), ('removed','database/cdbback/old.zip'),
('modified','database/cdbsvr/design.dat'),
('modified','other/database/icdb.dat'),
('modified','database/../board.prj'),
('modified','database/cdbsvr/log/../design.dat'),
])
def test_unknown_design_and_deleted_database_changes_remain_blocking(kind, name):
from mentor_pdf_export.source_policy import classify_source_changes
changes={'modified':[], 'added':[], 'removed':[]}; changes[kind]=[name]
accepted, blocked=classify_source_changes(changes,'database')
assert not any(accepted.values()) and blocked==changes
def test_uses_declared_database_directory_and_windows_case_insensitivity():
from mentor_pdf_export.source_policy import classify_source_changes
changes={'modified':['DATA/ICDB.DAT','database/icdb.dat'],'added':[],'removed':[]}
accepted, blocked=classify_source_changes(changes,'data')
assert accepted['modified']==['DATA/ICDB.DAT']
assert blocked['modified']==['database/icdb.dat']
@pytest.mark.parametrize('kind',['added','modified','removed'])
def test_native_backup_coordination_record_is_warning_not_design_edit(kind):
changes={k:[] for k in ('added','modified','removed')}
changes[kind]=['database/cdbsvr/backup.lck','database/cdbsvr/unknown.lck','other/cdbsvr/backup.lck']
accepted,blocked=classify_source_changes(changes,'database')
assert accepted[kind]==['database/cdbsvr/backup.lck']
assert blocked[kind]==['database/cdbsvr/unknown.lck','other/cdbsvr/backup.lck']
accepted,blocked=classify_source_changes(changes,'database',strict=True)
assert not accepted[kind] and blocked[kind]==changes[kind]
+445 -4
View File
@@ -1,20 +1,24 @@
import threading import threading
from pathlib import Path from pathlib import Path
import pytest
from pypdf import PdfWriter from pypdf import PdfWriter
from PySide6.QtCore import Qt from PySide6.QtCore import Qt
from PySide6.QtGui import QPalette
from PySide6.QtWidgets import QFileDialog, QLabel
from mentor_pdf_export.ui import MainWindow from mentor_pdf_export.ui import MainWindow
from mentor_pdf_export.exporter import Exporter from mentor_pdf_export.exporter import Exporter
from mentor_pdf_export.models import ExportResult
def runner(args, cwd, log_dir, cancel, timeout, on_event=None): def runner(args, cwd, log_dir, cancel, timeout, on_event=None, *, env=None):
writer = PdfWriter(); writer.add_blank_page(width=500,height=400) writer = PdfWriter(); writer.add_blank_page(width=500,height=400)
with Path(args[args.index("-a")+1]).open("wb") as f: with Path(args[args.index("-a")+1]).open("wb") as f:
writer.write(f) writer.write(f)
return 0 return 0
def make_window(qtbot, tmp_path, factory=None): def make_window(qtbot, tmp_path, factory=None, library=None):
window = MainWindow(root=str(tmp_path), output=str(tmp_path / "pdfs"), runs_root=tmp_path.parent / (tmp_path.name + "-runs"), exporter_factory=factory) window = MainWindow(root=str(tmp_path), output=str(tmp_path / "pdfs"), runs_root=tmp_path.parent / (tmp_path.name + "-runs"), exporter_factory=factory, library=library, font_mapping="preserve", print_theme="original", legacy_gbk=False)
qtbot.addWidget(window); window.show() qtbot.addWidget(window); window.show()
return window return window
@@ -47,6 +51,9 @@ def test_export_worker_result_and_buttons(qtbot, project_factory, tmp_path):
assert window.busy assert window.busy
assert not window.start_button.isEnabled() assert not window.start_button.isEnabled()
assert not window.options_group.isEnabled() assert not window.options_group.isEnabled()
assert not window.font_mapping_combo.isEnabled()
assert not window.print_theme_combo.isEnabled()
assert not window.legacy_gbk_check.isEnabled()
qtbot.waitUntil(lambda: not window.busy,timeout=10000) qtbot.waitUntil(lambda: not window.busy,timeout=10000)
assert window.table.item(0,3).text()=="成功" assert window.table.item(0,3).text()=="成功"
assert window.start_button.isEnabled() assert window.start_button.isEnabled()
@@ -58,7 +65,7 @@ def test_export_worker_result_and_buttons(qtbot, project_factory, tmp_path):
def test_cancel_signal_is_requested(qtbot, project_factory, tmp_path): def test_cancel_signal_is_requested(qtbot, project_factory, tmp_path):
project_factory() project_factory()
started=threading.Event() started=threading.Event()
def waiting(args,cwd,log_dir,cancel,timeout,on_event=None): def waiting(args,cwd,log_dir,cancel,timeout,on_event=None, *, env=None):
started.set() started.set()
assert cancel.wait(5) assert cancel.wait(5)
raise InterruptedError("任务已停止") raise InterruptedError("任务已停止")
@@ -101,3 +108,437 @@ def test_ui_preflights_all_source_paths_before_queue(qtbot,project_factory,tmp_p
qtbot.waitUntil(lambda:not window.busy,timeout=10000) qtbot.waitUntil(lambda:not window.busy,timeout=10000)
assert not unexpectedly_started assert not unexpectedly_started
assert window.worker is None assert window.worker is None
def test_direct_mode_has_no_library_replacement_controls(qtbot,tmp_path):
window=make_window(qtbot,tmp_path)
assert not hasattr(window,'library_edit')
assert not hasattr(window,'library_toggle')
assert '原工程' in window.root_edit.toolTip()
assert window.options().library_override==''
def test_constructor_rejects_library_replacement_in_direct_mode(qtbot,tmp_path):
with pytest.raises(ValueError,match='依赖库'):
MainWindow(root=tmp_path,library=tmp_path/'matching.lmc')
def test_library_information_is_read_only(qtbot,tmp_path):
window=make_window(qtbot,tmp_path)
assert not hasattr(window, 'library_help')
assert '不替换库' in window.root_edit.toolTip()
assert not any('依赖库' in label.text() for label in window.findChildren(QLabel) if label.isVisible())
assert not hasattr(window,'choose_library')
def test_profile_defaults_preserve_existing_export_modes(qtbot, tmp_path):
window = make_window(qtbot, tmp_path)
assert window.font_mapping_combo.currentData() == "preserve"
assert window.print_theme_combo.currentData() == "original"
options = window.options()
assert options.font_mapping == "preserve"
assert options.print_theme == "original"
assert options.color == 4
assert [window.color_combo.itemData(i) for i in range(window.color_combo.count())] == [4, 3, 1, 2]
assert not hasattr(window, "profile_warning_label")
@pytest.mark.parametrize("label, mapping", [
("原映射", "preserve"),
("Arial+中文回退(推荐)", "arial"),
("宋体(中文对照)", "simsun"),
("微软雅黑(中文对照)", "msyh"),
])
def test_font_mapping_flows_to_options(qtbot, tmp_path, label, mapping):
window = make_window(qtbot, tmp_path)
index = window.font_mapping_combo.findText(label)
assert index >= 0
window.font_mapping_combo.setCurrentIndex(index)
assert window.options().font_mapping == mapping
@pytest.mark.parametrize("theme", ["original", "high_contrast", "mono"])
def test_print_theme_enforces_color_and_restores_original_choice(qtbot, tmp_path, theme):
window = make_window(qtbot, tmp_path)
index = window.print_theme_combo.findData(theme)
assert index >= 0
window.print_theme_combo.setCurrentIndex(index)
for color_index, existing_color in enumerate([4, 3, 1, 2]):
window.color_combo.setCurrentIndex(color_index)
options = window.options()
assert options.print_theme == theme
expected_color = {"high_contrast": 4, "mono": 3}.get(theme, existing_color)
assert options.color == expected_color
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData("original"))
assert window.options().color == 2
def test_profile_tooltips_explain_processing_and_sample_limits(qtbot, tmp_path):
window = make_window(qtbot, tmp_path)
assert window.print_theme_combo.findText("白底高对比(可选)") >= 0
for mapping in ("arial", "simsun", "msyh"):
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData(mapping))
assert not hasattr(window, "profile_warning_label")
explanation = window.font_mapping_combo.toolTip()
assert "发布前" in explanation and "文字编码" in explanation
assert "样本" in explanation and "其他工程" in explanation
for detail in ("矢量", "坐标", "书签", "注释", "不添加白色遮罩", "不栅格化"):
assert detail in explanation
assert "未验证" not in explanation and "未生效" not in explanation
assert "不保证修复中文" not in explanation
if mapping == "arial":
assert "Arial" in explanation and "宋体" in explanation and "17" in explanation
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData("preserve"))
assert not hasattr(window, "profile_warning_label")
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData("high_contrast"))
assert not hasattr(window, "profile_warning_label")
assert "深色前景" in window.font_mapping_combo.toolTip()
assert "浅色填充" in window.font_mapping_combo.toolTip()
assert "0.35pt" in window.font_mapping_combo.toolTip()
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData("mono"))
assert not hasattr(window, "profile_warning_label")
assert "黑白" in window.font_mapping_combo.toolTip()
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData("original"))
assert not hasattr(window, "profile_warning_label")
@pytest.mark.parametrize("kind", ["scan", "batch"])
def test_new_controls_lock_and_restore_with_busy_state(qtbot, tmp_path, kind):
window = make_window(qtbot, tmp_path)
controls = (
window.root_edit, window.engine_edit,
window.font_mapping_combo, window.print_theme_combo, window.legacy_gbk_check,
)
window._set_busy(True, kind)
assert all(not control.isEnabled() for control in controls)
assert window.stop_button.isEnabled() == (kind == "batch")
window._set_busy(False, kind)
assert all(control.isEnabled() for control in controls)
def test_blue_gray_palette_has_blue_primary_and_white_cards(qtbot, project_factory, tmp_path):
project_factory()
window = make_window(qtbot, tmp_path)
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 1 and not window.busy, timeout=10000)
qtbot.wait(20)
assert window.start_button.palette().color(QPalette.Button).name() == "#2563eb"
assert window.palette().color(QPalette.Window).name() == "#f1f5f9"
assert window.paths_group.palette().color(QPalette.Window).name() == "#ffffff"
@pytest.mark.parametrize("status, color", [
("success", "#16a34a"), ("skipped", "#d97706"),
("uncertain", "#d97706"), ("failed", "#dc2626"),
("timeout", "#dc2626"),
])
def test_result_status_keeps_semantic_colors(qtbot, project_factory, tmp_path, status, color):
project_factory()
window = make_window(qtbot, tmp_path)
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 1 and not window.busy, timeout=10000)
window._item_result(0, ExportResult(project="board", status=status, message="对照结果"))
assert window.table.item(0, 3).foreground().color().name() == color
def test_selection_and_advanced_controls_do_not_reset_scroll(qtbot, project_factory, tmp_path):
for number in range(45):
project_factory(f"board-{number:02d}")
window = make_window(qtbot, tmp_path)
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 45 and not window.busy, timeout=10000)
scrollbar = window.table.verticalScrollBar()
qtbot.waitUntil(lambda: scrollbar.maximum() > 0)
scrollbar.setValue(scrollbar.maximum() // 2)
position = scrollbar.value()
item = window.table.item(25, 0)
item.setCheckState(Qt.Unchecked)
qtbot.mouseClick(window.select_all_button, Qt.LeftButton)
assert scrollbar.value() == position
assert window.table.item(25, 0) is item
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData("arial"))
qtbot.wait(20)
assert scrollbar.value() == position
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData("arial"))
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData("arial"))
qtbot.wait(20)
assert scrollbar.value() == position
assert window.selected_count() == 45
@pytest.mark.parametrize("theme", ["original", "high_contrast", "mono"])
def test_expanded_advanced_settings_leave_queue_rows_visible(qtbot, project_factory, tmp_path, theme):
for number in range(6):
project_factory(f"board-{number}")
window = make_window(qtbot, tmp_path)
qtbot.mouseClick(window.advanced_button, Qt.LeftButton)
assert window.advanced_panel.isVisible()
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 6 and not window.busy, timeout=10000)
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData("arial"))
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData("arial"))
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData(theme))
qtbot.wait(50)
assert window.table.viewport().visibleRegion().boundingRect().height() >= 2 * window.table.rowHeight(0)
@pytest.mark.parametrize("theme", ["original", "high_contrast", "mono"])
def test_color_selector_only_enabled_for_original_and_restores_after_busy(qtbot, tmp_path, theme):
window = make_window(qtbot, tmp_path)
window.color_combo.setCurrentIndex(window.color_combo.findData(2))
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData(theme))
assert window.color_combo.isEnabled() == (theme == "original")
assert window.color_combo.currentData() == 2
for kind in ("scan", "batch"):
window._set_busy(True, kind)
assert not window.color_combo.isEnabled()
window._set_busy(False, kind)
assert window.color_combo.isEnabled() == (theme == "original")
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData("original"))
assert window.color_combo.isEnabled()
assert window.options().color == 2
@pytest.mark.parametrize("mapping, theme", [
("arial", "high_contrast"), ("simsun", "mono"),
("msyh", "original"), ("preserve", "original"),
])
def test_constructor_accepts_explicit_profile_defaults(qtbot, tmp_path, mapping, theme):
window = MainWindow(root=tmp_path, output=tmp_path / "pdfs", font_mapping=mapping, print_theme=theme)
qtbot.addWidget(window)
window.show()
assert window.font_mapping_combo.currentData() == mapping
assert window.print_theme_combo.currentData() == theme
options = window.options()
assert options.font_mapping == mapping
assert options.print_theme == theme
assert options.color == (3 if theme == "mono" else 4)
assert window.color_combo.isEnabled() == (theme == "original")
assert not hasattr(window, "profile_warning_label")
@pytest.mark.parametrize("defaults, message", [
({"font_mapping": "arail"}, "字体"),
({"print_theme": "unknown"}, "配色"),
])
def test_constructor_rejects_unknown_profile_defaults(qtbot, defaults, message):
with pytest.raises(ValueError, match=message):
MainWindow(**defaults)
@pytest.mark.parametrize("mapping, theme", [
("arial", "original"), ("preserve", "high_contrast"), ("msyh", "mono"),
])
def test_profile_tooltips_expose_limited_compatibility_scope(qtbot, tmp_path, mapping, theme):
window = make_window(qtbot, tmp_path)
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData(mapping))
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData(theme))
assert not hasattr(window, "profile_warning_label")
assert "兼容范围有限" in window.font_mapping_combo.toolTip()
assert "其他工程" in window.font_mapping_combo.toolTip()
explanation = window.font_mapping_combo.toolTip()
assert "不代表所有 PDF" in explanation
assert "字体" in explanation and "文字结构" in explanation
assert "样张" in explanation
assert "未验证" not in explanation and "未生效" not in explanation
def test_legacy_gbk_is_explicit_and_respects_disabled_override(qtbot, tmp_path):
window = make_window(qtbot, tmp_path)
assert window.legacy_gbk_check.text() == "CP936 / GBK 修复"
assert not window.legacy_gbk_check.isChecked()
assert window.options().legacy_gbk is False
explanation = window.legacy_gbk_check.toolTip()
assert "WinAnsi" in explanation and "±" in explanation and "×" in explanation
assert "不适用于" in explanation
assert "已确认" in explanation
assert "Arial" in explanation and "不等于编码修复" in explanation
@pytest.mark.parametrize("mapping", ["arial", "simsun", "msyh"])
def test_font_mapping_alone_does_not_enable_encoding_repair(qtbot, tmp_path, mapping):
window = make_window(qtbot, tmp_path)
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData(mapping))
assert window.options().font_mapping == mapping
assert window.options().legacy_gbk is False
assert not window.legacy_gbk_check.isChecked()
assert "不自动修复编码" in window.font_mapping_combo.toolTip()
@pytest.mark.parametrize("mapping", ["arial", "simsun", "msyh"])
def test_explicit_legacy_gbk_flows_to_options(qtbot, tmp_path, mapping):
window = make_window(qtbot, tmp_path)
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData(mapping))
# Matches the CLI follow-up: explicitly opt in after constructing the window.
window.legacy_gbk_check.setChecked(True)
assert window.options().legacy_gbk is True
assert window.options().font_mapping == mapping
assert "CP936 / GBK" in window.font_mapping_combo.toolTip()
assert "修复" in window.font_mapping_combo.toolTip()
window.legacy_gbk_check.setChecked(False)
assert window.options().legacy_gbk is False
assert "不自动修复编码" in window.font_mapping_combo.toolTip()
def test_legacy_gbk_rejects_preserve_without_silently_changing_font(qtbot, tmp_path):
window = make_window(qtbot, tmp_path)
window.legacy_gbk_check.setChecked(True)
assert window.font_mapping_combo.currentData() == "preserve"
with pytest.raises(ValueError) as error:
window.options()
message = str(error.value)
for choice in ("Arial", "SimSun", "YaHei"):
assert choice in message
assert "选择" in message
window.legacy_gbk_check.setChecked(False)
assert window.options().legacy_gbk is False
def test_recommended_constructor_profiles_respect_disabled_legacy_gbk_override(qtbot, tmp_path):
window = MainWindow(root=tmp_path, font_mapping="arial", print_theme="high_contrast", legacy_gbk=False)
qtbot.addWidget(window)
window.show()
assert not window.legacy_gbk_check.isChecked()
assert window.options().legacy_gbk is False
assert window.options().color == 4
assert "不自动修复编码" in window.font_mapping_combo.toolTip()
def test_reference_palette_is_recommended_and_font_repair_is_independent(qtbot, tmp_path):
window = MainWindow(root=tmp_path);qtbot.addWidget(window);window.show()
assert window.print_theme_combo.currentText() == "工程参考配色(推荐)"
explanation = window.print_theme_combo.toolTip()
for detail in ("红色", "青绿色", "原生线宽", "界面", "字体", "子进程"):
assert detail in explanation
window.legacy_gbk_check.setChecked(False)
assert window.options().print_theme == "reference"
assert window.options().color == 4
assert not window.options().legacy_gbk
assert "子进程" in window.font_mapping_combo.toolTip()
def test_direct_mode_discloses_native_database_write_risk(qtbot, tmp_path):
window = make_window(qtbot, tmp_path)
assert not hasattr(window, "source_warning_label")
text = window.strict_source_check.toolTip()
for detail in ("原生引擎", "数据库", "待核验", "不发布"):
assert detail in text
def test_heading_has_no_engine_status_badge(qtbot, tmp_path):
window = make_window(qtbot, tmp_path)
assert not hasattr(window, "environment_label")
assert not window.findChildren(QLabel, "badge")
assert not any("已找到 Mentor" in label.text() for label in window.findChildren(QLabel))
@pytest.mark.parametrize("kind", ["scan", "batch"])
def test_busy_queue_can_scroll_but_cannot_change_selection(qtbot, project_factory, tmp_path, kind):
for number in range(45):
project_factory(f"queue-{number:02d}")
window = make_window(qtbot, tmp_path)
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 45 and not window.busy, timeout=10000)
scrollbar = window.table.verticalScrollBar()
qtbot.waitUntil(lambda: scrollbar.maximum() > 0)
before = [window.table.item(row, 0).checkState() for row in range(45)]
window._set_busy(True, kind)
try:
assert window.table.isEnabled()
assert scrollbar.isEnabled()
assert not window.select_all_button.isEnabled()
assert not window.clear_button.isEnabled()
assert not window.select_failed_button.isEnabled()
assert all(not (window.table.item(row, 0).flags() & Qt.ItemIsUserCheckable) for row in range(45))
scrollbar.setFocus()
qtbot.keyClick(scrollbar, Qt.Key_End)
assert scrollbar.value() == scrollbar.maximum()
qtbot.keyClick(scrollbar, Qt.Key_Home)
assert scrollbar.value() == scrollbar.minimum()
window.table.setCurrentCell(0, 0)
rect = window.table.visualItemRect(window.table.item(0, 0))
qtbot.mouseClick(window.table.viewport(), Qt.LeftButton, pos=rect.center())
qtbot.keyClick(window.table, Qt.Key_Space)
assert [window.table.item(row, 0).checkState() for row in range(45)] == before
finally:
window._set_busy(False, kind)
assert all(window.table.item(row, 0).flags() & Qt.ItemIsUserCheckable for row in range(45))
window.table.setCurrentCell(0, 0)
qtbot.keyClick(window.table, Qt.Key_Space)
assert window.table.item(0, 0).checkState() == Qt.Unchecked
def test_running_worker_keeps_queue_browsable_and_shows_direct_mode(qtbot, project_factory, tmp_path):
for number in range(30):
project_factory(f"active-{number:02d}")
started = threading.Event()
def waiting(args, cwd, log_dir, cancel, timeout, on_event=None, *, env=None):
started.set()
if cancel.wait(30):
raise InterruptedError("任务已停止")
raise TimeoutError("test worker did not receive stop")
window = make_window(qtbot, tmp_path, lambda engine, runs: Exporter(engine, runs, runner=waiting))
engine = tmp_path / "sch2pdf.exe"
engine.write_bytes(b"fake")
window.engine_edit.setText(str(engine))
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 30 and not window.busy, timeout=10000)
window.start_export()
try:
qtbot.waitUntil(started.is_set, timeout=10000)
assert window.busy and window.table.isEnabled()
scrollbar = window.table.verticalScrollBar()
scrollbar.setFocus()
qtbot.keyClick(scrollbar, Qt.Key_End)
assert scrollbar.maximum() > 0 and scrollbar.value() == scrollbar.maximum()
assert "直接" in window.status_label.text()
assert "副本" not in window.status_label.text()
assert "副本" not in window.table.item(0, 4).text()
assert "副本" not in window.log.placeholderText()
finally:
window.stop_export()
qtbot.waitUntil(lambda: not window.busy, timeout=10000)
assert window.table.item(0, 0).flags() & Qt.ItemIsUserCheckable
def test_native_update_warning_is_success_not_uncertain_in_ui(qtbot,project_factory,tmp_path):
project_factory();window=make_window(qtbot,tmp_path);window.scan_projects()
qtbot.waitUntil(lambda:window.table.rowCount()==1 and not window.busy,timeout=10000)
result=ExportResult(project='board',status='success',message='PDF valid; native database updated, not read-only',pages=1,warnings=('native update',))
window._item_result(0,result)
assert window.table.item(0,3).text()=='成功(有提示)'
assert window.table.columnWidth(3) >= 110
assert window.table.item(0,3).foreground().color().name()=='#d97706'
assert '1 页' in window.table.item(0,4).text()
assert 'native database' in window.table.item(0,4).toolTip()
def test_strict_source_check_is_optional_and_locks_during_export(qtbot,tmp_path):
window=make_window(qtbot,tmp_path)
assert not window.strict_source_check.isChecked() and not window.options().strict_source
assert '不阻止' in window.strict_source_check.toolTip()
window.strict_source_check.setChecked(True)
assert window.options().strict_source and '严格' in window.strict_source_check.toolTip()
window._set_busy(True)
assert not window.strict_source_check.isEnabled()
window._set_busy(False)
assert window.strict_source_check.isEnabled()
def test_batch_native_update_warnings_publish_and_count_as_success(qtbot,project_factory,tmp_path):
project_factory('one');project_factory('two')
def updating(args,cwd,logs,cancel,timeout,on_event=None, *, env=None):
rc=runner(args,cwd,logs,cancel,timeout,on_event)
(Path(cwd)/'database/icdb.dat').write_bytes(b'native update')
return rc
window=make_window(qtbot,tmp_path,lambda engine,runs:Exporter(engine,runs,runner=updating))
engine=tmp_path/'sch2pdf.exe';engine.write_bytes(b'fake');window.engine_edit.setText(str(engine))
window.scan_projects();qtbot.waitUntil(lambda:window.table.rowCount()==2 and not window.busy,timeout=10000)
window.start_export();qtbot.waitUntil(lambda:not window.busy,timeout=10000)
assert [window.table.item(row,3).text() for row in range(2)]==['成功(有提示)']*2
assert '成功 2' in window.status_label.text() and '有提示 2' in window.status_label.text()
assert all(Path(r.output).is_file() and r.warnings for r in window.worker.results)
+239
View File
@@ -0,0 +1,239 @@
from pathlib import Path
import pytest
from PySide6.QtCore import QPoint, Qt
from PySide6.QtWidgets import QLabel, QPushButton
from pypdf import PdfWriter
from mentor_pdf_export.exporter import Exporter
from mentor_pdf_export.models import ExportResult
from mentor_pdf_export.ui import MainWindow
@pytest.fixture
def compact_window(qtbot, tmp_path):
window = MainWindow(
root=tmp_path, output=tmp_path / "pdfs",
runs_root=tmp_path.parent / (tmp_path.name + "-runs"),
)
qtbot.addWidget(window)
window.show()
qtbot.waitUntil(lambda: window.isVisible())
return window
def visible_labels(window):
return [label.text() for label in window.findChildren(QLabel) if label.isVisible()]
@pytest.mark.parametrize("mapping,theme,strict", [
("arial", "reference", False), ("simsun", "high_contrast", True),
("preserve", "original", False), ("msyh", "mono", True),
])
def test_no_explanatory_paragraphs_in_any_profile(compact_window, mapping, theme, strict):
window = compact_window
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData(mapping))
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData(theme))
window.strict_source_check.setChecked(strict)
forbidden = (
"直接导出原工程", "依赖库", "默认工程参考配色", "发布前", "兼容范围",
"源文件变化", "原生引擎可能", "有效许可证", "不创建副本", "样本",
)
labels = visible_labels(window)
assert not [text for text in labels if any(phrase in text for phrase in forbidden)]
assert all(not label.wordWrap() for label in window.findChildren(QLabel) if label.isVisible())
assert not any("引擎" in text for text in labels if "导出引擎" != text)
def test_default_geometry_prioritizes_queue_and_compact_log(compact_window, qtbot):
window = compact_window
window.resize(1200, 820)
qtbot.wait(30)
assert window.table.height() >= 330
assert 60 <= window.log.height() <= 100
assert window.table.height() >= 3 * window.log.height()
assert window.table.visibleRegion().boundingRect().height() == window.table.height()
assert window.font_mapping_combo.currentData() == "arial"
assert window.print_theme_combo.currentData() == "reference"
assert window.legacy_gbk_check.isChecked()
assert window.options().legacy_gbk
def test_path_rows_and_option_columns_are_aligned(compact_window):
window = compact_window
paths = (window.root_edit, window.output_edit, window.engine_edit)
lefts = [widget.mapTo(window, QPoint()).x() for widget in paths]
assert len(set(lefts)) == 1
assert len({widget.width() for widget in paths}) == 1
assert len({widget.height() for widget in paths}) == 1
buttons = [button for button in window.paths_group.findChildren(QPushButton)
if button.text() in {"选择目录", "选择引擎"}]
assert len(buttons) == 3
assert len({button.width() for button in buttons}) == 1
for first, second in ((window.print_theme_combo, window.color_combo),
(window.font_mapping_combo, window.scope_combo)):
assert first.mapTo(window, QPoint()).x() == second.mapTo(window, QPoint()).x()
assert first.height() == second.height()
for widget in (*paths, window.print_theme_combo, window.font_mapping_combo,
window.scope_combo, window.timeout_spin):
assert window.rect().contains(widget.mapTo(window, widget.rect().bottomRight()))
@pytest.mark.parametrize("kind", ["scan", "batch"])
def test_busy_queue_scrolls_without_checkbox_or_settings_changes(compact_window, project_factory, qtbot, kind):
window = compact_window
for number in range(60):
project_factory(f"board-{number:02d}")
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 60 and not window.busy, timeout=10000)
qtbot.waitUntil(lambda: window.table.verticalScrollBar().maximum() > 0)
before = [window.table.item(row, 0).checkState() for row in range(60)]
window._set_busy(True, kind)
try:
assert window.table.isEnabled()
assert not window.options_group.isEnabled()
assert not window.root_edit.isEnabled()
assert not window.strict_source_check.isEnabled()
assert not window.stroke_check.isEnabled()
scrollbar = window.table.verticalScrollBar()
scrollbar.setFocus()
qtbot.keyClick(scrollbar, Qt.Key_End)
assert scrollbar.maximum() > 0 and scrollbar.value() == scrollbar.maximum()
qtbot.keyClick(scrollbar, Qt.Key_Home)
assert scrollbar.value() == 0
window.table.setCurrentCell(0, 0)
qtbot.mouseClick(window.table.viewport(), Qt.LeftButton,
pos=window.table.visualItemRect(window.table.item(0, 0)).center())
qtbot.keyClick(window.table, Qt.Key_Space)
assert [window.table.item(row, 0).checkState() for row in range(60)] == before
finally:
window._set_busy(False, kind)
assert window.strict_source_check.isEnabled()
assert window.stroke_check.isEnabled()
def test_worker_log_filters_bookkeeping_but_keeps_results_and_errors(compact_window, project_factory, tmp_path, qtbot):
window = compact_window
project_factory()
detail = "字体校验异常:无法读取字体映射"
bookkeeping = (
"核验原工程;直接读取,不创建工程副本或备份",
"原生引擎已启动,PID=1234", "等待原生引擎,已用时 10 秒",
"直接读取原工程;参考配色仅覆盖导出子进程配置,字体修复仅处理输出 PDF",
"字体/配色完成:转换 10 段文字,修复 2 段编码,中文回退 2 段",
"发布前验证 PDF 结构、页数与源工程内容指纹",
f"源工程路径:{tmp_path}",
)
def runner(args, cwd, logs, cancel, timeout, on_event=None, *, env=None):
for message in (*bookkeeping, detail):
on_event(message)
writer = PdfWriter()
writer.add_blank_page(width=500, height=400)
with Path(args[args.index("-a") + 1]).open("wb") as stream:
writer.write(stream)
return 0
window.exporter_factory = lambda engine, runs: Exporter(engine, runs, runner=runner)
engine = tmp_path / "sch2pdf.exe"
engine.write_bytes(b"fake")
window.engine_edit.setText(str(engine))
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 1 and not window.busy, timeout=10000)
window.start_export()
qtbot.waitUntil(lambda: not window.busy, timeout=10000)
text = window.log.toPlainText()
assert not any(message in text for message in bookkeeping)
assert "PID=" not in text and "批量报告:" not in text
assert "扫描" in text and "board" in text and "成功" in text and "队列结束" in text
assert detail in text
assert len(text.splitlines()) <= 8
def test_detailed_failure_reason_stays_in_tooltip_without_growing_layout(compact_window, project_factory, qtbot):
window = compact_window
project_factory()
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 1 and not window.busy, timeout=10000)
height = window.table.height()
detail = "PDF 字体校验失败:缺少字体资源\n" + "缺失对象 123;" * 90
window._item_result(0, ExportResult(project="board", status="failed", message=detail))
window._scan_failed(detail)
qtbot.wait(20)
assert window.table.item(0, 4).toolTip() == detail
assert "缺少字体资源" in window.table.item(0, 4).text()
assert len(window.table.item(0, 4).text()) <= 160
assert window.status_label.toolTip() == detail
assert "字体校验失败" in window.status_label.text()
assert len(window.status_label.text()) <= 160 and "\n" not in window.status_label.text()
assert window.table.height() == height
assert all(len(line) <= 180 for line in window.log.toPlainText().splitlines())
def test_advanced_controls_are_collapsed_and_reachable_without_queue_reset(compact_window, project_factory, qtbot):
window = compact_window
for number in range(45):
project_factory(f"advanced-{number:02d}")
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 45 and not window.busy, timeout=10000)
scrollbar = window.table.verticalScrollBar()
qtbot.waitUntil(lambda: scrollbar.maximum() > 0)
scrollbar.setValue(scrollbar.maximum() // 2)
position = scrollbar.value()
item = window.table.item(25, 0)
assert not window.advanced_panel.isVisible()
assert not window.strict_source_check.isVisible()
qtbot.mouseClick(window.advanced_button, Qt.LeftButton)
qtbot.waitUntil(lambda: window.advanced_panel.isVisible())
assert window.strict_source_check.isVisible() and window.stroke_check.isVisible()
qtbot.mouseClick(window.strict_source_check, Qt.LeftButton)
assert window.options().strict_source
assert window.table.item(25, 0) is item and scrollbar.value() == position
window._set_busy(True)
assert not window.advanced_button.isEnabled()
assert not window.strict_source_check.isEnabled()
window._set_busy(False)
qtbot.mouseClick(window.advanced_button, Qt.LeftButton)
qtbot.waitUntil(lambda: not window.advanced_panel.isVisible())
assert window.options().strict_source
assert window.table.item(25, 0) is item and scrollbar.value() == position
@pytest.mark.parametrize("message", [
"无法写入批量记录:权限不足", "PDF warning: missing glyph", "Unable to read PDF resources",
])
def test_worker_actionable_messages_are_not_filtered(compact_window, message):
compact_window._worker_message(message)
assert message in compact_window.log.toPlainText()
def test_selected_only_retry_passes_full_scanned_list_to_worker(compact_window, project_factory, qtbot, monkeypatch, tmp_path):
from unittest.mock import MagicMock
window = compact_window
for relative, name in (("left/Work", "Work"), ("right/Work", "Work"),
("left/Cert", "Cert"), ("right/Cert", "Cert")):
project_factory(relative, name=name)
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 4 and not window.busy, timeout=10000)
window.table.item(0, 3).setText("失败")
window.select_failed()
assert window.selected_count() == 1
captured = {}
worker = MagicMock()
def make_worker(items, output, options, exporter, parent=None, *, all_projects=None):
captured.update(items=items, all_projects=all_projects, parent=parent)
return worker
monkeypatch.setattr("mentor_pdf_export.ui.BatchWorker", make_worker)
window.exporter_factory = lambda engine, runs: object()
engine = tmp_path / "sch2pdf.exe"
engine.write_bytes(b"fake")
window.engine_edit.setText(str(engine))
window.start_export()
try:
worker.start.assert_called_once()
assert captured["items"] == [(0, window.projects[0])]
assert captured["all_projects"] is window.projects
assert len(captured["all_projects"]) == 4
assert captured["parent"] is window
finally:
window._set_busy(False)
+19
View File
@@ -50,3 +50,22 @@ def test_library_override_preserves_next_project_line(project_factory, tmp_path)
copied=prepare_workspace(source,tmp_path/"run",ExportOptions(library_override=str(library))) copied=prepare_workspace(source,tmp_path/"run",ExportOptions(library_override=str(library)))
lines=copied.read_text().splitlines() lines=copied.read_text().splitlines()
assert 'KEY DxD_Version "7.9.4"' in lines assert 'KEY DxD_Version "7.9.4"' in lines
def test_empty_library_override_preserves_project_bytes(project_factory,tmp_path):
source=project_factory()
source.write_text(source.read_text()+'KEY CentralLibrary "\\\\server\\library\\original.lmc"\n')
before=source.read_bytes()
copied=prepare_workspace(source,tmp_path/"run",ExportOptions(library_override=""))
assert copied.read_bytes()==before
assert source.read_bytes()==before
def test_compare_fingerprints_reports_sorted_added_removed_and_modified():
from mentor_pdf_export.workspace import compare_fingerprints
before = {"stable": "same", "db/b": "old", "db/a": "old", "deleted": "gone"}
after = {"stable": "same", "db/b": "new", "db/a": "new", "new/z": "z", "new/a": "a"}
assert compare_fingerprints(before, after) == {
"modified": ["db/a", "db/b"], "added": ["new/a", "new/z"], "removed": ["deleted"]
}
assert compare_fingerprints(before, before) == {"modified": [], "added": [], "removed": []}