diff --git a/docs/architecture.md b/docs/architecture.md index e4b7e02..f350d79 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -17,6 +17,12 @@ - `document_resources.py` 统一解析 Markdown 与 HTML 引用,提供 URL、源码位置及安全修改片段。文档检查、导出检查、文件监听和图片迁移共用该结果;代码和注释不作为资源引用。 - 图片迁移先生成 `ImageRelocation` 计划,读取和验证全部资源,再复制文件并保存文档。保存成功后才更新文档会话。 +## 导出边界 + +`MainWindow` 持有 `ExportController`,不再继承导出实现。控制器通过 `ExportContext` 获取明确的快照、渲染、页面读取、浏览器配置和状态通知接口;不会自行访问标签页或窗口的字体、样式等内部字段。 + +`ExportSnapshot` 同时保存文本与 `RenderOptions`,导出期间的标签或外观变化不改变当前任务。PDF 和 MHTML 各有独立任务对象,共用 `ExportLifecycle` 的进度窗口、截止计时和页面资源就绪检查。`mhtml_archive.py` 只处理归档数据,不创建 Qt 对象。 + ## 验证约定 每个重构阶段独立提交。运行单元测试,并按改动范围运行 `gui_smoke.py`、`improvements_smoke.py` 和 `reliability_smoke.py`。涉及浏览器生命周期的调整必须检查欢迎页、首次打开文件、标签切换以及预览滚动;涉及保存的调整必须检查保存失败、取消、另存为和后台标签。 diff --git a/mdhelper/export_lifecycle.py b/mdhelper/export_lifecycle.py new file mode 100644 index 0000000..4914ff3 --- /dev/null +++ b/mdhelper/export_lifecycle.py @@ -0,0 +1,41 @@ +"""Shared progress, deadline and browser readiness for export tasks.""" +from PySide6.QtCore import QTimer +from PySide6.QtWidgets import QProgressDialog + + +class ExportLifecycle: + def __init__(self, parent, title, label, cancel, timeout): + self.closed = False + self.progress = QProgressDialog(label, "取消", 0, 0, parent) + self.progress.setWindowTitle(title) + self.progress.setMinimumDuration(0) + self.progress.setAutoClose(False) + self.progress.canceled.connect(cancel) + self.deadline = QTimer(self.progress) + self.deadline.setSingleShot(True) + self.deadline.timeout.connect(timeout) + + def start(self, milliseconds=120_000): + self.deadline.start(milliseconds) + self.progress.show() + + def close(self): + if not self.closed: + self.closed = True + self.deadline.stop() + self.progress.blockSignals(True) + self.progress.close() + self.progress.deleteLater() + + +def page_readiness_script(require_images: bool) -> str: + return r"""(() => { + const images = [...document.images].filter(i => i.getAttribute('src') || i.getAttribute('srcset')); + const lazy = images.filter(i => i.loading === 'lazy'); + lazy.forEach(i => i.loading = 'eager'); + if (lazy.length || images.some(i => !i.complete) || + (document.fonts && document.fonts.status !== 'loaded') || + window.mdhelperRenderReady === false) return 'waiting'; + const missing = images.filter(i => !i.naturalWidth); + return REQUIRE_IMAGES && missing.length ? 'missing:' + missing.map(i => i.src).join('\n') : 'ready'; + })();""".replace("REQUIRE_IMAGES", "true" if require_images else "false") diff --git a/mdhelper/export_workflow.py b/mdhelper/export_workflow.py index 75fe92e..98ba21b 100644 --- a/mdhelper/export_workflow.py +++ b/mdhelper/export_workflow.py @@ -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() diff --git a/mdhelper/main_window.py b/mdhelper/main_window.py index 00d48fc..a384212 100644 --- a/mdhelper/main_window.py +++ b/mdhelper/main_window.py @@ -1,6 +1,7 @@ from __future__ import annotations import html +import copy import time import json import logging @@ -55,7 +56,8 @@ from .style_dialog import DocumentStyleEditorDialog, build_document_style_css from .style_sync import normalize_payload, render_css from .text_io import DEFAULT_TEXT_PREVIEW_BYTES, read_text_with_fallback from .startup_scan import StartupScan -from .export_workflow import ExportWorkflow +from .export_workflow import ExportController, ExportContext, ExportSnapshot +from .render_options import RenderOptions, render_document from .document_session import DocumentStore, DraftStore, DocumentCloseController, CloseChoice from .document_resources import analyze_document, resolve_local_reference from .tab_controller import TabController, document_path @@ -222,7 +224,7 @@ def re_find_markdown_links(source: str) -> list[str]: -class MainWindow(ExportWorkflow, QMainWindow): +class MainWindow(QMainWindow): def __init__( self, project_root: Path | None, @@ -334,6 +336,10 @@ class MainWindow(ExportWorkflow, QMainWindow): if app is not None: app.setWindowIcon(icon) self._build_ui() + self.exports = ExportController(ExportContext( + self, self.settings, self._export_snapshot, + lambda snapshot: render_document(self.renderer, snapshot.path, snapshot.source, snapshot.rendering), + lambda callback: self.web_view.page().toHtml(callback), self._configure_web_settings, self.status_label.setText)) self.tab_controller = TabController(self.tabs, self.document_closer.confirm, self._release_tab_widget, self._ensure_welcome_if_empty, self._on_tab_changed) self.scroll_capture_timer.start() self._populate_tree() @@ -2918,34 +2924,104 @@ class MainWindow(ExportWorkflow, QMainWindow): return False return True - def _render_document_file(self, path: Path, source: str | None = None) -> str: - if is_code_document(path): - return self.renderer.render_code_source( - self._read_text_preview(path), - path, - language=code_language_for_path(path), - theme=self.theme, - font_scale=self.font_scale, - wheel_scroll_speed=self.wheel_scroll_speed, - document_width_scale=self.reader_width_scale, - document_font_family=self.document_font_family, - document_font_size=self.document_font_size, - document_style_css=self._document_style_css(), - math_engine=self.math_engine, - ) + def _render_options(self) -> RenderOptions: + return RenderOptions(self.theme, self.font_scale, self.wheel_scroll_speed, self.reader_width_scale, + self.document_font_family, self.document_font_size, self._document_style_css(), self.math_engine) - return self.renderer.render_source( - path.read_text(encoding="utf-8") if source is None else source, - path, - theme=self.theme, - font_scale=self.font_scale, - wheel_scroll_speed=self.wheel_scroll_speed, - document_width_scale=self.reader_width_scale, - document_font_family=self.document_font_family, - document_font_size=self.document_font_size, - document_style_css=self._document_style_css(), - math_engine=self.math_engine, - ) + 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, RichMarkdownEditorDialog): + 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, self._render_options()) + + def _review_export(self, snapshot: ExportSnapshot, kind: str): + return self.exports._review_export(snapshot, kind) + + def _saved_page_settings(self): + return self.exports._saved_page_settings() + + def _choose_page_settings(self): + return self.exports._choose_page_settings() + + def _saved_pdf_margins(self): + return self.exports._saved_pdf_margins() + + def _save_pdf_margins(self, margins: PdfMargins): + return self.exports._save_pdf_margins(margins) + + def _start_export_job(self, title, callback, completed=None): + return self.exports._start_export_job(title, callback, completed) + + def export_current_docx(self): + return self.exports.export_current_docx() + + def export_docx_to_path(self, output_path: Path, engine: str='builtin', *, snapshot=None, page_settings=None, background=False): + return self.exports.export_docx_to_path(output_path, engine, snapshot=snapshot, page_settings=page_settings, background=background) + + def export_current_pdf(self): + return self.exports.export_current_pdf() + + def export_pdf_to_path(self, output_path: Path, margins=None, *, snapshot=None): + return self.exports.export_pdf_to_path(output_path, margins, snapshot=snapshot) + + def _begin_pdf_export(self, path, content, headings, settings, source_path=None): + return self.exports._begin_pdf_export(path, content, headings, settings, source_path) + + def _on_pdf_probe_ready(self, data): + return self.exports._on_pdf_probe_ready(data) + + def _cleanup_pdf_export(self): + return self.exports._cleanup_pdf_export() + + def export_current_html(self): + return self.exports.export_current_html() + + def export_current_mhtml(self): + return self.exports.export_current_mhtml() + + def _export_web_dialog(self, kind): + return self.exports._export_web_dialog(kind) + + def export_mhtml_to_path(self, output_path): + return self.exports.export_mhtml_to_path(output_path) + + def export_html_to_path(self, output_path): + return self.exports.export_html_to_path(output_path) + + def _write_exported_html(self, output_path, content): + return self.exports._write_exported_html(output_path, content) + + def _export_web_to_path(self, output_path, kind, snapshot=None): + return self.exports._export_web_to_path(output_path, kind, snapshot) + + def _begin_mhtml_export(self, output_path, content, source_path): + return self.exports._begin_mhtml_export(output_path, content, source_path) + + @property + def _pdf_controller(self): + return self.exports._pdf_controller + + @property + def _pdf_export_page(self): + return self.exports._pdf_export_page + + @property + def _mhtml_exports(self): + return self.exports._mhtml_exports + + @property + def _export_jobs(self): + return self.exports._export_jobs + + def _render_document_file(self, path: Path, source: str | None = None) -> str: + return render_document(self.renderer, path, source, self._render_options()) def refresh_project_view(self) -> None: self._refresh_document_entries(force=True) @@ -4578,11 +4654,7 @@ class MainWindow(ExportWorkflow, QMainWindow): if not self._confirm_window_close(): event.ignore() return - self._cleanup_pdf_export() - for controller in list(getattr(self, "_mhtml_exports", ())): - controller.cancel() - for job in getattr(self, "_export_jobs", set()): - job.cancel.set() + self.exports.cancel_all() self._startup_generation += 1 self._startup_scan_pending = False standby_host = self._standby_reader_host diff --git a/mdhelper/mhtml_archive.py b/mdhelper/mhtml_archive.py new file mode 100644 index 0000000..555d7ab --- /dev/null +++ b/mdhelper/mhtml_archive.py @@ -0,0 +1,118 @@ +"""Save a rendered, self-contained browser archive without a visible browser.""" +from __future__ import annotations + +import base64 +import hashlib +import mimetypes +import re +from email import encoders, policy +from email.parser import BytesParser +from html import escape, unescape +from html.parser import HTMLParser +from pathlib import Path +from urllib.parse import urljoin + +from .document_resources import resolve_local_reference +from urllib.parse import urlsplit + + +def portable_archive(data: bytes) -> bytes: + """Use archive IDs instead of file URLs, and embed CSS font dependencies. + + Chromium can block file: subresources even when present in an MHTML archive. + Native page saving also omits local fonts that were not painted on the page. + """ + import tinycss2 + message = BytesParser(policy=policy.default).parsebytes(data) + parts = [p for p in message.walk() if not p.is_multipart()] + aliases = {} + for part in parts: + location = part.get("Content-Location", "") + if location: + identifier = "mdhelper-" + hashlib.sha256(location.encode()).hexdigest()[:24] + if "Content-ID" in part: + identifier = part["Content-ID"].strip("<>") + else: + part["Content-ID"] = f"<{identifier}>" + aliases[location] = "cid:" + identifier + + def css_resource(url, base): + if url.startswith(("#", "data:", "cid:")): + return url + absolute = urljoin(base, url) + if absolute in aliases: + return aliases[absolute] + scheme = urlsplit(absolute).scheme + if scheme == "file": + path = resolve_local_reference(Path.cwd(), absolute) + # Bundled styles list legacy font fallbacks not shipped with the app. + if not path.is_file(): + return "data:," + mime = mimetypes.guess_type(path.name)[0] or "application/octet-stream" + return f"data:{mime};base64," + base64.b64encode(path.read_bytes()).decode("ascii") + if scheme in {"http", "https"}: + raise ValueError("以下样式资源未能包含在离线归档中,请改用本地资源后重试:" + absolute) + return absolute + + def css_text(text, base): + tokens = tinycss2.parse_stylesheet(text) + def visit(items): + for token in items: + if token.type == "url": + value = css_resource(token.value, base) + token.value = value + token.representation = 'url("' + value.replace('"', '%22') + '")' + elif token.type == "function" and token.lower_name == "url": + arguments = [item for item in token.arguments if item.type not in {"whitespace", "comment"}] + value = arguments[0].value if len(arguments) == 1 and arguments[0].type == "string" else tinycss2.serialize(token.arguments).strip() + token.arguments = tinycss2.parse_component_value_list('"' + css_resource(value, base).replace('"', '%22') + '"') + else: + if token.type == "at-rule" and token.lower_at_keyword == "import": + for value in token.prelude: + if value.type == "string": + value.value = css_resource(value.value, base) + value.representation = '"' + value.value + '"' + for name in ("content", "prelude", "arguments"): + if getattr(token, name, None): + visit(getattr(token, name)) + visit(tokens) + return tinycss2.serialize(tokens) + + class HtmlResources(HTMLParser): + def __init__(self, text): + super().__init__(convert_charrefs=False) + self.changes = [] + self.offsets = [0] + [m.end() for m in re.finditer("\n", text)] + self.feed(text) + + def handle_starttag(self, tag, attrs): + raw = self.get_starttag_text() + line, column = self.getpos() + offset = self.offsets[line - 1] + column + for match in re.finditer(r'''\b(?:src|href|poster)\s*=\s*(["'])(.*?)\1''', raw, re.S): + value = unescape(match[2]) + if value in aliases: + self.changes.append((offset + match.start(2), offset + match.end(2), escape(aliases[value], quote=True))) + + for part in parts: + kind = part.get_content_type() + if kind not in {"text/html", "text/css"}: + continue + text = part.get_payload(decode=True).decode(part.get_content_charset() or "utf-8") + if kind == "text/css": + text = css_text(text, part.get("Content-Location", "")) + else: + chunks, offset = [], 0 + for start, end, replacement in HtmlResources(text).changes: + chunks.extend((text[offset:start], replacement)); offset = end + chunks.append(text[offset:]) + text = "".join(chunks) + if "Content-Transfer-Encoding" in part: + del part["Content-Transfer-Encoding"] + part.set_param("charset", "utf-8") + part.set_payload(text.encode("utf-8")) + encoders.encode_base64(part) + # Chromium expects literal Content-Location values, not RFC 2047 folded URLs. + return message.as_bytes(policy=policy.SMTP.clone(max_line_length=0, refold_source="none", utf8=True)) + + diff --git a/mdhelper/mhtml_export.py b/mdhelper/mhtml_export.py index 4a19477..7571c0f 100644 --- a/mdhelper/mhtml_export.py +++ b/mdhelper/mhtml_export.py @@ -1,123 +1,13 @@ -"""Save a rendered, self-contained browser archive without a visible browser.""" +"""Browser task for a portable MHTML archive, without a visible browser.""" from __future__ import annotations - import os -import base64 -import hashlib -import mimetypes -import re import tempfile -from email import encoders, policy -from email.parser import BytesParser -from html import escape, unescape -from html.parser import HTMLParser from pathlib import Path -from urllib.parse import urljoin - from PySide6.QtCore import QTimer, QUrl from PySide6.QtWebEngineCore import QWebEngineDownloadRequest, QWebEnginePage, QWebEngineProfile -from PySide6.QtWidgets import QMessageBox, QProgressDialog - - -def portable_archive(data: bytes) -> bytes: - """Use archive IDs instead of file URLs, and embed CSS font dependencies. - - Chromium can block file: subresources even when present in an MHTML archive. - Native page saving also omits local fonts that were not painted on the page. - """ - import tinycss2 - message = BytesParser(policy=policy.default).parsebytes(data) - parts = [p for p in message.walk() if not p.is_multipart()] - aliases = {} - for part in parts: - location = part.get("Content-Location", "") - if location: - identifier = "mdhelper-" + hashlib.sha256(location.encode()).hexdigest()[:24] - if "Content-ID" in part: - identifier = part["Content-ID"].strip("<>") - else: - part["Content-ID"] = f"<{identifier}>" - aliases[location] = "cid:" + identifier - - def css_resource(url, base): - if url.startswith(("#", "data:", "cid:")): - return url - absolute = urljoin(base, url) - if absolute in aliases: - return aliases[absolute] - qurl = QUrl(absolute) - if qurl.isLocalFile(): - path = Path(qurl.toLocalFile()) - # Bundled styles list legacy font fallbacks not shipped with the app. - if not path.is_file(): - return "data:," - mime = mimetypes.guess_type(path.name)[0] or "application/octet-stream" - return f"data:{mime};base64," + base64.b64encode(path.read_bytes()).decode("ascii") - if qurl.scheme() in {"http", "https"}: - raise ValueError("以下样式资源未能包含在离线归档中,请改用本地资源后重试:" + absolute) - return absolute - - def css_text(text, base): - tokens = tinycss2.parse_stylesheet(text) - def visit(items): - for token in items: - if token.type == "url": - value = css_resource(token.value, base) - token.value = value - token.representation = 'url("' + value.replace('"', '%22') + '")' - elif token.type == "function" and token.lower_name == "url": - arguments = [item for item in token.arguments if item.type not in {"whitespace", "comment"}] - value = arguments[0].value if len(arguments) == 1 and arguments[0].type == "string" else tinycss2.serialize(token.arguments).strip() - token.arguments = tinycss2.parse_component_value_list('"' + css_resource(value, base).replace('"', '%22') + '"') - else: - if token.type == "at-rule" and token.lower_at_keyword == "import": - for value in token.prelude: - if value.type == "string": - value.value = css_resource(value.value, base) - value.representation = '"' + value.value + '"' - for name in ("content", "prelude", "arguments"): - if getattr(token, name, None): - visit(getattr(token, name)) - visit(tokens) - return tinycss2.serialize(tokens) - - class HtmlResources(HTMLParser): - def __init__(self, text): - super().__init__(convert_charrefs=False) - self.changes = [] - self.offsets = [0] + [m.end() for m in re.finditer("\n", text)] - self.feed(text) - - def handle_starttag(self, tag, attrs): - raw = self.get_starttag_text() - line, column = self.getpos() - offset = self.offsets[line - 1] + column - for match in re.finditer(r'''\b(?:src|href|poster)\s*=\s*(["'])(.*?)\1''', raw, re.S): - value = unescape(match[2]) - if value in aliases: - self.changes.append((offset + match.start(2), offset + match.end(2), escape(aliases[value], quote=True))) - - for part in parts: - kind = part.get_content_type() - if kind not in {"text/html", "text/css"}: - continue - text = part.get_payload(decode=True).decode(part.get_content_charset() or "utf-8") - if kind == "text/css": - text = css_text(text, part.get("Content-Location", "")) - else: - chunks, offset = [], 0 - for start, end, replacement in HtmlResources(text).changes: - chunks.extend((text[offset:start], replacement)); offset = end - chunks.append(text[offset:]) - text = "".join(chunks) - if "Content-Transfer-Encoding" in part: - del part["Content-Transfer-Encoding"] - part.set_param("charset", "utf-8") - part.set_payload(text.encode("utf-8")) - encoders.encode_base64(part) - # Chromium expects literal Content-Location values, not RFC 2047 folded URLs. - return message.as_bytes(policy=policy.SMTP.clone(max_line_length=0, refold_source="none", utf8=True)) - +from PySide6.QtWidgets import QMessageBox +from .export_lifecycle import ExportLifecycle, page_readiness_script +from .mhtml_archive import portable_archive class MhtmlExportController: def __init__(self, owner, output: Path, content: str, source_path: Path): @@ -125,14 +15,9 @@ class MhtmlExportController: self.base_url = QUrl.fromLocalFile(str(source_path.parent.resolve()) + os.sep) self.finished = False self.request = self.page = self.profile = self.temporary = None - self.progress = QProgressDialog("正在准备离线文档…", "取消", 0, 0, owner) - self.progress.setWindowTitle("导出 MHTML") - self.progress.setMinimumDuration(0) - self.progress.setAutoClose(False) - self.progress.canceled.connect(self.cancel) - self.timeout = QTimer(self.progress) - self.timeout.setSingleShot(True) - self.timeout.timeout.connect(lambda: self.fail("离线文档导出超时,请检查图片和公式资源。")) + self.lifecycle = ExportLifecycle(owner.context.parent, "导出 MHTML", "正在准备离线文档…", self.cancel, + lambda: self.fail("离线文档导出超时,请检查图片和公式资源。")) + self.progress = self.lifecycle.progress def start(self): try: @@ -140,14 +25,13 @@ class MhtmlExportController: self.temporary = tempfile.TemporaryDirectory(prefix=".mdhelper-mhtml-", dir=self.output.parent, ignore_cleanup_errors=True) self.staged = Path(self.temporary.name) / "document.mhtml" # A separate profile keeps unrelated downloads out of this operation. - self.profile = QWebEngineProfile(self.owner) - self.page = QWebEnginePage(self.profile, self.owner) - self.owner._configure_web_settings(self.page.settings()) + self.profile = QWebEngineProfile(self.owner.context.parent) + self.page = QWebEnginePage(self.profile, self.owner.context.parent) + self.owner.context.configure_web_settings(self.page.settings()) self.profile.downloadRequested.connect(self.download_requested) self.page.loadFinished.connect(self.loaded) - self.timeout.start(120_000) self.page.setHtml(self.content, self.base_url) - self.progress.show() + self.lifecycle.start() except OSError as exc: self.fail(str(exc)) @@ -163,16 +47,7 @@ class MhtmlExportController: def wait_ready(self): if self.finished: return - self.page.runJavaScript(r"""(() => { - const images = [...document.images].filter(i => i.getAttribute('src') || i.getAttribute('srcset')); - const lazy = images.filter(i => i.loading === 'lazy'); - lazy.forEach(i => i.loading = 'eager'); - if (lazy.length || images.some(i => !i.complete) || - (document.fonts && document.fonts.status !== 'loaded') || - window.mdhelperRenderReady === false) return 'waiting'; - const missing = images.filter(i => !i.naturalWidth); - return missing.length ? 'missing:' + missing.map(i => i.src).join('\n') : 'ready'; - })();""", self.ready) + self.page.runJavaScript(page_readiness_script(True), self.ready) def ready(self, state): if self.finished: @@ -208,22 +83,22 @@ class MhtmlExportController: except (OSError, ValueError, UnicodeError) as exc: self.fail(str(exc)) return - self.owner.status_label.setText(f"已导出:{self.output}") + self.owner.context.status(f"已导出:{self.output}") self.cleanup() def cancel(self): if not self.finished: - self.owner.status_label.setText("已取消 MHTML 导出,原有输出文件保持不变") + self.owner.context.status("已取消 MHTML 导出,原有输出文件保持不变") self.cleanup() def fail(self, message): if not self.finished: self.cleanup() - QMessageBox.warning(self.owner, "导出失败", message) + QMessageBox.warning(self.owner.context.parent, "导出失败", message) def cleanup(self): self.finished = True - self.timeout.stop() + self.lifecycle.close() if self.request is not None and not self.request.isFinished(): self.request.cancel() if self.page is not None: @@ -235,7 +110,4 @@ class MhtmlExportController: if self.temporary is not None: self.temporary.cleanup() self.temporary = None - self.progress.blockSignals(True) - self.progress.close() - self.progress.deleteLater() self.owner._mhtml_exports.discard(self) diff --git a/mdhelper/pdf_export_task.py b/mdhelper/pdf_export_task.py new file mode 100644 index 0000000..f6a7680 --- /dev/null +++ b/mdhelper/pdf_export_task.py @@ -0,0 +1,120 @@ +"""PDF browser task: page counting, rendering and final decoration.""" +from __future__ import annotations +import os +from PySide6.QtCore import QTimer, QUrl +from PySide6.QtWidgets import QMessageBox +from .export_lifecycle import ExportLifecycle, page_readiness_script +from .export_jobs import check_cancelled +from .export_settings import decorate_pdf +from .file_versions import atomic_write +from .pdf_export import build_pdf_export_html, build_pdf_page_layout, extract_heading_page_numbers + +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.lifecycle = ExportLifecycle(owner.context.parent, "导出 PDF", "正在准备 PDF 页面…", self.cancel, self.timeout) + self.progress = self.lifecycle.progress + self.job = None + + def start(self): + from PySide6.QtWebEngineCore import QWebEnginePage + self.page = QWebEnginePage(self.owner.context.parent) + self.owner.context.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.lifecycle.start() + + 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 + self.page.runJavaScript(page_readiness_script(False), self.ready) + + def ready(self, ready): + if self.cancelled or self.page is None: + return + self.wait_count += 1 + if ready != "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.context.parent, "导出失败", message) + + def cleanup(self): + if getattr(self, "cleaned", False): + return + self.cleaned = True + self.cancelled = True + self.lifecycle.close() + if self.page is not None: + self.page.deleteLater(); self.page = None + if getattr(self.owner, "_pdf_controller", None) is self: + self.owner._pdf_controller = None + + def cancel(self): + if self.cancelled: + return + if self.job: + self.job.cancel.set() + self.owner.context.status("已取消 PDF 导出,原有输出文件保持不变") + self.cleanup() diff --git a/mdhelper/render_options.py b/mdhelper/render_options.py new file mode 100644 index 0000000..fe44ceb --- /dev/null +++ b/mdhelper/render_options.py @@ -0,0 +1,29 @@ +"""Explicit rendering inputs shared by the reader, previews and exports.""" +from dataclasses import asdict, dataclass +from pathlib import Path + +from .document_tree import code_language_for_path, is_code_document +from .text_io import DEFAULT_TEXT_PREVIEW_BYTES, read_text_with_fallback + + +@dataclass(frozen=True) +class RenderOptions: + theme: str = "light" + font_scale: float = 1.0 + wheel_scroll_speed: float = 1.0 + document_width_scale: float = 1.0 + document_font_family: str = "" + document_font_size: int = 16 + document_style_css: str = "" + math_engine: str = "katex" + + def kwargs(self) -> dict: + return asdict(self) + + +def render_document(renderer, path: Path, source: str | None, options: RenderOptions) -> str: + if is_code_document(path): + return renderer.render_code_source(read_text_with_fallback(path, DEFAULT_TEXT_PREVIEW_BYTES), path, + language=code_language_for_path(path), **options.kwargs()) + return renderer.render_source(path.read_text(encoding="utf-8") if source is None else source, + path, **options.kwargs()) diff --git a/tests/pdf_export_smoke.py b/tests/pdf_export_smoke.py index 7ea0f94..8242291 100644 --- a/tests/pdf_export_smoke.py +++ b/tests/pdf_export_smoke.py @@ -40,13 +40,13 @@ def main() -> int: window = MainWindow(project_root=PROJECT_ROOT, initial_path=PROJECT_ROOT / "sample.md") window.settings = settings - original_probe_handler = window._on_pdf_probe_ready + original_probe_handler = window.exports._on_pdf_probe_ready def capture_probe(pdf_data: object) -> None: output_path.with_suffix(".probe.pdf").write_bytes(bytes(pdf_data)) original_probe_handler(pdf_data) - window._on_pdf_probe_ready = capture_probe + window.exports._on_pdf_probe_ready = capture_probe timeout_ticks = 0 def start_export() -> None: diff --git a/tests/test_export_improvements.py b/tests/test_export_improvements.py index 2f1f616..6b42468 100644 --- a/tests/test_export_improvements.py +++ b/tests/test_export_improvements.py @@ -15,7 +15,7 @@ from mdhelper.docx_exporter import export_markdown_to_docx from mdhelper.export_check import check_export from mdhelper.export_jobs import ExportCancelled from mdhelper.export_settings import PageSettings, decorate_pdf -from mdhelper.export_workflow import ExportWorkflow +from mdhelper.export_workflow import ExportController, ExportContext, ExportSnapshot from mdhelper.markdown_editor import MarkdownEditorDialog from mdhelper.markdown_renderer import MarkdownRenderer from mdhelper.pdf_export import build_pdf_page_layout, build_pdf_export_html @@ -94,22 +94,16 @@ def test_all_exports_use_unsaved_snapshot(tmp_path): path = tmp_path / "note.md"; path.write_text("# OLD_DISK", encoding="utf-8") renderer = MarkdownRenderer(tmp_path) editor = MarkdownEditorDialog(path, "# FRESH_EDITOR\n\n**最新内容**", renderer, "light", 1, "", 16) - class Window(ExportWorkflow): - current_file = path - tabs = SimpleNamespace(currentWidget=lambda: editor) - custom_document_styles = {} - document_style_id = "default" - document_font_family = "" - document_font_size = 16 - settings = QSettings(str(tmp_path / "settings.ini"), QSettings.Format.IniFormat) - status_label = SimpleNamespace(setText=lambda _: None) - def _render_document_file(self, path, source=None): - return renderer.render_source(source, path) + class Controller(ExportController): def _begin_pdf_export(self, output, content, headings, settings, source_path): self.pdf = (content, headings, source_path) def _begin_mhtml_export(self, output, content, source_path): self.mhtml = (content, source_path) - window = Window() + window = Controller(ExportContext( + parent=None, settings=QSettings(str(tmp_path / "settings.ini"), QSettings.Format.IniFormat), + snapshot=lambda: ExportSnapshot(path, editor.source_text(), {}, "", 16, "default"), + render=lambda snapshot: renderer.render_source(snapshot.source, snapshot.path), + page_html=lambda callback: None, configure_web_settings=lambda settings: None, status=lambda text: None)) try: snapshot = window._export_snapshot() editor.replace_source_undoable("changed later") diff --git a/tests/test_reliability.py b/tests/test_reliability.py index 62dbf50..2910db1 100644 --- a/tests/test_reliability.py +++ b/tests/test_reliability.py @@ -156,6 +156,18 @@ def test_save_as_missing_image_keeps_original_context(editing, tmp_path): assert original.read_text() == "# Original" +def test_export_snapshot_keeps_rendering_choices_after_ui_changes(editing, tmp_path): + window, editor, path = editing + window.theme = "dark" + snapshot = window._export_snapshot() + window.theme = "light" + editor.replace_source_undoable("changed later") + output = tmp_path / "snapshot.html" + window.exports._export_web_to_path(output, "html", snapshot) + html = output.read_text(encoding="utf-8") + assert 'data-theme="dark"' in html and "changed later" not in html + + def test_save_as_copies_images_and_can_undo_rewritten_urls(editing, tmp_path): window, editor, original = editing source = store_image(original, b"image bytes")