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
+134
View File
@@ -0,0 +1,134 @@
from __future__ import annotations
import json
import threading
import zipfile
from io import BytesIO
from pathlib import Path
from types import SimpleNamespace
import pytest
from lxml import etree
from PySide6.QtCore import QSettings
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.markdown_editor import MarkdownEditorDialog
from mdhelper.markdown_renderer import MarkdownRenderer
from mdhelper.pdf_export import build_pdf_page_layout, build_pdf_export_html
def test_export_check_ignores_code_and_detects_actual_missing_resources(tmp_path):
source = '```md\n![example](ignore.png)\n```\n\n![photo](missing.png)\n\n- a\n - b\n\n$x$\n'
issues = check_export(source, tmp_path / "x.md", "builtin", "p { background: red; font-size: 12pt; }")
messages = "\n".join(i.message for i in issues)
assert "ignore.png" not in messages and "missing.png" in messages
assert "多级列表" in messages and "公式" in messages and "background" in messages
assert "font-size" not in messages
assert any(i.line == 5 and "missing.png" in i.message for i in issues)
@pytest.mark.parametrize("engine", ["pandoc", "python-docx", "builtin"])
def test_word_page_settings_and_inline_styles(tmp_path, engine):
settings = PageSettings(paper="A3", landscape=True, top=22, left=18, include_toc=True, toc_depth=4,
header="项目报告", footer="内部资料", page_numbers=True)
path = tmp_path / (engine + ".docx")
export_markdown_to_docx("# 新内容\n\n正文 **中文加粗。**后续\n", path, engine=engine, page_settings=settings,
style_rules={"paragraph": {"font_size": 14, "font_size_unit": "pt"}})
with zipfile.ZipFile(path) as package:
doc = etree.fromstring(package.read("word/document.xml"))
ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
assert doc.xpath("//w:pgSz/@w:orient", namespaces=ns) == ["landscape"]
assert int(doc.xpath("//w:pgSz/@w:w", namespaces=ns)[0]) > int(doc.xpath("//w:pgSz/@w:h", namespaces=ns)[0])
assert any('1-4' in value for value in doc.xpath("//w:fldSimple/@w:instr", namespaces=ns))
assert doc.xpath("//w:r[w:rPr/w:b]/w:t/text()", namespaces=ns)
assert "项目报告" in package.read("word/header1.xml").decode()
footer = package.read("word/footer1.xml").decode()
assert "NUMPAGES" in footer and "内部资料" in footer
def test_cancelled_word_export_preserves_old_output(tmp_path):
path = tmp_path / "old.docx"; path.write_bytes(b"previous output")
cancel = threading.Event()
def stage(_):
cancel.set()
with pytest.raises(ExportCancelled):
export_markdown_to_docx("new", path, engine="builtin", cancel=cancel, progress=stage)
assert path.read_bytes() == b"previous output"
def test_pdf_layout_and_toc_switch():
from mdhelper.markdown_utils import Heading
settings = PageSettings(paper="Letter", landscape=True, include_toc=False)
layout = build_pdf_page_layout(settings)
assert layout.fullRect(layout.Unit.Millimeter).width() > layout.fullRect(layout.Unit.Millimeter).height()
output = build_pdf_export_html('<html data-theme="dark"><style></style><body><h1 id="a">a</h1></body></html>', [Heading(1, "a", "a")],
include_page_markers=False, settings=settings)
assert '<section class="pdf-toc' not in output
assert '<div class="pdf-body-start-marker">' not in output
assert 'data-theme="light"' in output and 'data-theme="dark"' not in output
def test_pdf_header_footer_and_cancel(tmp_path):
from PySide6.QtWidgets import QApplication
from pypdf import PdfWriter, PdfReader
app = QApplication.instance() or QApplication([])
writer = PdfWriter(); writer.add_blank_page(width=842, height=595)
data = BytesIO(); writer.write(data)
result = decorate_pdf(data.getvalue(), PageSettings(landscape=True, header="报告 Header", footer="Footer"))
page = PdfReader(BytesIO(result)).pages[0]
assert float(page.mediabox.width) == 842
text = page.extract_text()
assert "Header" in text and "Footer" in text and "1" in text
cancel = threading.Event(); cancel.set()
with pytest.raises(ExportCancelled):
decorate_pdf(data.getvalue(), PageSettings(), cancel)
def test_all_exports_use_unsaved_snapshot(tmp_path):
from PySide6.QtWidgets import QApplication
app = QApplication.instance() or QApplication([])
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)
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()
try:
snapshot = window._export_snapshot()
editor.replace_source_undoable("changed later")
for kind in ("html", "mhtml"):
target = tmp_path / ("result." + kind)
window._export_web_to_path(target, kind, snapshot)
if kind == "mhtml":
text, source_path = window.mhtml
assert source_path == path
else:
text = target.read_text(encoding="utf-8")
assert "FRESH_EDITOR" in text and "OLD_DISK" not in text
window.export_docx_to_path(tmp_path / "result.docx", snapshot=snapshot, page_settings=PageSettings(include_toc=False))
with zipfile.ZipFile(tmp_path / "result.docx") as package:
assert b"FRESH_EDITOR" in package.read("word/document.xml")
window.export_pdf_to_path(tmp_path / "result.pdf", snapshot=snapshot)
assert "FRESH_EDITOR" in window.pdf[0]
assert window.pdf[1][0].title == "FRESH_EDITOR"
assert path.read_text() == "# OLD_DISK"
finally:
editor.preview_refresh_timer.stop(); editor.draft_save_timer.stop()
editor.deleteLater(); app.processEvents()