refactor: compose export controller with explicit snapshots and task lifecycle
This commit is contained in:
+70
-172
@@ -1,25 +1,24 @@
|
||||
"""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.QtCore import QThreadPool
|
||||
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 .export_jobs import ExportJob
|
||||
from .export_settings import PageSettings
|
||||
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)
|
||||
from .render_options import RenderOptions
|
||||
from typing import Callable
|
||||
from .pdf_export_task import PdfExportController
|
||||
from .pdf_export import PdfExportSettingsDialog, PdfMargins
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -30,30 +29,49 @@ class ExportSnapshot:
|
||||
font: str
|
||||
font_size: float
|
||||
preset: str
|
||||
rendering: RenderOptions | None = None
|
||||
|
||||
|
||||
class ExportWorkflow:
|
||||
@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]
|
||||
|
||||
|
||||
class ExportController:
|
||||
def __init__(self, context: ExportContext):
|
||||
self.context = context
|
||||
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()
|
||||
|
||||
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)
|
||||
return self.context.snapshot()
|
||||
|
||||
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", "")))
|
||||
return confirm_export(self.context.parent, 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", "{}")))
|
||||
value = json.loads(str(self.context.settings.value("export/page_settings", "{}")))
|
||||
if isinstance(value, dict) and value:
|
||||
return PageSettings.from_dict(value).normalized()
|
||||
except (TypeError, ValueError):
|
||||
@@ -62,28 +80,28 @@ class ExportWorkflow:
|
||||
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)
|
||||
dialog = PdfExportSettingsDialog(self._saved_page_settings(), self.context.parent)
|
||||
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))
|
||||
self.context.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))))
|
||||
return max(0, min(50, float(self.context.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))
|
||||
self.context.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 = QProgressDialog(title, "取消", 0, 0, self.context.parent)
|
||||
progress.setWindowTitle("导出文档")
|
||||
progress.setMinimumDuration(0)
|
||||
progress.setAutoClose(False)
|
||||
@@ -96,11 +114,11 @@ class ExportWorkflow:
|
||||
self._export_jobs.discard(job)
|
||||
progress.blockSignals(True); progress.close(); progress.deleteLater()
|
||||
if error:
|
||||
QMessageBox.warning(self, "导出失败", error)
|
||||
QMessageBox.warning(self.context.parent, "导出失败", error)
|
||||
elif result:
|
||||
self.status_label.setText(f"已导出:{result}")
|
||||
self.context.status(f"已导出:{result}")
|
||||
else:
|
||||
self.status_label.setText("已取消导出,原有输出文件保持不变")
|
||||
self.context.status("已取消导出,原有输出文件保持不变")
|
||||
if completed:
|
||||
completed()
|
||||
job.signals.finished.connect(finished)
|
||||
@@ -109,10 +127,10 @@ class ExportWorkflow:
|
||||
return job
|
||||
|
||||
def export_current_docx(self) -> None:
|
||||
if self.current_file is None:
|
||||
if self._export_snapshot() is None:
|
||||
return
|
||||
labels = list(DOCX_EXPORT_ENGINES.values())
|
||||
label, ok = QInputDialog.getItem(self, "选择 Word 导出方式", "导出方式", labels, 0, False)
|
||||
label, ok = QInputDialog.getItem(self.context.parent, "选择 Word 导出方式", "导出方式", labels, 0, False)
|
||||
if not ok:
|
||||
return
|
||||
engine = next(key for key, value in DOCX_EXPORT_ENGINES.items() if value == label)
|
||||
@@ -123,11 +141,11 @@ class ExportWorkflow:
|
||||
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)")
|
||||
file_name, _ = QFileDialog.getSaveFileName(self.context.parent, "导出 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))
|
||||
QMessageBox.warning(self.context.parent, "导出失败", str(exc))
|
||||
|
||||
def export_docx_to_path(self, output_path: Path, engine: str = "builtin", *, snapshot=None, page_settings=None, background=False):
|
||||
try:
|
||||
@@ -148,11 +166,11 @@ class ExportWorkflow:
|
||||
return output_path
|
||||
return convert()
|
||||
except Exception as exc:
|
||||
QMessageBox.warning(self, "导出失败", str(exc))
|
||||
QMessageBox.warning(self.context.parent, "导出失败", str(exc))
|
||||
return None
|
||||
|
||||
def export_current_pdf(self) -> None:
|
||||
if self.current_file is None:
|
||||
if self._export_snapshot() is None:
|
||||
return
|
||||
settings = self._choose_page_settings()
|
||||
if settings is None:
|
||||
@@ -161,15 +179,15 @@ class ExportWorkflow:
|
||||
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)")
|
||||
file_name, _ = QFileDialog.getSaveFileName(self.context.parent, "导出 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))
|
||||
QMessageBox.warning(self.context.parent, "导出失败", 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 导出任务正在进行,请等待完成或取消。")
|
||||
QMessageBox.information(self.context.parent, "正在导出", "已有 PDF 导出任务正在进行,请等待完成或取消。")
|
||||
return None
|
||||
try:
|
||||
snapshot = snapshot or self._export_snapshot()
|
||||
@@ -181,7 +199,7 @@ class ExportWorkflow:
|
||||
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)
|
||||
content = self.context.render(snapshot)
|
||||
headings = []
|
||||
if snapshot.source is not None:
|
||||
from .markdown_renderer import MarkdownRenderer
|
||||
@@ -190,14 +208,14 @@ class ExportWorkflow:
|
||||
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))
|
||||
self.context.page_html(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))
|
||||
QMessageBox.warning(self.context.parent, "导出失败", 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)
|
||||
controller = PdfExportController(self, path, content, headings, settings, source_path or self._export_snapshot().path)
|
||||
self._pdf_controller = controller
|
||||
controller.start()
|
||||
|
||||
@@ -220,12 +238,12 @@ class ExportWorkflow:
|
||||
snapshot = self._export_snapshot()
|
||||
if snapshot is None or not self._review_export(snapshot, kind):
|
||||
return
|
||||
file_name, _ = QFileDialog.getSaveFileName(self, f"导出 {kind.upper()}",
|
||||
file_name, _ = QFileDialog.getSaveFileName(self.context.parent, 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))
|
||||
QMessageBox.warning(self.context.parent, "导出失败", str(exc))
|
||||
|
||||
def export_mhtml_to_path(self, output_path):
|
||||
return self._export_web_to_path(output_path, "mhtml")
|
||||
@@ -236,9 +254,9 @@ class ExportWorkflow:
|
||||
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}")
|
||||
self.context.status(f"HTML 已导出:{output_path}")
|
||||
except OSError as exc:
|
||||
QMessageBox.warning(self, "导出失败", str(exc))
|
||||
QMessageBox.warning(self.context.parent, "导出失败", str(exc))
|
||||
|
||||
def _export_web_to_path(self, output_path, kind, snapshot=None):
|
||||
try:
|
||||
@@ -252,16 +270,16 @@ class ExportWorkflow:
|
||||
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}")
|
||||
self.context.status(f"已导出:{output_path}")
|
||||
except OSError as exc:
|
||||
QMessageBox.warning(self, "导出失败", str(exc))
|
||||
QMessageBox.warning(self.context.parent, "导出失败", str(exc))
|
||||
if snapshot.source is not None or is_code_document(snapshot.path):
|
||||
write(self._render_document_file(snapshot.path, source=snapshot.source))
|
||||
write(self.context.render(snapshot))
|
||||
else:
|
||||
self.web_view.page().toHtml(write)
|
||||
self.context.page_html(write)
|
||||
return output_path
|
||||
except (OSError, ValueError) as exc:
|
||||
QMessageBox.warning(self, "导出失败", str(exc))
|
||||
QMessageBox.warning(self.context.parent, "导出失败", str(exc))
|
||||
return None
|
||||
|
||||
def _begin_mhtml_export(self, output_path, content, source_path):
|
||||
@@ -271,123 +289,3 @@ class ExportWorkflow:
|
||||
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()
|
||||
|
||||
Reference in New Issue
Block a user