fix: protect editor content and harden document exports

Protect pending edits on window close, keep save-as paths and drafts consistent,
copy relative image resources, reject oversized table imports without truncation,
and preserve independent preview scrolling during refresh.

Archive rendered MHTML resources with portable references and embedded local
fonts. Preserve existing outputs on export cancellation or failure. Convert
editor match positions and filter directory results in linear passes.

Include the previously completed editor image/table/history improvements,
undoable replacement, export snapshots, shared page settings, and cancellable
PDF/Word export workflow. Update documentation and version to 0.3.1.

Validation: 142 pytest cases passed; GUI smoke, improvements integration, and
offline MHTML/scroll reliability smoke checks passed.
This commit is contained in:
2026-10-29 18:22:42 +08:00
parent fac5cbb011
commit 8dae91c2ca
26 changed files with 2722 additions and 385 deletions
+393
View File
@@ -0,0 +1,393 @@
"""Export UI: immutable editor snapshots, review, and cancellable jobs."""
from __future__ import annotations
import copy
import json
import os
from dataclasses import asdict, dataclass
from pathlib import Path
from PySide6.QtCore import QThreadPool, QTimer, QUrl
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
from .export_jobs import ExportJob, check_cancelled
from .export_settings import PageSettings, decorate_pdf
from .file_versions import atomic_write
from .markdown_editor import MarkdownEditorDialog
from .markdown_utils import Heading
from .pdf_export import (PdfExportSettingsDialog, PdfMargins, build_pdf_export_html,
build_pdf_page_layout, extract_heading_page_numbers)
@dataclass(frozen=True)
class ExportSnapshot:
path: Path
source: str | None
style: dict
font: str
font_size: float
preset: str
class ExportWorkflow:
def _export_snapshot(self) -> ExportSnapshot | None:
if self.current_file is None:
return None
path = self.current_file
widget = self.tabs.currentWidget()
source = None
if isinstance(widget, MarkdownEditorDialog):
source = widget.source_text()
elif path.suffix.lower() in {".md", ".markdown"}:
source = path.read_text(encoding="utf-8")
return ExportSnapshot(path, source, copy.deepcopy(self.custom_document_styles.get(self.document_style_id, {})),
self.document_font_family, self.document_font_size, self.document_style_id)
def _review_export(self, snapshot: ExportSnapshot, kind: str) -> bool:
if snapshot.source is None:
return True
return confirm_export(self, check_export(snapshot.source, snapshot.path, kind, snapshot.style.get("css", "")))
def _saved_page_settings(self) -> PageSettings:
try:
value = json.loads(str(self.settings.value("export/page_settings", "{}")))
if isinstance(value, dict) and value:
return PageSettings.from_dict(value).normalized()
except (TypeError, ValueError):
pass
margins = self._saved_pdf_margins()
return PageSettings(top=margins.top, bottom=margins.bottom, left=margins.left, right=margins.right)
def _choose_page_settings(self) -> PageSettings | None:
dialog = PdfExportSettingsDialog(self._saved_page_settings(), self)
if dialog.exec() != QDialog.DialogCode.Accepted:
return None
settings = dialog.page_settings()
self.settings.setValue("export/page_settings", json.dumps(asdict(settings), ensure_ascii=False))
return settings
def _saved_pdf_margins(self) -> PdfMargins:
def value(name):
try:
return max(0, min(50, float(self.settings.value(f"pdf/{name}_margin_mm", 15))))
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"):
self.settings.setValue(f"pdf/{name}_margin_mm", getattr(margins, name))
def _start_export_job(self, title, callback, completed=None):
job = ExportJob(callback)
progress = QProgressDialog(title, "取消", 0, 0, self)
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:
QMessageBox.warning(self, "导出失败", error)
elif result:
self.status_label.setText(f"已导出:{result}")
else:
self.status_label.setText("已取消导出,原有输出文件保持不变")
if completed:
completed()
job.signals.finished.connect(finished)
progress.show()
QThreadPool.globalInstance().start(job)
return job
def export_current_docx(self) -> None:
if self.current_file is None:
return
labels = list(DOCX_EXPORT_ENGINES.values())
label, ok = QInputDialog.getItem(self, "选择 Word 导出方式", "导出方式", labels, 0, False)
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
file_name, _ = QFileDialog.getSaveFileName(self, "导出 Word", str(snapshot.path.with_suffix(".docx")), "Word 文档 (*.docx)")
if file_name:
self.export_docx_to_path(Path(file_name), engine, snapshot=snapshot, page_settings=settings, background=True)
except (OSError, ValueError) as exc:
QMessageBox.warning(self, "导出失败", str(exc))
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:
QMessageBox.warning(self, "导出失败", str(exc))
return None
def export_current_pdf(self) -> None:
if self.current_file is None:
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
file_name, _ = QFileDialog.getSaveFileName(self, "导出 PDF", str(snapshot.path.with_suffix(".pdf")), "PDF (*.pdf)")
if file_name:
self.export_pdf_to_path(Path(file_name), settings, snapshot=snapshot)
except (OSError, ValueError) as exc:
QMessageBox.warning(self, "导出失败", str(exc))
def export_pdf_to_path(self, output_path: Path, margins=None, *, snapshot=None):
if getattr(self, "_pdf_export_page", None) is not None:
QMessageBox.information(self, "正在导出", "已有 PDF 导出任务正在进行,请等待完成或取消。")
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):
content = self._render_document_file(snapshot.path, source=snapshot.source)
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:
self.web_view.page().toHtml(lambda content: self._begin_pdf_export(output_path, content, [], settings, snapshot.path))
return output_path
except (OSError, ValueError) as exc:
QMessageBox.warning(self, "导出失败", str(exc))
return None
def _begin_pdf_export(self, path, content, headings, settings, source_path=None):
controller = PdfExportController(self, path, content, headings, settings, source_path or self.current_file)
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
file_name, _ = QFileDialog.getSaveFileName(self, f"导出 {kind.upper()}",
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:
QMessageBox.warning(self, "导出失败", str(exc))
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"))
self.status_label.setText(f"HTML 已导出:{output_path}")
except OSError as exc:
QMessageBox.warning(self, "导出失败", str(exc))
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"))
self.status_label.setText(f"已导出:{output_path}")
except OSError as exc:
QMessageBox.warning(self, "导出失败", str(exc))
if snapshot.source is not None or is_code_document(snapshot.path):
write(self._render_document_file(snapshot.path, source=snapshot.source))
else:
self.web_view.page().toHtml(write)
return output_path
except (OSError, ValueError) as exc:
QMessageBox.warning(self, "导出失败", str(exc))
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()
class PdfExportController:
def __init__(self, owner, output, content, headings, settings, source_path):
self.owner, self.output, self.content, self.settings = owner, output, content, settings
self.headings = [h for h in headings if h.level <= settings.toc_depth] if settings.include_toc else []
self.base_url = QUrl.fromLocalFile(str(source_path.parent.resolve()) + os.sep)
self.page = None
self.cancelled = False
self.stage = "probe" if settings.include_toc else "final"
self.progress = QProgressDialog("正在准备 PDF 页面…", "取消", 0, 0, owner)
self.progress.setWindowTitle("导出 PDF"); self.progress.setMinimumDuration(0)
self.progress.setAutoClose(False); self.progress.canceled.connect(self.cancel)
self.job = None
def start(self):
from PySide6.QtWebEngineCore import QWebEnginePage
self.page = QWebEnginePage(self.owner)
self.owner._pdf_export_page = self.page
self.owner._configure_web_settings(self.page.settings())
self.page.loadFinished.connect(self.loaded)
self.page.setHtml(build_pdf_export_html(self.content, self.headings, settings=self.settings,
include_page_markers=self.stage == "probe"), self.base_url)
self.progress.show()
QTimer.singleShot(120_000, self.timeout)
def loaded(self, ok):
if self.cancelled:
return
if not ok:
self.fail("PDF 页面加载失败。")
return
self.progress.setLabelText("正在等待图片、公式和图表完成…")
self.wait_count = 0
self.wait_ready()
def wait_ready(self):
if self.cancelled or self.page is None:
return
script = """(() => {
const images = [...document.images].every(i => i.complete);
const fonts = !document.fonts || document.fonts.status === 'loaded';
return images && fonts && window.mdhelperRenderReady !== false;
})();"""
self.page.runJavaScript(script, self.ready)
def ready(self, ready):
if self.cancelled or self.page is None:
return
self.wait_count += 1
if not ready:
if self.wait_count >= 100:
self.fail("图片或公式加载超时,请检查资源后重试。")
else:
QTimer.singleShot(100, self.wait_ready)
return
# Allow layout to settle without showing an additional browser window.
QTimer.singleShot(150, self.print_page)
def print_page(self):
if self.cancelled or self.page is None:
return
self.progress.setLabelText("正在计算目录页码…" if self.stage == "probe" else "正在生成 PDF…")
callback = self.owner._on_pdf_probe_ready if self.stage == "probe" else self.final_ready
self.page.printToPdf(lambda data: callback(data) if not self.cancelled else None, build_pdf_page_layout(self.settings))
def probe_ready(self, data):
if self.cancelled or self.page is None:
return
try:
numbers = extract_heading_page_numbers(bytes(data), len(self.headings))
self.stage = "final"
self.page.setHtml(build_pdf_export_html(self.content, self.headings, numbers, include_page_markers=False,
settings=self.settings), self.base_url)
except Exception as exc:
self.fail(str(exc))
def final_ready(self, data):
if self.cancelled:
return
raw = bytes(data)
if not raw:
self.fail("未能生成 PDF 内容。")
return
self.progress.blockSignals(True); self.progress.hide()
def decorate(cancel, progress):
progress("正在添加页眉、页脚和页码…")
result = decorate_pdf(raw, self.settings, cancel)
check_cancelled(cancel)
atomic_write(self.output, result)
return self.output
self.job = self.owner._start_export_job("正在完成 PDF…", decorate, self.cleanup)
def timeout(self):
if self.page is not None and not self.cancelled:
self.fail("PDF 导出超时。")
def fail(self, message):
self.cancel()
QMessageBox.warning(self.owner, "导出失败", message)
def cleanup(self):
if getattr(self, "cleaned", False):
return
self.cleaned = True
self.cancelled = True
self.progress.blockSignals(True); self.progress.close(); self.progress.deleteLater()
if self.page is not None:
self.page.deleteLater(); self.page = None
if getattr(self.owner, "_pdf_controller", None) is self:
self.owner._pdf_export_page = None
self.owner._pdf_controller = None
def cancel(self):
if self.cancelled:
return
if self.job:
self.job.cancel.set()
self.owner.status_label.setText("已取消 PDF 导出,原有输出文件保持不变")
self.cleanup()