feat: add safe native Mentor PDF exporter and tested portable UI

This commit is contained in:
Codex committed 2026-10-09 21:32:31 +08:00
1 parent 10a87d2cee
commit d4928af5b6
33 files changed
+2267 -13

No files matched your search

+58
View File
@@ -0,0 +1,58 @@
# Mentor 工程批量导出 PDF 测试工具
独立 Windows 简易界面,扫描 DxDesigner 原理图工程,通过本机原生 `sch2pdf.exe` 串行导出 PDF。每个任务在独立工程副本中执行,不保存或改写源工程,不修改源工程的 `dxpdf.ini`。这是 v0.1.0 测试版,不是无需 Mentor 的独立转换器。
## 使用便携版
解压整个发行目录,双击 `MentorPDFExporter.exe`。不能只复制 exe,必须保留 `_internal` 文件夹。用户不需要安装 Python,但本机必须安装 Mentor、拥有有效许可证,工程引用的库必须可访问。
1. 选择包含一个或多个工程的目录,点击“扫描工程”。排除 PCB、备份、输出、运行目录;会完整递归而不是根目录发现工程后提前结束。
2. 选择源工程外部的 PDF 输出目录。工程名相同的项目通过路径摘要区分,不会互相覆盖。
3. 检查自动发现的 `sch2pdf.exe`,必要时手动选择。
4. 网络中心库不可达时,显式选择对应本地 `.lmc`。工具只修改工作副本的 `CentralLibrary`,不改源工程;不会自动选择可能不匹配的库。
5. 勾选工程,确认配置,然后开始导出。默认不覆盖已有 PDF。失败项可通过“选中失败项重试”重新执行。
6. 可以停止当前任务及后续队列;仅结束工具启动的引擎进程树,不关闭用户的 DxDesigner。
## 配置与安全
- 默认白底彩色并保留彩色文字(`-c 4`)、器件弹出菜单开启、可见超链接关闭、URL-valued 清空、ICT 转原理图开启、线宽 1。
- `Use exclusion info` 按截图保持勾选,它不等于“去掉文字掩盖”。不要为了掩盖问题直接关闭排除信息。
- 整工程范围可能包含非顶层 Block;如只需要截图中的 Block 范围,选择“指定原理图 / Block”并填真实名称,例如 `PON`,不是 `Board1`。
- 现有字体映射保留;笔画字体提供对照方式。不同工程的中文、特殊字符和背景掩盖效果仍须查看样张。PDF 结构成功不代表排版、中文及图页范围全部验收完成。
- 源数据库必须在工程内部,含外部数据库路径或链接的工程不执行,以免副本反而写回原数据库。
- 工作副本中排除 PCB、CES、ICXPro、Integration、备份与历史日志;不依赖这些目录的标准原理图工程已做验证,特殊外部依赖需要人工检查。
- 已有输出只有显式勾选覆盖后才替换。引擎正常退出且 PDF 解析成功、至少一页、源内容指纹一致后,才发布新文件。
## 日志
默认保存到 `%LOCALAPPDATA%\MentorPDFExporter\runs`。每次记录源工程指纹、实际命令、副本配置、stdout/stderr、PDF 页数/摘要以及结果 JSON,失败输出不会成为正式 PDF。发布前以原子写入并刷盘方式持久化提交预记录;覆盖前保留旧 PDF 备份。若提交后结果记录写入失败,会返回“待核验”并保留真实输出路径,不能当作完整成功。工作副本包含工程数据,请按公司要求保存;测试版不自动删除运行记录。
## 已确认的真实测试
本机 EE 7.9.5;PON 示例工程原引用 `192.168.0.252` 的网络中心库,首次默认路径导出超时且只产生空 PDF;在副本中显式使用本地对应库后正常导出 24 页。源工程参与复制的文件内容指纹一致。样张外部 URL 数为零。
默认样张部分中文批注存在乱码、浅色原理图对象对白底对比度较低,因此该版本只标为测试版,不把 PDF 结构验证当作最终出图质量验收。
## 额外安全保护
- 队列开始前统一检查全部源工程,防止 A 的输出目录误选到 B 的数据库中。
- CLI 报告仅允许 `.json`,拒绝写入源工程/运行证据目录或覆盖非本工具的 JSON;自动测试截图也不能写入源目录。
- 最后一次源内容核验在发布之前完成,不在覆盖旧 PDF 后才否决结果。
- 批量队列预记录写入失败时不启动引擎;末尾记录更新失败仍保留计数、内存结果和逐工程提交预记录。
- 打包排除构建机 PATH 中误发现的第三方 ICU DLL,使用与本机 Qt 轮子配套的 Windows 系统依赖。
- 当前真实验收环境为 Windows 11;尚未对其他 Windows 版本做兼容性验收。
## 开发
Python 3.12。安装依赖后:
```powershell
$env:PYTHONPATH = "$(Get-Location)\src"
.\.venv\Scripts\python.exe -m mentor_pdf_export
.\.venv\Scripts\python.exe -m pytest -q
.\.venv\Scripts\python.exe -m PyInstaller packaging\MentorPDFExporter.spec --distpath release --workpath build\pyinstaller --noconfirm
```
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`。
源码、测试和说明纳入 Git。原始文档、Mentor 工程、PDF、运行数据和发行产物不入 Git。无自动上传、联网更新或用户环境变量修改。
+15
View File
@@ -0,0 +1,15 @@
@echo off
setlocal
cd /d "%~dp0"
if exist "%~dp0release\MentorPDFExporter\MentorPDFExporter.exe" (
start "" "%~dp0release\MentorPDFExporter\MentorPDFExporter.exe"
exit /b 0
)
if exist "%~dp0.venv\Scripts\pythonw.exe" (
set "PYTHONPATH=%~dp0src"
start "" "%~dp0.venv\Scripts\pythonw.exe" -m mentor_pdf_export
exit /b 0
)
echo Portable executable or development environment not found.
pause
exit /b 1
@@ -17,24 +17,34 @@
### Task 1: Native feasibility and safe core
Files: tests/test_scanner.py, tests/test_profiles.py, tests/test_workspace.py, src/mentor_pdf_export/{models,scanner,profiles,workspace,engine}.py, tools/live_smoke.py.
Interfaces: scan_projects(root, excluded_roots=()) -> list[ProjectInfo]; ExportOptions; prepare_workspace(project, run_dir, options) -> Path; build_command(engine, project, output, options) -> list[str].
- [ ] Write failing tests for recursive discovery/pruning, profile values and safe isolated workspace.
- [ ] Run pytest and confirm intended import/behavior failures.
- [ ] Implement core, rerun tests until passing.
- [ ] Export the local PON example ONLY from a copied workspace; retain logs and compare source hashes.
- [ ] Investigate config/ICT/font behavior and record actual evidence/limits.
- [x] Write failing tests for recursive discovery/pruning, profile values and safe isolated workspace.
- [x] Run pytest and confirm intended import/behavior failures.
- [x] Implement core, rerun tests until passing.
- [x] Export the local PON example ONLY from a copied workspace; retain logs and compare source hashes.
- [x] Investigate config/ICT/font behavior and record actual evidence/limits.
### Task 2: Reliable export transaction
Files: tests/test_exporter.py, tests/test_engine.py, src/mentor_pdf_export/{exporter,validation}.py.
Interfaces: Exporter.export(ProjectInfo, output_root, ExportOptions, cancel_event, event_callback) -> ExportResult; discover_engine(explicit=None) -> Path.
- [ ] Write failing tests for valid/invalid PDF, old output preservation, source changes, timeout/cancel and duplicate names.
- [ ] Run red, implement, then run green.
- [ ] Include isolated output staging, JSON run report and retained stdout/stderr.
- [x] Write failing tests for valid/invalid PDF, old output preservation, source changes, timeout/cancel and duplicate names.
- [x] Run red, implement, then run green.
- [x] Include isolated output staging, JSON run report and retained stdout/stderr.
### Task 3: Simple UI and portable release
Files: tests/test_ui.py, src/mentor_pdf_export/{ui,__main__,cli}.py, packaging/mentor_pdf.spec, README.md, Start-MentorPDF.cmd.
Interfaces: MainWindow(root=None, output=None); CLI --self-check/--export/--ui-smoke.
- [ ] Write failing Qt tests: scan checkbox state, settings locking, background signals, cancel, result display.
- [ ] Implement minimal usable UI; run Qt tests and capture window PNG.
- [ ] Run real UI batch on sample copy, render native PDF and check pages/text/colors visually.
- [ ] Build PyInstaller onedir and ZIP; execute packaged --self-check and UI smoke.
- [ ] Run full tests, review diff and document release limitations/evidence.
- [x] Write failing Qt tests: scan checkbox state, settings locking, background signals, cancel, result display.
- [x] Implement minimal usable UI; run Qt tests and capture window PNG.
- [x] Run real UI batch on sample copy, render native PDF and check pages/text/colors visually.
- [x] Build PyInstaller onedir and ZIP; execute packaged --self-check and UI smoke.
- [x] Run full tests, review diff and document release limitations/evidence.
## Safety review fix ledger
- Findings 1/2: whole-queue output/run path preflight and protected CLI report/screenshot destinations; unknown existing JSON is never overwritten. Added red/green regressions.
- Finding 3: suspended Windows process creation, explicit inherited handle whitelist, Job assignment before ResumeThread; worker scope engine.py/test_engine.py only, 20 engine tests passing.
- Findings 4/5: final source check before publication; fsync atomic commit/result pre-record, old output backup; post-commit record failures return traceable uncertain status. Batch pre-record prevents running without durable queue identity.
- Cleanup residual: staging exists/stat is inside guarded cleanup so result recording still happens after filesystem errors. Red/green test added.
- Full test suite after fixes: 63 passed; final rebuilt executable QA remains the release gate.
- Ruling: preserve the new feat/pdf-export repository in the requested directory, without merge/push/worktree cleanup; this task is local test-tool delivery, not shared-branch integration.
Final release gate: rebuilt exe native UI queue success2/failure0 (17 pages each), source209 files and library hashes unchanged, ZIP CRC and extracted clean-PATH self-check passed. Independent scoped review found no remaining blockers in the reported cases.
@@ -22,3 +22,7 @@ ui.py PySide6 工程表、配置栏、后台串行任务、日志、停止、结
## 验收
自动测试覆盖扫描、配置、复制路径安全、错误处理、输出冲突、取消超时、PDF 校验、UI 按钮与后台任务。真实副本导出记录参数、配置、日志、页数与源工程前后指纹,并渲染检查。UI 做 offscreen 行为测试及真实窗口截图。打包后 exe 至少做自检和 UI 启动,不以源码运行替代 exe 验收。
## 验证后补充的约束
实际示例工程的网络中心库不可达;提供用户显式指定对应本地 .lmc 的配置,仅覆盖副本的 CentralLibrary。白底彩色样张部分中文批注乱码与低对比度未消除,版本标为测试版,不能宣称出图质量全部通过。
全队列统一校验输出/运行路径,CLI 报告和截图不能写入源工程;CLI 不覆盖非工具 JSON。所有决定发布的源核验在提交之前完成;预先 fsync/原子记录提交状态,覆盖旧输出先留备份。提交后记录故障返回可追溯待核验,不丢弃当前结果。Windows 引擎必须在执行前进入自有 Job,不允许先启动再绑定的子进程逃逸竞态。
+28
View File
@@ -0,0 +1,28 @@
# Mentor PDF 测试版验收记录
## 真实工程与前置条件
本机 Windows 11、Mentor EE 7.9.5,原生 sch2pdf 报告 V6.0。参考工程 PON.prj 原引用 192.168.0.252 网络库;SMB 连接探测超时。未强行保存或关闭用户 CAD,仅对独立工作副本导出。
## 探测结果
1. 原网络库配置:180 秒超时,零字节 PDF,被验证器拒绝,没有发布正式输出。
2. 显式对应本地 .lmc:正常退出,24 页、约 6 MB PDF,结构验证通过。源工程复制范围哈希不变。
3. 原生 `-u All` 实际失败(Incorrect font name null);`-uAll` 实测正常,命令构建已使用后者。笔画模式也没有消除样张中的中文乱码。
4. PDF 第 1/12/24 页已渲染检查;部分中文批注乱码,浅色对象低对比度,不能按最终出图质量交付。外部 URL 链接数为零。
## UI 与打包
源代码 UI 用 PON 工程两个独立副本做实际串行队列:各 24 页,27.6/18.1 秒,同名工程输出文件不同。原工程全部209个文件以及本地 .lmc 内容哈希一致。便携 exe 原范围 PON 的初次真实 UI 队列各 17 页,说明 Block 与整工程范围不同。
初版打包误收集 PATH 中 Poppler 的 ICU,导致 QtWidgets DLL 缺符号;通过模块导入符号与系统 ICU 对照定位。排除第三方 ICU 后 packaged 自检通过,并加入打包策略回归测试。
## 安全审查
独立审查确认并修复报告覆盖源文件、跨队列目录保护、Job 绑定竞态、发布后才否决源核验、结果记录失败丢失当前结果以及清理 stat 错误绕过结果记录。所有修复有红绿测试证据;最新完整测试63项通过。Windows engine 专项20项,覆盖早期子进程逃逸、取消/超时、标准句柄白名单、启动失败清理及不误杀独立进程。
## 交付边界
仅本机 Windows 11 与本机 EE 7.9.5 真实验收;没有声称全部工程、中文字体、掩盖效果、其他 Windows/Mentor 版本均通过。最终安全修复后的 rebuilt exe 和 ZIP 自检/UI 验收结果在下方追加。
## 最终安全修复后的交付验收
- 最终 rebuilt exe 自检退出码0;实际 UI 串行处理两个独立 PON 副本,每项指定 PON 范围17页,42.9/44.8秒,成功2/失败0。
- 两项均有 commit.json 与最终 status=success 的 result.json,正式 PDF 重新解析为17页。
- 原工程全部209个文件与本地 .lmc 内容摘要保持一致。
- ZIP CRC 检查通过;解压后清除 PYTHONPATH/PYTHONHOME/Qt 路径,仅保留 Windows PATH,exe 自检仍退出0。
- 便携包250个文件,54,992,126字节。没有 Mentor 二进制、CAD 工程、中心库、原文档或测试 PDF。
- 独立定界复核:最初5项 Important 及 cleanup stat 残留,针对已报告触发条件均实质解决。
+26
View File
@@ -0,0 +1,26 @@
# Portable onedir bundle: no Mentor binaries, licenses or private projects.
from pathlib import Path
import sys
sys.path.insert(0, SPECPATH)
from bundle_policy import filter_binaries
root = Path(SPECPATH).parent
analysis = Analysis(
[str(root / "packaging" / "entrypoint.py")],
pathex=[str(root / "src")],
binaries=[],
datas=[],
hiddenimports=["win32job", "win32api", "win32con"],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=["PyQt5","PyQt6","PySide2","matplotlib","numpy","scipy","pandas","torch","tensorflow","IPython","pytest","pymupdf","fitz","tkinter"],
noarchive=False,
optimize=0,
)
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,
strip=False, upx=False, console=False, disable_windowed_traceback=False)
coll = COLLECT(exe, analysis.binaries, analysis.datas, strip=False, upx=False,
name="MentorPDFExporter")
+15
View File
@@ -0,0 +1,15 @@
"""Build-time DLL policy for the Windows PySide6 6.11 wheel.
Qt imports unversioned ICU symbols from the Windows OS ICU implementation.
A version-suffixed ICU accidentally picked from Poppler on the build PATH
causes WinError 127 even though every Qt DLL has the correct version.
Do not bundle an unrelated ICU provider; use the Windows OS dependency.
"""
from pathlib import PureWindowsPath
def filter_binaries(entries):
def allowed(entry):
name = PureWindowsPath(entry[0]).name.casefold()
return name not in {"icuuc.dll", "icuin.dll"} and not (name.startswith("icudt") and name.endswith(".dll"))
return [entry for entry in entries if allowed(entry)]
+3
View File
@@ -0,0 +1,3 @@
from mentor_pdf_export.cli import main
if __name__ == "__main__":
raise SystemExit(main())
+5
View File
@@ -0,0 +1,5 @@
# Exact runtime/build versions used for the 2026-10-09 Windows release.
PySide6==6.11.2
pypdf==6.20.0
pywin32==312
PyInstaller==6.22.3
+25
View File
@@ -0,0 +1,25 @@
[build-system]
requires = ["setuptools>=75"]
build-backend = "setuptools.build_meta"
[project]
name = "mentor-pdf-export"
version = "0.1.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"]
[project.scripts]
mentor-pdf-export = "mentor_pdf_export.cli:main"
[project.optional-dependencies]
dev = ["pytest>=8,<9", "pytest-qt>=4.4,<5", "PyInstaller>=6,<7"]
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-ra"
cache_dir = "build/pytest-cache"
+2
View File
@@ -0,0 +1,2 @@
"""Mentor native batch PDF exporter."""
__version__ = "0.1.0"
+2
View File
@@ -0,0 +1,2 @@
from .cli import main
raise SystemExit(main())
+139
View File
@@ -0,0 +1,139 @@
from __future__ import annotations
import argparse
from dataclasses import asdict
import json
import os
from pathlib import Path
import sys
import threading
from . import __version__
from .engine import discover_engine
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
def _print(value):
if sys.stdout is not None:
print(value, flush=True)
def main(argv=None) -> int:
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("--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("--schematic",default="")
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)
# 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 [])]
if args.project_root:
protected_dirs.append(args.project_root.resolve())
runs_root=args.runs_root or Path(os.environ.get("LOCALAPPDATA",str(Path.home())))/"MentorPDFExporter"/"runs"
try:
validate_artifact_path(args.report,".json",source_dirs=protected_dirs,reserved_dirs=[runs_root])
validate_artifact_path(args.ui_smoke,".png",source_dirs=protected_dirs,reserved_dirs=[runs_root])
except Exception as error:
_print(str(error))
return 2
if args.self_check:
data={"tool":"MentorPDFExporter","version":__version__,"python":sys.version.split()[0],"platform":sys.platform,"frozen":bool(getattr(sys,"frozen",False))}
try:
import PySide6
import pypdf
from PySide6.QtWidgets import QApplication
data.update(qt=PySide6.__version__,pypdf=pypdf.__version__,ui_import_ok=True)
try:
data.update(engine_available=True,engine=str(discover_engine(args.engine)))
except Exception as error:
data.update(engine_available=False,engine_error=str(error))
if args.report:
args.report.parent.mkdir(parents=True,exist_ok=True);write_json(args.report,data)
_print(json.dumps(data,ensure_ascii=False,indent=2));return 0
except Exception as error:
data["error"]=str(error)
if args.report:
args.report.parent.mkdir(parents=True,exist_ok=True);write_json(args.report,data)
_print(str(error));return 2
if args.export:
preflight_ok=False
try:
if not args.output:raise ValueError("--export 必须指定 --output")
infos=[]
for project in args.export:
if not project.is_file():raise ValueError(f"工程不存在:{project}")
info=read_project(project)
if not info:raise ValueError(f"不是 DxDesigner 原理图工程:{project}")
infos.append(info)
validate_queue_paths(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]
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)
_print(json.dumps(data,ensure_ascii=False,indent=2))
return 0 if all(result.status in {"success","skipped"} for result in results) else 1
except Exception as error:
_print(str(error))
if args.report and preflight_ok:
try:
args.report.parent.mkdir(parents=True,exist_ok=True);write_json(args.report,{"tool":"MentorPDFExporter","error":str(error)})
except Exception:
pass
return 2
if args.ui_export_smoke and not (args.ui_smoke and args.project_root and args.output):
parser.error("--ui-export-smoke 需要 --ui-smoke、--project-root、--output")
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QApplication
from .ui import MainWindow
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)
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)
window.show()
smoke_phase="new"
if args.ui_smoke:
import time
began=time.monotonic()
def finish():
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()}
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)))
timer.stop();app.exit(0 if ok else 1)
def tick():
nonlocal smoke_phase
if smoke_phase=="new":
smoke_phase="scan"
if args.project_root:window.scan_projects()
return
if window.busy:
if time.monotonic()-began > max(40,args.timeout*max(1,len(window.projects))+40):window.stop_export()
return
if smoke_phase=="scan" and args.ui_export_smoke:
smoke_phase="export"
if not window.projects:
finish();return
window.start_export();return
finish()
timer=QTimer(window);timer.timeout.connect(tick);timer.start(250)
return app.exec()
+180
View File
@@ -0,0 +1,180 @@
from __future__ import annotations
import os
from pathlib import Path
def discover_engine(explicit: str | Path | None = None) -> Path:
if explicit:
candidates = [Path(explicit)]
else:
candidates = []
if os.environ.get("SDD_HOME"):
candidates.append(Path(os.environ["SDD_HOME"]) / "wv/win32/bin/sch2pdf.exe")
for drive in "CDEFG":
for vendor in ("Mentor", "MentorGraphics"):
parent = Path(f"{drive}:/") / vendor
if parent.is_dir():
for version in sorted(parent.iterdir(), reverse=True):
if version.is_dir():
candidates.append(version / "SDD_HOME/wv/win32/bin/sch2pdf.exe")
for candidate in candidates:
if candidate.is_file() and candidate.name.casefold() == "sch2pdf.exe":
return candidate.resolve()
raise FileNotFoundError("未找到 sch2pdf.exe,请选择本机 Mentor EE 安装中的原生导出引擎")
class _WindowsProcess:
"""Small native process owner; retains the handle returned by CreateProcess."""
def __init__(self, args, handle, pid):
self.args, self.handle, self.pid = args, handle, pid
self.returncode = None
def poll(self):
import _winapi
if self.returncode is None and _winapi.WaitForSingleObject(self.handle, 0) == _winapi.WAIT_OBJECT_0:
self.returncode = _winapi.GetExitCodeProcess(self.handle)
return self.returncode
def wait(self, timeout):
import _winapi
import subprocess
if _winapi.WaitForSingleObject(self.handle, max(0, int(timeout * 1000))) == _winapi.WAIT_TIMEOUT:
raise subprocess.TimeoutExpired(self.args, timeout)
self.returncode = _winapi.GetExitCodeProcess(self.handle)
return self.returncode
def kill(self):
import _winapi
try:
_winapi.TerminateProcess(self.handle, 1)
except OSError as error:
# Job close starts asynchronous termination. TerminateProcess can
# return ACCESS_DENIED before that process becomes signalled.
if error.winerror != 5 or _winapi.WaitForSingleObject(self.handle, 10000) != _winapi.WAIT_OBJECT_0:
raise
def close(self):
import _winapi
if self.handle is not None:
_winapi.CloseHandle(self.handle)
self.handle = None
def _create_job(process):
"""Assign the still-suspended process, using its retained creation handle."""
import win32job
job = win32job.CreateJobObject(None, "")
try:
info = win32job.QueryInformationJobObject(job, win32job.JobObjectExtendedLimitInformation)
info["BasicLimitInformation"]["LimitFlags"] |= win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
win32job.SetInformationJobObject(job, win32job.JobObjectExtendedLimitInformation, info)
win32job.AssignProcessToJobObject(job, process.handle)
except BaseException:
job.Close()
raise
return job
def _start_windows_process(args, cwd, stdout, stderr, cancel):
import _winapi
import msvcrt
import subprocess
import win32con
import win32process
from .workspace import check_cancel
process = None
job = None
thread_handle = None
inherited = []
with open(os.devnull, "rb") as stdin:
try:
current = _winapi.GetCurrentProcess()
for stream in (stdin, stdout, stderr):
inherited.append(_winapi.DuplicateHandle(
current, msvcrt.get_osfhandle(stream.fileno()), current,
0, True, _winapi.DUPLICATE_SAME_ACCESS,
))
startup = subprocess.STARTUPINFO()
startup.dwFlags = subprocess.STARTF_USESTDHANDLES
startup.hStdInput, startup.hStdOutput, startup.hStdError = inherited
startup.lpAttributeList = {"handle_list": inherited}
# CPython's native CreateProcess supports STARTUPINFOEX's explicit
# handle list and, unlike Popen, lets us retain the primary thread.
handle, thread_handle, pid, _ = _winapi.CreateProcess(
None, subprocess.list2cmdline([os.fspath(arg) for arg in args]),
None, None, True,
win32con.CREATE_SUSPENDED | subprocess.CREATE_NO_WINDOW,
None, os.fspath(cwd), startup,
)
process = _WindowsProcess(args, handle, pid)
job = _create_job(process)
check_cancel(cancel)
win32process.ResumeThread(thread_handle)
return process, job
except BaseException:
try:
if job is not None:
job.Close()
finally:
if process is not None:
try:
if process.poll() is None:
process.kill()
process.wait(timeout=10)
finally:
process.close()
raise
finally:
try:
if thread_handle is not None:
_winapi.CloseHandle(thread_handle)
finally:
for handle in inherited:
_winapi.CloseHandle(handle)
def run_engine(args, cwd, log_dir, cancel, timeout, on_event=None) -> int:
import subprocess
import time
from .workspace import check_cancel
check_cancel(cancel)
log_dir = Path(log_dir)
log_dir.mkdir(parents=True, exist_ok=True)
emit = on_event or (lambda message: None)
started = time.monotonic()
process = None
job = None
with (log_dir / "stdout.log").open("wb") as stdout, (log_dir / "stderr.log").open("wb") as stderr:
try:
if os.name == "nt":
process, job = _start_windows_process(args, cwd, stdout, stderr, cancel)
else:
process = subprocess.Popen(args, cwd=cwd, stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr)
emit(f"原生引擎已启动,PID={process.pid}")
last_heartbeat = started
while process.poll() is None:
check_cancel(cancel)
now = time.monotonic()
if now - started > timeout:
raise TimeoutError(f"原生导出超过 {timeout:g} 秒;仅终止本工具启动的进程树")
if now - last_heartbeat >= 10:
emit(f"等待原生引擎,已用时 {now-started:.0f} 秒")
last_heartbeat = now
time.sleep(.05)
check_cancel(cancel)
return process.returncode
finally:
try:
if job is not None:
job.Close()
finally:
if process is not None:
try:
if process.poll() is None:
process.kill()
process.wait(timeout=10)
finally:
if os.name == "nt":
process.close()
+172
View File
@@ -0,0 +1,172 @@
from __future__ import annotations
from dataclasses import asdict, replace
from datetime import datetime
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 .validation import validate_pdf
from .workspace import check_cancel, fingerprint, prepare_workspace
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"
def write_json(path: Path, data) -> None:
"""Atomic, flushed evidence writes; existing records cannot be torn."""
path = Path(path)
temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex[:8]}.tmp")
try:
with temporary.open("x", encoding="utf-8", newline="\n") as stream:
json.dump(data, stream, ensure_ascii=False, indent=2)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
try:
if temporary.exists():
temporary.unlink()
except OSError:
pass
class Exporter:
def __init__(self, engine: Path, runs_root: Path, *, runner=run_engine):
self.engine = Path(engine)
self.runs_root = Path(runs_root)
self.runner = runner
self._lock = threading.Lock()
def export(self, project: ProjectInfo, output_root: Path, options: ExportOptions, cancel: threading.Event, on_event=None) -> ExportResult:
if not self._lock.acquire(blocking=False):
return ExportResult(str(project.path), "failed", "已有导出在执行,不允许并行调用 Mentor")
try:
return self._execute(project, output_root, options, cancel, on_event)
finally:
self._lock.release()
def _execute(self, project, output_root, options, cancel, on_event):
start = time.monotonic()
run = stage = before = final = None
published = False
source_verified = False
status, message, pages = "failed", "", 0
external = on_event or (lambda message: None)
def notify(message):
# UI/log delivery is observational, not a reason to lose a result.
try:
external(message)
except Exception:
pass
def emit(message):
notify(message)
if run:
with (run / "events.log").open("a", encoding="utf-8") as log:
log.write(datetime.now().isoformat(timespec="seconds") + " " + message + "\n")
try:
check_cancel(cancel)
source_root = project.path.parent.resolve()
output_root = Path(output_root).resolve()
runs_root = self.runs_root.resolve()
validate_queue_paths([project], output_root, runs_root)
final = output_path(project, output_root)
if final.exists() and not options.overwrite:
status, message = "skipped", "已有同名 PDF,未勾选覆盖,已跳过"
else:
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("核验源工程并创建独立工作副本")
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)
write_json(run / "command.json", args)
emit("导出仅操作工作副本;源工程不保存、不修改")
rc = self.runner(args, copied.parent, run, cancel, options.timeout, emit)
check_cancel(cancel)
if rc != 0:
details = []
for name in ("stderr.log", "stdout.log"):
log = run / name
if log.exists():
with log.open("rb") as stream:
stream.seek(max(0, log.stat().st_size - 2000))
details.append(stream.read().decode("gb18030", errors="replace").strip())
tail = " / ".join(text for text in details if text)
raise RuntimeError(f"原生引擎退出码 {rc}。{tail or '请检查工程、许可证及运行日志。'}")
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
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})
# If this write fails, the old output has not been touched.
write_json(run / "result.json", asdict(prepared))
check_cancel(cancel)
if options.overwrite:
os.replace(stage, final)
elif os.name == "nt":
os.rename(stage, final) # no overwrite on Windows
else:
os.link(stage, final)
stage.unlink()
published, stage, pages, status = True, None, check.pages, "success"
message = f"已导出 {pages} 页;发布前源内容指纹一致。图页完整性及字体效果请人工复核。"
except InterruptedError as error:
status, message = "cancelled", str(error)
except TimeoutError as error:
status, message = "timeout", str(error)
except Exception as error:
status, message = "failed", str(error)
finally:
# 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:
try:
after = fingerprint(project.path.parent.resolve())
write_json(run / "source-after.json", after)
if after != before:
status, message = "uncertain", "源工程在任务期间发生变化,未发布 PDF,结果待人工核验"
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 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。"))
notify(result.message)
return result
+42
View File
@@ -0,0 +1,42 @@
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class ProjectInfo:
path: Path
name: str
root_blocks: tuple[str, ...] = ()
@dataclass(frozen=True)
class ExportOptions:
library_override: str = ""
color: int = 4
popup: bool = True
use_exclusion: bool = True
change_ict: bool = True
stroke_fonts: bool = False
schematic: str = ""
stop_at: str = "STD"
line_width: int = 1
stroke_width: int = 1
timeout: float = 180.0
overwrite: bool = False
def __post_init__(self):
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:
raise ValueError("超时和线宽必须大于零")
if any(c in self.schematic + self.stop_at + self.library_override for c in "\r\n\x00"):
raise ValueError("原理图名称或 Stop At 含无效字符")
@dataclass(frozen=True)
class ExportResult:
project: str
status: str
message: str
output: str = ""
pages: int = 0
run_dir: str = ""
duration: float = 0.0
+44
View File
@@ -0,0 +1,44 @@
"""Preflight every writable destination against the entire source queue."""
from __future__ import annotations
from pathlib import Path
import json
def source_roots(projects):
return tuple(dict.fromkeys(Path(info.path if hasattr(info, "path") else info).resolve().parent for info in projects))
def validate_queue_paths(projects, output_root: Path, runs_root: Path) -> None:
output = Path(output_root).resolve()
runs = Path(runs_root).resolve()
if output == runs or output.is_relative_to(runs) or runs.is_relative_to(output):
raise ValueError("输出目录与运行副本目录不能互相包含")
for source in source_roots(projects):
if output == source or output.is_relative_to(source):
raise ValueError(f"输出目录位于队列中源工程内部:{source}")
if runs == source or runs.is_relative_to(source) or source.is_relative_to(runs):
raise ValueError(f"运行目录与队列中源工程互相包含:{source}")
def validate_artifact_path(path: Path | None, suffix: str, *, source_dirs=(), reserved_dirs=()) -> None:
if path is None:
return
path = Path(path).absolute()
if path.suffix.casefold() != suffix or path.is_dir():
raise ValueError(f"报告/截图必须使用独立的 {suffix} 文件,不能覆盖工程、数据库或 PDF")
if path.exists() and (path.is_symlink() or path.stat().st_nlink > 1):
raise ValueError("报告/截图不能覆盖链接或多硬链接文件")
if path.exists() and suffix == ".json":
try:
if path.stat().st_size > 10 * 1024 * 1024:
raise ValueError("existing report too large")
data = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(data,dict) or data.get("tool") != "MentorPDFExporter":
raise ValueError("not owned by this tool")
except (OSError,ValueError) as error:
raise ValueError("报告路径已有非本工具记录,为避免误覆盖请另选新文件") from error
resolved = path.resolve()
for directory in (*source_dirs, *reserved_dirs):
root = Path(directory).resolve()
if resolved == root or resolved.is_relative_to(root):
raise ValueError(f"报告/截图不能写入源工程或运行证据目录:{root}")
+62
View File
@@ -0,0 +1,62 @@
from __future__ import annotations
from pathlib import Path
from .models import ExportOptions
def write_profile(path: Path, options: ExportOptions) -> None:
original = path.read_bytes() if path.exists() else b""
encoding = "utf-8"
for candidate in ("utf-8-sig", "gb18030", "cp1252"):
try:
text = original.decode(candidate)
encoding = "utf-8" if candidate == "utf-8-sig" else candidate
break
except UnicodeDecodeError:
pass
values = {
"AddPopup": str(int(options.popup)),
"ChangeIct2Sch": str(int(options.change_ict)),
"Color": str(options.color),
"VisibleHLs": "0",
"StartAcrobat": "0",
"UrlProperties": "",
"UseExclusion": str(int(options.use_exclusion)),
"UseDxDMapping": str(int(not options.stroke_fonts)),
"LineThickness": str(options.line_width),
"StrokeThickness": str(options.stroke_width),
"SheetOrder": "",
"HorizontalScale": "100",
}
aliases = {key.casefold(): key for key in values}
lines = []
seen = set()
for line in text.splitlines():
parts = line.split(maxsplit=1)
key = aliases.get(parts[0].casefold()) if parts else None
if key:
if key not in seen:
lines.append(f"{key} {values[key]}")
seen.add(key)
else:
lines.append(line)
lines.extend(f"{key} {value}" for key, value in values.items() if key not in seen)
path.write_bytes(("\n".join(lines) + "\n").encode(encoding))
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)]
if options.popup:
args.append("-p")
if options.use_exclusion:
args.append("-e")
if options.change_ict:
args.append("-i2s")
if options.stroke_fonts:
args.append("-uAll") # Verified on EE 7.9.5; separated -u All fails.
else:
args.append("-udx")
if options.stop_at:
args.extend(["-l", options.stop_at])
if options.schematic:
args.extend(["-schematic", options.schematic])
return args
+56
View File
@@ -0,0 +1,56 @@
from __future__ import annotations
import os
import re
import stat
from pathlib import Path
from .models import ProjectInfo
PRUNED_DIRS = frozenset({"pcb", "projectbackup", "backup", "backups", ".git", ".venv", "__pycache__", "output", "runs", "artifacts", "dist", "build", "log files"})
HEADER_LIMIT = 512 * 1024
_FRONT = re.compile(rb'^\s*KEY\s+FrontEndSnapshot\s+"DxD"\s*$', re.I | re.M)
_DATABASE = re.compile(rb'^\s*KEY\s+iCDBDir\s+"([^"]+)"\s*$', re.I | re.M)
_ROOT = re.compile(rb'^\s*KEY\s+RootBlock\s+"([^"]+)"\s*$', re.I | re.M)
def is_link(path: Path) -> bool:
details = path.lstat()
return stat.S_ISLNK(details.st_mode) or bool(getattr(details, "st_file_attributes", 0) & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400))
def decode_text(value: bytes) -> str:
for encoding in ("utf-8-sig", "gb18030", "cp1252"):
try:
return value.decode(encoding)
except UnicodeDecodeError:
pass
raise ValueError("无法解码工程名称")
def read_project(path: Path) -> ProjectInfo | None:
with path.open("rb") as stream:
data = stream.read(HEADER_LIMIT)
if not (_FRONT.search(data) and _DATABASE.search(data)):
return None
roots = tuple(dict.fromkeys(decode_text(value) for value in _ROOT.findall(data)))
return ProjectInfo(path.resolve(), path.stem, roots)
def scan_projects(root: Path, *, excluded_roots: tuple[Path, ...] = ()) -> list[ProjectInfo]:
root = Path(root).absolute()
if not root.is_dir() or is_link(root):
raise ValueError("工程根目录不存在,或是链接/重解析点")
root = root.resolve()
excluded = tuple(Path(p).resolve() for p in excluded_roots)
found: dict[str, ProjectInfo] = {}
def blocked(path):
return any(path == target or path.is_relative_to(target) for target in excluded)
for directory, dirs, filenames in os.walk(root, followlinks=False):
current = Path(directory)
dirs[:] = sorted((name for name in dirs if name.casefold() not in PRUNED_DIRS and not blocked(current / name) and not is_link(current / name)), key=str.casefold)
if blocked(current):
dirs[:] = []
continue
for name in sorted(filenames, key=str.casefold):
path = current / name
if path.suffix.casefold() != ".prj" or is_link(path):
continue
info = read_project(path)
if info:
found[os.path.normcase(str(info.path))] = info
return sorted(found.values(), key=lambda info: str(info.path).casefold())
+299
View File
@@ -0,0 +1,299 @@
from __future__ import annotations
import os
from pathlib import Path
from datetime import datetime
from PySide6.QtCore import Qt, QUrl
from PySide6.QtGui import QColor, QDesktopServices, QFont
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,
)
from . import __version__
from .engine import discover_engine
from .exporter import Exporter
from .models import ExportOptions
from .path_policy import validate_queue_paths
from .workers import ScanWorker, BatchWorker
STATUS = {"success":"成功", "failed":"失败", "timeout":"超时", "cancelled":"已停止", "skipped":"已跳过", "uncertain":"待核验"}
def default_data_root() -> Path:
return Path(os.environ.get("LOCALAPPDATA", str(Path.home()))) / "MentorPDFExporter"
class MainWindow(QMainWindow):
def __init__(self, root=None, output=None, engine=None, library=None, runs_root=None, exporter_factory=None):
super().__init__()
self.setWindowTitle(f"Mentor PDF 批量导出 · 测试版 {__version__}")
self.resize(1200, 820)
self.setMinimumSize(940, 660)
self.runs_root = Path(runs_root) if runs_root else default_data_root() / "runs"
self.exporter_factory = exporter_factory or Exporter
self.projects = []
self.busy = False
self.worker = None
self.scan_worker = None
self._close_after_stop = False
self._done = 0
self._queue_rows = []
self._build()
if library:
self.library_edit.setText(str(library))
if root:
self.root_edit.setText(str(root))
if output:
self.output_edit.setText(str(output))
elif root:
path = Path(root)
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)
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)
layout.addWidget(self.paths_group)
self.options_group = QGroupBox("2 统一导出设置")
options = QGridLayout(self.options_group)
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)
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)
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.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)
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_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.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;}
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;}
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;}
""")
def choose_root(self):
path=QFileDialog.getExistingDirectory(self,"选择工程根目录",self.root_edit.text())
if path:
self.root_edit.setText(path)
if not self.output_edit.text().strip():
root=Path(path);self.output_edit.setText(str(root.parent/(root.name+"_PDF")))
self.scan_projects()
def choose_output(self):
path=QFileDialog.getExistingDirectory(self,"选择源工程外部输出目录",self.output_edit.text())
if path:self.output_edit.setText(path)
def choose_engine(self):
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)
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)
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、备份和输出目录……")
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)
self.scan_worker.found.connect(self._scan_found);self.scan_worker.failed.connect(self._scan_failed)
self.scan_worker.finished.connect(self._scan_finished);self.scan_worker.start()
def _scan_found(self,projects):
previous={info.path:self.table.item(row,0).checkState() for row,info in enumerate(self.projects)}
self.projects=projects;self.table.blockSignals(True);self.table.setRowCount(len(projects))
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)
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)} 个工程。勾选后开始导出。")
def _scan_failed(self,message):
self.append_log("扫描失败:"+message);self.status_label.setText("扫描失败,请检查目录权限。")
def _scan_finished(self):
self._set_busy(False)
if self._close_after_stop:self.close()
def selected_count(self):
return sum(self.table.item(row,0).checkState()==Qt.Checked for row in range(self.table.rowCount()))
def _update_selection(self,*args):
self.selection_label.setText(f"3 工程队列 共 {self.table.rowCount()} 个 · 已选 {self.selected_count()} 个")
if not self.busy:self.start_button.setEnabled(bool(self.projects) and self.selected_count()>0)
def _select(self,predicate):
if self.busy:return
for row in range(self.table.rowCount()):self.table.item(row,0).setCheckState(Qt.Checked if predicate(row) else Qt.Unchecked)
self._update_selection()
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 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())
def start_export(self):
if self.busy:return
items=[(row,info) for row,info in enumerate(self.projects) if self.table.item(row,0).checkState()==Qt.Checked]
try:
if not items:raise ValueError("请至少勾选一个工程")
if not self.output_edit.text().strip():raise ValueError("请选择输出目录")
options=self.options();engine=discover_engine(self.engine_edit.text().strip() or None)
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._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.append_log(f"开始队列:{len(items)} 个工程,单工程超时 {options.timeout:g} 秒。")
self.worker=BatchWorker(items,self.output_edit.text().strip(),options,exporter,self)
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.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.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
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)
def _batch_completed(self,message):
self.status_label.setText(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("队列停止,可重新勾选")
def _batch_finished(self):
self._set_busy(False);self._update_selection()
if self._close_after_stop:self.close()
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("已请求停止当前任务及后续队列。")
def closeEvent(self,event):
if self.busy:
if QMessageBox.question(self,"任务仍在运行","停止任务后关闭窗口?",QMessageBox.Yes|QMessageBox.No,QMessageBox.No)==QMessageBox.Yes:
self._close_after_stop=True;self.stop_export()
event.ignore()
else:event.accept()
+43
View File
@@ -0,0 +1,43 @@
from __future__ import annotations
import hashlib
from dataclasses import dataclass
from pathlib import Path
from pypdf import PdfReader
@dataclass(frozen=True)
class PdfCheck:
pages: int
size: int
sha256: str
def validate_pdf(path: Path) -> PdfCheck:
path = Path(path)
if not path.is_file():
raise ValueError("原生引擎未生成 PDF")
try:
with path.open("rb") as stream:
if stream.read(5) != b"%PDF-":
raise ValueError("输出不是有效 PDF")
stream.seek(0)
reader = PdfReader(stream, strict=True)
if reader.is_encrypted:
raise ValueError("输出 PDF 加密,无法验证")
pages = len(reader.pages)
if pages < 1:
raise ValueError("PDF 页数为零")
# Resolve each page and decompress content so truncated streams do
# not get accepted solely because the catalog is readable.
for page in reader.pages:
content = page.get_contents()
if content is not None:
content.get_data()
except ValueError:
raise
except Exception as error:
raise ValueError(f"PDF 结构验证失败:{error}") from error
digest = hashlib.sha256()
with path.open("rb") as stream:
while chunk := stream.read(1024 * 1024):
digest.update(chunk)
return PdfCheck(pages, path.stat().st_size, digest.hexdigest())
+85
View File
@@ -0,0 +1,85 @@
from __future__ import annotations
from collections import Counter
from dataclasses import asdict
from datetime import datetime
from pathlib import Path
import threading
import uuid
from PySide6.QtCore import QThread, Signal
from .scanner import scan_projects
from .exporter import write_json
from .path_policy import validate_queue_paths
class ScanWorker(QThread):
found = Signal(object)
failed = Signal(str)
def __init__(self, root, excluded, parent=None):
super().__init__(parent)
self.root, self.excluded = Path(root), tuple(excluded)
def run(self):
try:
self.found.emit(scan_projects(self.root, excluded_roots=self.excluded))
except Exception as error:
self.failed.emit(str(error))
class BatchWorker(QThread):
current = Signal(int, str)
result = Signal(int, object)
message = Signal(str)
completed = Signal(str)
def __init__(self, items, output, options, exporter, parent=None):
super().__init__(parent)
self.items, self.output, self.options, self.exporter = items, Path(output), options, exporter
self.cancel_event = threading.Event()
self.results = []
self.summary_path = ""
def run(self):
report = None
error_text = ""
record_error = ""
try:
validate_queue_paths([project for _,project in self.items],self.output,self.exporter.runs_root)
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:
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)
except Exception as error:
from .models import ExportResult
result = ExportResult(str(project.path),"uncertain",f"执行器异常,结果待核验:{error}")
error_text = str(error)
self.results.append(result)
self.result.emit(row, result)
try:
write_json(report, {"phase":"running", "requested":[str(p.path) for _,p in self.items], "results":[asdict(r) for r in self.results]})
except Exception as error:
record_error = str(error)
self.message.emit(f"批量记录更新失败,内存结果及逐工程提交预记录仍保留:{error}")
if result.status == "cancelled" or error_text:
break
except Exception as error:
error_text = str(error)
self.message.emit(f"队列执行异常:{error}")
finally:
counts = Counter(r.status 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}"
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]})
self.message.emit(f"批量报告:{report}")
except Exception as error:
record_error = str(error)
if error_text:
text += f";队列异常:{error_text}"
if record_error:
text += f";批量记录更新失败:{record_error},请核对逐工程预记录"
self.completed.emit(text)
+95
View File
@@ -0,0 +1,95 @@
from __future__ import annotations
import hashlib
import re
import shutil
import threading
from pathlib import Path, PureWindowsPath
from .scanner import PRUNED_DIRS, _DATABASE, HEADER_LIMIT, is_link, decode_text
from .models import ExportOptions
from .profiles import write_profile
COPY_PRUNED = PRUNED_DIRS | {"ces", "icxpro", "integration"}
def check_cancel(cancel: threading.Event | None) -> None:
if cancel is not None and cancel.is_set():
raise InterruptedError("任务已停止")
def source_files(root: Path):
root = Path(root)
def walk(directory):
for path in sorted(directory.iterdir(), key=lambda p: p.name.casefold()):
if path.is_dir() and path.name.casefold() in COPY_PRUNED:
continue
if is_link(path):
raise ValueError(f"工程含链接/重解析点,不复制:{path}")
if path.is_dir():
yield from walk(path)
elif path.is_file():
yield path
yield from walk(root)
def fingerprint(root: Path, cancel: threading.Event | None = None) -> dict[str, str]:
result = {}
for path in source_files(root):
check_cancel(cancel)
digest = hashlib.sha256()
with path.open("rb") as stream:
while chunk := stream.read(1024 * 1024):
check_cancel(cancel)
digest.update(chunk)
result[path.relative_to(root).as_posix()] = digest.hexdigest()
return result
def validate_project_database(project: Path) -> Path:
with project.open("rb") as stream:
match = _DATABASE.search(stream.read(HEADER_LIMIT))
if not match:
raise ValueError("工程缺少 iCDBDir 数据库路径")
value = PureWindowsPath(decode_text(match.group(1)))
if value.is_absolute() or value.drive or value.root or ".." in value.parts:
raise ValueError("数据库路径必须位于工程内,不能是绝对或父目录路径")
database = project.parent.joinpath(*value.parts)
if not database.is_dir() or is_link(database):
raise ValueError("工程数据库目录不存在,或是链接")
if any(part.casefold() in COPY_PRUNED for part in value.parts):
raise ValueError("数据库路径位于排除目录")
return database
def prepare_workspace(project: Path, run_dir: Path, options: ExportOptions, cancel: threading.Event | None = None) -> Path:
project = Path(project).absolute()
if is_link(project) or is_link(project.parent):
raise ValueError("工程或工程目录是链接")
project = project.resolve()
validate_project_database(project)
run_dir = Path(run_dir).resolve()
if run_dir == project.parent or run_dir.is_relative_to(project.parent) or project.parent.is_relative_to(run_dir):
raise ValueError("工作副本 workspace 与源工程目录不能互相包含")
destination = run_dir / "project"
destination.mkdir(parents=True, exist_ok=False)
for source in source_files(project.parent):
check_cancel(cancel)
target = destination / source.relative_to(project.parent)
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, target)
copied_project = destination / project.name
if options.library_override:
library = Path(options.library_override).absolute()
if not library.is_file() or library.suffix.casefold() != ".lmc" or is_link(library):
raise ValueError("本地中心库不存在、不是 .lmc,或是链接")
value = str(library.resolve()).replace("\\", "/")
if any(char in value for char in '\r\n\x00"'):
raise ValueError("本地中心库路径含非法字符")
payload = copied_project.read_bytes()
line = b'KEY CentralLibrary "' + value.encode("gb18030") + b'"'
pattern = rb'^\s*KEY\s+CentralLibrary\s+"[^"]*"\s*$'
if not re.search(pattern, payload, re.I | re.M):
raise ValueError("工程没有 CentralLibrary 项,无法安全覆盖本地中心库路径")
payload = re.sub(pattern, lambda match: line, payload, flags=re.I | re.M)
copied_project.write_bytes(payload)
write_profile(destination / "dxpdf.ini", options)
return copied_project
+14
View File
@@ -0,0 +1,14 @@
from pathlib import Path
import pytest
@pytest.fixture
def project_factory(tmp_path):
def make(relative="board", name="board", schematic=True):
root = tmp_path / relative
root.mkdir(parents=True, exist_ok=True)
project = root / f"{name}.prj"
project.write_text('SECTION DesignInfo\nKEY FrontEndSnapshot "DxD"\nENDSECTION\nSECTION Board1\nKEY RootBlock "ROOT"\nENDSECTION\nSECTION iCDB\nKEY iCDBDir ".\\database"\nENDSECTION\n' if schematic else 'SECTION PCB\nKEY ConfigType "PCB"\nENDSECTION\n')
(root / "database").mkdir(exist_ok=True)
(root / "database" / "icdb.dat").write_bytes(b"sample database")
return project
return make
+72
View File
@@ -0,0 +1,72 @@
import json
from pathlib import Path
from mentor_pdf_export.cli import main
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"
assert "engine_available" in data
def test_invalid_cli_export_returns_nonzero(tmp_path):
assert main(["--export",str(tmp_path / "missing.prj"),"--output",str(tmp_path / "pdf")]) != 0
def test_report_never_overwrites_project_even_for_self_check(project_factory):
project=project_factory()
before=project.read_bytes()
assert main(["--self-check","--report",str(project)]) == 2
assert project.read_bytes()==before
def test_report_inside_source_is_rejected_before_export(project_factory,tmp_path,monkeypatch):
from mentor_pdf_export import cli
from mentor_pdf_export.exporter import Exporter
from pypdf import PdfWriter
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):
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 engine,runs:Exporter(engine,runs,runner=runner))
rc=main(["--export",str(project),"--engine",str(engine),"--output",str(tmp_path/"pdfs"),"--runs-root",str(tmp_path/"runs"),"--report",str(protected)])
assert rc==2
assert protected.read_text()=="original"
assert not (tmp_path/"pdfs").exists()
def test_queue_destinations_protect_every_source_before_first_export(project_factory,tmp_path,monkeypatch):
from mentor_pdf_export import cli
from mentor_pdf_export.exporter import Exporter
from mentor_pdf_export.workspace import fingerprint
from pypdf import PdfWriter
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):
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 engine,runs:Exporter(engine,runs,runner=runner))
rc=main(["--export",str(a),str(b),"--engine",str(engine),"--output",str(b.parent/"database"),"--runs-root",str(tmp_path/"runs")])
assert rc==2
assert fingerprint(b.parent)==before
assert not (tmp_path/"runs").exists()
def test_self_check_cannot_overwrite_unowned_json(tmp_path):
report=tmp_path/"critical.json";report.write_text('{"user_setting":123}')
before=report.read_bytes()
assert main(["--self-check","--report",str(report)]) == 2
assert report.read_bytes()==before
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
+325
View File
@@ -0,0 +1,325 @@
import sys
import threading
from pathlib import Path
import pytest
from mentor_pdf_export.engine import run_engine, discover_engine
def test_capture_exit_and_logs(tmp_path):
rc = run_engine([sys.executable, "-c", "import sys; print('hello'); print('bad',file=sys.stderr); sys.exit(3)"], tmp_path, tmp_path / "log", threading.Event(), 10)
assert rc == 3
assert b"hello" in (tmp_path / "log/stdout.log").read_bytes()
assert b"bad" in (tmp_path / "log/stderr.log").read_bytes()
def test_engine_timeout(tmp_path):
with pytest.raises(TimeoutError):
run_engine([sys.executable, "-c", "import time; time.sleep(20)"], tmp_path, tmp_path / "logs", threading.Event(), .3)
def test_pre_cancel_does_not_launch(tmp_path):
cancel = threading.Event(); cancel.set()
with pytest.raises(InterruptedError):
run_engine(["must-not-run.exe"], tmp_path, tmp_path / "logs", cancel, 10)
def test_cancel_running_process(tmp_path):
cancel = threading.Event()
timer = threading.Timer(.3, cancel.set); timer.start()
try:
with pytest.raises(InterruptedError):
run_engine([sys.executable, "-c", "import time; time.sleep(20)"], tmp_path, tmp_path / "logs", cancel, 10)
finally:
timer.cancel()
def test_explicit_invalid_engine_never_falls_back(tmp_path):
with pytest.raises(FileNotFoundError):
discover_engine(tmp_path / "missing.exe")
@pytest.fixture
def owned_process_handles():
"""Retain handles, not recyclable PIDs; clean even assertion failures."""
import os
if os.name != "nt":
pytest.skip("Windows Job Object test")
import win32api
import win32con
import win32event
handles = []
def capture(pid):
handle = win32api.OpenProcess(
win32con.SYNCHRONIZE | win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_TERMINATE,
False, pid,
)
handles.append(handle)
return handle
yield capture
for handle in reversed(handles):
try:
if win32event.WaitForSingleObject(handle, 0) == win32event.WAIT_TIMEOUT:
win32api.TerminateProcess(handle, 1)
assert win32event.WaitForSingleObject(handle, 5000) == win32event.WAIT_OBJECT_0
finally:
handle.Close()
def child_tree_command(pid_file):
child = "import time; time.sleep(30)"
code = (
"import subprocess,time,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)); time.sleep(30)"
)
return [sys.executable, "-B", "-c", code]
def capture_child(pid_file, capture):
import time
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
try:
return capture(int(pid_file.read_text()))
except (FileNotFoundError, ValueError):
time.sleep(.01)
pytest.fail("Synthetic parent did not publish its child PID")
def test_timeout_terminates_owned_child_tree(tmp_path, monkeypatch, owned_process_handles):
import win32event
from mentor_pdf_export import engine
original = engine._create_job
child_handles = []
pid_file = tmp_path / "child.pid"
def assign(process):
owned_process_handles(process.pid)
return original(process)
def started(message):
if "PID=" in message:
child_handles.append(capture_child(pid_file, owned_process_handles))
monkeypatch.setattr(engine, "_create_job", assign)
with pytest.raises(TimeoutError):
run_engine(child_tree_command(pid_file), tmp_path, tmp_path / "logs", threading.Event(), 1.2, started)
assert len(child_handles) == 1
assert win32event.WaitForSingleObject(child_handles[0], 5000) == win32event.WAIT_OBJECT_0
@pytest.mark.parametrize("stop", ["timeout", "cancel"])
def test_delayed_job_binding_cannot_allow_early_child_escape(tmp_path, monkeypatch, owned_process_handles, stop):
import time
import win32event
from mentor_pdf_export import engine
original = engine._create_job
pid_file = tmp_path / "early-child.pid"
ran_before_binding = []
child_handles = []
cancel = threading.Event()
def delayed_assign(process):
owned_process_handles(process.pid)
# Old launch is running: wait for its early child. Fixed launch must
# remain suspended for the entire delay, without executing user code.
deadline = time.monotonic() + .8
while not pid_file.exists() and time.monotonic() < deadline:
time.sleep(.01)
ran_before_binding.append(pid_file.exists())
return original(process)
def started(message):
if "PID=" in message:
child_handles.append(capture_child(pid_file, owned_process_handles))
if stop == "cancel":
cancel.set()
monkeypatch.setattr(engine, "_create_job", delayed_assign)
expected = TimeoutError if stop == "timeout" else InterruptedError
with pytest.raises(expected):
run_engine(child_tree_command(pid_file), tmp_path, tmp_path / "logs", cancel, 2.2, started)
assert len(child_handles) == 1
child_stopped = win32event.WaitForSingleObject(child_handles[0], 1000) == win32event.WAIT_OBJECT_0
assert (ran_before_binding, child_stopped) == ([False], True), "Engine ran before Job binding or its early child survived stop"
def test_windows_native_launch_streams_flags_and_handle_allowlist(tmp_path, monkeypatch, owned_process_handles):
import _winapi
import win32api
import win32con
import win32event
from mentor_pdf_export import engine
original = _winapi.CreateProcess
launches = []
extra = win32event.CreateEvent(None, True, False, None)
win32api.SetHandleInformation(extra, win32con.HANDLE_FLAG_INHERIT, win32con.HANDLE_FLAG_INHERIT)
def create(*args):
flags, info = args[5], args[8]
inherited = info.lpAttributeList.get("handle_list", []) if info.lpAttributeList else []
launches.append((flags, set(inherited), {info.hStdInput, info.hStdOutput, info.hStdError}))
return original(*args)
monkeypatch.setattr(_winapi, "CreateProcess", create)
cwd = tmp_path / "working folder"
cwd.mkdir()
event_code = f"try:\n win32event.SetEvent({int(extra)})\nexcept pywintypes.error:\n pass"
code = (
"import os,sys,win32event,pywintypes; "
"assert sys.stdin.buffer.read()==b''; "
"print(os.getcwd()); print('stdout marker'); print('stderr marker',file=sys.stderr); "
f"exec({event_code!r}); "
"sys.exit(7)"
)
try:
assert engine.run_engine([sys.executable, "-B", "-c", code], cwd, tmp_path / "logs", threading.Event(), 10) == 7
assert len(launches) == 1
flags, inherited, standard = launches[0]
assert flags & 0x00000004, "CREATE_SUSPENDED is required"
assert flags & _winapi.CREATE_NO_WINDOW
assert len(inherited) == 3 and inherited == standard
assert win32event.WaitForSingleObject(extra, 0) == win32event.WAIT_TIMEOUT
assert str(cwd).encode() in (tmp_path / "logs/stdout.log").read_bytes()
assert b"stdout marker" in (tmp_path / "logs/stdout.log").read_bytes()
assert b"stderr marker" in (tmp_path / "logs/stderr.log").read_bytes()
finally:
extra.Close()
def process_handle_count():
import ctypes
from ctypes import wintypes
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
kernel.GetCurrentProcess.restype = wintypes.HANDLE
kernel.GetProcessHandleCount.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]
kernel.GetProcessHandleCount.restype = wintypes.BOOL
count = wintypes.DWORD()
assert kernel.GetProcessHandleCount(kernel.GetCurrentProcess(), ctypes.byref(count))
return count.value
@pytest.mark.parametrize("failure", ["create", "job_create", "job_configure", "assign", "resume", "cancel"])
def test_windows_startup_failures_do_not_execute_or_leak(tmp_path, monkeypatch, owned_process_handles, failure):
import gc
import _winapi
import msvcrt
import win32job
import win32process
import win32event
import mentor_pdf_export.workspace
from mentor_pdf_export import engine
original_create = _winapi.CreateProcess
original_assign = win32job.AssignProcessToJobObject
cancel = threading.Event()
parents = []
marker = tmp_path / "must-not-execute.txt"
def create(*args):
if failure == "create":
raise OSError("injected create failure")
result = original_create(*args)
parents.append(owned_process_handles(result[2]))
return result
def assign(*args):
if failure == "assign":
raise OSError("injected assignment failure")
result = original_assign(*args)
if failure == "cancel":
cancel.set()
return result
def resume(*args):
raise OSError("injected resume failure")
monkeypatch.setattr(_winapi, "CreateProcess", create)
monkeypatch.setattr(win32job, "AssignProcessToJobObject", assign)
if failure == "resume":
monkeypatch.setattr(win32process, "ResumeThread", resume)
if failure in {"job_create", "job_configure"}:
def fail_job(*args):
raise OSError("injected job setup failure")
target = "CreateJobObject" if failure == "job_create" else "SetInformationJobObject"
monkeypatch.setattr(win32job, target, fail_job)
gc.collect()
baseline = process_handle_count()
expected = InterruptedError if failure == "cancel" else OSError
with pytest.raises(expected):
run_engine([sys.executable, "-B", "-c", f"from pathlib import Path; Path({str(marker)!r}).write_text('unsafe')"], tmp_path, tmp_path / "logs", cancel, 10)
assert not marker.exists(), "Suspended process must not execute on setup failure/cancellation"
for handle in parents:
assert win32event.WaitForSingleObject(handle, 5000) == win32event.WAIT_OBJECT_0
gc.collect()
assert process_handle_count() == baseline + len(parents), "Leaked process/thread/job/stdio handle"
@pytest.mark.parametrize("fail_at", [1, 2, 3])
def test_windows_partial_stdio_setup_closes_handles(tmp_path, monkeypatch, owned_process_handles, fail_at):
import _winapi
import msvcrt
import mentor_pdf_export.workspace
from mentor_pdf_export import engine
original = _winapi.DuplicateHandle
calls = []
def duplicate(*args):
calls.append(args)
if len(calls) == fail_at:
raise OSError("injected stdio duplication failure")
return original(*args)
def must_not_launch(*args):
pytest.fail("Incomplete stdio must not create a process")
monkeypatch.setattr(_winapi, "DuplicateHandle", duplicate)
monkeypatch.setattr(_winapi, "CreateProcess", must_not_launch)
baseline = process_handle_count()
with pytest.raises(OSError, match="stdio duplication"):
engine.run_engine([sys.executable, "-B", "-c", "pass"], tmp_path, tmp_path / "logs", threading.Event(), 10)
assert process_handle_count() == baseline
def test_windows_exit_code_259_is_not_mistaken_for_running(tmp_path, owned_process_handles):
assert run_engine([sys.executable, "-B", "-c", "import sys; sys.exit(259)"], tmp_path, tmp_path / "logs", threading.Event(), 10) == 259
def test_callback_error_stops_owned_tree_but_not_other_process(tmp_path, monkeypatch, owned_process_handles):
import subprocess
import win32event
from mentor_pdf_export import engine
original = engine._create_job
pid_file = tmp_path / "callback-child.pid"
children = []
other = subprocess.Popen(
[sys.executable, "-B", "-c", "import time; time.sleep(30)"],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
creationflags=subprocess.CREATE_NO_WINDOW,
)
try:
other_handle = owned_process_handles(other.pid)
def assign(process):
owned_process_handles(process.pid)
return original(process)
def started(message):
if "PID=" in message:
children.append(capture_child(pid_file, owned_process_handles))
raise RuntimeError("injected event callback failure")
monkeypatch.setattr(engine, "_create_job", assign)
with pytest.raises(RuntimeError, match="event callback failure"):
run_engine(child_tree_command(pid_file), tmp_path, tmp_path / "logs", threading.Event(), 10, started)
assert len(children) == 1
assert win32event.WaitForSingleObject(children[0], 5000) == win32event.WAIT_OBJECT_0
assert win32event.WaitForSingleObject(other_handle, 0) == win32event.WAIT_TIMEOUT
finally:
if other.poll() is None:
other.kill()
other.wait(timeout=10)
+164
View File
@@ -0,0 +1,164 @@
from pathlib import Path
import threading
import pytest
from pypdf import PdfWriter
from mentor_pdf_export.models import ExportOptions
from mentor_pdf_export.scanner import read_project
from mentor_pdf_export.validation import validate_pdf
from mentor_pdf_export.exporter import Exporter, output_path
def pdf(path):
writer = PdfWriter()
writer.add_blank_page(width=500, height=400)
with Path(path).open("wb") as f:
writer.write(f)
def fake_runner(args, cwd, log_dir, cancel, timeout, on_event=None):
pdf(args[args.index("-a") + 1])
return 0
def test_validate_pdf(tmp_path):
file = tmp_path / "a.pdf"; pdf(file)
assert validate_pdf(file).pages == 1
file.write_bytes(b"not a pdf")
with pytest.raises(ValueError):
validate_pdf(file)
def test_invalid_zero_page_pdf(tmp_path):
file = tmp_path / "empty.pdf"
with file.open("wb") as f:
PdfWriter().write(f)
with pytest.raises(ValueError, match="页"):
validate_pdf(file)
def test_success_and_json_report(project_factory, tmp_path):
info = read_project(project_factory())
exporter = Exporter(Path("fake.exe"), tmp_path / "runs", runner=fake_runner)
result = exporter.export(info, tmp_path / "pdfs", ExportOptions(), threading.Event())
assert result.status == "success" and result.pages == 1
assert Path(result.output).is_file()
assert (Path(result.run_dir) / "result.json").is_file()
def test_old_output_preserved_on_failed_export(project_factory, tmp_path):
info = read_project(project_factory())
output = output_path(info, tmp_path / "pdfs"); output.parent.mkdir(); output.write_bytes(b"previous")
def failure(*args):
return 2
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=failure).export(info, output.parent, ExportOptions(overwrite=True), threading.Event())
assert result.status == "failed"
assert output.read_bytes() == b"previous"
def test_existing_output_needs_explicit_overwrite(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(), threading.Event())
assert result.status == "skipped"
assert output.read_bytes() == b"previous"
def test_failure_not_published_even_when_file_exists(project_factory, tmp_path):
info = read_project(project_factory())
def bad(args, *rest):
pdf(args[args.index("-a") + 1]); return 9
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=bad).export(info, tmp_path / "pdfs", ExportOptions(), threading.Event())
assert result.status == "failed"
assert not output_path(info, tmp_path / "pdfs").exists()
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")
return 0
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=changing).export(info, tmp_path / "pdfs", ExportOptions(), threading.Event())
assert result.status == "uncertain"
assert not output_path(info, tmp_path / "pdfs").exists()
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")
def test_cannot_output_inside_source(project_factory, tmp_path):
info = read_project(project_factory())
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=fake_runner).export(info, info.path.parent / "pdf", ExportOptions(), threading.Event())
assert result.status == "failed"
def test_pre_cancel_returns_cancelled(project_factory, tmp_path):
info = read_project(project_factory())
cancel = threading.Event(); cancel.set()
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=fake_runner).export(info, tmp_path / "pdfs", ExportOptions(), cancel)
assert result.status == "cancelled"
def test_final_source_check_is_before_publish(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")
original=module.fingerprint
count=0
def checked(*args):
nonlocal count
count+=1
assert output.read_bytes()==b"previous", "final source validation happened after publication"
return original(*args)
monkeypatch.setattr(module,"fingerprint",checked)
result=Exporter(Path("fake.exe"),tmp_path/"runs",runner=fake_runner).export(info,output.parent,ExportOptions(overwrite=True),threading.Event())
assert result.status=="success"
def test_result_record_failure_never_overwrites_old_pdf(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")
original=module.write_json
def fail_result(path,data):
if Path(path).name=="result.json":raise OSError("disk full")
return original(path,data)
monkeypatch.setattr(module,"write_json",fail_result)
result=Exporter(Path("fake.exe"),tmp_path/"runs",runner=fake_runner).export(info,output.parent,ExportOptions(overwrite=True),threading.Event())
assert result.status in {"failed","uncertain"}
assert output.read_bytes()==b"previous"
def test_post_publish_record_failure_returns_traceable_uncertain_result(project_factory,tmp_path,monkeypatch):
import mentor_pdf_export.exporter as module
info=read_project(project_factory())
original=module.write_json
count=0
def fail_final(path,data):
nonlocal count
if Path(path).name=="result.json":
count+=1
if count>=2:raise OSError("disk full after publish")
return original(path,data)
monkeypatch.setattr(module,"write_json",fail_final)
result=Exporter(Path("fake.exe"),tmp_path/"runs",runner=fake_runner).export(info,tmp_path/"pdfs",ExportOptions(),threading.Event())
assert result.status=="uncertain"
assert Path(result.output).is_file()
assert (Path(result.run_dir)/"result.json").is_file()
def test_staging_stat_failure_still_returns_and_records_result(project_factory,tmp_path,monkeypatch):
info=read_project(project_factory())
original=Path.exists
def denied(path):
if path.name.endswith(".partial.pdf"):raise OSError("staging stat denied")
return original(path)
monkeypatch.setattr(Path,"exists",denied)
def failure(args,*rest):
pdf(args[args.index("-a")+1]);return 2
result=Exporter(Path("fake.exe"),tmp_path/"runs",runner=failure).export(info,tmp_path/"pdfs",ExportOptions(),threading.Event())
assert result.status=="failed"
assert (Path(result.run_dir)/"result.json").is_file()
assert "暂存" in result.message
+16
View File
@@ -0,0 +1,16 @@
import importlib.util
from pathlib import Path
def test_bundle_excludes_foreign_icu_but_keeps_qt_and_crt():
file=Path(__file__).parents[1]/"packaging/bundle_policy.py"
spec=importlib.util.spec_from_file_location("bundle_policy",file)
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
entries=[
("icuuc.dll",r"C:\tools\poppler\icuuc.dll","BINARY"),
("icudt78.dll",r"C:\tools\poppler\icudt78.dll","BINARY"),
(r"PySide6\Qt6Core.dll",r"C:\python\PySide6\Qt6Core.dll","BINARY"),
("VCRUNTIME140.dll",r"C:\python\VCRUNTIME140.dll","BINARY"),
]
filtered=module.filter_binaries(entries)
assert filtered == entries[2:]
+33
View File
@@ -0,0 +1,33 @@
from pathlib import Path
from mentor_pdf_export.models import ExportOptions
from mentor_pdf_export.profiles import write_profile, build_command
def test_profile_clears_url_and_preserves_fonts(tmp_path):
ini = tmp_path / "dxpdf.ini"
ini.write_text("Color 1\nUrlProperties Value\nStartAcrobat 1\nFont_1 Courier-Bold\n")
write_profile(ini, ExportOptions())
lines = ini.read_text().splitlines()
assert "Color 4" in lines
assert "UrlProperties " in lines
assert "StartAcrobat 0" in lines
assert "Font_1 Courier-Bold" in lines
assert "ChangeIct2Sch 1" in lines
assert "VisibleHLs 0" in lines
def test_command_is_argument_list_not_shell():
args = build_command(Path("engine.exe"), Path("工程 x.prj"), Path("x.pdf"), ExportOptions(schematic="ROOT"))
assert args[:3] == ["engine.exe", "-project", "工程 x.prj"]
assert args[args.index("-c") + 1] == "4"
assert args[args.index("-schematic") + 1] == "ROOT"
assert "-p" in args and "-e" in args and "-i2s" in args
assert "-s" not in args and "-v" not in args and "-i" not in args
def test_disabled_flags_not_enabled():
args = build_command(Path("engine.exe"), Path("a.prj"), Path("a.pdf"), ExportOptions(popup=False, use_exclusion=False, change_ict=False))
assert "-p" not in args and "-e" not in args and "-i2s" not in args
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
+23
View File
@@ -0,0 +1,23 @@
from mentor_pdf_export.scanner import scan_projects
def test_scans_children_even_when_root_contains_project(project_factory, tmp_path):
root = project_factory(".", "top")
child = project_factory("nested", "child")
assert {p.path for p in scan_projects(tmp_path)} == {root.resolve(), child.resolve()}
def test_prunes_pcb_backups_and_output(project_factory, tmp_path):
good = project_factory("good")
project_factory("good/PCB", "fake")
project_factory("ProjectBackup/old", "old")
project_factory("output", "export_copy")
project_factory("layout", "layout", schematic=False)
assert [p.path for p in scan_projects(tmp_path)] == [good.resolve()]
def test_explicit_excluded_root(project_factory, tmp_path):
good = project_factory("good")
project_factory("other")
assert [p.path for p in scan_projects(tmp_path, excluded_roots=(tmp_path / "other",))] == [good.resolve()]
def test_reads_actual_root_block(project_factory, tmp_path):
project_factory()
assert scan_projects(tmp_path)[0].root_blocks == ("ROOT",)
+103
View File
@@ -0,0 +1,103 @@
import threading
from pathlib import Path
from pypdf import PdfWriter
from PySide6.QtCore import Qt
from mentor_pdf_export.ui import MainWindow
from mentor_pdf_export.exporter import Exporter
def runner(args, cwd, log_dir, cancel, timeout, on_event=None):
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
def make_window(qtbot, tmp_path, factory=None):
window = MainWindow(root=str(tmp_path), output=str(tmp_path / "pdfs"), runs_root=tmp_path.parent / (tmp_path.name + "-runs"), exporter_factory=factory)
qtbot.addWidget(window); window.show()
return window
def test_scan_and_toggle_does_not_reset_table(qtbot, project_factory, tmp_path):
project_factory()
window = make_window(qtbot,tmp_path)
qtbot.mouseClick(window.scan_button, Qt.LeftButton)
qtbot.waitUntil(lambda: window.table.rowCount() == 1, timeout=10000)
qtbot.waitUntil(lambda: not window.busy)
item = window.table.item(0,0)
assert item.checkState() == Qt.Checked
item.setCheckState(Qt.Unchecked)
assert window.table.item(0,0) is item
assert window.selected_count() == 0
window.select_all()
assert window.selected_count() == 1
def test_export_worker_result_and_buttons(qtbot, project_factory, tmp_path):
project_factory()
def factory(engine, runs):
return Exporter(engine,runs,runner=runner)
window = make_window(qtbot,tmp_path,factory)
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()
assert window.busy
assert not window.start_button.isEnabled()
assert not window.options_group.isEnabled()
qtbot.waitUntil(lambda: not window.busy,timeout=10000)
assert window.table.item(0,3).text()=="成功"
assert window.start_button.isEnabled()
assert not window.stop_button.isEnabled()
assert window.progress.value()==1
assert "1 页" in window.table.item(0,4).text()
def test_cancel_signal_is_requested(qtbot, project_factory, tmp_path):
project_factory()
started=threading.Event()
def waiting(args,cwd,log_dir,cancel,timeout,on_event=None):
started.set()
assert cancel.wait(5)
raise InterruptedError("任务已停止")
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()==1 and not window.busy,timeout=10000)
window.start_export()
qtbot.waitUntil(started.is_set,timeout=10000)
window.stop_export()
qtbot.waitUntil(lambda:not window.busy,timeout=10000)
assert window.table.item(0,3).text()=="已停止"
def test_failed_only_selection(qtbot, project_factory, tmp_path):
project_factory("one");project_factory("two")
window = make_window(qtbot,tmp_path)
window.scan_projects()
qtbot.waitUntil(lambda:window.table.rowCount()==2 and not window.busy,timeout=10000)
window.table.item(0,3).setText("失败")
window.table.item(1,3).setText("成功")
window.select_failed()
assert window.table.item(0,0).checkState()==Qt.Checked
assert window.table.item(1,0).checkState()==Qt.Unchecked
def test_ui_preflights_all_source_paths_before_queue(qtbot,project_factory,tmp_path):
project_factory("a");b=project_factory("b")
window=make_window(qtbot,tmp_path,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()==2 and not window.busy,timeout=10000)
window.output_edit.setText(str(b.parent/"database"))
window.start_export()
# A must not start and write into B while the second source is unprotected.
unexpectedly_started=window.busy
if window.busy:
window.stop_export()
qtbot.waitUntil(lambda:not window.busy,timeout=10000)
assert not unexpectedly_started
assert window.worker is None
+42
View File
@@ -0,0 +1,42 @@
from pathlib import Path
from pypdf import PdfWriter
from mentor_pdf_export.models import ExportOptions
from mentor_pdf_export.scanner import read_project
from mentor_pdf_export.exporter import Exporter
from mentor_pdf_export.workers import BatchWorker
def test_batch_pre_record_failure_stops_before_engine(qapp,project_factory,tmp_path,monkeypatch):
from mentor_pdf_export import workers
called=[]
def runner(*args):called.append(True);return 0
def full(*args):raise OSError("disk full")
monkeypatch.setattr(workers,"write_json",full)
info=read_project(project_factory())
worker=BatchWorker([(0,info)],tmp_path/"pdfs",ExportOptions(),Exporter(Path("fake.exe"),tmp_path/"runs",runner=runner))
worker.run()
assert not called
assert not worker.results
def test_late_batch_record_failure_keeps_result_and_pre_record(qapp,project_factory,tmp_path,monkeypatch):
from mentor_pdf_export import workers
original=workers.write_json
count=0
def fail_later(path,data):
nonlocal count
count+=1
if count>1:raise OSError("disk full later")
original(path,data)
monkeypatch.setattr(workers,"write_json",fail_later)
def runner(args,*rest):
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
info=read_project(project_factory())
worker=BatchWorker([(0,info)],tmp_path/"pdfs",ExportOptions(),Exporter(Path("fake.exe"),tmp_path/"runs",runner=runner))
texts=[];worker.completed.connect(texts.append)
worker.run()
assert len(worker.results)==1 and worker.results[0].status=="success"
assert Path(worker.summary_path).exists()
assert "成功 1" in texts[-1] and "记录" in texts[-1]
+52
View File
@@ -0,0 +1,52 @@
import pytest
from mentor_pdf_export.models import ExportOptions
from mentor_pdf_export.workspace import prepare_workspace, fingerprint
def test_copy_changes_profile_not_original(project_factory, tmp_path):
source = project_factory()
(source.parent / "dxpdf.ini").write_text("Color 1\nUrlProperties Value\n")
(source.parent / "PCB").mkdir()
(source.parent / "PCB" / "private.bin").write_bytes(b"pcb")
before = fingerprint(source.parent)
copied = prepare_workspace(source, tmp_path / "runs" / "one", ExportOptions())
assert copied.is_file()
assert not (copied.parent / "PCB").exists()
assert "Color 4" in (copied.parent / "dxpdf.ini").read_text()
assert before == fingerprint(source.parent)
def test_rejects_database_outside_project(project_factory, tmp_path):
project = project_factory()
project.write_text(project.read_text().replace('.\\database', '..\\other'))
with pytest.raises(ValueError, match="数据库|database"):
prepare_workspace(project, tmp_path / "run", ExportOptions())
def test_rejects_workspace_inside_source(project_factory):
source = project_factory()
with pytest.raises(ValueError, match="副本|workspace"):
prepare_workspace(source, source.parent / "run", ExportOptions())
def test_library_override_only_changes_copy(project_factory, tmp_path):
source = project_factory()
source.write_text(source.read_text() + 'KEY CentralLibrary "\\\\oldserver\\lib\\mentor.lmc"\n')
library = tmp_path / "library.lmc";library.write_bytes(b"sample library")
before = fingerprint(source.parent)
copied = prepare_workspace(source, tmp_path / "run", ExportOptions(library_override=str(library)))
assert str(library).replace("\\", "/") in copied.read_text().replace("\\", "/")
assert fingerprint(source.parent) == before
assert library.read_bytes() == b"sample library"
def test_missing_library_override_rejected(project_factory, tmp_path):
source = project_factory()
with pytest.raises(ValueError, match="中心库"):
prepare_workspace(source, tmp_path / "run", ExportOptions(library_override=str(tmp_path / "missing.lmc")))
def test_library_override_preserves_next_project_line(project_factory, tmp_path):
source = project_factory()
source.write_text(source.read_text() + 'KEY CentralLibrary "\\\\oldserver\\lib\\mentor.lmc"\nKEY DxD_Version "7.9.4"\n')
library=tmp_path/"local.lmc";library.write_bytes(b"lib")
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