feat: add current-project PDF export
This commit is contained in:
1 parent
771d8efb87
commit
c8caaf8daf
22 files changed
+1959
-1
No files matched your search
@@ -34,6 +34,11 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
result = UpdateInstaller().install(plan)
|
||||
return 0 if result.state == "installed" else 1
|
||||
|
||||
if arguments and arguments[0] == "pdf-export-event":
|
||||
from dx_productivity.features.pdf_export.cli import main as pdf_export_main
|
||||
|
||||
return pdf_export_main(arguments[1:])
|
||||
|
||||
if arguments and arguments[0] == "ui":
|
||||
arguments = arguments[1:]
|
||||
|
||||
|
||||
@@ -49,6 +49,12 @@ def load_request(path: Path) -> DesignSnapshot:
|
||||
|
||||
nets = _parse_nets(data)
|
||||
selected_nets = _parse_selected_nets(data)
|
||||
active_block_name = data.get("active_block_name", "")
|
||||
if not isinstance(active_block_name, str):
|
||||
raise ProtocolError("active_block_name must be a string")
|
||||
current_sheet_number = data.get("current_sheet_number")
|
||||
if current_sheet_number is not None and type(current_sheet_number) is not int:
|
||||
raise ProtocolError("current_sheet_number must be an integer or null")
|
||||
|
||||
return DesignSnapshot(
|
||||
format_version=FORMAT_VERSION,
|
||||
@@ -59,6 +65,8 @@ def load_request(path: Path) -> DesignSnapshot:
|
||||
components=components,
|
||||
nets=nets,
|
||||
selected_nets=selected_nets,
|
||||
active_block_name=active_block_name,
|
||||
current_sheet_number=current_sheet_number,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -194,6 +194,8 @@ class DesignSnapshot:
|
||||
components: tuple[ComponentRecord, ...]
|
||||
nets: tuple[NetRecord, ...] = ()
|
||||
selected_nets: tuple[str, ...] = ()
|
||||
active_block_name: str = ""
|
||||
current_sheet_number: int | None = None
|
||||
|
||||
@property
|
||||
def component_count(self) -> int:
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Single-project PDF export for DxDesigner."""
|
||||
@@ -0,0 +1,41 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
from .exporter import export_project
|
||||
from .settings import load_settings, normalized_project_path
|
||||
|
||||
|
||||
def _write_status(path: Path, value: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex[:8]}.tmp")
|
||||
try:
|
||||
temporary.write_text(value.strip() + "\n", encoding="utf-8")
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="DxDesignerTools pdf-export-event")
|
||||
parser.add_argument("--settings", required=True, type=Path)
|
||||
parser.add_argument("--project", required=True, type=Path)
|
||||
parser.add_argument("--active-block", default="")
|
||||
parser.add_argument("--status-file", required=True, type=Path)
|
||||
options = parser.parse_args(argv)
|
||||
settings = load_settings(options.project, config_path=options.settings)
|
||||
if not settings.auto_export or normalized_project_path(settings.project_path) != normalized_project_path(options.project):
|
||||
_write_status(options.status_file, "自动导出已忽略:设置未启用或当前工程不同")
|
||||
return 0
|
||||
result = export_project(
|
||||
settings,
|
||||
threading.Event(),
|
||||
active_block_name=options.active_block,
|
||||
overwrite=True,
|
||||
)
|
||||
_write_status(options.status_file, result.message)
|
||||
return 0 if result.state == "success" else 1
|
||||
@@ -0,0 +1,243 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from typing import Callable, Sequence
|
||||
|
||||
|
||||
def discover_engine(explicit: Path | None = None) -> Path:
|
||||
candidates = [Path(explicit)] if explicit else []
|
||||
if not explicit and os.environ.get("SDD_HOME"):
|
||||
candidates.append(Path(os.environ["SDD_HOME"]) / "wv/win32/bin/sch2pdf.exe")
|
||||
if not explicit:
|
||||
for drive in "CDEFG":
|
||||
for vendor in ("Mentor", "MentorGraphics"):
|
||||
parent = Path(f"{drive}:/") / vendor
|
||||
if not parent.is_dir():
|
||||
continue
|
||||
for version in sorted(parent.iterdir(), reverse=True):
|
||||
candidates.append(version / "SDD_HOME/wv/win32/bin/sch2pdf.exe")
|
||||
for candidate in candidates:
|
||||
if candidate.is_file() and candidate.name.casefold() == "sch2pdf.exe":
|
||||
return candidate.resolve()
|
||||
raise FileNotFoundError(
|
||||
"未找到 sch2pdf.exe,请选择本机 DxDesigner EE 安装中的原生导出引擎"
|
||||
)
|
||||
|
||||
|
||||
class _WindowsProcess:
|
||||
def __init__(self, args: Sequence[str], handle: int, pid: int) -> None:
|
||||
self.args = list(args)
|
||||
self.handle = handle
|
||||
self.pid = pid
|
||||
self.returncode: int | None = None
|
||||
|
||||
def poll(self) -> int | None:
|
||||
import _winapi
|
||||
|
||||
if self.returncode is None and _winapi.WaitForSingleObject(self.handle, 0) == _winapi.WAIT_OBJECT_0:
|
||||
self.returncode = _winapi.GetExitCodeProcess(self.handle)
|
||||
return self.returncode
|
||||
|
||||
def wait(self, timeout: float) -> int:
|
||||
import _winapi
|
||||
|
||||
if _winapi.WaitForSingleObject(self.handle, max(0, int(timeout * 1000))) == _winapi.WAIT_TIMEOUT:
|
||||
raise subprocess.TimeoutExpired(self.args, timeout)
|
||||
self.returncode = _winapi.GetExitCodeProcess(self.handle)
|
||||
return self.returncode
|
||||
|
||||
def kill(self) -> None:
|
||||
import _winapi
|
||||
|
||||
try:
|
||||
_winapi.TerminateProcess(self.handle, 1)
|
||||
except OSError as error:
|
||||
if error.winerror != 5 or _winapi.WaitForSingleObject(self.handle, 10000) != _winapi.WAIT_OBJECT_0:
|
||||
raise
|
||||
|
||||
def close(self) -> None:
|
||||
import _winapi
|
||||
|
||||
if self.handle is not None:
|
||||
_winapi.CloseHandle(self.handle)
|
||||
self.handle = None
|
||||
|
||||
|
||||
def _create_job(process: _WindowsProcess):
|
||||
import win32job
|
||||
|
||||
job = win32job.CreateJobObject(None, "")
|
||||
try:
|
||||
info = win32job.QueryInformationJobObject(
|
||||
job, win32job.JobObjectExtendedLimitInformation
|
||||
)
|
||||
info["BasicLimitInformation"]["LimitFlags"] |= (
|
||||
win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
)
|
||||
win32job.SetInformationJobObject(
|
||||
job, win32job.JobObjectExtendedLimitInformation, info
|
||||
)
|
||||
win32job.AssignProcessToJobObject(job, process.handle)
|
||||
except BaseException:
|
||||
job.Close()
|
||||
raise
|
||||
return job
|
||||
|
||||
|
||||
def _start_windows_process(
|
||||
args: Sequence[str], cwd: Path, stdout, stderr, cancel: Event
|
||||
):
|
||||
import _winapi
|
||||
import msvcrt
|
||||
import win32con
|
||||
import win32process
|
||||
|
||||
process = None
|
||||
job = None
|
||||
thread_handle = None
|
||||
inherited = []
|
||||
with open(os.devnull, "rb") as stdin:
|
||||
try:
|
||||
current = _winapi.GetCurrentProcess()
|
||||
for stream in (stdin, stdout, stderr):
|
||||
inherited.append(
|
||||
_winapi.DuplicateHandle(
|
||||
current,
|
||||
msvcrt.get_osfhandle(stream.fileno()),
|
||||
current,
|
||||
0,
|
||||
True,
|
||||
_winapi.DUPLICATE_SAME_ACCESS,
|
||||
)
|
||||
)
|
||||
startup = subprocess.STARTUPINFO()
|
||||
startup.dwFlags = subprocess.STARTF_USESTDHANDLES
|
||||
startup.hStdInput, startup.hStdOutput, startup.hStdError = inherited
|
||||
startup.lpAttributeList = {"handle_list": inherited}
|
||||
handle, thread_handle, pid, _ = _winapi.CreateProcess(
|
||||
None,
|
||||
subprocess.list2cmdline([os.fspath(arg) for arg in args]),
|
||||
None,
|
||||
None,
|
||||
True,
|
||||
win32con.CREATE_SUSPENDED | subprocess.CREATE_NO_WINDOW,
|
||||
None,
|
||||
os.fspath(cwd),
|
||||
startup,
|
||||
)
|
||||
process = _WindowsProcess(args, handle, pid)
|
||||
job = _create_job(process)
|
||||
if cancel.is_set():
|
||||
raise InterruptedError("导出已取消")
|
||||
win32process.ResumeThread(thread_handle)
|
||||
return process, job
|
||||
except BaseException:
|
||||
try:
|
||||
if job is not None:
|
||||
job.Close()
|
||||
finally:
|
||||
if process is not None:
|
||||
try:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait(10)
|
||||
finally:
|
||||
process.close()
|
||||
raise
|
||||
finally:
|
||||
if thread_handle is not None:
|
||||
_winapi.CloseHandle(thread_handle)
|
||||
for handle in inherited:
|
||||
_winapi.CloseHandle(handle)
|
||||
|
||||
|
||||
def _preserve_completed_job_children(job) -> None:
|
||||
import win32job
|
||||
|
||||
info = win32job.QueryInformationJobObject(
|
||||
job, win32job.JobObjectExtendedLimitInformation
|
||||
)
|
||||
info["BasicLimitInformation"]["LimitFlags"] &= (
|
||||
~win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
)
|
||||
win32job.SetInformationJobObject(
|
||||
job, win32job.JobObjectExtendedLimitInformation, info
|
||||
)
|
||||
|
||||
|
||||
def run_engine(
|
||||
args: Sequence[str],
|
||||
cwd: Path,
|
||||
log_dir: Path,
|
||||
cancel: Event,
|
||||
timeout: float,
|
||||
on_event: Callable[[str], None] | None = None,
|
||||
) -> int:
|
||||
log_dir = Path(log_dir)
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
emit = on_event or (lambda _message: None)
|
||||
started = time.monotonic()
|
||||
process = None
|
||||
job = None
|
||||
with (log_dir / "stdout.log").open("wb") as stdout, (log_dir / "stderr.log").open("wb") as stderr:
|
||||
try:
|
||||
if os.name == "nt":
|
||||
process, job = _start_windows_process(args, Path(cwd), stdout, stderr, cancel)
|
||||
else:
|
||||
process = subprocess.Popen(
|
||||
args,
|
||||
cwd=cwd,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=stdout,
|
||||
stderr=stderr,
|
||||
)
|
||||
emit(f"原生引擎已启动,PID={process.pid}")
|
||||
last_heartbeat = started
|
||||
while process.poll() is None:
|
||||
if cancel.is_set():
|
||||
raise InterruptedError("导出已取消")
|
||||
now = time.monotonic()
|
||||
if now - started > timeout:
|
||||
raise TimeoutError(f"原生导出超过 {timeout:g} 秒")
|
||||
if now - last_heartbeat >= 10:
|
||||
emit(f"等待原生引擎,已用时 {now - started:.0f} 秒")
|
||||
last_heartbeat = now
|
||||
time.sleep(0.05)
|
||||
if job is not None and process.returncode == 0:
|
||||
import win32job
|
||||
|
||||
_preserve_completed_job_children(job)
|
||||
announced = False
|
||||
while win32job.QueryInformationJobObject(
|
||||
job, win32job.JobObjectBasicAccountingInformation
|
||||
)["ActiveProcesses"]:
|
||||
if not announced:
|
||||
emit("原生出图完成,等待后台数据库服务完成写回")
|
||||
announced = True
|
||||
if cancel.is_set():
|
||||
raise InterruptedError("导出已取消;后台数据库服务继续完成写回")
|
||||
if time.monotonic() - started > timeout:
|
||||
raise TimeoutError("后台数据库服务未在限时内完成写回,未发布 PDF")
|
||||
time.sleep(0.05)
|
||||
if cancel.is_set():
|
||||
raise InterruptedError("导出已取消")
|
||||
return int(process.returncode)
|
||||
finally:
|
||||
try:
|
||||
if job is not None:
|
||||
if process is not None and process.poll() is not None:
|
||||
_preserve_completed_job_children(job)
|
||||
job.Close()
|
||||
finally:
|
||||
if process is not None:
|
||||
try:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait(timeout=10) if os.name != "nt" else process.wait(10)
|
||||
finally:
|
||||
if os.name == "nt":
|
||||
process.close()
|
||||
@@ -0,0 +1,446 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PureWindowsPath
|
||||
import re
|
||||
import stat
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import suppress
|
||||
from typing import Callable
|
||||
|
||||
from pypdf import PdfReader
|
||||
|
||||
from .engine import discover_engine, run_engine
|
||||
from .models import ExportScope, PdfExportResult, PdfExportSettings
|
||||
|
||||
|
||||
HEADER_LIMIT = 512 * 1024
|
||||
PRUNED_DIRS = frozenset(
|
||||
{"pcb", "projectbackup", "backup", "backups", ".git", ".venv", "__pycache__", "output", "runs", "artifacts", "dist", "build", "log files"}
|
||||
)
|
||||
FRONT_END = re.compile(rb'^\s*KEY\s+FrontEndSnapshot\s+"DxD"\s*$', re.I | re.M)
|
||||
DATABASE = re.compile(rb'^\s*KEY\s+iCDBDir\s+"([^"]+)"\s*$', re.I | re.M)
|
||||
_WRITE_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _is_link(path: Path) -> bool:
|
||||
details = path.lstat()
|
||||
return stat.S_ISLNK(details.st_mode) or bool(
|
||||
getattr(details, "st_file_attributes", 0)
|
||||
& getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
|
||||
)
|
||||
|
||||
|
||||
def validate_project(project: Path) -> tuple[Path, Path]:
|
||||
project = Path(project).absolute()
|
||||
if project.suffix.casefold() != ".prj" or not project.is_file() or _is_link(project):
|
||||
raise ValueError("当前文件不是有效的 DxDesigner .prj 工程")
|
||||
project = project.resolve()
|
||||
source_root = project.parent
|
||||
if _is_link(source_root):
|
||||
raise ValueError("工程目录是链接或重解析点,无法安全核验")
|
||||
with project.open("rb") as stream:
|
||||
header = stream.read(HEADER_LIMIT)
|
||||
if not FRONT_END.search(header):
|
||||
raise ValueError("工程文件不是 DxDesigner 原理图工程")
|
||||
match = DATABASE.search(header)
|
||||
if not match:
|
||||
raise ValueError("工程文件缺少 iCDBDir 数据库路径")
|
||||
raw = match.group(1)
|
||||
database_text = ""
|
||||
for encoding in ("utf-8-sig", "gb18030", "cp1252"):
|
||||
try:
|
||||
database_text = raw.decode(encoding)
|
||||
break
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
if not database_text:
|
||||
raise ValueError("无法解码工程数据库路径")
|
||||
relative = PureWindowsPath(database_text)
|
||||
if relative.is_absolute() or relative.drive or relative.root or ".." in relative.parts:
|
||||
raise ValueError("工程数据库路径必须位于工程目录内")
|
||||
database = source_root.joinpath(*relative.parts)
|
||||
current = source_root
|
||||
for part in relative.parts:
|
||||
current = current / part
|
||||
if current.exists() and _is_link(current):
|
||||
raise ValueError("工程数据库路径含链接或重解析点")
|
||||
if not database.is_dir():
|
||||
raise ValueError("工程数据库目录不存在,或是链接")
|
||||
resolved_database = database.resolve()
|
||||
if not resolved_database.is_relative_to(source_root):
|
||||
raise ValueError("工程数据库目录解析到了工程目录之外")
|
||||
return project, resolved_database
|
||||
|
||||
|
||||
def _source_files(root: Path):
|
||||
def walk(directory: Path):
|
||||
for path in sorted(directory.iterdir(), key=lambda item: item.name.casefold()):
|
||||
if path.is_dir() and path.name.casefold() in PRUNED_DIRS:
|
||||
continue
|
||||
if _is_link(path):
|
||||
raise ValueError(f"工程含链接或重解析点,无法安全核验:{path}")
|
||||
if path.is_dir():
|
||||
yield from walk(path)
|
||||
elif path.is_file():
|
||||
yield path
|
||||
|
||||
yield from walk(root)
|
||||
|
||||
|
||||
def _fingerprint(root: Path, cancel: threading.Event) -> dict[str, str]:
|
||||
digest_map: dict[str, str] = {}
|
||||
for path in _source_files(root):
|
||||
if cancel.is_set():
|
||||
raise InterruptedError("导出已取消")
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
while chunk := stream.read(1024 * 1024):
|
||||
if cancel.is_set():
|
||||
raise InterruptedError("导出已取消")
|
||||
digest.update(chunk)
|
||||
digest_map[path.relative_to(root).as_posix()] = digest.hexdigest()
|
||||
return digest_map
|
||||
|
||||
|
||||
def _changes(before: dict[str, str], after: dict[str, str]) -> dict[str, list[str]]:
|
||||
old, new = set(before), set(after)
|
||||
return {
|
||||
"modified": sorted(name for name in old & new if before[name] != after[name]),
|
||||
"added": sorted(new - old),
|
||||
"removed": sorted(old - new),
|
||||
}
|
||||
|
||||
|
||||
def _classify_changes(
|
||||
changes: dict[str, list[str]], database_relative: str
|
||||
) -> tuple[dict[str, list[str]], dict[str, list[str]]]:
|
||||
accepted = {kind: [] for kind in changes}
|
||||
blocked = {kind: [] for kind in changes}
|
||||
prefix = tuple(part.casefold() for part in database_relative.strip("/").split("/") if part)
|
||||
runtime_dirs = {"events", "log", "plog", "dbcheck", "dbupgrade"}
|
||||
for kind, names in changes.items():
|
||||
for name in names:
|
||||
parts = tuple(name.split("/"))
|
||||
folded = tuple(part.casefold() for part in parts)
|
||||
relative = folded[len(prefix):] if folded[: len(prefix)] == prefix else ()
|
||||
native = False
|
||||
if relative == ("icdb.dat",):
|
||||
native = kind == "modified"
|
||||
elif relative in {("cdbsvr", "saddress.adr"), ("cdbsvr", "backup.lck")}:
|
||||
native = True
|
||||
elif len(relative) > 2 and relative[0] == "cdbsvr" and relative[1] in runtime_dirs:
|
||||
native = True
|
||||
elif len(relative) == 2 and relative[0] == "cdbback" and relative[1].endswith(".zip"):
|
||||
native = kind == "added"
|
||||
(accepted if native else blocked)[kind].append(name)
|
||||
return accepted, blocked
|
||||
|
||||
|
||||
def _validate_pdf(path: Path) -> tuple[int, int, str]:
|
||||
if not path.is_file():
|
||||
raise ValueError("原生引擎未生成 PDF")
|
||||
try:
|
||||
with path.open("rb") as stream:
|
||||
if stream.read(5) != b"%PDF-":
|
||||
raise ValueError("输出不是有效 PDF")
|
||||
stream.seek(0)
|
||||
reader = PdfReader(stream, strict=True)
|
||||
if reader.is_encrypted:
|
||||
raise ValueError("输出 PDF 已加密,无法验证")
|
||||
pages = len(reader.pages)
|
||||
if pages < 1:
|
||||
raise ValueError("PDF 页数为零")
|
||||
for page in reader.pages:
|
||||
contents = page.get_contents()
|
||||
if contents is not None:
|
||||
contents.get_data()
|
||||
except ValueError:
|
||||
raise
|
||||
except Exception as error:
|
||||
raise ValueError(f"PDF 结构验证失败:{error}") from error
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
while chunk := stream.read(1024 * 1024):
|
||||
digest.update(chunk)
|
||||
return pages, path.stat().st_size, digest.hexdigest()
|
||||
|
||||
|
||||
def _write_json(path: Path, payload: object) -> None:
|
||||
temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex[:8]}.tmp")
|
||||
try:
|
||||
with temporary.open("x", encoding="utf-8", newline="\n") as stream:
|
||||
json.dump(payload, stream, ensure_ascii=False, indent=2)
|
||||
stream.write("\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _safe_name(value: str) -> str:
|
||||
cleaned = re.sub(r'[<>:"/\\|?*\x00-\x1f]+', "_", value).strip(" .")
|
||||
return cleaned[:80] or "block"
|
||||
|
||||
|
||||
def output_path(settings: PdfExportSettings, active_block_name: str = "") -> Path:
|
||||
project = Path(settings.project_path)
|
||||
stem = _safe_name(project.stem)
|
||||
if settings.scope is ExportScope.PROJECT:
|
||||
suffix = "whole-project"
|
||||
elif settings.scope is ExportScope.CURRENT_PAGE:
|
||||
name = active_block_name.strip()
|
||||
if not name:
|
||||
raise ValueError("无法读取当前活动页的 Block 名称,请刷新设计快照")
|
||||
digest = hashlib.sha256(name.casefold().encode("utf-8")).hexdigest()[:6]
|
||||
suffix = f"current-page-{_safe_name(name)}-{digest}"
|
||||
else:
|
||||
name = settings.block_name.strip()
|
||||
if not name:
|
||||
raise ValueError("请输入原理图或 Block 名称")
|
||||
digest = hashlib.sha256(name.casefold().encode("utf-8")).hexdigest()[:6]
|
||||
suffix = f"block-{_safe_name(name)}-{digest}"
|
||||
return Path(settings.output_dir) / f"{stem}_{suffix}.pdf"
|
||||
|
||||
|
||||
def build_command(
|
||||
engine: Path,
|
||||
project: Path,
|
||||
output: Path,
|
||||
scope: ExportScope,
|
||||
block_name: str = "",
|
||||
) -> list[str]:
|
||||
command = [
|
||||
str(engine),
|
||||
"-project",
|
||||
str(project),
|
||||
"-a",
|
||||
str(output),
|
||||
"-c",
|
||||
"4",
|
||||
"-p",
|
||||
"-e",
|
||||
"-i2s",
|
||||
"-udx",
|
||||
]
|
||||
if scope is not ExportScope.PROJECT:
|
||||
if not block_name.strip() or any(char in block_name for char in "\r\n\x00"):
|
||||
raise ValueError("当前页或指定范围缺少有效 Block 名称")
|
||||
command.extend(("-schematic", block_name.strip()))
|
||||
return command
|
||||
|
||||
|
||||
def _validate_output_location(project_root: Path, output_dir: Path) -> Path:
|
||||
output = Path(output_dir).expanduser().resolve(strict=False)
|
||||
if output == project_root or output.is_relative_to(project_root):
|
||||
raise ValueError("PDF 输出目录必须位于源工程目录之外")
|
||||
return output
|
||||
|
||||
|
||||
def export_project(
|
||||
settings: PdfExportSettings,
|
||||
cancel: threading.Event,
|
||||
on_event: Callable[[str], None] | None = None,
|
||||
*,
|
||||
active_block_name: str = "",
|
||||
overwrite: bool = False,
|
||||
timeout: float = 300,
|
||||
local_app_data: Path | None = None,
|
||||
) -> PdfExportResult:
|
||||
began = time.monotonic()
|
||||
emit_external = on_event or (lambda _message: None)
|
||||
run_root = Path(
|
||||
local_app_data or os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local")
|
||||
) / "DxProductivity" / "pdf-runs"
|
||||
state_root = run_root.parent
|
||||
run_dir = run_root / (datetime.now().strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8])
|
||||
stage: Path | None = None
|
||||
final_path: Path | None = None
|
||||
pages = 0
|
||||
state, message = "failed", ""
|
||||
warnings: list[str] = []
|
||||
lock_acquired = False
|
||||
file_lock = None
|
||||
file_lock_acquired = False
|
||||
before: dict[str, str] | None = None
|
||||
source_root: Path | None = None
|
||||
database_relative: str | None = None
|
||||
|
||||
def emit(value: str) -> None:
|
||||
try:
|
||||
emit_external(value)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
with (run_dir / "events.log").open("a", encoding="utf-8") as stream:
|
||||
stream.write(datetime.now().isoformat(timespec="seconds") + " " + value + "\n")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
try:
|
||||
if not _WRITE_LOCK.acquire(blocking=False):
|
||||
return PdfExportResult(Path(settings.project_path), "failed", "已有 PDF 导出正在执行")
|
||||
lock_acquired = True
|
||||
state_root.mkdir(parents=True, exist_ok=True)
|
||||
file_lock = (state_root / "pdf-export.lock").open("a+b")
|
||||
file_lock.seek(0, os.SEEK_END)
|
||||
if file_lock.tell() == 0:
|
||||
file_lock.write(b"0")
|
||||
file_lock.flush()
|
||||
file_lock.seek(0)
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
try:
|
||||
msvcrt.locking(file_lock.fileno(), msvcrt.LK_NBLCK, 1)
|
||||
except OSError:
|
||||
return PdfExportResult(Path(settings.project_path), "failed", "已有 PDF 导出正在执行")
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
try:
|
||||
fcntl.flock(file_lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except OSError:
|
||||
return PdfExportResult(Path(settings.project_path), "failed", "已有 PDF 导出正在执行")
|
||||
file_lock_acquired = True
|
||||
run_dir.mkdir(parents=True, exist_ok=False)
|
||||
project, database = validate_project(Path(settings.project_path))
|
||||
source_root = project.parent
|
||||
database_relative = database.relative_to(source_root).as_posix()
|
||||
output_dir = _validate_output_location(source_root, Path(settings.output_dir))
|
||||
final_path = output_path(settings, active_block_name)
|
||||
final_path = output_dir / final_path.name
|
||||
if final_path.exists() and not overwrite:
|
||||
state, message = "exists", f"已有同名 PDF:{final_path}"
|
||||
return PdfExportResult(project, state, message, final_path, run_dir=run_dir)
|
||||
engine = discover_engine(settings.engine_path)
|
||||
block_name = (
|
||||
active_block_name.strip()
|
||||
if settings.scope is ExportScope.CURRENT_PAGE
|
||||
else settings.block_name.strip()
|
||||
)
|
||||
stage = output_dir / f".{final_path.stem}.{uuid.uuid4().hex[:8]}.partial.pdf"
|
||||
command = build_command(engine, project, stage, settings.scope, block_name)
|
||||
_write_json(
|
||||
run_dir / "request.json",
|
||||
{
|
||||
"project": str(project),
|
||||
"scope": settings.scope.value,
|
||||
"block_name": block_name,
|
||||
"output": str(final_path),
|
||||
"engine": str(engine),
|
||||
"command": command,
|
||||
},
|
||||
)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
emit("核验当前工程和输出目录")
|
||||
before = _fingerprint(source_root, cancel)
|
||||
_write_json(run_dir / "source-before.json", before)
|
||||
emit("直接调用本机 sch2pdf.exe;读取当前工程配置")
|
||||
return_code = run_engine(command, source_root, run_dir, cancel, timeout, emit)
|
||||
if return_code != 0:
|
||||
raise RuntimeError(f"原生引擎退出码 {return_code};请检查工程、许可和运行日志")
|
||||
if cancel.is_set():
|
||||
raise InterruptedError("导出已取消")
|
||||
pages, size, sha256 = _validate_pdf(stage)
|
||||
_write_json(
|
||||
run_dir / "pdf-check.json",
|
||||
{"pages": pages, "size": size, "sha256": sha256},
|
||||
)
|
||||
after = _fingerprint(source_root, cancel)
|
||||
_write_json(run_dir / "source-after.json", after)
|
||||
differences = _changes(before, after)
|
||||
accepted, blocked = _classify_changes(
|
||||
differences, database.relative_to(source_root).as_posix()
|
||||
)
|
||||
if any(blocked.values()):
|
||||
_write_json(run_dir / "source-assessment.json", {"accepted": accepted, "blocked": blocked})
|
||||
state = "uncertain"
|
||||
message = "导出期间工程文件发生变化,未发布 PDF;请检查运行记录中的 source-assessment.json"
|
||||
return PdfExportResult(project, state, message, final_path, pages, run_dir)
|
||||
if any(accepted.values()):
|
||||
warnings.append("原生数据库或运行记录发生变化;这不代表源工程只读")
|
||||
_write_json(run_dir / "source-assessment.json", {"accepted": accepted, "blocked": blocked})
|
||||
if cancel.is_set():
|
||||
raise InterruptedError("导出已取消")
|
||||
if overwrite:
|
||||
os.replace(stage, final_path)
|
||||
elif os.name == "nt":
|
||||
os.rename(stage, final_path)
|
||||
else:
|
||||
os.link(stage, final_path)
|
||||
stage.unlink()
|
||||
stage = None
|
||||
state = "success"
|
||||
message = f"PDF 已导出,共 {pages} 页:{final_path}"
|
||||
if warnings:
|
||||
message += "。" + warnings[0]
|
||||
except InterruptedError as error:
|
||||
state, message = "cancelled", str(error)
|
||||
except TimeoutError as error:
|
||||
state, message = "timeout", str(error)
|
||||
except Exception as error:
|
||||
state, message = "failed", str(error)
|
||||
finally:
|
||||
if (
|
||||
before is not None
|
||||
and source_root is not None
|
||||
and database_relative is not None
|
||||
and run_dir.exists()
|
||||
and state not in {"success", "uncertain"}
|
||||
):
|
||||
try:
|
||||
after = _fingerprint(source_root, threading.Event())
|
||||
_write_json(run_dir / "source-after.json", after)
|
||||
changes = _changes(before, after)
|
||||
accepted, blocked = _classify_changes(changes, database_relative)
|
||||
_write_json(run_dir / "source-assessment.json", {"accepted": accepted, "blocked": blocked})
|
||||
if any(blocked.values()):
|
||||
state = "uncertain"
|
||||
message += ";失败期间源工程也发生变化,请核对 source-assessment.json"
|
||||
except Exception as error:
|
||||
state = "uncertain"
|
||||
message += f";无法完成失败路径的源工程检查:{error}"
|
||||
if stage is not None:
|
||||
try:
|
||||
stage.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
message += ";临时 PDF 清理失败,请检查运行记录"
|
||||
if run_dir.exists():
|
||||
try:
|
||||
_write_json(
|
||||
run_dir / "result.json",
|
||||
{
|
||||
"state": state,
|
||||
"message": message,
|
||||
"output": str(final_path) if final_path else "",
|
||||
"pages": pages,
|
||||
"duration_seconds": round(time.monotonic() - began, 3),
|
||||
},
|
||||
)
|
||||
except Exception as error:
|
||||
message += f";运行结果记录失败:{error}"
|
||||
if file_lock_acquired and file_lock is not None:
|
||||
with suppress(OSError):
|
||||
file_lock.seek(0)
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
msvcrt.locking(file_lock.fileno(), msvcrt.LK_UNLCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(file_lock.fileno(), fcntl.LOCK_UN)
|
||||
if file_lock is not None:
|
||||
file_lock.close()
|
||||
if lock_acquired:
|
||||
_WRITE_LOCK.release()
|
||||
return PdfExportResult(
|
||||
Path(settings.project_path), state, message, final_path, pages, run_dir
|
||||
)
|
||||
@@ -0,0 +1,49 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def ensure_listener(config_path: Path, tool_root: Path) -> str | None:
|
||||
windows_root = Path(os.environ.get("WINDIR", r"C:\Windows"))
|
||||
script_path = Path(tool_root) / "PdfSaveListener.vbs"
|
||||
host = windows_root / "SysWOW64" / "wscript.exe"
|
||||
if not host.is_file():
|
||||
if os.environ.get("PROCESSOR_ARCHITEW6432"):
|
||||
return "未找到 32 位 Windows Script Host,自动导出监听未启动"
|
||||
host = windows_root / "System32" / "wscript.exe"
|
||||
if not host.is_file() or not script_path.is_file():
|
||||
return "找不到 DxDesigner 保存事件监听脚本,自动导出监听未启动"
|
||||
if getattr(sys, "frozen", False):
|
||||
executable = Path(sys.executable)
|
||||
mode = "exe"
|
||||
working_root = executable.parent
|
||||
else:
|
||||
executable = Path(sys.executable)
|
||||
mode = "module"
|
||||
working_root = Path(__file__).resolve().parents[4]
|
||||
command = [
|
||||
str(host),
|
||||
"//B",
|
||||
"//NoLogo",
|
||||
str(script_path),
|
||||
str(Path(config_path).resolve()),
|
||||
str(executable),
|
||||
mode,
|
||||
str(working_root),
|
||||
]
|
||||
try:
|
||||
subprocess.Popen(
|
||||
command,
|
||||
cwd=working_root,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
close_fds=True,
|
||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||
)
|
||||
except OSError as error:
|
||||
return f"无法启动保存事件监听:{error}"
|
||||
return None
|
||||
@@ -0,0 +1,38 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class ExportScope(StrEnum):
|
||||
PROJECT = "project"
|
||||
CURRENT_PAGE = "current-page"
|
||||
BLOCK = "block"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PdfExportSettings:
|
||||
project_path: Path
|
||||
scope: ExportScope
|
||||
block_name: str
|
||||
output_dir: Path
|
||||
auto_export: bool = False
|
||||
engine_path: Path | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
values = [str(self.project_path), str(self.output_dir), self.block_name]
|
||||
if self.engine_path is not None:
|
||||
values.append(str(self.engine_path))
|
||||
if any(any(char in value for char in "\r\n\x00") for value in values):
|
||||
raise ValueError("PDF 导出设置含无效换行或空字符")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PdfExportResult:
|
||||
project_path: Path
|
||||
state: str
|
||||
message: str
|
||||
output_path: Path | None = None
|
||||
pages: int = 0
|
||||
run_dir: Path | None = None
|
||||
@@ -0,0 +1,125 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from .models import ExportScope, PdfExportSettings
|
||||
|
||||
|
||||
def settings_path(local_app_data: Path | None = None) -> Path:
|
||||
root = Path(
|
||||
local_app_data
|
||||
or os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local")
|
||||
)
|
||||
return root / "DxProductivity" / "pdf-export-settings.json"
|
||||
|
||||
|
||||
def normalized_project_path(path: Path | str) -> str:
|
||||
return os.path.normcase(str(Path(path).expanduser().resolve(strict=False)))
|
||||
|
||||
|
||||
def default_output_dir(
|
||||
project_path: Path | str, local_app_data: Path | None = None
|
||||
) -> Path:
|
||||
project = Path(project_path).expanduser().resolve(strict=False)
|
||||
root = Path(
|
||||
local_app_data
|
||||
or os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local")
|
||||
)
|
||||
digest = hashlib.sha256(normalized_project_path(project).encode("utf-8")).hexdigest()[:8]
|
||||
safe_stem = re.sub(r"[<>:\"/\\|?*\x00-\x1f]+", "_", project.stem).strip(" .") or "project"
|
||||
return root / "DxProductivity" / "pdf-output" / f"{safe_stem}-{digest}"
|
||||
|
||||
|
||||
def default_settings(
|
||||
project_path: Path | str, local_app_data: Path | None = None
|
||||
) -> PdfExportSettings:
|
||||
project = Path(project_path).expanduser().resolve(strict=False)
|
||||
return PdfExportSettings(
|
||||
project_path=project,
|
||||
scope=ExportScope.PROJECT,
|
||||
block_name="",
|
||||
output_dir=default_output_dir(project, local_app_data),
|
||||
)
|
||||
|
||||
|
||||
def load_settings(
|
||||
project_path: Path | str,
|
||||
*,
|
||||
config_path: Path | None = None,
|
||||
local_app_data: Path | None = None,
|
||||
) -> PdfExportSettings:
|
||||
defaults = default_settings(project_path, local_app_data)
|
||||
target = Path(config_path or settings_path(local_app_data))
|
||||
try:
|
||||
data = json.loads(target.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return defaults
|
||||
if not isinstance(data, dict):
|
||||
return defaults
|
||||
try:
|
||||
matches_project = normalized_project_path(
|
||||
str(data.get("project_path", ""))
|
||||
) == normalized_project_path(defaults.project_path)
|
||||
except (OSError, TypeError, ValueError):
|
||||
return defaults
|
||||
if not matches_project:
|
||||
return defaults
|
||||
try:
|
||||
scope = ExportScope(data.get("scope", ExportScope.PROJECT.value))
|
||||
except (TypeError, ValueError):
|
||||
scope = ExportScope.PROJECT
|
||||
block_name = data.get("block_name", "")
|
||||
output_value = data.get("output_dir", "")
|
||||
engine_value = data.get("engine_path", "")
|
||||
if not isinstance(block_name, str) or not isinstance(output_value, str):
|
||||
return defaults
|
||||
if not isinstance(engine_value, str):
|
||||
engine_value = ""
|
||||
try:
|
||||
return PdfExportSettings(
|
||||
project_path=defaults.project_path,
|
||||
scope=scope,
|
||||
block_name=block_name,
|
||||
output_dir=Path(output_value) if output_value else defaults.output_dir,
|
||||
auto_export=data.get("auto_export") is True,
|
||||
engine_path=Path(engine_value) if engine_value else None,
|
||||
)
|
||||
except (OSError, TypeError, ValueError):
|
||||
return defaults
|
||||
|
||||
|
||||
def save_settings(
|
||||
settings: PdfExportSettings, *, config_path: Path | None = None
|
||||
) -> Path:
|
||||
target = Path(config_path or settings_path())
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = {
|
||||
"format_version": 1,
|
||||
"project_path": str(settings.project_path.resolve(strict=False)),
|
||||
"scope": settings.scope.value,
|
||||
"block_name": settings.block_name,
|
||||
"output_dir": str(settings.output_dir.resolve(strict=False)),
|
||||
"auto_export": bool(settings.auto_export),
|
||||
"engine_path": str(settings.engine_path.resolve(strict=False))
|
||||
if settings.engine_path
|
||||
else "",
|
||||
}
|
||||
temporary = target.with_name(f".{target.name}.{uuid.uuid4().hex[:8]}.tmp")
|
||||
try:
|
||||
with temporary.open("x", encoding="utf-8", newline="\n") as stream:
|
||||
json.dump(payload, stream, ensure_ascii=False, indent=2)
|
||||
stream.write("\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, target)
|
||||
finally:
|
||||
try:
|
||||
temporary.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
return target
|
||||
@@ -29,6 +29,8 @@ from dx_productivity.ui.property_visibility_controller import (
|
||||
PropertyVisibilityController,
|
||||
)
|
||||
from dx_productivity.ui.property_visibility_page import PropertyVisibilityPage
|
||||
from dx_productivity.ui.pdf_export_controller import PdfExportController
|
||||
from dx_productivity.ui.pdf_export_page import PdfExportPage
|
||||
from dx_productivity.ui.history_controller import HistoryController
|
||||
from dx_productivity.ui.history_page import HistoryPage
|
||||
from dx_productivity.ui.inspection_controller import InspectionController
|
||||
@@ -76,6 +78,7 @@ FEATURE_PAGE_INDEX = {
|
||||
"bom": 5,
|
||||
"history": 6,
|
||||
"settings": 7,
|
||||
"pdf-export": 8,
|
||||
}
|
||||
|
||||
STATUS_TEXT = {
|
||||
@@ -249,6 +252,15 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
|
||||
window.set_page(7, settings_page, "设置")
|
||||
window.settings_controller = settings_controller
|
||||
window.settings_page = settings_page
|
||||
|
||||
pdf_export_page = PdfExportPage()
|
||||
pdf_export_controller = PdfExportController(
|
||||
pdf_export_page,
|
||||
tool_root=_tool_root(),
|
||||
)
|
||||
pdf_export_controller.status_changed.connect(window.operation_status.setText)
|
||||
window.set_page(8, pdf_export_page, "PDF 导出")
|
||||
window.pdf_export_controller = pdf_export_controller
|
||||
if settings_controller.auto_check_due(persisted_settings):
|
||||
QTimer.singleShot(
|
||||
0,
|
||||
@@ -270,12 +282,15 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
|
||||
window.bom_controller.load_snapshot(snapshot)
|
||||
if history_controller is not None:
|
||||
history_controller.load_snapshot(snapshot)
|
||||
pdf_export_controller.load_snapshot(snapshot)
|
||||
if run_paths is not None:
|
||||
watcher = _install_snapshot_watcher(window, request_path, run_paths)
|
||||
if watcher is not None and history_controller is not None:
|
||||
watcher.snapshot_reloaded.connect(
|
||||
lambda _snapshot: history_controller.refresh()
|
||||
)
|
||||
if watcher is not None:
|
||||
watcher.snapshot_reloaded.connect(pdf_export_controller.load_snapshot)
|
||||
window.navigation.setCurrentRow(0)
|
||||
window.pages.setCurrentIndex(0)
|
||||
window.page_title.setText("自动位号")
|
||||
|
||||
@@ -31,6 +31,7 @@ NAVIGATION = (
|
||||
("BOM 工具", "fa6s.table"),
|
||||
("操作历史", "fa6s.clock-rotate-left"),
|
||||
("设置", "fa6s.gear"),
|
||||
("PDF 导出", "fa6s.file-pdf"),
|
||||
)
|
||||
|
||||
|
||||
@@ -74,6 +75,7 @@ class MainWindow(QMainWindow):
|
||||
getattr(self, "settings_controller", None),
|
||||
getattr(self, "refdes_controller", None),
|
||||
getattr(self, "history_controller", None),
|
||||
getattr(self, "pdf_export_controller", None),
|
||||
):
|
||||
shutdown = getattr(controller, "shutdown", None)
|
||||
if callable(shutdown):
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import QObject, QThread, Signal, Slot
|
||||
|
||||
from dx_productivity.domain.models import DesignSnapshot
|
||||
from dx_productivity.features.pdf_export.exporter import export_project, output_path
|
||||
from dx_productivity.features.pdf_export.listener import ensure_listener
|
||||
from dx_productivity.features.pdf_export.models import (
|
||||
ExportScope,
|
||||
PdfExportResult,
|
||||
PdfExportSettings,
|
||||
)
|
||||
from dx_productivity.features.pdf_export.settings import (
|
||||
load_settings,
|
||||
save_settings,
|
||||
settings_path,
|
||||
)
|
||||
from dx_productivity.ui.pdf_export_page import PdfExportPage
|
||||
|
||||
|
||||
class _ExportWorker(QObject):
|
||||
finished = Signal(object)
|
||||
progress = Signal(str)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: PdfExportSettings,
|
||||
active_block_name: str,
|
||||
overwrite: bool,
|
||||
cancel: threading.Event,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.settings = settings
|
||||
self.active_block_name = active_block_name
|
||||
self.overwrite = overwrite
|
||||
self.cancel = cancel
|
||||
|
||||
@Slot()
|
||||
def run(self) -> None:
|
||||
result = export_project(
|
||||
self.settings,
|
||||
self.cancel,
|
||||
self.progress.emit,
|
||||
active_block_name=self.active_block_name,
|
||||
overwrite=self.overwrite,
|
||||
)
|
||||
self.finished.emit(result)
|
||||
|
||||
|
||||
class PdfExportController(QObject):
|
||||
status_changed = Signal(str)
|
||||
|
||||
def __init__(self, page: PdfExportPage, *, tool_root: Path) -> None:
|
||||
super().__init__(page)
|
||||
self.page = page
|
||||
self.tool_root = Path(tool_root)
|
||||
self.config_path = settings_path()
|
||||
self.snapshot: DesignSnapshot | None = None
|
||||
self._thread: QThread | None = None
|
||||
self._worker: _ExportWorker | None = None
|
||||
self._cancel: threading.Event | None = None
|
||||
page.settings_changed.connect(self._save_settings)
|
||||
page.export_requested.connect(self.export)
|
||||
page.cancel_requested.connect(self.cancel)
|
||||
|
||||
def load_snapshot(self, snapshot: DesignSnapshot) -> None:
|
||||
self.snapshot = snapshot
|
||||
settings = load_settings(
|
||||
snapshot.design_path,
|
||||
config_path=self.config_path,
|
||||
)
|
||||
self.page.bind(snapshot, settings)
|
||||
effective_settings = self.page.settings()
|
||||
if effective_settings is not None and settings.auto_export and not effective_settings.auto_export:
|
||||
try:
|
||||
save_settings(effective_settings, config_path=self.config_path)
|
||||
except OSError as error:
|
||||
self.page.set_status(f"无法保存 PDF 设置:{error}")
|
||||
if effective_settings is not None and effective_settings.auto_export:
|
||||
self._ensure_listener()
|
||||
|
||||
def _save_settings(self, settings: PdfExportSettings) -> None:
|
||||
if self.snapshot is None:
|
||||
return
|
||||
try:
|
||||
save_settings(settings, config_path=self.config_path)
|
||||
except OSError as error:
|
||||
self.page.set_status(f"无法保存 PDF 设置:{error}")
|
||||
return
|
||||
if settings.auto_export:
|
||||
self._ensure_listener()
|
||||
return
|
||||
self.status_changed.emit("保存后自动导出已关闭")
|
||||
|
||||
def _ensure_listener(self) -> None:
|
||||
result = ensure_listener(self.config_path, self.tool_root)
|
||||
if result:
|
||||
self.status_changed.emit(result)
|
||||
self.page.set_status(result)
|
||||
else:
|
||||
self.status_changed.emit("保存后自动导出监听已启动")
|
||||
self.page.set_status("保存后自动导出已启用")
|
||||
|
||||
def export(self) -> None:
|
||||
if self.snapshot is None:
|
||||
self.page.set_status("未连接 DxDesigner 工程")
|
||||
return
|
||||
if self._thread is not None and self._thread.isRunning():
|
||||
return
|
||||
settings = self.page.settings()
|
||||
if settings is None:
|
||||
return
|
||||
if not str(settings.output_dir).strip():
|
||||
self.page.set_status("请选择 PDF 输出目录")
|
||||
return
|
||||
if settings.scope is not ExportScope.PROJECT and not settings.block_name.strip():
|
||||
self.page.set_status("当前范围没有可用的 Block 名称")
|
||||
return
|
||||
try:
|
||||
target = output_path(settings, self.snapshot.active_block_name)
|
||||
except ValueError as error:
|
||||
self.page.set_status(str(error))
|
||||
return
|
||||
overwrite = False
|
||||
if target.exists():
|
||||
if not self.page.confirm_overwrite(str(target)):
|
||||
self.page.set_status("已取消导出")
|
||||
return
|
||||
overwrite = True
|
||||
self._save_settings(settings)
|
||||
self._cancel = threading.Event()
|
||||
self._thread = QThread(self)
|
||||
self._worker = _ExportWorker(
|
||||
settings,
|
||||
self.snapshot.active_block_name,
|
||||
overwrite,
|
||||
self._cancel,
|
||||
)
|
||||
self._worker.moveToThread(self._thread)
|
||||
self._thread.started.connect(self._worker.run)
|
||||
self._worker.progress.connect(self.page.set_status)
|
||||
self._worker.finished.connect(self._on_finished)
|
||||
self._worker.finished.connect(self._thread.quit)
|
||||
self._worker.finished.connect(self._worker.deleteLater)
|
||||
self._thread.finished.connect(self._finish_thread)
|
||||
self._thread.finished.connect(self._thread.deleteLater)
|
||||
self.page.set_busy(True)
|
||||
self.page.set_status("正在调用原生 PDF 引擎…")
|
||||
self._thread.start()
|
||||
|
||||
@Slot(object)
|
||||
def _on_finished(self, result: PdfExportResult) -> None:
|
||||
self.page.set_status(result.message)
|
||||
self.status_changed.emit(result.message)
|
||||
self.page.set_busy(False)
|
||||
self.page.set_can_export(self.snapshot is not None)
|
||||
|
||||
@Slot()
|
||||
def _finish_thread(self) -> None:
|
||||
self._thread = None
|
||||
self._worker = None
|
||||
self._cancel = None
|
||||
|
||||
def cancel(self) -> None:
|
||||
if self._cancel is not None:
|
||||
self._cancel.set()
|
||||
self.page.set_status("正在取消导出…")
|
||||
|
||||
def shutdown(self) -> None:
|
||||
self.cancel()
|
||||
if self._thread is not None and self._thread.isRunning():
|
||||
self._thread.quit()
|
||||
self._thread.wait()
|
||||
@@ -0,0 +1,255 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import QSize, Signal
|
||||
from PySide6.QtWidgets import (
|
||||
QCheckBox,
|
||||
QComboBox,
|
||||
QFileDialog,
|
||||
QFormLayout,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QMessageBox,
|
||||
QPushButton,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from dx_productivity.domain.models import DesignSnapshot
|
||||
from dx_productivity.features.pdf_export.models import ExportScope, PdfExportSettings
|
||||
from dx_productivity.ui.theme import Theme, themed_icon
|
||||
|
||||
|
||||
class PdfExportPage(QWidget):
|
||||
settings_changed = Signal(object)
|
||||
export_requested = Signal()
|
||||
cancel_requested = Signal()
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.snapshot: DesignSnapshot | None = None
|
||||
self._loading = False
|
||||
self._theme = Theme.LIGHT
|
||||
self._build_ui()
|
||||
|
||||
def _build_ui(self) -> None:
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(20, 16, 20, 16)
|
||||
layout.setSpacing(12)
|
||||
|
||||
form = QFormLayout()
|
||||
form.setHorizontalSpacing(14)
|
||||
form.setVerticalSpacing(12)
|
||||
|
||||
self.project_input = QLineEdit()
|
||||
self.project_input.setReadOnly(True)
|
||||
self.project_input.setPlaceholderText("未连接 DxDesigner 工程")
|
||||
form.addRow("当前工程", self.project_input)
|
||||
|
||||
self.scope_combo = QComboBox()
|
||||
self.scope_combo.addItem("整工程", ExportScope.PROJECT.value)
|
||||
self.scope_combo.addItem("当前页", ExportScope.CURRENT_PAGE.value)
|
||||
self.scope_combo.addItem("指定原理图或 Block", ExportScope.BLOCK.value)
|
||||
form.addRow("导出范围", self.scope_combo)
|
||||
|
||||
block_row = QHBoxLayout()
|
||||
self.block_input = QLineEdit()
|
||||
self.block_input.setPlaceholderText("DxDesigner 原理图或 Block 名称")
|
||||
block_row.addWidget(self.block_input, 1)
|
||||
self.active_block_label = QLabel("")
|
||||
self.active_block_label.setMinimumWidth(160)
|
||||
block_row.addWidget(self.active_block_label)
|
||||
form.addRow("Block", block_row)
|
||||
|
||||
output_row = QHBoxLayout()
|
||||
self.output_input = QLineEdit()
|
||||
self.output_button = QPushButton("浏览…")
|
||||
self.output_button.setIconSize(QSize(16, 16))
|
||||
self.output_button.clicked.connect(self._choose_output)
|
||||
output_row.addWidget(self.output_input, 1)
|
||||
output_row.addWidget(self.output_button)
|
||||
form.addRow("输出目录", output_row)
|
||||
|
||||
engine_row = QHBoxLayout()
|
||||
self.engine_input = QLineEdit()
|
||||
self.engine_input.setPlaceholderText("自动发现本机 sch2pdf.exe")
|
||||
self.engine_button = QPushButton("浏览…")
|
||||
self.engine_button.setIconSize(QSize(16, 16))
|
||||
self.engine_button.clicked.connect(self._choose_engine)
|
||||
engine_row.addWidget(self.engine_input, 1)
|
||||
engine_row.addWidget(self.engine_button)
|
||||
form.addRow("原生引擎", engine_row)
|
||||
layout.addLayout(form)
|
||||
|
||||
self.auto_export_checkbox = QCheckBox("保存工程后自动导出")
|
||||
self.auto_export_checkbox.setEnabled(False)
|
||||
layout.addWidget(self.auto_export_checkbox)
|
||||
|
||||
self.warning_label = QLabel(
|
||||
"原生出图直接读取当前工程;DxDesigner 可能更新数据库或运行记录。"
|
||||
)
|
||||
self.warning_label.setWordWrap(True)
|
||||
self.warning_label.setObjectName("secondaryLabel")
|
||||
layout.addWidget(self.warning_label)
|
||||
|
||||
layout.addStretch(1)
|
||||
self.status_label = QLabel("未连接工程")
|
||||
self.status_label.setWordWrap(True)
|
||||
layout.addWidget(self.status_label)
|
||||
|
||||
actions = QHBoxLayout()
|
||||
actions.addStretch(1)
|
||||
self.cancel_button = QPushButton("取消导出")
|
||||
self.cancel_button.clicked.connect(self.cancel_requested)
|
||||
self.cancel_button.setEnabled(False)
|
||||
self.export_button = QPushButton("导出 PDF")
|
||||
self.export_button.setObjectName("primaryButton")
|
||||
self.export_button.clicked.connect(self.export_requested)
|
||||
self.export_button.setEnabled(False)
|
||||
actions.addWidget(self.cancel_button)
|
||||
actions.addWidget(self.export_button)
|
||||
layout.addLayout(actions)
|
||||
|
||||
self.scope_combo.currentIndexChanged.connect(self._scope_changed)
|
||||
self.block_input.editingFinished.connect(self._emit_settings)
|
||||
self.output_input.editingFinished.connect(self._emit_settings)
|
||||
self.engine_input.editingFinished.connect(self._emit_settings)
|
||||
self.auto_export_checkbox.toggled.connect(self._emit_settings)
|
||||
|
||||
def bind(self, snapshot: DesignSnapshot | None, settings: PdfExportSettings) -> None:
|
||||
self._loading = True
|
||||
self.snapshot = snapshot
|
||||
self.project_input.setText(snapshot.design_path if snapshot else "")
|
||||
scope_index = self.scope_combo.findData(settings.scope.value)
|
||||
self.scope_combo.setCurrentIndex(max(scope_index, 0))
|
||||
self.block_input.setText(
|
||||
settings.block_name
|
||||
if settings.scope is ExportScope.BLOCK
|
||||
else (snapshot.active_block_name if snapshot else "")
|
||||
)
|
||||
self.output_input.setText(str(settings.output_dir))
|
||||
self.engine_input.setText(str(settings.engine_path or ""))
|
||||
self.auto_export_checkbox.setChecked(settings.auto_export)
|
||||
project_ready = bool(snapshot and Path(snapshot.design_path).suffix.casefold() == ".prj")
|
||||
self.auto_export_checkbox.setEnabled(project_ready)
|
||||
self.status_label.setText("就绪" if snapshot else "未连接 DxDesigner 工程")
|
||||
self._scope_changed()
|
||||
self._loading = False
|
||||
self.set_can_export(project_ready)
|
||||
|
||||
def settings(self) -> PdfExportSettings | None:
|
||||
if self.snapshot is None:
|
||||
return None
|
||||
output_value = self.output_input.text().strip()
|
||||
if not output_value:
|
||||
return None
|
||||
scope = ExportScope(self.scope_combo.currentData())
|
||||
engine_value = self.engine_input.text().strip()
|
||||
block_name = self.block_input.text().strip()
|
||||
if scope is ExportScope.PROJECT:
|
||||
block_name = ""
|
||||
elif scope is ExportScope.CURRENT_PAGE:
|
||||
block_name = self.snapshot.active_block_name.strip()
|
||||
return PdfExportSettings(
|
||||
project_path=Path(self.snapshot.design_path),
|
||||
scope=scope,
|
||||
block_name=block_name,
|
||||
output_dir=Path(output_value),
|
||||
auto_export=self.auto_export_checkbox.isChecked(),
|
||||
engine_path=Path(engine_value) if engine_value else None,
|
||||
)
|
||||
|
||||
def confirm_overwrite(self, path: str) -> bool:
|
||||
answer = QMessageBox.question(
|
||||
self,
|
||||
"覆盖现有 PDF",
|
||||
f"下列文件已存在,是否替换?\n{path}",
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
QMessageBox.StandardButton.No,
|
||||
)
|
||||
return answer == QMessageBox.StandardButton.Yes
|
||||
|
||||
def set_can_export(self, enabled: bool) -> None:
|
||||
settings = self.settings()
|
||||
valid_project = bool(settings) and settings.project_path.suffix.casefold() == ".prj"
|
||||
valid_scope = valid_project and (
|
||||
settings.scope is ExportScope.PROJECT
|
||||
or bool(settings.block_name.strip())
|
||||
)
|
||||
self.export_button.setEnabled(enabled and valid_scope)
|
||||
auto_enabled = enabled and valid_scope
|
||||
self.auto_export_checkbox.setEnabled(auto_enabled)
|
||||
if not auto_enabled and self.auto_export_checkbox.isChecked():
|
||||
was_blocked = self.auto_export_checkbox.blockSignals(True)
|
||||
self.auto_export_checkbox.setChecked(False)
|
||||
self.auto_export_checkbox.blockSignals(was_blocked)
|
||||
|
||||
def set_busy(self, busy: bool) -> None:
|
||||
self.export_button.setEnabled(not busy and self.snapshot is not None)
|
||||
self.cancel_button.setEnabled(busy)
|
||||
self.scope_combo.setEnabled(not busy)
|
||||
self.output_input.setEnabled(not busy)
|
||||
self.output_button.setEnabled(not busy)
|
||||
self.engine_input.setEnabled(not busy)
|
||||
self.engine_button.setEnabled(not busy)
|
||||
project_ready = bool(self.snapshot and self.snapshot.design_path.casefold().endswith(".prj"))
|
||||
self.auto_export_checkbox.setEnabled(not busy and project_ready)
|
||||
self.block_input.setEnabled(
|
||||
not busy and self.scope_combo.currentData() == ExportScope.BLOCK.value
|
||||
)
|
||||
|
||||
def set_status(self, message: str) -> None:
|
||||
self.status_label.setText(message)
|
||||
|
||||
def refresh_icons(self, theme: Theme) -> None:
|
||||
self._theme = theme
|
||||
self.output_button.setIcon(themed_icon("fa6s.folder-open", theme))
|
||||
self.engine_button.setIcon(themed_icon("fa6s.folder-open", theme))
|
||||
self.export_button.setIcon(themed_icon("fa6s.file-pdf", theme))
|
||||
self.cancel_button.setIcon(themed_icon("fa6s.xmark", theme))
|
||||
|
||||
def _scope_changed(self, *_args) -> None:
|
||||
scope = self.scope_combo.currentData()
|
||||
current = scope == ExportScope.CURRENT_PAGE.value
|
||||
specified = scope == ExportScope.BLOCK.value
|
||||
self.block_input.setEnabled(specified)
|
||||
self.active_block_label.setText(
|
||||
f"活动页:{self.snapshot.active_block_name}"
|
||||
if current and self.snapshot and self.snapshot.active_block_name
|
||||
else ("活动 Block 不可用" if current else "")
|
||||
)
|
||||
self.active_block_label.setVisible(current)
|
||||
if not self._loading:
|
||||
self.set_can_export(self.snapshot is not None)
|
||||
self._emit_settings()
|
||||
|
||||
def _emit_settings(self, *_args) -> None:
|
||||
if self._loading:
|
||||
return
|
||||
settings = self.settings()
|
||||
if settings is not None:
|
||||
self.set_can_export(self.snapshot is not None)
|
||||
settings = self.settings()
|
||||
if settings is not None:
|
||||
self.settings_changed.emit(settings)
|
||||
|
||||
def _choose_output(self) -> None:
|
||||
current = self.output_input.text().strip()
|
||||
path = QFileDialog.getExistingDirectory(self, "选择 PDF 输出目录", current)
|
||||
if path:
|
||||
self.output_input.setText(path)
|
||||
self._emit_settings()
|
||||
|
||||
def _choose_engine(self) -> None:
|
||||
current = self.engine_input.text().strip()
|
||||
path, _ = QFileDialog.getOpenFileName(
|
||||
self,
|
||||
"选择 DxDesigner 原生 sch2pdf.exe",
|
||||
current,
|
||||
"DxDesigner PDF 引擎 (sch2pdf.exe)",
|
||||
)
|
||||
if path:
|
||||
self.engine_input.setText(path)
|
||||
self._emit_settings()
|
||||
Reference in new issue
Block a user