Files
MDHelper/mdhelper/export_check.py
T
shen 8dae91c2ca 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.
2026-10-29 18:22:42 +08:00

106 lines
5.4 KiB
Python

"""Content-aware export checks; code examples are never scanned as links."""
from __future__ import annotations
import re
from dataclasses import dataclass
from pathlib import Path
from urllib.parse import unquote, urlsplit
from urllib.request import url2pathname
@dataclass(frozen=True)
class ExportIssue:
line: int
message: str
def check_export(source: str, path: Path, kind: str, css_source: str = "") -> list[ExportIssue]:
from .markdown_renderer import MarkdownRenderer
from html.parser import HTMLParser
issues: list[ExportIssue] = []
seen: set[tuple[int, str]] = set()
def add(line: int, message: str) -> None:
if (line, message) not in seen:
seen.add((line, message)); issues.append(ExportIssue(line, message))
word = kind in {"pandoc", "python-docx", "builtin"}
basic = kind in {"python-docx", "builtin"}
def target(value: str, line: int, image: bool) -> None:
parsed = urlsplit(value)
if parsed.scheme in {"http", "https"}:
if image:
add(line, "远程图片依赖网络,离线导出可能缺失:" + value)
return
if parsed.scheme not in {"", "file"} or not parsed.path:
return
local = Path(url2pathname(unquote(parsed.path))) if parsed.scheme == "file" else path.parent / unquote(parsed.path)
if not local.exists():
add(line, "本地图片不存在:" + value if image else "本地链接目标不存在:" + value)
if image and basic:
add(line, "此 Word 导出方式不嵌入图片,建议选择 Pandoc。")
tokens = MarkdownRenderer(path.parent).markdown.parse(source)
list_depth = 0
for token in tokens:
line = token.map[0] + 1 if token.map else 0
if token.type in {"bullet_list_open", "ordered_list_open"}:
list_depth += 1
if basic and list_depth > 1:
add(line, "此 Word 导出方式不能完整保留多级列表,建议选择 Pandoc。")
if kind == "builtin" and token.type == "ordered_list_open":
add(line, "内置导出使用简化编号,建议选择 Pandoc 保留连续编号。")
elif token.type in {"bullet_list_close", "ordered_list_close"}:
list_depth -= 1
if word and token.type == "fence" and token.info.strip().lower() == "mermaid":
add(line, "Mermaid 图表在 Word 中会保留为代码;需要图形时请先转换为图片。")
if basic and token.type == "math_block":
add(line, "此 Word 导出方式不转换公式,建议选择 Pandoc。")
for child in token.children or []:
if child.type == "image":
target(child.attrGet("src") or "", line, True)
elif child.type == "link_open":
target(child.attrGet("href") or "", line, False)
elif basic and child.type == "math_inline":
add(line, "此 Word 导出方式不转换公式,建议选择 Pandoc。")
html_tokens = [token] if token.type == "html_block" else [c for c in token.children or [] if c.type == "html_inline"]
for raw in html_tokens:
if word:
add(line, "含有内嵌 HTML,Word 可能无法保留其内容或布局,请核对导出结果。")
class Links(HTMLParser):
def handle_starttag(self, tag, attrs):
for name, value in attrs:
if name in {"src", "href"} and value:
target(value, line, tag.lower() == "img")
Links().feed(raw.content)
if word and css_source.strip():
from .style_sync import analyze_css, CORE_PROPERTIES
import tinycss2
analysis = analyze_css(css_source)
for note in analysis.notes:
add(0, "Word 样式限制:" + note)
unsupported: set[str] = set()
for rule in tinycss2.parse_stylesheet(css_source, skip_whitespace=True, skip_comments=True):
if rule.type == "qualified-rule":
for declaration in tinycss2.parse_declaration_list(rule.content):
if declaration.type == "declaration" and declaration.lower_name not in CORE_PROPERTIES | {"font", "margin"}:
unsupported.add(declaration.lower_name)
if unsupported:
add(0, "以下 CSS 效果不会转换为 Word 格式:" + "、".join(sorted(unsupported)))
return issues
def confirm_export(parent: object, issues: list[ExportIssue]) -> bool:
if not issues:
return True
from PySide6.QtWidgets import QDialog, QDialogButtonBox, QLabel, QPlainTextEdit, QVBoxLayout
dialog = QDialog(parent); dialog.setWindowTitle("导出前检查"); dialog.resize(760, 460)
layout = QVBoxLayout(dialog)
layout.addWidget(QLabel("发现以下内容需要留意。可以返回编辑,或继续导出后核对结果。"))
details = QPlainTextEdit(); details.setReadOnly(True)
details.setPlainText("\n\n".join((f"第 {issue.line} 行:" if issue.line else "") + issue.message for issue in issues))
layout.addWidget(details)
buttons = QDialogButtonBox()
buttons.addButton("继续导出", QDialogButtonBox.ButtonRole.AcceptRole)
buttons.addButton("返回编辑", QDialogButtonBox.ButtonRole.RejectRole)
buttons.accepted.connect(dialog.accept); buttons.rejected.connect(dialog.reject)
layout.addWidget(buttons)
return dialog.exec() == QDialog.DialogCode.Accepted