2026-10-29 18:22:42 +08:00
|
|
|
"""Export UI: immutable editor snapshots, review, and cancellable jobs."""
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
from dataclasses import asdict, dataclass
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
2026-10-29 19:26:11 +08:00
|
|
|
from PySide6.QtCore import QThreadPool
|
2026-10-29 18:22:42 +08:00
|
|
|
from PySide6.QtWidgets import QDialog, QFileDialog, QInputDialog, QMessageBox, QProgressDialog
|
|
|
|
|
|
|
|
|
|
from .document_tree import is_code_document
|
|
|
|
|
from .docx_exporter import DOCX_EXPORT_ENGINES, export_markdown_to_docx
|
|
|
|
|
from .export_check import check_export, confirm_export
|
2026-10-29 19:26:11 +08:00
|
|
|
from .export_jobs import ExportJob
|
|
|
|
|
from .export_settings import PageSettings
|
2026-10-29 18:22:42 +08:00
|
|
|
from .file_versions import atomic_write
|
|
|
|
|
from .markdown_utils import Heading
|
2026-10-29 19:26:11 +08:00
|
|
|
from .render_options import RenderOptions
|
2026-10-29 19:40:45 +08:00
|
|
|
from .preferences import ConfigurationStore
|
2026-10-29 19:26:11 +08:00
|
|
|
from typing import Callable
|
|
|
|
|
from .pdf_export_task import PdfExportController
|
|
|
|
|
from .pdf_export import PdfExportSettingsDialog, PdfMargins
|
2026-10-29 18:22:42 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
|
|
|
class ExportSnapshot:
|
|
|
|
|
path: Path
|
|
|
|
|
source: str | None
|
|
|
|
|
style: dict
|
|
|
|
|
font: str
|
|
|
|
|
font_size: float
|
|
|
|
|
preset: str
|
2026-10-29 19:26:11 +08:00
|
|
|
rendering: RenderOptions | None = None
|
2026-10-29 18:22:42 +08:00
|
|
|
|
|
|
|
|
|
2026-10-29 19:26:11 +08:00
|
|
|
@dataclass(frozen=True)
|
|
|
|
|
class ExportContext:
|
|
|
|
|
parent: object
|
|
|
|
|
settings: object
|
|
|
|
|
snapshot: Callable[[], ExportSnapshot | None]
|
|
|
|
|
render: Callable[[ExportSnapshot], str]
|
|
|
|
|
page_html: Callable
|
|
|
|
|
configure_web_settings: Callable
|
|
|
|
|
status: Callable[[str], None]
|
2026-10-29 21:48:19 +08:00
|
|
|
page_settings: Callable[[], PageSettings] | None = None
|
|
|
|
|
save_page_settings: Callable[[PageSettings], None] | None = None
|
2026-10-29 19:26:11 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class ExportController:
|
|
|
|
|
def __init__(self, context: ExportContext):
|
|
|
|
|
self.context = context
|
2026-10-29 19:40:45 +08:00
|
|
|
self.configuration = ConfigurationStore(context.settings)
|
2026-10-29 19:26:11 +08:00
|
|
|
self._export_jobs = set()
|
|
|
|
|
self._mhtml_exports = set()
|
|
|
|
|
self._pdf_controller = None
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def _pdf_export_page(self):
|
|
|
|
|
return self._pdf_controller.page if self._pdf_controller else None
|
|
|
|
|
|
|
|
|
|
def cancel_all(self):
|
|
|
|
|
self._cleanup_pdf_export()
|
|
|
|
|
for controller in list(self._mhtml_exports):
|
|
|
|
|
controller.cancel()
|
|
|
|
|
for job in self._export_jobs:
|
|
|
|
|
job.cancel.set()
|
|
|
|
|
|
2026-10-29 18:22:42 +08:00
|
|
|
def _export_snapshot(self) -> ExportSnapshot | None:
|
2026-10-29 19:26:11 +08:00
|
|
|
return self.context.snapshot()
|
2026-10-29 18:22:42 +08:00
|
|
|
|
|
|
|
|
def _review_export(self, snapshot: ExportSnapshot, kind: str) -> bool:
|
|
|
|
|
if snapshot.source is None:
|
|
|
|
|
return True
|
2026-10-29 19:26:11 +08:00
|
|
|
return confirm_export(self.context.parent, check_export(snapshot.source, snapshot.path, kind, snapshot.style.get("css", "")))
|
2026-10-29 18:22:42 +08:00
|
|
|
|
|
|
|
|
def _saved_page_settings(self) -> PageSettings:
|
2026-10-29 21:48:19 +08:00
|
|
|
if self.context.page_settings:
|
|
|
|
|
return self.context.page_settings()
|
2026-10-29 19:40:45 +08:00
|
|
|
return self.configuration.load_page_settings()
|
2026-10-29 18:22:42 +08:00
|
|
|
|
|
|
|
|
def _choose_page_settings(self) -> PageSettings | None:
|
2026-10-29 19:26:11 +08:00
|
|
|
dialog = PdfExportSettingsDialog(self._saved_page_settings(), self.context.parent)
|
2026-10-29 18:22:42 +08:00
|
|
|
if dialog.exec() != QDialog.DialogCode.Accepted:
|
|
|
|
|
return None
|
|
|
|
|
settings = dialog.page_settings()
|
2026-10-29 21:48:19 +08:00
|
|
|
if self.context.save_page_settings:
|
|
|
|
|
self.context.save_page_settings(settings)
|
|
|
|
|
else:
|
|
|
|
|
self.configuration.save_page_settings(settings)
|
2026-10-29 18:22:42 +08:00
|
|
|
return settings
|
|
|
|
|
|
|
|
|
|
def _saved_pdf_margins(self) -> PdfMargins:
|
|
|
|
|
def value(name):
|
|
|
|
|
try:
|
2026-10-29 19:26:11 +08:00
|
|
|
return max(0, min(50, float(self.context.settings.value(f"pdf/{name}_margin_mm", 15))))
|
2026-10-29 18:22:42 +08:00
|
|
|
except (ValueError, TypeError):
|
|
|
|
|
return 15
|
|
|
|
|
return PdfMargins(*(value(name) for name in ("top", "bottom", "left", "right")))
|
|
|
|
|
|
|
|
|
|
def _save_pdf_margins(self, margins: PdfMargins) -> None:
|
|
|
|
|
for name in ("top", "bottom", "left", "right"):
|
2026-10-29 19:26:11 +08:00
|
|
|
self.context.settings.setValue(f"pdf/{name}_margin_mm", getattr(margins, name))
|
2026-10-29 18:22:42 +08:00
|
|
|
|
2026-10-29 21:37:30 +08:00
|
|
|
def _start_export_job(self, title, callback, completed=None, outcome=None):
|
2026-10-29 18:22:42 +08:00
|
|
|
job = ExportJob(callback)
|
2026-10-29 19:26:11 +08:00
|
|
|
progress = QProgressDialog(title, "取消", 0, 0, self.context.parent)
|
2026-10-29 18:22:42 +08:00
|
|
|
progress.setWindowTitle("导出文档")
|
|
|
|
|
progress.setMinimumDuration(0)
|
|
|
|
|
progress.setAutoClose(False)
|
|
|
|
|
progress.canceled.connect(job.cancel.set)
|
|
|
|
|
job.signals.progress.connect(progress.setLabelText)
|
|
|
|
|
if not hasattr(self, "_export_jobs"):
|
|
|
|
|
self._export_jobs = set()
|
|
|
|
|
self._export_jobs.add(job)
|
|
|
|
|
def finished(result, error):
|
|
|
|
|
self._export_jobs.discard(job)
|
|
|
|
|
progress.blockSignals(True); progress.close(); progress.deleteLater()
|
|
|
|
|
if error:
|
2026-10-29 19:26:11 +08:00
|
|
|
QMessageBox.warning(self.context.parent, "导出失败", error)
|
2026-10-29 18:22:42 +08:00
|
|
|
elif result:
|
2026-10-29 19:26:11 +08:00
|
|
|
self.context.status(f"已导出:{result}")
|
2026-10-29 18:22:42 +08:00
|
|
|
else:
|
2026-10-29 19:26:11 +08:00
|
|
|
self.context.status("已取消导出,原有输出文件保持不变")
|
2026-10-29 18:22:42 +08:00
|
|
|
if completed:
|
|
|
|
|
completed()
|
2026-10-29 21:37:30 +08:00
|
|
|
if outcome:
|
|
|
|
|
outcome(result, error, job.cancel.is_set())
|
2026-10-29 18:22:42 +08:00
|
|
|
job.signals.finished.connect(finished)
|
|
|
|
|
progress.show()
|
|
|
|
|
QThreadPool.globalInstance().start(job)
|
|
|
|
|
return job
|
|
|
|
|
|
|
|
|
|
def export_current_docx(self) -> None:
|
2026-10-29 19:26:11 +08:00
|
|
|
if self._export_snapshot() is None:
|
2026-10-29 18:22:42 +08:00
|
|
|
return
|
|
|
|
|
labels = list(DOCX_EXPORT_ENGINES.values())
|
2026-10-29 19:26:11 +08:00
|
|
|
label, ok = QInputDialog.getItem(self.context.parent, "选择 Word 导出方式", "导出方式", labels, 0, False)
|
2026-10-29 18:22:42 +08:00
|
|
|
if not ok:
|
|
|
|
|
return
|
|
|
|
|
engine = next(key for key, value in DOCX_EXPORT_ENGINES.items() if value == label)
|
|
|
|
|
settings = self._choose_page_settings()
|
|
|
|
|
if settings is None:
|
|
|
|
|
return
|
|
|
|
|
try:
|
|
|
|
|
snapshot = self._export_snapshot()
|
|
|
|
|
if snapshot is None or not self._review_export(snapshot, engine):
|
|
|
|
|
return
|
2026-10-29 19:26:11 +08:00
|
|
|
file_name, _ = QFileDialog.getSaveFileName(self.context.parent, "导出 Word", str(snapshot.path.with_suffix(".docx")), "Word 文档 (*.docx)")
|
2026-10-29 18:22:42 +08:00
|
|
|
if file_name:
|
|
|
|
|
self.export_docx_to_path(Path(file_name), engine, snapshot=snapshot, page_settings=settings, background=True)
|
|
|
|
|
except (OSError, ValueError) as exc:
|
2026-10-29 19:26:11 +08:00
|
|
|
QMessageBox.warning(self.context.parent, "导出失败", str(exc))
|
2026-10-29 18:22:42 +08:00
|
|
|
|
|
|
|
|
def export_docx_to_path(self, output_path: Path, engine: str = "builtin", *, snapshot=None, page_settings=None, background=False):
|
|
|
|
|
try:
|
|
|
|
|
snapshot = snapshot or self._export_snapshot()
|
|
|
|
|
if snapshot is None:
|
|
|
|
|
return None
|
|
|
|
|
if snapshot.source is None:
|
|
|
|
|
raise ValueError("Word 导出仅支持 Markdown 文档。")
|
|
|
|
|
output_path = output_path.with_suffix(".docx")
|
|
|
|
|
settings = page_settings or self._saved_page_settings()
|
|
|
|
|
def convert(cancel=None, progress=None):
|
|
|
|
|
return export_markdown_to_docx(snapshot.source, output_path, engine=engine, source_path=snapshot.path,
|
|
|
|
|
style_rules=snapshot.style.get("rules", {}), document_font_family=snapshot.font,
|
|
|
|
|
document_font_size=snapshot.font_size, preset=snapshot.preset,
|
|
|
|
|
page_settings=settings, cancel=cancel, progress=progress)
|
|
|
|
|
if background:
|
|
|
|
|
self._start_export_job("正在准备 Word 导出…", convert)
|
|
|
|
|
return output_path
|
|
|
|
|
return convert()
|
|
|
|
|
except Exception as exc:
|
2026-10-29 19:26:11 +08:00
|
|
|
QMessageBox.warning(self.context.parent, "导出失败", str(exc))
|
2026-10-29 18:22:42 +08:00
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
def export_current_pdf(self) -> None:
|
2026-10-29 19:26:11 +08:00
|
|
|
if self._export_snapshot() is None:
|
2026-10-29 18:22:42 +08:00
|
|
|
return
|
|
|
|
|
settings = self._choose_page_settings()
|
|
|
|
|
if settings is None:
|
|
|
|
|
return
|
|
|
|
|
try:
|
|
|
|
|
snapshot = self._export_snapshot()
|
|
|
|
|
if snapshot is None or not self._review_export(snapshot, "pdf"):
|
|
|
|
|
return
|
2026-10-29 19:26:11 +08:00
|
|
|
file_name, _ = QFileDialog.getSaveFileName(self.context.parent, "导出 PDF", str(snapshot.path.with_suffix(".pdf")), "PDF (*.pdf)")
|
2026-10-29 18:22:42 +08:00
|
|
|
if file_name:
|
|
|
|
|
self.export_pdf_to_path(Path(file_name), settings, snapshot=snapshot)
|
|
|
|
|
except (OSError, ValueError) as exc:
|
2026-10-29 19:26:11 +08:00
|
|
|
QMessageBox.warning(self.context.parent, "导出失败", str(exc))
|
2026-10-29 18:22:42 +08:00
|
|
|
|
|
|
|
|
def export_pdf_to_path(self, output_path: Path, margins=None, *, snapshot=None):
|
|
|
|
|
if getattr(self, "_pdf_export_page", None) is not None:
|
2026-10-29 19:26:11 +08:00
|
|
|
QMessageBox.information(self.context.parent, "正在导出", "已有 PDF 导出任务正在进行,请等待完成或取消。")
|
2026-10-29 18:22:42 +08:00
|
|
|
return None
|
|
|
|
|
try:
|
|
|
|
|
snapshot = snapshot or self._export_snapshot()
|
|
|
|
|
if snapshot is None:
|
|
|
|
|
return None
|
|
|
|
|
settings = margins if isinstance(margins, PageSettings) else self._saved_page_settings()
|
|
|
|
|
if isinstance(margins, PdfMargins):
|
|
|
|
|
values = asdict(settings); values.update(asdict(margins)); settings = PageSettings(**values)
|
|
|
|
|
settings = settings.normalized()
|
|
|
|
|
output_path = output_path.with_suffix(".pdf")
|
|
|
|
|
if snapshot.source is not None or is_code_document(snapshot.path):
|
2026-10-29 19:26:11 +08:00
|
|
|
content = self.context.render(snapshot)
|
2026-10-29 18:22:42 +08:00
|
|
|
headings = []
|
|
|
|
|
if snapshot.source is not None:
|
|
|
|
|
from .markdown_renderer import MarkdownRenderer
|
|
|
|
|
environment = {"path": str(snapshot.path), "headings": []}
|
|
|
|
|
MarkdownRenderer(snapshot.path.parent).markdown.parse(snapshot.source, environment)
|
|
|
|
|
headings = [Heading(**item) for item in environment["headings"]]
|
|
|
|
|
self._begin_pdf_export(output_path, content, headings, settings, snapshot.path)
|
|
|
|
|
else:
|
2026-10-29 19:26:11 +08:00
|
|
|
self.context.page_html(lambda content: self._begin_pdf_export(output_path, content, [], settings, snapshot.path))
|
2026-10-29 18:22:42 +08:00
|
|
|
return output_path
|
|
|
|
|
except (OSError, ValueError) as exc:
|
2026-10-29 19:26:11 +08:00
|
|
|
QMessageBox.warning(self.context.parent, "导出失败", str(exc))
|
2026-10-29 18:22:42 +08:00
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
def _begin_pdf_export(self, path, content, headings, settings, source_path=None):
|
2026-10-29 19:26:11 +08:00
|
|
|
controller = PdfExportController(self, path, content, headings, settings, source_path or self._export_snapshot().path)
|
2026-10-29 18:22:42 +08:00
|
|
|
self._pdf_controller = controller
|
|
|
|
|
controller.start()
|
|
|
|
|
|
|
|
|
|
def _on_pdf_probe_ready(self, data):
|
|
|
|
|
if getattr(self, "_pdf_controller", None):
|
|
|
|
|
self._pdf_controller.probe_ready(data)
|
|
|
|
|
|
|
|
|
|
def _cleanup_pdf_export(self):
|
|
|
|
|
if getattr(self, "_pdf_controller", None):
|
|
|
|
|
self._pdf_controller.cancel()
|
|
|
|
|
|
|
|
|
|
def export_current_html(self):
|
|
|
|
|
self._export_web_dialog("html")
|
|
|
|
|
|
|
|
|
|
def export_current_mhtml(self):
|
|
|
|
|
self._export_web_dialog("mhtml")
|
|
|
|
|
|
|
|
|
|
def _export_web_dialog(self, kind):
|
|
|
|
|
try:
|
|
|
|
|
snapshot = self._export_snapshot()
|
|
|
|
|
if snapshot is None or not self._review_export(snapshot, kind):
|
|
|
|
|
return
|
2026-10-29 19:26:11 +08:00
|
|
|
file_name, _ = QFileDialog.getSaveFileName(self.context.parent, f"导出 {kind.upper()}",
|
2026-10-29 18:22:42 +08:00
|
|
|
str(snapshot.path.with_suffix("." + kind)), f"{kind.upper()} (*.{kind})")
|
|
|
|
|
if file_name:
|
|
|
|
|
self._export_web_to_path(Path(file_name), kind, snapshot)
|
|
|
|
|
except (OSError, ValueError) as exc:
|
2026-10-29 19:26:11 +08:00
|
|
|
QMessageBox.warning(self.context.parent, "导出失败", str(exc))
|
2026-10-29 18:22:42 +08:00
|
|
|
|
|
|
|
|
def export_mhtml_to_path(self, output_path):
|
|
|
|
|
return self._export_web_to_path(output_path, "mhtml")
|
|
|
|
|
|
|
|
|
|
def export_html_to_path(self, output_path):
|
|
|
|
|
return self._export_web_to_path(output_path, "html")
|
|
|
|
|
|
|
|
|
|
def _write_exported_html(self, output_path, content):
|
|
|
|
|
try:
|
|
|
|
|
atomic_write(output_path, content.encode("utf-8"))
|
2026-10-29 19:26:11 +08:00
|
|
|
self.context.status(f"HTML 已导出:{output_path}")
|
2026-10-29 18:22:42 +08:00
|
|
|
except OSError as exc:
|
2026-10-29 19:26:11 +08:00
|
|
|
QMessageBox.warning(self.context.parent, "导出失败", str(exc))
|
2026-10-29 18:22:42 +08:00
|
|
|
|
|
|
|
|
def _export_web_to_path(self, output_path, kind, snapshot=None):
|
|
|
|
|
try:
|
|
|
|
|
snapshot = snapshot or self._export_snapshot()
|
|
|
|
|
if snapshot is None:
|
|
|
|
|
return None
|
|
|
|
|
output_path = output_path.with_suffix("." + kind)
|
|
|
|
|
def write(content):
|
|
|
|
|
try:
|
|
|
|
|
if kind == "mhtml":
|
|
|
|
|
self._begin_mhtml_export(output_path, content, snapshot.path)
|
|
|
|
|
return
|
|
|
|
|
atomic_write(output_path, content.encode("utf-8"))
|
2026-10-29 19:26:11 +08:00
|
|
|
self.context.status(f"已导出:{output_path}")
|
2026-10-29 18:22:42 +08:00
|
|
|
except OSError as exc:
|
2026-10-29 19:26:11 +08:00
|
|
|
QMessageBox.warning(self.context.parent, "导出失败", str(exc))
|
2026-10-29 18:22:42 +08:00
|
|
|
if snapshot.source is not None or is_code_document(snapshot.path):
|
2026-10-29 19:26:11 +08:00
|
|
|
write(self.context.render(snapshot))
|
2026-10-29 18:22:42 +08:00
|
|
|
else:
|
2026-10-29 19:26:11 +08:00
|
|
|
self.context.page_html(write)
|
2026-10-29 18:22:42 +08:00
|
|
|
return output_path
|
|
|
|
|
except (OSError, ValueError) as exc:
|
2026-10-29 19:26:11 +08:00
|
|
|
QMessageBox.warning(self.context.parent, "导出失败", str(exc))
|
2026-10-29 18:22:42 +08:00
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
def _begin_mhtml_export(self, output_path, content, source_path):
|
|
|
|
|
from .mhtml_export import MhtmlExportController
|
|
|
|
|
if not hasattr(self, "_mhtml_exports"):
|
|
|
|
|
self._mhtml_exports = set()
|
|
|
|
|
controller = MhtmlExportController(self, output_path, content, source_path)
|
|
|
|
|
self._mhtml_exports.add(controller)
|
|
|
|
|
controller.start()
|