From 0334f2b85b2d2de5c3fa695fe2527b80c29e8176 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Sat, 10 Oct 2026 16:28:18 +0800 Subject: [PATCH] release: ship validated Mentor PDF exporter v1.0.0 --- .gitignore | 5 + CHANGELOG.md | 16 + README.md | 92 ++-- Start-MentorPDF.cmd | 4 +- docs/releases/1.0.0.md | 28 ++ .../2026-10-09-ui-dependency-font-color.md | 34 ++ .../2026-10-10-v03-reference-preview.md | 50 ++ docs/testing/2026-10-10-v031-ui-fix.md | 50 ++ docs/testing/2026-10-10-v032-native-policy.md | 66 +++ .../2026-10-10-v033-reference-quality.md | 59 +++ .../2026-10-10-v034-compact-and-failures.md | 46 ++ packaging/ICON-NOTICE.md | 7 + packaging/MentorPDFExporter.spec | 25 +- packaging/build_release.py | 223 +++++++++ packaging/generate_icon.py | 46 ++ packaging/publish_release.py | 214 +++++++++ packaging/requirements-release.txt | 5 +- packaging/verify_release.py | 134 ++++++ pyproject.toml | 7 +- src/mentor_pdf_export/__init__.py | 2 +- src/mentor_pdf_export/assets/app.ico | Bin 0 -> 24794 bytes src/mentor_pdf_export/assets/app.png | Bin 0 -> 11112 bytes src/mentor_pdf_export/assets/app.svg | 15 + src/mentor_pdf_export/branding.py | 48 ++ src/mentor_pdf_export/cli.py | 34 +- src/mentor_pdf_export/engine.py | 36 +- src/mentor_pdf_export/exporter.py | 101 ++-- src/mentor_pdf_export/models.py | 13 + src/mentor_pdf_export/naming.py | 45 ++ src/mentor_pdf_export/pdf_fonts.py | 119 +++++ src/mentor_pdf_export/pdf_styles.py | 350 ++++++++++++++ src/mentor_pdf_export/profiles.py | 56 ++- src/mentor_pdf_export/source_policy.py | 33 ++ src/mentor_pdf_export/ui.py | 440 ++++++++++++----- src/mentor_pdf_export/workers.py | 19 +- src/mentor_pdf_export/workspace.py | 12 +- tests/test_cli.py | 66 ++- tests/test_engine.py | 39 ++ tests/test_exporter.py | 140 +++++- tests/test_output_names.py | 72 +++ tests/test_pdf_styles.py | 330 +++++++++++++ tests/test_profiles.py | 28 ++ tests/test_reference_profile.py | 68 +++ tests/test_release_branding.py | 124 +++++ tests/test_release_packaging.py | 111 +++++ tests/test_release_publish.py | 37 ++ tests/test_source_policy.py | 61 +++ tests/test_ui.py | 449 +++++++++++++++++- tests/test_ui_compact.py | 239 ++++++++++ tests/test_workspace.py | 19 + 50 files changed, 3998 insertions(+), 219 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 docs/releases/1.0.0.md create mode 100644 docs/superpowers/plans/2026-10-09-ui-dependency-font-color.md create mode 100644 docs/testing/2026-10-10-v03-reference-preview.md create mode 100644 docs/testing/2026-10-10-v031-ui-fix.md create mode 100644 docs/testing/2026-10-10-v032-native-policy.md create mode 100644 docs/testing/2026-10-10-v033-reference-quality.md create mode 100644 docs/testing/2026-10-10-v034-compact-and-failures.md create mode 100644 packaging/ICON-NOTICE.md create mode 100644 packaging/build_release.py create mode 100644 packaging/generate_icon.py create mode 100644 packaging/publish_release.py create mode 100644 packaging/verify_release.py create mode 100644 src/mentor_pdf_export/assets/app.ico create mode 100644 src/mentor_pdf_export/assets/app.png create mode 100644 src/mentor_pdf_export/assets/app.svg create mode 100644 src/mentor_pdf_export/branding.py create mode 100644 src/mentor_pdf_export/naming.py create mode 100644 src/mentor_pdf_export/pdf_fonts.py create mode 100644 src/mentor_pdf_export/pdf_styles.py create mode 100644 src/mentor_pdf_export/source_policy.py create mode 100644 tests/test_output_names.py create mode 100644 tests/test_pdf_styles.py create mode 100644 tests/test_reference_profile.py create mode 100644 tests/test_release_branding.py create mode 100644 tests/test_release_packaging.py create mode 100644 tests/test_release_publish.py create mode 100644 tests/test_source_policy.py create mode 100644 tests/test_ui_compact.py diff --git a/.gitignore b/.gitignore index dc09333..32b3e9f 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,8 @@ __pycache__/ *.prj *.pdf *.zip + +# Local engineering references and evidence are never published. +/PDF参考/ +*.lmc +*.log diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..88f47ab --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,16 @@ +# 更新记录 + +## 1.0.0 — 2026-10-10 + +首个正式版,延续已验收的直接导出、参考配色和中文修复行为。 + +- 原工程名输出;同名版本使用自然子目录,不添加摘要后缀。 +- 修复安全 ASCII 笔画隐藏检索层被误拦截的问题,保留原有矢量内容。 +- 精简界面说明,统一控件对齐,扩大工程队列,执行时支持滚动。 +- 简化可见日志,保留完整运行记录和失败重试。 +- 统一正式产品名称、版本号、窗口 / 任务栏 / EXE 图标及 Windows 文件属性。 +- 添加可重复构建、包校验与组织仓库发行流程。 + +## 0.3.x — 内部验证阶段 + +完成原生引擎、源保护、编码、配色、批量扫描和成品验证。历史内部测试记录不作为所有工程、平台或 Mentor 版本的兼容性保证。 diff --git a/README.md b/README.md index a87826b..1240801 100644 --- a/README.md +++ b/README.md @@ -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、备份、输出、运行目录;会完整递归而不是根目录发现工程后提前结束。 -2. 选择源工程外部的 PDF 输出目录。工程名相同的项目通过路径摘要区分,不会互相覆盖。 -3. 检查自动发现的 `sch2pdf.exe`,必要时手动选择。 -4. 网络中心库不可达时,显式选择对应本地 `.lmc`。工具只修改工作副本的 `CentralLibrary`,不改源工程;不会自动选择可能不匹配的库。 -5. 勾选工程,确认配置,然后开始导出。默认不覆盖已有 PDF。失败项可通过“选中失败项重试”重新执行。 -6. 可以停止当前任务及后续队列;仅结束工具启动的引擎进程树,不关闭用户的 DxDesigner。 +从组织仓库的 **Releases / 发行版** 下载 `MentorPDFExporter-1.0.0-win64.zip`,解压整个文件夹,双击 `MentorPDFExporter.exe`。不能单独复制 EXE,必须保留 `_internal` 文件夹。 -## 配置与安全 +- 用户无需安装 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 -$env:PYTHONPATH = "$(Get-Location)\src" -.\.venv\Scripts\python.exe -m mentor_pdf_export +python -m venv .venv +.\.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 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 或发行包。 diff --git a/Start-MentorPDF.cmd b/Start-MentorPDF.cmd index 854a8d3..95541b6 100644 --- a/Start-MentorPDF.cmd +++ b/Start-MentorPDF.cmd @@ -1,8 +1,8 @@ @echo off setlocal cd /d "%~dp0" -if exist "%~dp0release\MentorPDFExporter\MentorPDFExporter.exe" ( - start "" "%~dp0release\MentorPDFExporter\MentorPDFExporter.exe" +if exist "%~dp0release\MentorPDFExporter-1.0.0\MentorPDFExporter.exe" ( + start "" "%~dp0release\MentorPDFExporter-1.0.0\MentorPDFExporter.exe" exit /b 0 ) if exist "%~dp0.venv\Scripts\pythonw.exe" ( diff --git a/docs/releases/1.0.0.md b/docs/releases/1.0.0.md new file mode 100644 index 0000000..bb03ad6 --- /dev/null +++ b/docs/releases/1.0.0.md @@ -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 成员均有拒绝回归。 diff --git a/docs/superpowers/plans/2026-10-09-ui-dependency-font-color.md b/docs/superpowers/plans/2026-10-09-ui-dependency-font-color.md new file mode 100644 index 0000000..1e875f4 --- /dev/null +++ b/docs/superpowers/plans/2026-10-09-ui-dependency-font-color.md @@ -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. diff --git a/docs/testing/2026-10-10-v03-reference-preview.md b/docs/testing/2026-10-10-v03-reference-preview.md new file mode 100644 index 0000000..5fd60f7 --- /dev/null +++ b/docs/testing/2026-10-10-v03-reference-preview.md @@ -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。 +- 本轮只读审查未发现阻塞问题;这不改变上文原生数据库变化风险。 diff --git a/docs/testing/2026-10-10-v031-ui-fix.md b/docs/testing/2026-10-10-v031-ui-fix.md new file mode 100644 index 0000000..c7f0805 --- /dev/null +++ b/docs/testing/2026-10-10-v031-ui-fix.md @@ -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。 diff --git a/docs/testing/2026-10-10-v032-native-policy.md b/docs/testing/2026-10-10-v032-native-policy.md new file mode 100644 index 0000000..ccbcf1a --- /dev/null +++ b/docs/testing/2026-10-10-v032-native-policy.md @@ -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。 diff --git a/docs/testing/2026-10-10-v033-reference-quality.md b/docs/testing/2026-10-10-v033-reference-quality.md new file mode 100644 index 0000000..f3e6bf4 --- /dev/null +++ b/docs/testing/2026-10-10-v033-reference-quality.md @@ -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 的公式区域)仍可能重叠,字体修复保持原定位,不自动重新排版。旧参考与当前工程内容可能来自不同修订,不承诺逐字/逐像素相同。数据库/运行记录写回默认提示并非只读或设计语义不变保证。 diff --git a/docs/testing/2026-10-10-v034-compact-and-failures.md b/docs/testing/2026-10-10-v034-compact-and-failures.md new file mode 100644 index 0000000..caacd8c --- /dev/null +++ b/docs/testing/2026-10-10-v034-compact-and-failures.md @@ -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 检查通过。 diff --git a/packaging/ICON-NOTICE.md b/packaging/ICON-NOTICE.md new file mode 100644 index 0000000..a393476 --- /dev/null +++ b/packaging/ICON-NOTICE.md @@ -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. diff --git a/packaging/MentorPDFExporter.spec b/packaging/MentorPDFExporter.spec index 2479680..cb52134 100644 --- a/packaging/MentorPDFExporter.spec +++ b/packaging/MentorPDFExporter.spec @@ -1,14 +1,33 @@ # Portable onedir bundle: no Mentor binaries, licenses or private projects. from pathlib import Path import sys +import tomllib +from PyInstaller.utils.win32.versioninfo import VSVersionInfo, FixedFileInfo, StringFileInfo, StringTable, StringStruct, VarFileInfo, VarStruct sys.path.insert(0, SPECPATH) from bundle_policy import filter_binaries 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( [str(root / "packaging" / "entrypoint.py")], pathex=[str(root / "src")], binaries=[], - datas=[], + datas=[(str(assets), "mentor_pdf_export/assets")], hiddenimports=["win32job", "win32api", "win32con"], hookspath=[], hooksconfig={}, @@ -20,7 +39,7 @@ analysis = Analysis( analysis.binaries = filter_binaries(analysis.binaries) pyz = PYZ(analysis.pure) 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) coll = COLLECT(exe, analysis.binaries, analysis.datas, strip=False, upx=False, - name="MentorPDFExporter") + name=f"MentorPDFExporter-{version}") diff --git a/packaging/build_release.py b/packaging/build_release.py new file mode 100644 index 0000000..7bf6b31 --- /dev/null +++ b/packaging/build_release.py @@ -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()) diff --git a/packaging/generate_icon.py b/packaging/generate_icon.py new file mode 100644 index 0000000..96fe0a4 --- /dev/null +++ b/packaging/generate_icon.py @@ -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(" 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()) diff --git a/packaging/requirements-release.txt b/packaging/requirements-release.txt index e087714..90e6f82 100644 --- a/packaging/requirements-release.txt +++ b/packaging/requirements-release.txt @@ -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 pypdf==6.20.0 pywin32==312 PyInstaller==6.22.3 +fonttools==4.66.1 +cryptography==45.0.7 +cffi==2.1.1 diff --git a/packaging/verify_release.py b/packaging/verify_release.py new file mode 100644 index 0000000..583290f --- /dev/null +++ b/packaging/verify_release.py @@ -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()) diff --git a/pyproject.toml b/pyproject.toml index 44a1b2e..37f012b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,10 +4,10 @@ build-backend = "setuptools.build_meta" [project] name = "mentor-pdf-export" -version = "0.1.0" +version = "1.0.0" description = "Safe native Mentor DxDesigner batch PDF exporter" 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] mentor-pdf-export = "mentor_pdf_export.cli:main" @@ -23,3 +23,6 @@ testpaths = ["tests"] pythonpath = ["src"] addopts = "-ra" cache_dir = "build/pytest-cache" + +[tool.setuptools.package-data] +mentor_pdf_export = ["assets/*.ico", "assets/*.svg", "assets/*.png"] diff --git a/src/mentor_pdf_export/__init__.py b/src/mentor_pdf_export/__init__.py index c4bd2ce..1169d3e 100644 --- a/src/mentor_pdf_export/__init__.py +++ b/src/mentor_pdf_export/__init__.py @@ -1,2 +1,2 @@ """Mentor native batch PDF exporter.""" -__version__ = "0.1.0" +__version__ = "1.0.0" diff --git a/src/mentor_pdf_export/assets/app.ico b/src/mentor_pdf_export/assets/app.ico new file mode 100644 index 0000000000000000000000000000000000000000..576635cfa8c0b1cbd1f23018bd0055e9f6851221 GIT binary patch literal 24794 zcmagFby!HvmgsPUiFL{Z#@05Ec3LN`3Y6<@JWY2QK9;HaP$Q zZzV4ysUZ;Ko1`F@tVZD9{c`6{b?m^Bm#m&{VZGd!i5pn=p%KH&zX40H!TNU@U*QqE zmG;aOs(u4&AW^_)E5tsz-;5PjV}G--kHe=zgAF`4m2;b~Gj2Jnop95%NQxU1%U7@@n5Z~g8Qg}LlnHl?vP5%>P zLu~3!BLJ0#MoPrm<6cBcD2pZZ3QbB`nLK*`m^AfDl$T%_hD;#x%(KlB`F28(QXW+j@;OKd+(3Qm>uqg&`}a)Sv{@z35%P)u zKvsaOPL2&o^R$DqIi=h*JpBFfQ9iUk{PT=gG2)O_X2<80)m~zBHBwZQcJ_!;ma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dai zLPo z;;(FRZmXnNN3S^FocSw#2(U2j^7vGV$yjdAIwqg(D$C;BN7Sux#&20Gdp!}zMvMNa zG&!bgKg#lnK9W_Gw%$QJEsKsm}2!w^g7_ZQZx13AKtT*(^6{EnT1I=AYqn z1?qeW`Y%@>2xbihVAjrpf_xBp%9H`X{a zyB+-^6O18AkzZ$F5}%Em7f2h8F_CurXAggc&b_`t{CBkTs;~S{hc1rFY}?_flbB`S zsGxzG^Ydpj;g-GGhld+$73*Kk>kET2B{A&ch@Tg56o)#FzZeOr$Vo_NlnrTc+`xZF;?jF#ESzFuyBEw4@M?qhE2 z-H0K0<+l!JU|W5fF0OLcXGJ)(8CqY@EPRFYX&AjQ)wtGdA=)KwId8=Y=+)d$?;!n| zPdwe1c)EVSrKygop0M%V^(RqZ({1A1>_a3EoivggrJ-F=% zkAgcN&|f?99|LCEP1wo@d>*3*x#dF&5U`QQ$$1MNFzSh`69rI6v#N?W5v`qLs4xh) z3+3HFlzD|NyDs|#eIQ0N4!hHk+85zg?zun9wMV^1lxN}Hm*wxi(Ts@25|v;0rPdmu zj_0=*T}^Ue>4BDy`z_q(vrSN9~D5(szRaJ3WhCZqaG zRHt44pGI)&QG%VDxAp^NT1bz69F?M3^Q|dGdcq#m+Qt%vRr~9RcVUBVK|?ZP6PFt5 zG*)~7FRH3gw4R|SiRaC>8CynTaQ+TLZ>6NaO&^pITlo5XUS>|2Bv^nbJfi+d^OG{g zMc_i@w-^d7#)#<_AiT5_Jqo%plj>!?)hZM#`XP&aS$`$9j5Yt$O|bxiF&~-o&?r%X z2o^?BFzDVp0^VI$TUKM;6Z%_ixU1GAYLp3hBiM#wqYxnT2C3e^Jt$zuLnW`$a+No6 z23<91e~v^$Ar?JAf*v&b?}ixv18AL_gHKcaIf33s$8g|Ns47r4xWFip-qD Me;=09$TEo&W#< literal 0 HcmV?d00001 diff --git a/src/mentor_pdf_export/assets/app.png b/src/mentor_pdf_export/assets/app.png new file mode 100644 index 0000000000000000000000000000000000000000..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Yl(<_6j;8tiLsA zKwfg}R9ox1y&%Acswxy`Wat2nvD`>nShrftynIQFsZMqIvY*DuroiE zl3Mdw{@4+G$)xQ81_y^#*gUejkT=}`RKX3Ht3lIIEzCqYe0$nCQg}aDosR7P_B=|z b1TWrY=Nnwr=;3((iTuT`nx9Pxhu>#P~W literal 0 HcmV?d00001 diff --git a/src/mentor_pdf_export/assets/app.svg b/src/mentor_pdf_export/assets/app.svg new file mode 100644 index 0000000..6017df1 --- /dev/null +++ b/src/mentor_pdf_export/assets/app.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/src/mentor_pdf_export/branding.py b/src/mentor_pdf_export/branding.py new file mode 100644 index 0000000..55cb2be --- /dev/null +++ b/src/mentor_pdf_export/branding.py @@ -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()) diff --git a/src/mentor_pdf_export/cli.py b/src/mentor_pdf_export/cli.py index 92873a1..9852eb3 100644 --- a/src/mentor_pdf_export/cli.py +++ b/src/mentor_pdf_export/cli.py @@ -12,6 +12,7 @@ from .exporter import Exporter, write_json from .models import ExportOptions from .scanner import read_project from .path_policy import validate_artifact_path, validate_queue_paths +from .naming import plan_output_directories def _print(value): @@ -20,21 +21,30 @@ def _print(value): 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("--report",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("--output",type=Path) parser.add_argument("--runs-root",type=Path) parser.add_argument("--export",nargs="+",type=Path,metavar="PROJECT") parser.add_argument("--timeout",type=float,default=300) 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("--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-export-smoke",action="store_true",help="自动在 UI 内扫描并实际导出;需要 --ui-smoke、--project-root、--output") 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, # including self-check and exception handling. protected_dirs=[project.resolve().parent for project in (args.export or [])] @@ -76,12 +86,12 @@ def main(argv=None) -> int: info=read_project(project) if not info:raise ValueError(f"不是 DxDesigner 原理图工程:{project}") infos.append(info) - validate_queue_paths(infos,args.output,runs_root) + directories=plan_output_directories(infos,args.output,runs_root) preflight_ok=True engine=discover_engine(args.engine) 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 "") - results=[exporter.export(info,args.output,options,threading.Event(),_print) for info in infos] + 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,directory,options,threading.Event(),_print) for info,directory in zip(infos,directories)] data={"tool":"MentorPDFExporter","results":[asdict(result) for result in results]} if args.report: 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.QtWidgets import QApplication 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.setApplicationName("MentorPDFExporter");app.setOrganizationName("MentorTools") - window=MainWindow(root=args.project_root,output=args.output,engine=args.engine,library=args.library,runs_root=args.runs_root) + configure_application(app) + 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) if 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) saved=window.grab().save(str(args.ui_smoke)) 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: 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) def tick(): nonlocal smoke_phase diff --git a/src/mentor_pdf_export/engine.py b/src/mentor_pdf_export/engine.py index 09ce08c..1956a35 100644 --- a/src/mentor_pdf_export/engine.py +++ b/src/mentor_pdf_export/engine.py @@ -76,7 +76,7 @@ def _create_job(process): 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 msvcrt 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, None, True, win32con.CREATE_SUSPENDED | subprocess.CREATE_NO_WINDOW, - None, os.fspath(cwd), startup, + env, os.fspath(cwd), startup, ) process = _WindowsProcess(args, handle, pid) job = _create_job(process) @@ -116,6 +116,8 @@ def _start_windows_process(args, cwd, stdout, stderr, cancel): except BaseException: try: if job is not None: + if process is not None and process.poll() is not None: + _preserve_completed_job_children(job) job.Close() finally: if process is not None: @@ -135,7 +137,15 @@ def _start_windows_process(args, cwd, stdout, stderr, cancel): _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 time 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: try: 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: - 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}") last_heartbeat = started 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} 秒") last_heartbeat = now 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) return process.returncode finally: try: if job is not None: + if process is not None and process.poll() is not None: + _preserve_completed_job_children(job) job.Close() finally: if process is not None: diff --git a/src/mentor_pdf_export/exporter.py b/src/mentor_pdf_export/exporter.py index 89214d9..1f05915 100644 --- a/src/mentor_pdf_export/exporter.py +++ b/src/mentor_pdf_export/exporter.py @@ -5,21 +5,21 @@ import hashlib import json import os from pathlib import Path -import shutil import threading import time import uuid from .engine import run_engine from .models import ExportOptions, ExportResult, ProjectInfo 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 .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: - identity = hashlib.sha256(os.path.normcase(str(project.path.resolve())).encode("utf-8")).hexdigest()[:8] - return Path(output_root) / f"{project.name}__{identity}.pdf" + return Path(output_root) / (Path(project.path).stem + ".pdf") def write_json(path: Path, data) -> None: @@ -40,6 +40,28 @@ def write_json(path: Path, data) -> None: 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: def __init__(self, engine: Path, runs_root: Path, *, runner=run_engine): self.engine = Path(engine) @@ -59,7 +81,9 @@ class Exporter: start = time.monotonic() run = stage = before = final = None published = False - source_verified = False + source_checked = False + source_identical = False + warnings = [] status, message, pages = "failed", "", 0 external = on_event or (lambda message: None) def notify(message): @@ -75,7 +99,12 @@ class Exporter: log.write(datetime.now().isoformat(timespec="seconds") + " " + message + "\n") try: 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() runs_root = self.runs_root.resolve() 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.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)}) - emit("核验源工程并创建独立工作副本") + emit("核验原工程;直接读取,不创建工程副本或备份") before = fingerprint(source_root, cancel) 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) 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) - emit("导出仅操作工作副本;源工程不保存、不修改") - rc = self.runner(args, copied.parent, run, cancel, options.timeout, emit) + env = prepare_native_environment(run, options) + 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) if rc != 0: details = [] @@ -109,22 +139,30 @@ class Exporter: details.append(stream.read().decode("gb18030", errors="replace").strip()) tail = " / ".join(text for text in details if text) 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 结构、页数与源工程内容指纹") check = validate_pdf(stage) write_json(run / "pdf-check.json", asdict(check)) after = fingerprint(source_root, cancel) write_json(run / "source-after.json", after) - if before != after: - status, message = "uncertain", "源工程在任务期间发生变化,未发布 PDF;请检查并重新导出" - else: - source_verified = True + source_identical = before == after + blocked = False + if not source_identical: + 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) - 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) - 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. write_json(run / "result.json", asdict(prepared)) check_cancel(cancel) @@ -136,7 +174,7 @@ class Exporter: os.link(stage, final) stage.unlink() published, stage, pages, status = True, None, check.pages, "success" - message = f"已导出 {pages} 页;发布前源内容指纹一致。图页完整性及字体效果请人工复核。" + message = f"已导出 {pages} 页;PDF 结构与发布前检查通过。" + ("源内容指纹一致。" if source_identical else "存在源数据库/运行记录更新提示。") + "图页完整性及字体效果请人工复核。" except InterruptedError as error: status, message = "cancelled", str(error) except TimeoutError as error: @@ -147,26 +185,31 @@ class Exporter: # Failure-path checks never happen AFTER irrevocable publication. # A source edit after the final pre-commit observation is a new # 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: after = fingerprint(project.path.parent.resolve()) write_json(run / "source-after.json", after) 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: status, message = "uncertain", f"无法完成源工程核验,未发布 PDF:{error}" if stage is not None: try: if stage.exists(): - shutil.copyfile(stage, run / "unpublished.pdf") stage.unlink() except OSError: 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: try: write_json(run / "result.json", asdict(result)) 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) return result diff --git a/src/mentor_pdf_export/models.py b/src/mentor_pdf_export/models.py index 1ddf1e9..b453e47 100644 --- a/src/mentor_pdf_export/models.py +++ b/src/mentor_pdf_export/models.py @@ -11,6 +11,9 @@ class ProjectInfo: @dataclass(frozen=True) class ExportOptions: library_override: str = "" + font_mapping: str = "preserve" + print_theme: str = "original" + legacy_gbk: bool = False color: int = 4 popup: bool = True use_exclusion: bool = True @@ -22,8 +25,17 @@ class ExportOptions: stroke_width: int = 1 timeout: float = 180.0 overwrite: bool = False + strict_source: bool = False 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): raise ValueError("无效颜色模式") if self.timeout <= 0 or self.line_width < 1 or self.stroke_width < 1: @@ -40,3 +52,4 @@ class ExportResult: pages: int = 0 run_dir: str = "" duration: float = 0.0 + warnings: tuple[str, ...] = () diff --git a/src/mentor_pdf_export/naming.py b/src/mentor_pdf_export/naming.py new file mode 100644 index 0000000..6701a28 --- /dev/null +++ b/src/mentor_pdf_export/naming.py @@ -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 diff --git a/src/mentor_pdf_export/pdf_fonts.py b/src/mentor_pdf_export/pdf_fonts.py new file mode 100644 index 0000000..7c66987 --- /dev/null +++ b/src/mentor_pdf_export/pdf_fonts.py @@ -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> ","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() diff --git a/src/mentor_pdf_export/pdf_styles.py b/src/mentor_pdf_export/pdf_styles.py new file mode 100644 index 0000000..f84bdc2 --- /dev/null +++ b/src/mentor_pdf_export/pdf_styles.py @@ -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=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) diff --git a/src/mentor_pdf_export/profiles.py b/src/mentor_pdf_export/profiles.py index be86d16..b731ec5 100644 --- a/src/mentor_pdf_export/profiles.py +++ b/src/mentor_pdf_export/profiles.py @@ -1,8 +1,14 @@ from __future__ import annotations from pathlib import Path +import os +import xml.etree.ElementTree as ET 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: original = path.read_bytes() if path.exists() else b"" encoding = "utf-8" @@ -16,7 +22,7 @@ def write_profile(path: Path, options: ExportOptions) -> None: values = { "AddPopup": str(int(options.popup)), "ChangeIct2Sch": str(int(options.change_ict)), - "Color": str(options.color), + "Color": str(effective_color(options)), "VisibleHLs": "0", "StartAcrobat": "0", "UrlProperties": "", @@ -27,6 +33,10 @@ def write_profile(path: Path, options: ExportOptions) -> None: "SheetOrder": "", "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} lines = [] 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]: - 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: args.append("-p") if options.use_exclusion: @@ -53,10 +63,50 @@ def build_command(engine: Path, project: Path, output: Path, options: ExportOpti args.append("-i2s") if options.stroke_fonts: args.append("-uAll") # Verified on EE 7.9.5; separated -u All fails. - else: + elif options.font_mapping == "preserve": args.append("-udx") if options.stop_at: args.extend(["-l", options.stop_at]) if options.schematic: args.extend(["-schematic", options.schematic]) 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 diff --git a/src/mentor_pdf_export/source_policy.py b/src/mentor_pdf_export/source_policy.py new file mode 100644 index 0000000..f7b2b0a --- /dev/null +++ b/src/mentor_pdf_export/source_policy.py @@ -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 diff --git a/src/mentor_pdf_export/ui.py b/src/mentor_pdf_export/ui.py index c5f466e..c1b024d 100644 --- a/src/mentor_pdf_export/ui.py +++ b/src/mentor_pdf_export/ui.py @@ -8,9 +8,10 @@ from PySide6.QtWidgets import ( QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout, QLabel, QLineEdit, QPushButton, QGroupBox, QComboBox, QCheckBox, QSpinBox, QTableWidget, QTableWidgetItem, QHeaderView, QAbstractItemView, - QPlainTextEdit, QProgressBar, QFileDialog, QMessageBox, QSplitter, + QPlainTextEdit, QProgressBar, QFileDialog, QMessageBox, QSplitter, QToolButton, QSizePolicy, ) from . import __version__ +from .branding import application_icon from .engine import discover_engine from .exporter import Exporter from .models import ExportOptions @@ -25,9 +26,13 @@ def default_data_root() -> Path: 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__() - 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.setMinimumSize(940, 660) 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._queue_rows = [] self._build() - if library: - self.library_edit.setText(str(library)) + self.font_mapping_combo.setCurrentIndex(self.font_mapping_combo.findData(initial_options.font_mapping)) + 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: self.root_edit.setText(str(root)) if output: @@ -51,112 +58,248 @@ class MainWindow(QMainWindow): self.output_edit.setText(str(path.parent / (path.name + "_PDF"))) try: self.engine_edit.setText(str(discover_engine(engine))) - self.environment_label.setText("● 已找到 Mentor 原生引擎") except Exception: if engine: self.engine_edit.setText(str(engine)) - self.environment_label.setText("● 请指定本机 sch2pdf.exe") self._update_selection() def _build(self): - central = QWidget(); self.setCentralWidget(central) - layout = QVBoxLayout(central); layout.setContentsMargins(20,16,20,16); layout.setSpacing(10) - heading = QHBoxLayout() - title = QLabel("Mentor 工程批量导出 PDF"); title.setObjectName("title") - heading.addWidget(title); heading.addStretch() - self.environment_label = QLabel(); self.environment_label.setObjectName("badge"); heading.addWidget(self.environment_label) - layout.addLayout(heading) - subtitle = QLabel("原生导出引擎 · 独立工程副本 · 串行队列 · PDF 结构校验"); subtitle.setObjectName("muted"); layout.addWidget(subtitle) + central = QWidget() + self.setCentralWidget(central) + layout = QVBoxLayout(central) + layout.setContentsMargins(18, 10, 18, 10) + layout.setSpacing(5) + title = QLabel("Mentor 工程批量导出 PDF") + title.setObjectName("title") + layout.addWidget(title) + self.paths_group = QGroupBox("1 工程与输出位置") - grid = QGridLayout(self.paths_group);grid.setColumnStretch(1,1) - self.root_edit = QLineEdit();self.root_edit.setPlaceholderText("选择包含多个原理图工程的目录,自动排除 PCB 与备份") - self.output_edit = QLineEdit();self.output_edit.setPlaceholderText("选择源工程外部的 PDF 输出目录") - self.engine_edit = QLineEdit();self.engine_edit.setPlaceholderText("本机 Mentor 安装目录中的 sch2pdf.exe") - choose_root = QPushButton("选择目录");choose_root.clicked.connect(self.choose_root) - 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) - self.library_edit = QLineEdit();self.library_edit.setPlaceholderText("可选:网络库不可达时选择对应本地 .lmc,仅修改工作副本") - choose_library = QPushButton("选择中心库");choose_library.clicked.connect(self.choose_library) - grid.addWidget(QLabel("本地中心库"),3,0);grid.addWidget(self.library_edit,3,1);grid.addWidget(choose_library,3,2) - library_note=QLabel("可留空");library_note.setObjectName("muted");grid.addWidget(library_note,3,3) + grid = QGridLayout(self.paths_group) + grid.setContentsMargins(10, 6, 10, 6) + grid.setColumnStretch(1, 1) + grid.setVerticalSpacing(5) + self.root_edit = QLineEdit() + self.root_edit.setPlaceholderText("工程根目录") + self.root_edit.setToolTip("依赖库沿用原工程设置,无需选择;路径有误请在 Mentor 配置。工具不替换库、不改工程配色。扫描时排除 PCB 与备份目录。") + self.output_edit = QLineEdit() + self.output_edit.setPlaceholderText("PDF 输出目录") + self.output_edit.setToolTip("输出目录必须位于源工程外部;默认不覆盖已有 PDF。") + self.engine_edit = QLineEdit() + self.engine_edit.setPlaceholderText("sch2pdf.exe") + self.engine_edit.setToolTip("选择本机 Mentor 安装目录中的 sch2pdf.exe;需要有效许可证。") + choose_root = QPushButton("选择目录") + choose_root.clicked.connect(self.choose_root) + 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) + self.options_group = QGroupBox("2 统一导出设置") 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() - for label, value in (("白底彩色 · 保留彩色文字(推荐)",4),("白底黑白 · 保留黑色文字",3),("白底彩色",1),("黑底彩色",2)): - self.color_combo.addItem(label,value) - self.scope_combo = QComboBox();self.scope_combo.addItems(["整工程", "指定原理图 / Block"]) - self.schematic_edit = QLineEdit();self.schematic_edit.setPlaceholderText("填真实原理图名称,不是 Board1");self.schematic_edit.setEnabled(False) - self.scope_combo.currentIndexChanged.connect(lambda value:self.schematic_edit.setEnabled(value==1)) - self.timeout_spin = QSpinBox();self.timeout_spin.setRange(30,3600);self.timeout_spin.setValue(300);self.timeout_spin.setSuffix(" 秒 / 工程") - options.addWidget(QLabel("颜色"),0,0);options.addWidget(self.color_combo,0,1) - options.addWidget(QLabel("范围"),0,2);options.addWidget(self.scope_combo,0,3);options.addWidget(self.schematic_edit,0,4) - options.addWidget(QLabel("超时"),0,5);options.addWidget(self.timeout_spin,0,6) - 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.overwrite_check=QCheckBox("允许覆盖已有 PDF");self.overwrite_check.setObjectName("warning") - checks=QHBoxLayout() - for check in (self.popup_check,self.exclusion_check,self.ict_check,self.stroke_check,self.overwrite_check):checks.addWidget(check) - checks.addStretch();options.addLayout(checks,1,0,1,7) - note=QLabel("固定设置:清空 URL-valued,隐藏可见超链接,线宽 1;批量导出不打开阅读器。字体与掩盖效果请核对样张。") - note.setObjectName("muted");note.setWordWrap(True);options.addWidget(note,2,0,1,7) + for label, value in (("白底彩色 · 保留彩色文字(推荐)", 4), ("白底黑白 · 保留黑色文字", 3), ("白底彩色", 1), ("黑底彩色", 2)): + self.color_combo.addItem(label, value) + self.color_combo.setToolTip("仅原生配色可选择此模式;白底高对比固定白底彩色,黑白打印固定黑白模式。切回原生配色会保留之前的选择。") + self.scope_combo = QComboBox() + self.scope_combo.addItems(["整工程", "指定原理图 / Block"]) + self.schematic_edit = QLineEdit() + self.schematic_edit.setPlaceholderText("原理图名称") + self.schematic_edit.setToolTip("填写真实原理图名称,不是 Board1。") + self.schematic_edit.setEnabled(False) + self.scope_combo.currentIndexChanged.connect(lambda value: self.schematic_edit.setEnabled(value == 1)) + scope = QHBoxLayout() + scope.setContentsMargins(0, 0, 0, 0) + scope.addWidget(self.scope_combo) + scope.addWidget(self.schematic_edit, 1) + self.timeout_spin = QSpinBox() + self.timeout_spin.setRange(30, 3600) + self.timeout_spin.setValue(300) + self.timeout_spin.setSuffix(" 秒 / 工程") + 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) - splitter=QSplitter(Qt.Vertical) - list_panel=QWidget();list_layout=QVBoxLayout(list_panel);list_layout.setContentsMargins(0,0,0,0) - 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) + + splitter = QSplitter(Qt.Vertical) + splitter.setChildrenCollapsible(False) + list_panel = QWidget() + list_layout = QVBoxLayout(list_panel) + list_layout.setContentsMargins(0, 0, 0, 0) + list_layout.setSpacing(5) + 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) - self.table=QTableWidget(0,6);self.table.setHorizontalHeaderLabels(["选择","工程","工程路径","状态","结果","PDF 输出 / 日志"]) - self.table.setEditTriggers(QAbstractItemView.NoEditTriggers);self.table.setAlternatingRowColors(True) - self.table.setSelectionBehavior(QAbstractItemView.SelectRows);self.table.verticalHeader().setVisible(False) + self.table = QTableWidget(0, 6) + self.table.setHorizontalHeaderLabels(["选择", "工程", "工程路径", "状态", "结果", "PDF 输出 / 日志"]) + self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) + self.table.setAlternatingRowColors(True) + self.table.setSelectionBehavior(QAbstractItemView.SelectRows) + self.table.verticalHeader().setVisible(False) self.table.setWordWrap(False) - header=self.table.horizontalHeader();header.setSectionResizeMode(QHeaderView.Interactive) - self.table.setColumnWidth(0,48);self.table.setColumnWidth(1,140);self.table.setColumnWidth(2,290) - self.table.setColumnWidth(3,76);self.table.setColumnWidth(4,150);header.setStretchLastSection(True) - self.table.itemChanged.connect(self._update_selection);list_layout.addWidget(self.table) + self.table.setMinimumHeight(180) + header = self.table.horizontalHeader() + header.setSectionResizeMode(QHeaderView.Interactive) + 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) - log_panel=QWidget();log_layout=QVBoxLayout(log_panel);log_layout.setContentsMargins(0,0,0,0) - 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_panel = QWidget() + log_layout = QVBoxLayout(log_panel) + 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) - self.log=QPlainTextEdit();self.log.setReadOnly(True);self.log.setMaximumBlockCount(2000) - self.log.setPlaceholderText("先扫描工程,再勾选并开始导出。日志会记录副本、原生引擎、校验及错误。") - log_layout.addWidget(self.log);splitter.addWidget(log_panel);splitter.setSizes([330,135]);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("就绪。测试版需要本机 Mentor 及有效许可证;默认不覆盖已有 PDF。");self.status_label.setWordWrap(True);self.status_label.setObjectName("muted");layout.addWidget(self.status_label) + self.log = QPlainTextEdit() + self.log.setReadOnly(True) + self.log.setMaximumBlockCount(500) + self.log.setMinimumHeight(60) + self.log.setMaximumHeight(100) + self.log.setPlaceholderText("扫描与导出结果") + self.log.setToolTip("完整证据与原生进程明细保存在运行记录中。") + log_layout.addWidget(self.log) + 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(""" - QWidget {font-family:'Microsoft YaHei UI';font-size:12px;color:#243443;} - QMainWindow {background:#f4f7fa;} QLabel#title {font-size:23px;font-weight:600;color:#102e3c;} - QLabel#muted {color:#647585;} QLabel#badge {color:#087c72;background:#e1f2ee;padding:7px 10px;border-radius:5px;} - QGroupBox {background:white;border:1px solid #dce4eb;border-radius:7px;margin-top:10px;padding-top:10px;font-weight:600;} + QWidget {font-family:'Microsoft YaHei UI';font-size:12px;color:#334155;} + QMainWindow {background:#f1f5f9;} QLabel#title {font-size:23px;font-weight:600;color:#0f172a;} + QLabel#muted {color:#64748b;} + 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;} - QLineEdit,QComboBox,QSpinBox {background:white;border:1px solid #ccd7e1;border-radius:4px;padding:5px;min-height:19px;} - QPushButton {background:white;border:1px solid #ccd7e1;border-radius:4px;padding:6px 12px;min-height:19px;} - QPushButton:hover {background:#eaf3f5;border-color:#80b8b7;} QPushButton:disabled {color:#a0aeb8;background:#f1f4f7;} - QPushButton#primary {background:#087f78;color:white;border:0;padding:8px 23px;font-weight:600;} - QPushButton#primary:disabled {background:#a8c8c6;} QCheckBox#warning {color:#9d5d14;} + 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:4px 12px;min-height:17px;} + QPushButton:hover {background:#eff6ff;border-color:#93c5fd;} QPushButton:disabled {color:#a0aeb8;background:#f1f4f7;} + QPushButton#primary {background:#2563EB;color:white;border:0;padding:8px 23px;font-weight:600;} + 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;} 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;} 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): path=QFileDialog.getExistingDirectory(self,"选择工程根目录",self.root_edit.text()) if path: @@ -173,29 +316,55 @@ class MainWindow(QMainWindow): path,_=QFileDialog.getOpenFileName(self,"选择 Mentor 原生 sch2pdf.exe",self.engine_edit.text(),"导出引擎 (sch2pdf.exe)") 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): path=Path(value.strip()) if value.strip() else None if path and path.is_dir():QDesktopServices.openUrl(QUrl.fromLocalFile(str(path.resolve()))) else:self.append_log("目录尚不存在;完成一次导出后再打开。") - def append_log(self,message): - self.log.appendPlainText(datetime.now().strftime("%H:%M:%S")+" "+message) + @staticmethod + 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"): 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") def scan_projects(self): if self.busy:return root=self.root_edit.text().strip() if not root or not Path(root).is_dir(): - self.append_log("请选择存在的工程根目录。");self.status_label.setText("工程目录无效。");return - self._set_busy(True,"scan");self.status_label.setText("正在扫描原理图工程,排除 PCB、备份和输出目录……") + self.append_log("请选择存在的工程根目录。");self._set_status("工程目录无效。");return + self._set_busy(True,"scan");self._set_status("正在扫描工程…");self.append_log("开始扫描工程") excluded=[self.runs_root] if self.output_edit.text().strip():excluded.append(Path(self.output_edit.text().strip())) 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)} self.projects=projects;self.table.blockSignals(True);self.table.setRowCount(len(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): item=QTableWidgetItem(text);item.setToolTip(text);self.table.setItem(row,col,item) self.table.blockSignals(False);self._update_selection() - self.append_log(f"发现 {len(projects)} 个原理图工程。PCB 与备份目录已排除。") - self.status_label.setText(f"扫描完成:{len(projects)} 个工程。勾选后开始导出。") + self.append_log(f"扫描完成:{len(projects)} 个工程") + self._set_status(f"扫描完成:{len(projects)} 个工程") 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): self._set_busy(False) @@ -235,10 +407,51 @@ class MainWindow(QMainWindow): 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 _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): schematic=self.schematic_edit.text().strip() if self.scope_combo.currentIndex()==1 else "" 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): 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) exporter=self.exporter_factory(engine,self.runs_root) 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] for row,_ in items: 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.status_label.setText("执行中:仅在副本操作。请勿编辑源工程;可随时请求停止。") + self._set_status("执行中 · 直接导出") 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.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() 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}") def _item_result(self,row,result): self._done+=1;self.progress.setValue(self._done) - item=self.table.item(row,3);item.setText(STATUS.get(result.status,result.status)) - item.setForeground(QColor("#087f78" if result.status=="success" else "#9d5d14" if result.status=="skipped" else "#b64343")) - text=f"{result.pages} 页 · {result.duration:.1f} 秒" if result.status=="success" else result.message + warned = result.status == "success" and bool(result.warnings) + item=self.table.item(row,3);item.setText("成功(有提示)" if warned else STATUS.get(result.status,result.status)) + 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) destination=result.output or result.run_dir or "—" 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): - self.status_label.setText(message);self.append_log("队列结束:"+message) + self._set_status(message);self.append_log("队列结束:"+message) for row in self._queue_rows: if self.table.item(row,3).text() in {"排队中","导出中"}: self.table.item(row,3).setText("未执行");self.table.item(row,4).setText("队列停止,可重新勾选") @@ -288,8 +504,8 @@ class MainWindow(QMainWindow): def stop_export(self): if self.worker and self.worker.isRunning(): self.worker.cancel_event.set();self.stop_button.setEnabled(False) - self.status_label.setText("正在安全停止:仅终止本工具启动的原生进程树,不关闭用户 CAD。") - self.append_log("已请求停止当前任务及后续队列。") + self._set_status("正在停止…", detail="仅终止本工具启动的原生进程树,不关闭用户 CAD。") + self.append_log("已请求停止队列") def closeEvent(self,event): if self.busy: diff --git a/src/mentor_pdf_export/workers.py b/src/mentor_pdf_export/workers.py index 0ad69e1..7ba7394 100644 --- a/src/mentor_pdf_export/workers.py +++ b/src/mentor_pdf_export/workers.py @@ -9,6 +9,7 @@ from PySide6.QtCore import QThread, Signal from .scanner import scan_projects from .exporter import write_json from .path_policy import validate_queue_paths +from .naming import plan_output_directories class ScanWorker(QThread): @@ -29,9 +30,10 @@ class BatchWorker(QThread): result = Signal(int, object) message = 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) 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.results = [] self.summary_path = "" @@ -40,18 +42,24 @@ class BatchWorker(QThread): error_text = "" record_error = "" 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) 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. 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) - for row, project in self.items: + for (row, project), directory in zip(self.items, directories): if self.cancel_event.is_set(): break self.current.emit(row, project.name) 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: from .models import ExportResult result = ExportResult(str(project.path),"uncertain",f"执行器异常,结果待核验:{error}") @@ -70,8 +78,9 @@ class BatchWorker(QThread): self.message.emit(f"队列执行异常:{error}") finally: 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) - 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: try: write_json(report, {"phase":"completed", "summary":text, "error":error_text, "not_run":not_run, "results":[asdict(r) for r in self.results]}) diff --git a/src/mentor_pdf_export/workspace.py b/src/mentor_pdf_export/workspace.py index 643a305..d895029 100644 --- a/src/mentor_pdf_export/workspace.py +++ b/src/mentor_pdf_export/workspace.py @@ -23,7 +23,7 @@ def source_files(root: Path): if path.is_dir() and path.name.casefold() in COPY_PRUNED: continue if is_link(path): - raise ValueError(f"工程含链接/重解析点,不复制:{path}") + raise ValueError(f"工程含链接/重解析点,无法安全核验:{path}") if path.is_dir(): yield from walk(path) elif path.is_file(): @@ -44,6 +44,16 @@ def fingerprint(root: Path, cancel: threading.Event | None = None) -> dict[str, 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: with project.open("rb") as stream: match = _DATABASE.search(stream.read(HEADER_LIMIT)) diff --git a/tests/test_cli.py b/tests/test_cli.py index d110ff6..3d9920a 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,4 +1,5 @@ import json +import pytest from pathlib import Path 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" assert main(["--self-check","--report",str(report)]) == 0 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 @@ -29,7 +31,7 @@ def test_report_inside_source_is_rejected_before_export(project_factory,tmp_path project=project_factory() protected=project.parent/"settings.json";protected.write_text("original") 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) with Path(args[args.index("-a")+1]).open("wb") as out:writer.write(out) 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") engine=tmp_path/"sch2pdf.exe";engine.write_bytes(b"fake") before=fingerprint(b.parent) - def runner(args,*rest): + 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 @@ -70,3 +72,61 @@ def test_self_check_can_refresh_its_own_report(tmp_path): report=tmp_path/"self-check.json" 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 diff --git a/tests/test_engine.py b/tests/test_engine.py index 00021b8..bd350b0 100644 --- a/tests/test_engine.py +++ b/tests/test_engine.py @@ -323,3 +323,42 @@ def test_callback_error_stops_owned_tree_but_not_other_process(tmp_path, monkeyp if other.poll() is None: other.kill() 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' diff --git a/tests/test_exporter.py b/tests/test_exporter.py index 97de055..fe3c2e7 100644 --- a/tests/test_exporter.py +++ b/tests/test_exporter.py @@ -76,7 +76,7 @@ def test_source_change_never_claims_success(project_factory, tmp_path): project = project_factory(); info = read_project(project) def changing(args, *rest): 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 result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=changing).export(info, tmp_path / "pdfs", ExportOptions(), threading.Event()) 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): 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): @@ -162,3 +165,136 @@ def test_staging_stat_failure_still_returns_and_records_result(project_factory,t assert result.status=="failed" assert (Path(result.run_dir)/"result.json").is_file() 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 diff --git a/tests/test_output_names.py b/tests/test_output_names.py new file mode 100644 index 0000000..9723265 --- /dev/null +++ b/tests/test_output_names.py @@ -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() diff --git a/tests/test_pdf_styles.py b/tests/test_pdf_styles.py new file mode 100644 index 0000000..1f9859f --- /dev/null +++ b/tests/test_pdf_styles.py @@ -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) diff --git a/tests/test_profiles.py b/tests/test_profiles.py index 0574f72..5017cf7 100644 --- a/tests/test_profiles.py +++ b/tests/test_profiles.py @@ -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)) assert "-uAll" 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" diff --git a/tests/test_reference_profile.py b/tests/test_reference_profile.py new file mode 100644 index 0000000..d3432f7 --- /dev/null +++ b/tests/test_reference_profile.py @@ -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')] diff --git a/tests/test_release_branding.py b/tests/test_release_branding.py new file mode 100644 index 0000000..717090e --- /dev/null +++ b/tests/test_release_branding.py @@ -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("= 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) diff --git a/tests/test_ui_compact.py b/tests/test_ui_compact.py new file mode 100644 index 0000000..f58a9b3 --- /dev/null +++ b/tests/test_ui_compact.py @@ -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) diff --git a/tests/test_workspace.py b/tests/test_workspace.py index 34ee72c..a3a6686 100644 --- a/tests/test_workspace.py +++ b/tests/test_workspace.py @@ -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))) lines=copied.read_text().splitlines() 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": []}