From 8dae91c2ca954248c3f09e357bd4d3a8d62a8206 Mon Sep 17 00:00:00 2001 From: shen Date: Thu, 29 Oct 2026 18:22:42 +0800 Subject: [PATCH] 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. --- README.md | 8 +- docs/troubleshooting.md | 24 ++ docs/user_manual.md | 30 ++- mdhelper/__init__.py | 2 +- mdhelper/docx_exporter.py | 72 ++++-- mdhelper/editor_assets.py | 171 +++++++++++++ mdhelper/export_check.py | 105 ++++++++ mdhelper/export_jobs.py | 36 +++ mdhelper/export_settings.py | 152 +++++++++++ mdhelper/export_workflow.py | 393 +++++++++++++++++++++++++++++ mdhelper/file_versions.py | 108 ++++++++ mdhelper/main_window.py | 405 ++++++------------------------ mdhelper/markdown_editor.py | 200 +++++++++++++-- mdhelper/markdown_renderer.py | 22 +- mdhelper/mhtml_export.py | 241 ++++++++++++++++++ mdhelper/pdf_export.py | 53 +++- mdhelper/resources/reader.js | 40 ++- mdhelper/search.py | 26 +- mdhelper/table_editor.py | 165 ++++++++++++ tests/conftest.py | 21 ++ tests/improvements_smoke.py | 153 +++++++++++ tests/reliability_smoke.py | 126 ++++++++++ tests/test_editor_improvements.py | 125 +++++++++ tests/test_export_improvements.py | 134 ++++++++++ tests/test_mhtml_export.py | 46 ++++ tests/test_reliability.py | 249 ++++++++++++++++++ 26 files changed, 2722 insertions(+), 385 deletions(-) create mode 100644 mdhelper/editor_assets.py create mode 100644 mdhelper/export_check.py create mode 100644 mdhelper/export_jobs.py create mode 100644 mdhelper/export_settings.py create mode 100644 mdhelper/export_workflow.py create mode 100644 mdhelper/file_versions.py create mode 100644 mdhelper/mhtml_export.py create mode 100644 mdhelper/table_editor.py create mode 100644 tests/conftest.py create mode 100644 tests/improvements_smoke.py create mode 100644 tests/reliability_smoke.py create mode 100644 tests/test_editor_improvements.py create mode 100644 tests/test_export_improvements.py create mode 100644 tests/test_mhtml_export.py create mode 100644 tests/test_reliability.py diff --git a/README.md b/README.md index 1a2179e..0d88082 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # MDHelper -当前版本:`0.2.3` +当前版本:`0.3.1` MDHelper 是一个本地 Markdown / 代码文档阅读器,使用 PySide6 构建桌面窗口,用 Qt WebEngine 展示由 Markdown 转换得到的 HTML 页面。它面向本地项目文档、技术手册、源码说明和离线帮助文件,重点是离线可用、多标签阅读、全文搜索、样式管理和导出。 @@ -22,6 +22,7 @@ MDHelper 是一个本地 Markdown / 代码文档阅读器,使用 PySide6 构 - 提供“样式”菜单,支持内置文档样式和自定义样式文件,样式可配置字体、缩进、行距、段前段后间距等。 - 图形样式支持磅值/中文字号、字体颜色、字符间距、对齐、左右和特殊缩进、同样式段落间距及分页控制。图形设置与高级 CSS 双向同步,三个 DOCX 导出引擎均保留可识别的核心设置;背景、边框及条件规则等扩展效果用于阅读器及 HTML/PDF。 - 导出支持 PDF、HTML、DOCX、MHTML;DOCX 可选择 `pandoc` 或 `python-docx` 相关实现。 +- 退出时检查未保存内容;另存为到其他目录会复制相对引用图片。MHTML 保存已渲染的图片、公式、图表及样式资源,支持离线携带。 - 图片点击放大,支持缩放、旋转、适应窗口、原始大小、保存图片和在文件夹中显示。 - 表格支持横向滚动和一键复制。 - 支持导入/导出配置 JSON,便于迁移主题、书签、最近文件、阅读位置、样式和外部程序映射。 @@ -59,6 +60,9 @@ MDHelper 是一个本地 Markdown / 代码文档阅读器,使用 PySide6 构 - 阅读模式只显示正文,左侧大纲按需点击跳转。 - 编辑模式保留源码编辑、左侧大纲、分屏预览和保存冲突检测。 - 编辑预览刷新使用防抖,避免每次输入都完整重建 HTML。 +- 分屏按源码段落双向同步滚动,可关闭;支持粘贴截图、拖入图片及图形化表格编辑。 +- 全部替换和历史版本恢复可撤销;安全保存保留最近 20 个保存前版本。 +- 四种导出均使用当前编辑内容。Word / PDF 共用纸张、方向、页边距、目录及页眉页脚设置,并提供导出前检查和可取消的生成流程。 ## 快捷键 @@ -117,7 +121,7 @@ MDHelper 是一个本地 Markdown / 代码文档阅读器,使用 PySide6 构 首次缺少 Inno Setup 时会从官方来源下载、校验发布者签名并安装到 `pack\.tools`;后续构建复用。 需要可用的 64 位 Python 3.10+;兼容当前项目的两种 `mdhelper_env` 目录布局。 -安装程序位于 `pack\output\MDHelper-Setup-0.2.3-x64.exe`(版本号自动读取),同目录包含 SHA256 校验文件。 +构建后的安装程序位于 `pack\output\MDHelper-Setup-<版本号>-x64.exe`(版本号自动读取),同目录包含 SHA256 校验文件。 默认按当前用户安装,提供开始菜单入口、可选桌面快捷方式,以及 Windows 卸载入口。 程序运行时无需单独安装 Python 或 Pandoc。 diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 036b9fe..7bc3711 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -81,6 +81,18 @@ MDHelper 读取文档时不会锁定文件,外部编辑器仍可保存。 可先导出 HTML,确认内容渲染正常,再导出 PDF。 +## 导出的 Word 目录仍显示提示文字 + +Word 目录使用可更新的目录域。打开文件后,在目录提示文字处右键选择“更新域”,由 Word 按实际页面生成页码。PDF 的目录页码在导出时自动生成。 + +## 修改已经保存,想恢复旧内容 + +使用“文件 → 历史版本”,查看版本差异后恢复到编辑区。确认无误再保存;恢复操作本身可以撤销。本机每个文件路径保留最近 20 个保存前版本,重命名后的路径有独立记录。 + +## 分享文档后图片无法显示 + +粘贴或拖入的图片保存在文档旁的“文档名.assets”文件夹。移动或分享 Markdown 时,请将该文件夹一起带走,并保持相对位置不变。 + ## 代码文件不显示 打开 `工具 - 设置 - 展示文件类型`,勾选需要的类型: @@ -113,6 +125,18 @@ MDHelper 读取文档时不会锁定文件,外部编辑器仍可保存。 .\dist\MDHelper\MDHelper.exe --check --project-root . ``` +## 另存为失败或图片无法复制 + +另存为到其他目录会同时复制相对引用的图片。请确认源图片存在且目标目录可写。失败时编辑内容、原文档路径和草稿仍保留;只有全部保存成功才切换到新路径。 + +## 从 Excel 粘贴表格提示超限 + +图形表格上限为 1000 行(含表头)、100 列。超限时不导入任何单元格,以免静默截断。可拆分后粘贴,或直接编辑 Markdown 源码。 + +## MHTML 导出失败 + +离线归档需要先加载文档中的实际图片、公式及图表。请根据提示修复资源路径,或将未能封装的远程样式资源改为本地资源。取消和失败均保留原有输出文件。成功导出的归档可单独移动,不需要原图片目录。 + ## 如何定位日志 MDHelper 会把日志写到用户可写目录。若启动或打开文档异常,优先查看最近的运行日志,并把错误堆栈和打开的文件路径一起记录下来。 diff --git a/docs/user_manual.md b/docs/user_manual.md index 3178d9e..3d62aee 100644 --- a/docs/user_manual.md +++ b/docs/user_manual.md @@ -2,7 +2,7 @@ MDHelper 是一个本地 Markdown / 代码文档阅读器,适合阅读项目说明、技术手册、源码旁文档和离线帮助文件。它使用 PySide6 提供桌面窗口,用 Qt WebEngine 渲染 Markdown 转换后的 HTML 页面,并在本地完成全文搜索、样式管理、导出和自动刷新。 -当前版本:`0.2.3` +当前版本:`0.3.1` ## 1. 适用场景 @@ -121,6 +121,24 @@ Markdown 支持: - 自动保存草稿和恢复草稿。 - 保存前检测磁盘文件是否被外部程序修改,避免覆盖外部编辑。 +“全部替换”支持一次撤销,并保留此前的编辑记录。替换文本中的反斜杠按普通字符处理,可直接填写 Windows 路径。 + +关闭软件时,会先记录所有编辑标签的最新草稿,再提供“保存 / 放弃 / 取消”。选择保存但写入失败时窗口保持打开;选择取消会保留草稿;选择放弃会清除相应草稿。即使尚未等到定时保存草稿,也会检查当前编辑内容。 + +另存为成功后,后续草稿归属于新文件。若保存失败,编辑器继续使用原路径。另存为到其他文件夹时,相对引用的 Markdown 图片和 HTML `img src` 图片会复制到新文档旁的资源文件夹并更新引用;原文件和原资源保留。引用式图片会转换为等价的行内图片,代码示例不改动。找不到图片或无法复制时会提示,并保留当前编辑内容和原路径。 + +保存采用完整写入后替换原文件的方式。每个文件路径保留最近 20 个保存前版本,位于 `%LOCALAPPDATA%\MDHelper\history`。从“文件 → 历史版本”或编辑器工具栏打开,可查看与当前内容的差异,再恢复到编辑区;恢复可撤销,只有再次保存才覆盖磁盘文件。历史版本属于本机,不随文档或配置导出。 + +图片可通过工具栏选择、从文件管理器拖入,或直接粘贴截图。程序自动复制到文档旁的“文档名.assets”文件夹,插入相对路径;相同图片复用资源。移动或分享文档时,请同时携带该资源文件夹。撤销图片插入不会删除已保存的图片资源。 + +点击“表格”可设置行列数、增删当前行列、调整列对齐,并通过“从 Excel 粘贴”转换复制的单元格。第一行为表头。光标位于普通 Markdown 表格中时编辑原表格;引用或列表中的嵌套表格仍请使用源码编辑。应用整个表格后可一次撤销。 + +图形表格最多支持 1000 行(含表头)、100 列。粘贴或编辑超限表格会明确提示,不截断内容;原表格保持不变。更大的表格请拆分,或通过源码编辑。 + +分屏的“同步滚动”按标题、段落和代码块对应位置双向同步,支持自动换行的源码与大图片。取消勾选后两侧独立滚动。同步只在编辑预览中按滚动事件运行,阅读窗口不增加持续扫描。 + +关闭同步滚动后,编辑引起的预览刷新也会保留预览原来的滚动位置。 + 编辑时左侧大纲可点击定位源码标题。预览刷新使用防抖机制,避免每次按键都重新渲染。 ## 9. 样式管理 @@ -203,7 +221,15 @@ MDHelper 读取文档时不会独占文件,外部程序仍可修改文件。 - DOCX - MHTML -PDF 导出前会显示设置窗口,可分别设置上、下、左、右页边距。导出文件固定使用白色纸张背景,自动移除阅读页大纲和进度条,并在正文前生成带真实页码的目录;正文从目录后的新页面开始。 +MHTML 会等待图片、公式和 Mermaid 图表渲染完成,再将页面与样式、图片和本地字体封装到单文件中。导出时显示进度并支持取消;取消或失败不会覆盖已有输出。缺失图片、加载超时或无法封装的远程样式资源会提示失败,请先修复路径或改用本地资源。离线归档用于保存静态显示效果,音视频、外部链接及需要联网的交互内容不属于静态归档范围。 + +PDF 和 Word 共用导出页面设置:A4 / A3 / Letter、纵向或横向、四个方向页边距、目录开关及 1–6 级目录、页眉、页脚和页码。设置会自动记住。页眉或页脚启用时,对应页边距至少为 12 mm,避免遮挡正文。 + +PDF 使用白色纸张背景,按所选层级生成带真实页码的目录;启用目录时正文从新页面开始。Word 使用目录域,打开文件后如未自动生成目录,可右键目录提示文字并选择“更新域”;页码由 Word 的实际分页决定。 + +四种格式均导出当前编辑区内容,包括尚未保存的修改;导出不会代替保存源文件。导出开始后使用固定内容,切换标签不会改变正在导出的文档或图片路径。 + +导出前检查会提示缺失的本地图片/链接、远程图片依赖,以及当前 Word 导出方式对公式、多级列表、Mermaid、内嵌 HTML 和扩展 CSS 的限制。可返回编辑或继续导出核对。Word 和 PDF 的耗时生成阶段提供进度状态及取消;成功后才替换目标文件,失败或取消不会覆盖已有输出。 DOCX 导出可选择 `pandoc` 或 `python-docx` 相关实现。正式安装版已包含 Pandoc,无需用户另行下载或配置 PATH。导出的 HTML 与阅读页一样不包含阅读进度控件。 diff --git a/mdhelper/__init__.py b/mdhelper/__init__.py index 72666a2..fd6ffd5 100644 --- a/mdhelper/__init__.py +++ b/mdhelper/__init__.py @@ -1,3 +1,3 @@ """MDHelper package.""" -__version__ = "0.2.3" +__version__ = "0.3.1" diff --git a/mdhelper/docx_exporter.py b/mdhelper/docx_exporter.py index 71d7c72..f338d33 100644 --- a/mdhelper/docx_exporter.py +++ b/mdhelper/docx_exporter.py @@ -5,6 +5,7 @@ import shutil import subprocess import sys import tempfile +import time import zipfile from dataclasses import dataclass from pathlib import Path @@ -55,18 +56,39 @@ def export_markdown_to_docx( document_font_family: str = "", document_font_size: float = 16, preset: str = "default", + page_settings: object = None, + cancel: object = None, + progress: object = None, ) -> Path: from .docx_style import apply_docx_styles - - if engine == "pandoc": - result = export_markdown_to_docx_pandoc(source, output_path, source_path=source_path) - elif engine == "python-docx": - result = export_markdown_to_docx_python_docx(source, output_path) - else: - result = export_markdown_to_docx_builtin(source, output_path) - apply_docx_styles(result, style_rules, font_family=document_font_family, - font_size_px=document_font_size, preset=preset) - return result + from .export_jobs import check_cancelled + from .file_versions import atomic_write + if output_path.suffix.lower() != ".docx": + output_path = output_path.with_suffix(".docx") + check_cancelled(cancel) + if progress: + progress("正在转换 Word 内容…") + with tempfile.TemporaryDirectory(prefix="mdhelper-export-") as directory: + target = Path(directory) / "document.docx" + if engine == "pandoc": + result = export_markdown_to_docx_pandoc(source, target, source_path=source_path, cancel=cancel) + elif engine == "python-docx": + result = export_markdown_to_docx_python_docx(source, target) + else: + result = export_markdown_to_docx_builtin(source, target) + check_cancelled(cancel) + if progress: + progress("正在应用字体、段落和页面设置…") + apply_docx_styles(result, style_rules, font_family=document_font_family, + font_size_px=document_font_size, preset=preset) + if page_settings is not None: + from .export_settings import apply_docx_page_settings + apply_docx_page_settings(result, page_settings) + check_cancelled(cancel) + data = result.read_bytes() + check_cancelled(cancel) + atomic_write(output_path, data) + return output_path def export_markdown_to_docx_builtin(source: str, output_path: Path) -> Path: @@ -86,7 +108,7 @@ def export_markdown_to_docx_builtin(source: str, output_path: Path) -> Path: return output_path -def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path: Path | None = None) -> Path: +def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path: Path | None = None, cancel: object = None) -> Path: output_path = output_path.resolve() if output_path.suffix.lower() != ".docx": output_path = output_path.with_suffix(".docx") @@ -109,15 +131,31 @@ def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path: if sys.platform == "win32": run_options["creationflags"] = subprocess.CREATE_NO_WINDOW try: - result = subprocess.run( + from .export_jobs import check_cancelled + process = subprocess.Popen( command, cwd=str(resource_directory), - capture_output=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, - timeout=120, - check=False, + encoding="utf-8", errors="replace", **run_options, ) + started = time.monotonic() + try: + while True: + check_cancelled(cancel) + if time.monotonic() - started > 120: + raise subprocess.TimeoutExpired(command, 120) + try: + stdout, stderr = process.communicate(timeout=0.1) + break + except subprocess.TimeoutExpired: + continue + finally: + if process.poll() is None: + process.kill() + process.communicate() except FileNotFoundError as exc: raise DocxExportError("程序内置的 Pandoc 无法启动,当前 MDHelper 安装包可能不完整。") from exc except subprocess.TimeoutExpired as exc: @@ -129,8 +167,8 @@ def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path: except OSError: pass - if result.returncode != 0: - detail = (result.stderr or result.stdout or "pandoc 返回错误。").strip() + if process.returncode != 0: + detail = (stderr or stdout or "pandoc 返回错误。").strip() raise DocxExportError(detail) return output_path diff --git a/mdhelper/editor_assets.py b/mdhelper/editor_assets.py new file mode 100644 index 0000000..cccdf96 --- /dev/null +++ b/mdhelper/editor_assets.py @@ -0,0 +1,171 @@ +from __future__ import annotations + +import hashlib +import re +from html import escape, unescape +from html.parser import HTMLParser +from pathlib import Path +from urllib.parse import quote, unquote, urlsplit, urlunsplit + +from .file_versions import atomic_write + +IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg", ".tif", ".tiff"} + + +def relocate_images(source: str, original: Path, target: Path) -> str: + """Copy relative image resources and patch only parsed image destinations. + + Keep Markdown/code formatting intact. Reference images become inline images + so shared reference definitions used by ordinary links need not be changed. + """ + from markdown_it.rules_inline import image, html_inline + from .markdown_renderer import MarkdownRenderer + + if original.resolve().parent == target.resolve().parent: + return source + replacements: list[tuple[int, int, str]] = [] + copied: dict[str, str] = {} + + def copy_url(url: str) -> str: + if url in copied: + return copied[url] + parts = urlsplit(url) + local = Path(unquote(parts.path)) + if not parts.path or parts.scheme or parts.netloc or local.is_absolute(): + return url + resource = (original.parent / local).resolve() + data = resource.read_bytes() # Abort the save on missing/unreadable resources. + folder = target.parent / (target.stem + ".assets") + destination = folder / (hashlib.sha256(data).hexdigest()[:24] + resource.suffix.lower()) + if not destination.exists(): + atomic_write(destination, data) + relative = quote(destination.relative_to(target.parent).as_posix(), safe="/") + copied[url] = urlunsplit(("", "", relative, parts.query, parts.fragment)) + return copied[url] + + class HtmlImages(HTMLParser): + def __init__(self, raw: str, offset: int): + super().__init__(convert_charrefs=False) + self.document_offset = offset + self.lines = [0] + for match in re.finditer("\n", raw): + self.lines.append(match.end()) + self.feed(raw) + + def handle_starttag(self, tag, attrs): + if tag != "img": + return + raw = self.get_starttag_text() + # Tokenize attributes rather than matching 'src' inside another value. + pattern = r'''([^\s=<>/]+)(?:\s*=\s*("[^"]*"|'[^']*'|[^\s>]+))?''' + for match in re.finditer(pattern, raw[4:]): + if match[1].lower() != "src" or match[2] is None: + continue + value = match[2] + quoted = value[:1] in {"'", '"'} + url = unescape(value[1:-1] if quoted else value) + moved = copy_url(url) + if moved != url: + line, column = self.getpos() + start = self.document_offset + self.lines[line - 1] + column + 4 + match.start(2) + replacements.append((start, start + len(value), '"' + escape(moved, quote=True) + '"')) + + parser = MarkdownRenderer(original.parent).markdown + env = {} + tokens = parser.parse(source, env) + lines = source.splitlines(keepends=True) + offsets = [0] + for line in lines: + offsets.append(offsets[-1] + len(line)) + masked = list(source) + excluded = [] + for token in tokens: + if token.map and token.type in {"fence", "code_block", "math_block", "html_block"}: + start, end = (offsets[n] for n in token.map) + if token.type == "html_block": + HtmlImages(source[start:end], start) + excluded.append((start, end)) + for ref in env.get("references", {}).values(): + excluded.append(tuple(offsets[n] for n in ref["map"])) + for start, end in excluded: + masked[start:end] = ["\n" if char == "\n" else " " for char in source[start:end]] + inline_source = "".join(masked) + + def capture_image(state, silent): + start = state.pos + matched = image(state, silent) + if matched and not silent and state.src is inline_source: + token = state.tokens[-1] + url = token.attrGet("src") or "" + moved = copy_url(url) + if moved != url: + label_end = parser.helpers.parseLinkLabel(state, start + 1, False) + pos = label_end + 1 + if pos < len(source) and source[pos] == "(": + pos += 1 + while source[pos].isspace(): + pos += 1 + destination = parser.helpers.parseLinkDestination(source, pos, len(source)) + replacements.append((pos, destination.pos, moved)) + else: + title = token.attrGet("title") + suffix = ' "' + title.replace("\\", "\\\\").replace('"', '\\"') + '"' if title else "" + replacements.append((start, state.pos, source[start:label_end + 1] + "(" + moved + suffix + ")")) + return matched + + def capture_html(state, silent): + start = state.pos + matched = html_inline(state, silent) + if matched and not silent and state.src is inline_source: + HtmlImages(source[start:state.pos], start) + return matched + + parser.inline.ruler.at("image", capture_image) + parser.inline.ruler.at("html_inline", capture_html) + parser.inline.parse(inline_source, parser, env, []) + pieces = [] + offset = 0 + for start, end, replacement in sorted(replacements): + pieces.extend((source[offset:start], replacement)) + offset = end + pieces.append(source[offset:]) + return "".join(pieces) + + +def store_image(document: Path, data: bytes, suffix: str = ".png", label: str = "图片") -> str: + suffix = suffix.lower() + if suffix not in IMAGE_SUFFIXES or not data: + raise ValueError("不支持的图片或图片内容为空") + folder = document.parent / (document.stem + ".assets") + digest = hashlib.sha256(data).hexdigest()[:24] + target = folder / (digest + suffix) + if not target.exists(): + atomic_write(target, data) + relative = quote(target.relative_to(document.parent).as_posix(), safe="/") + label = label.replace("\\", "\\\\").replace("[", "\\[").replace("]", "\\]").replace("\n", " ") + return f"![{label}]({relative})" + + +def image_files(mime: object) -> list[Path]: + if not mime.hasUrls(): + return [] + urls = mime.urls() + paths = [Path(url.toLocalFile()) for url in urls if url.isLocalFile()] + return paths if len(paths) == len(urls) and all(p.suffix.lower() in IMAGE_SUFFIXES and p.is_file() for p in paths) else [] + + +def image_markdown(mime: object, document: Path) -> str | None: + files = image_files(mime) + if files: + return "\n".join(store_image(document, p.read_bytes(), p.suffix, p.stem) for p in files) + if mime.hasImage(): + from PySide6.QtCore import QBuffer, QByteArray, QIODevice + from PySide6.QtGui import QImage, QPixmap + data = mime.imageData() + picture = data.toImage() if isinstance(data, QPixmap) else QImage(data) + buffer = QBuffer() + buffer.open(QIODevice.OpenModeFlag.WriteOnly) + if picture.isNull() or not picture.save(buffer, "PNG"): + raise ValueError("无法读取剪贴板图片") + return store_image(document, bytes(buffer.data()), label="截图") + return None diff --git a/mdhelper/export_check.py b/mdhelper/export_check.py new file mode 100644 index 0000000..74a94b8 --- /dev/null +++ b/mdhelper/export_check.py @@ -0,0 +1,105 @@ +"""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 diff --git a/mdhelper/export_jobs.py b/mdhelper/export_jobs.py new file mode 100644 index 0000000..4e1c834 --- /dev/null +++ b/mdhelper/export_jobs.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +import threading +from pathlib import Path +from PySide6.QtCore import QObject, QRunnable, Signal + + +class ExportCancelled(Exception): + pass + + +def check_cancelled(cancel: object) -> None: + if cancel is not None and cancel.is_set(): + raise ExportCancelled() + + +class ExportSignals(QObject): + finished = Signal(object, str) + progress = Signal(str) + + +class ExportJob(QRunnable): + def __init__(self, callback: object) -> None: + super().__init__() + self.signals = ExportSignals() + self.cancel = threading.Event() + self.callback = callback + + def run(self) -> None: + try: + result = self.callback(self.cancel, self.signals.progress.emit) + self.signals.finished.emit(result, "") + except ExportCancelled: + self.signals.finished.emit(None, "") + except Exception as exc: + self.signals.finished.emit(None, str(exc)) diff --git a/mdhelper/export_settings.py b/mdhelper/export_settings.py new file mode 100644 index 0000000..45e7918 --- /dev/null +++ b/mdhelper/export_settings.py @@ -0,0 +1,152 @@ +from __future__ import annotations + +from dataclasses import asdict, dataclass, fields + + +PAPER_MM = {"A4": (210.0, 297.0), "A3": (297.0, 420.0), "Letter": (215.9, 279.4)} + + +@dataclass(frozen=True) +class PageSettings: + paper: str = "A4" + landscape: bool = False + top: float = 15.0 + bottom: float = 15.0 + left: float = 15.0 + right: float = 15.0 + include_toc: bool = True + toc_depth: int = 3 + header: str = "" + footer: str = "" + page_numbers: bool = True + + @classmethod + def from_dict(cls, data: dict) -> "PageSettings": + known = {field.name for field in fields(cls)} + clean = {key: value for key, value in data.items() if key in known} + defaults = cls() + for name in ("landscape", "include_toc", "page_numbers"): + clean[name] = clean.get(name, getattr(defaults, name)) in (True, 1, "true") + for name in ("top", "bottom", "left", "right"): + try: + clean[name] = max(0.0, min(50.0, float(clean.get(name, 15)))) + except (ValueError, TypeError): + clean[name] = 15.0 + clean["paper"] = clean.get("paper") if clean.get("paper") in PAPER_MM else "A4" + try: + clean["toc_depth"] = max(1, min(6, int(clean.get("toc_depth", 3)))) + except (ValueError, TypeError): + clean["toc_depth"] = 3 + for name in ("header", "footer"): + clean[name] = str(clean.get(name, "")).replace("\n", " ")[:100] + return cls(**clean) + + def normalized(self) -> "PageSettings": + result = asdict(self) + if self.header: + result["top"] = max(12.0, self.top) + if self.footer or self.page_numbers: + result["bottom"] = max(12.0, self.bottom) + return self.from_dict(result) + + def size_mm(self) -> tuple[float, float]: + width, height = PAPER_MM.get(self.paper, PAPER_MM["A4"]) + return (height, width) if self.landscape else (width, height) + + +def apply_docx_page_settings(path: object, settings: PageSettings) -> None: + from docx import Document + from docx.enum.text import WD_BREAK, WD_ALIGN_PARAGRAPH + from docx.enum.section import WD_ORIENT + from docx.oxml import OxmlElement + from docx.oxml.ns import qn + from docx.shared import Mm, Pt + settings = settings.normalized() + document = Document(str(path)) + width, height = settings.size_mm() + for section in document.sections: + section.orientation = WD_ORIENT.LANDSCAPE if settings.landscape else WD_ORIENT.PORTRAIT + section.page_width, section.page_height = Mm(width), Mm(height) + for name in ("top", "bottom", "left", "right"): + setattr(section, name + "_margin", Mm(getattr(settings, name))) + section.header_distance = Mm(5) + section.footer_distance = Mm(5) + for container, text in ((section.header, settings.header), (section.footer, settings.footer)): + paragraph = container.paragraphs[0] + paragraph.clear() + paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER + run = paragraph.add_run(text) + run.font.size = Pt(9) + if settings.page_numbers: + paragraph = section.footer.paragraphs[0] + paragraph.add_run(" " if settings.footer else "") + paragraph.add_run("第 ") + for instruction, following in [("PAGE", " 页 / 共 "), ("NUMPAGES", " 页")]: + field = OxmlElement("w:fldSimple") + field.set(qn("w:instr"), instruction) + paragraph._p.append(field) + paragraph.add_run(following) + available_width = Mm(width - settings.left - settings.right) + available_height = Mm(height - settings.top - settings.bottom - 5) + for shape in document.inline_shapes: + if shape.width and shape.height: + scale = min(1.0, available_width / shape.width, available_height / shape.height) + if scale < 1: + shape.width = round(shape.width * scale) + shape.height = round(shape.height * scale) + if settings.include_toc: + # Word calculates page numbers using its own layout engine when fields update. + body = document.element.body + heading = OxmlElement("w:p") + r = OxmlElement("w:r"); t = OxmlElement("w:t"); t.text = "目录"; r.append(t); heading.append(r) + body.insert(0, heading) + paragraph = OxmlElement("w:p") + field = OxmlElement("w:fldSimple") + field.set(qn("w:instr"), f'TOC \\o "1-{settings.toc_depth}" \\h \\z \\u') + field.set(qn("w:dirty"), "true") + run = OxmlElement("w:r"); text = OxmlElement("w:t") + text.text = "请在 Word 中右键此处,选择“更新域”生成目录和页码。" + run.append(text); field.append(run); paragraph.append(field); body.insert(1, paragraph) + page_break = OxmlElement("w:p"); run = OxmlElement("w:r"); br = OxmlElement("w:br") + br.set(qn("w:type"), "page"); run.append(br); page_break.append(run); body.insert(2, page_break) + update = document.settings.element.find(qn("w:updateFields")) + if update is None: + update = OxmlElement("w:updateFields"); document.settings.element.append(update) + update.set(qn("w:val"), "true") + document.save(str(path)) + + +def decorate_pdf(data: bytes, settings: PageSettings, cancel: object = None) -> bytes: + if not (settings.header or settings.footer or settings.page_numbers): + return data + from io import BytesIO + from pypdf import PdfReader, PdfWriter + from PySide6.QtCore import QBuffer, QIODevice, QMarginsF, QRectF, QSizeF, Qt + from PySide6.QtGui import QColor, QFont, QPageLayout, QPageSize, QPainter, QPdfWriter + from .export_jobs import check_cancelled + reader, writer = PdfReader(BytesIO(data)), PdfWriter() + writer.clone_document_from_reader(reader) + for index, page in enumerate(writer.pages): + check_cancelled(cancel) + width, height = float(page.mediabox.width), float(page.mediabox.height) + buffer = QBuffer(); buffer.open(QIODevice.OpenModeFlag.ReadWrite) + pdf = QPdfWriter(buffer); pdf.setResolution(72) + pdf.setPageLayout(QPageLayout(QPageSize(QSizeF(width, height), QPageSize.Unit.Point), + QPageLayout.Orientation.Portrait, QMarginsF(0, 0, 0, 0))) + painter = QPainter(pdf); painter.setPen(QColor("#333333")); painter.setFont(QFont("Microsoft YaHei", 9)) + left = settings.left * 72 / 25.4 + right = width - settings.right * 72 / 25.4 + header_box = QRectF(left, 4 * 72 / 25.4, right - left, 16) + footer_box = QRectF(left, height - 10 * 72 / 25.4, right - left, 16) + painter.drawText(header_box, Qt.AlignmentFlag.AlignCenter, settings.header) + if settings.page_numbers: + painter.drawText(footer_box, Qt.AlignmentFlag.AlignRight, f"第 {index + 1} 页 / 共 {len(writer.pages)} 页") + footer_box.setWidth(max(1, footer_box.width() - 150)) + painter.drawText(footer_box, Qt.AlignmentFlag.AlignLeft if settings.page_numbers else Qt.AlignmentFlag.AlignCenter, settings.footer) + painter.end() + del painter + del pdf + page.merge_page(PdfReader(BytesIO(bytes(buffer.data()))).pages[0]) + check_cancelled(cancel) + output = BytesIO(); writer.write(output) + return output.getvalue() diff --git a/mdhelper/export_workflow.py b/mdhelper/export_workflow.py new file mode 100644 index 0000000..75fe92e --- /dev/null +++ b/mdhelper/export_workflow.py @@ -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() diff --git a/mdhelper/file_versions.py b/mdhelper/file_versions.py new file mode 100644 index 0000000..8fc9a40 --- /dev/null +++ b/mdhelper/file_versions.py @@ -0,0 +1,108 @@ +"""Atomic writes and bounded, per-document local version history.""" +from __future__ import annotations + +import hashlib +import os +import tempfile +import time +import uuid +from pathlib import Path + + +def atomic_write(path: Path, data: bytes) -> None: + path = path.resolve() + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent) + try: + with os.fdopen(descriptor, "wb") as stream: + stream.write(data) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + finally: + Path(temporary).unlink(missing_ok=True) + + +class VersionStore: + def __init__(self, root: Path | None = None, limit: int = 20) -> None: + base = Path(os.environ.get("LOCALAPPDATA", str(Path.home() / ".local" / "share"))) + self.root = root or Path(os.environ.get("MDHELPER_HISTORY_DIR", str(base / "MDHelper" / "history"))) + self.limit = max(1, limit) + + def directory(self, path: Path) -> Path: + key = hashlib.sha256(os.path.normcase(str(path.resolve())).encode("utf-8")).hexdigest() + return self.root / key + + def versions(self, path: Path) -> list[Path]: + return sorted(self.directory(path).glob("*.md"), reverse=True) + + def save(self, path: Path, source: str) -> None: + data = source.encode("utf-8") + previous = path.read_bytes() if path.exists() else None + if previous == data: + return + if previous is not None: + versions = self.versions(path) + if not versions or versions[0].read_bytes() != previous: + name = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000_000:09d}-{uuid.uuid4().hex[:6]}.md" + atomic_write(self.directory(path) / name, previous) + # A failed replacement leaves the original file and its history intact. + atomic_write(path, data) + for expired in self.versions(path)[self.limit:]: + try: + expired.unlink() + except OSError: + pass # History housekeeping must not turn a successful save into a failure. + + +def show_version_history(parent: object, path: Path, current: str) -> str | None: + import difflib + from PySide6.QtWidgets import (QDialog, QDialogButtonBox, QHBoxLayout, QLabel, + QListWidget, QPlainTextEdit, QSplitter, QVBoxLayout) + from PySide6.QtCore import Qt + + versions = VersionStore().versions(path) + dialog = QDialog(parent) + dialog.setWindowTitle(f"历史版本 — {path.name}") + dialog.resize(1000, 650) + layout = QVBoxLayout(dialog) + layout.addWidget(QLabel("保留最近 20 个保存前版本。恢复只替换编辑区内容,可撤销;按保存后才写入原文件。")) + splitter = QSplitter(Qt.Orientation.Horizontal) + listing = QListWidget() + preview = QPlainTextEdit() + preview.setReadOnly(True) + splitter.addWidget(listing) + splitter.addWidget(preview) + splitter.setSizes([240, 760]) + layout.addWidget(splitter) + buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel) + restore = buttons.addButton("恢复到编辑区", QDialogButtonBox.ButtonRole.AcceptRole) + restore.setEnabled(False) + buttons.accepted.connect(dialog.accept) + buttons.rejected.connect(dialog.reject) + layout.addWidget(buttons) + contents: dict[int, str] = {} + for version in versions: + stamp = version.name[:15] + listing.addItem(f"{stamp[:4]}-{stamp[4:6]}-{stamp[6:8]} {stamp[9:11]}:{stamp[11:13]}:{stamp[13:15]}") + + def selected(row: int) -> None: + restore.setEnabled(False) + if row < 0: + return + try: + source = versions[row].read_text(encoding="utf-8-sig") + contents[row] = source + diff = "\n".join(difflib.unified_diff(current.splitlines(), source.splitlines(), + fromfile="当前编辑内容", tofile="选中的历史版本", lineterm="")) + preview.setPlainText(diff or "此版本与当前编辑内容相同。") + restore.setEnabled(True) + except (OSError, UnicodeError) as exc: + preview.setPlainText(f"无法读取此版本:{exc}") + + listing.currentRowChanged.connect(selected) + if versions: + listing.setCurrentRow(0) + else: + preview.setPlainText("暂无历史版本。文件内容改变并保存后,会自动保留保存前的内容。") + return contents.get(listing.currentRow()) if dialog.exec() == QDialog.DialogCode.Accepted else None diff --git a/mdhelper/main_window.py b/mdhelper/main_window.py index 8d0fdf4..847002b 100644 --- a/mdhelper/main_window.py +++ b/mdhelper/main_window.py @@ -98,6 +98,7 @@ 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 BOOKMARKS_SETTING_KEY = "bookmarks/items" @@ -536,7 +537,7 @@ class CompactTreeDelegate(QStyledItemDelegate): return size -class MainWindow(QMainWindow): +class MainWindow(ExportWorkflow, QMainWindow): def __init__( self, project_root: Path | None, @@ -785,6 +786,10 @@ class MainWindow(QMainWindow): self.close_folder_action.triggered.connect(self.close_project_folder) file_menu.addAction(self.close_folder_action) + self.version_history_action = QAction("历史版本", self) + self.version_history_action.triggered.connect(self.show_document_history) + file_menu.addAction(self.version_history_action) + self.export_pdf_action = QAction("导出 PDF", self) self.export_pdf_action.setShortcut("Ctrl+P") self.export_pdf_action.triggered.connect(self.export_current_pdf) @@ -2817,10 +2822,10 @@ class MainWindow(QMainWindow): math_engine=self.math_engine, original_source=disk_source, file_signature=self._file_signature(path), - draft_callback=lambda draft_source, file_path=path: self._save_editor_draft(file_path, draft_source), embedded=True, parent=self, ) + editor.draft_callback = lambda source: self._save_editor_draft(editor.path, source) editor.setProperty("current_file", str(path)) editor.setProperty("original_path", str(path)) editor.editor.textChanged.connect(lambda widget=editor: self._on_editor_content_changed(widget)) @@ -2845,21 +2850,41 @@ class MainWindow(QMainWindow): if self.tabs.currentWidget() is editor: self._populate_toc_from_text(editor.source_text()) + def show_document_history(self) -> None: + widget = self.tabs.currentWidget() + if not isinstance(widget, RichMarkdownEditorDialog): + self.edit_current_markdown() + widget = self.tabs.currentWidget() + if isinstance(widget, RichMarkdownEditorDialog): + widget.show_history() + def _save_editor_tab( self, editor: RichMarkdownEditorDialog, target_path: Path, source: str, expected_signature: tuple[int, int] | None, - ) -> None: + ) -> bool: original_path_value = editor.property("original_path") original_path = Path(str(original_path_value)).resolve() if original_path_value else editor.path.resolve() target_path = target_path.resolve() - if target_path == original_path and source == self._read_markdown_source(original_path): + try: + unchanged = target_path == original_path and source == self._read_markdown_source(original_path) + except (OSError, UnicodeError): + unchanged = False + if unchanged: self._clear_editor_draft(original_path) editor.mark_saved(target_path, source, self._file_signature(target_path)) self.status_label.setText("编辑内容未变化") - return + return True + + if target_path.parent != original_path.parent: + try: + from .editor_assets import relocate_images + source = relocate_images(source, original_path, target_path) + except (OSError, ValueError) as exc: + QMessageBox.warning(self, "保存失败", f"无法复制文档图片:\n{exc}") + return False ok = self.save_markdown_source( target_path, @@ -2869,16 +2894,17 @@ class MainWindow(QMainWindow): reload_current=False, ) if not ok: - return + return False editor.setProperty("current_file", str(target_path)) editor.setProperty("original_path", str(target_path)) editor.mark_saved(target_path, source, self._file_signature(target_path)) self._update_tab_title(editor, editor.windowTitle()) - self.current_file = target_path if self.tabs.currentWidget() is editor: + self.current_file = target_path self._populate_toc_from_text(editor.source_text()) self.status_label.setText(f"已保存:{self._display_path(target_path)}") + return True def _close_editor_tab(self, editor: RichMarkdownEditorDialog) -> None: index = self.tabs.indexOf(editor) @@ -2968,7 +2994,8 @@ class MainWindow(QMainWindow): self.internal_save_paths.add(path) try: - path.write_text(source, encoding="utf-8", newline="") + from .file_versions import VersionStore + VersionStore().save(path, source) except OSError as exc: self.internal_save_paths.discard(path) LOGGER.exception("Failed to save Markdown source: %s", path) @@ -3382,320 +3409,6 @@ class MainWindow(QMainWindow): self._confirm_open_with_local_app_now(path) - def export_current_pdf(self) -> None: - if self.current_file is None: - return - settings_dialog = PdfExportSettingsDialog(self._saved_pdf_margins(), self) - if settings_dialog.exec() != QDialog.DialogCode.Accepted: - return - margins = settings_dialog.margins() - - default_name = self.current_file.with_suffix(".pdf").name - file_name, _ = QFileDialog.getSaveFileName( - self, - "导出当前文档为 PDF", - str(self.project_root / default_name), - "PDF Files (*.pdf)", - ) - if not file_name: - return - - self._save_pdf_margins(margins) - output_path = self.export_pdf_to_path(Path(file_name), margins) - if output_path is None: - return - LOGGER.info("Exporting PDF: %s", output_path) - self.status_label.setText(f"正在导出 PDF:{output_path}") - - def export_pdf_to_path(self, output_path: Path, margins: PdfMargins | None = None) -> Path | None: - if self.current_file is None: - return None - if getattr(self, "_pdf_export_page", None) is not None: - QMessageBox.information(self, "正在导出", "已有一个 PDF 导出任务正在进行,请稍候。") - return None - if output_path.suffix.lower() != ".pdf": - output_path = output_path.with_suffix(".pdf") - - selected_margins = margins or self._saved_pdf_margins() - if self.current_file.suffix.lower() in {".md", ".markdown"} or is_code_document(self.current_file): - try: - content = self._render_document_file(self.current_file) - headings = self._pdf_headings(self.current_file) - except (OSError, UnicodeDecodeError) as exc: - LOGGER.exception("Failed to render PDF export: %s", self.current_file) - QMessageBox.warning(self, "导出失败", f"无法渲染当前文档:\n{self.current_file}\n\n{exc}") - return None - self._begin_pdf_export(output_path, content, headings, selected_margins) - else: - self.web_view.page().toHtml( - lambda content, target=output_path, selected=selected_margins: self._begin_pdf_export( - target, - content, - [], - selected, - ) - ) - return output_path - - def _saved_pdf_margins(self) -> PdfMargins: - def setting(name: str) -> float: - try: - return max(0.0, min(50.0, float(self.settings.value(f"pdf/{name}_margin_mm", 15.0)))) - except (TypeError, ValueError): - return 15.0 - - return PdfMargins( - top=setting("top"), - bottom=setting("bottom"), - left=setting("left"), - right=setting("right"), - ) - - def _save_pdf_margins(self, margins: PdfMargins) -> None: - self.settings.setValue("pdf/top_margin_mm", margins.top) - self.settings.setValue("pdf/bottom_margin_mm", margins.bottom) - self.settings.setValue("pdf/left_margin_mm", margins.left) - self.settings.setValue("pdf/right_margin_mm", margins.right) - - def _pdf_headings(self, path: Path) -> list[Heading]: - if is_code_document(path): - return extract_code_headings(path, self._read_text_preview(path)) - return extract_headings(path) - - def _begin_pdf_export( - self, - output_path: Path, - content: str, - headings: list[Heading], - margins: PdfMargins, - ) -> None: - printable_headings = [heading for heading in headings if heading.level <= 3] - self._pdf_export_output_path = output_path - self._pdf_export_base_html = content - self._pdf_export_headings = printable_headings - self._pdf_export_layout = build_pdf_page_layout(margins) - self._pdf_export_stage = "probe" - - page = QWebEnginePage(self) - self._pdf_export_page = page - self._configure_web_settings(page.settings()) - page.loadFinished.connect(self._on_pdf_export_page_loaded) - page.pdfPrintingFinished.connect(self._on_dedicated_pdf_printing_finished) - base_path = str(self.current_file.parent.resolve()) + os.sep if self.current_file is not None else str(self.project_root) + os.sep - self._pdf_export_base_url = QUrl.fromLocalFile(base_path) - page.setHtml( - build_pdf_export_html(content, printable_headings), - self._pdf_export_base_url, - ) - self.status_label.setText(f"正在生成 PDF 目录页码:{output_path}") - - def _on_pdf_export_page_loaded(self, ok: bool) -> None: - if not ok: - self._fail_pdf_export("PDF 导出页面加载失败。") - return - stage = getattr(self, "_pdf_export_stage", "") - QTimer.singleShot(800, lambda expected=stage: self._print_pdf_export_stage(expected)) - - def _print_pdf_export_stage(self, expected_stage: str) -> None: - page = getattr(self, "_pdf_export_page", None) - if page is None or expected_stage != getattr(self, "_pdf_export_stage", ""): - return - if expected_stage == "probe": - page.printToPdf(self._on_pdf_probe_ready, self._pdf_export_layout) - elif expected_stage == "final": - page.printToPdf(str(self._pdf_export_output_path), self._pdf_export_layout) - - def _on_pdf_probe_ready(self, pdf_data: object) -> None: - page = getattr(self, "_pdf_export_page", None) - if page is None or getattr(self, "_pdf_export_stage", "") != "probe": - return - raw_pdf = bytes(pdf_data) - if not raw_pdf: - self._fail_pdf_export("无法生成 PDF 页码预览。") - return - try: - page_numbers = extract_heading_page_numbers(raw_pdf, len(self._pdf_export_headings)) - except Exception as exc: - LOGGER.exception("Failed to extract PDF heading pages") - self._fail_pdf_export(str(exc)) - return - - self._pdf_export_stage = "final" - page.setHtml( - build_pdf_export_html( - self._pdf_export_base_html, - self._pdf_export_headings, - page_numbers, - include_page_markers=False, - ), - self._pdf_export_base_url, - ) - self.status_label.setText(f"正在导出 PDF:{self._pdf_export_output_path}") - - def _on_dedicated_pdf_printing_finished(self, file_path: str, success: bool) -> None: - self._on_pdf_printing_finished(file_path, success) - self._cleanup_pdf_export() - - def _fail_pdf_export(self, message: str) -> None: - output_path = getattr(self, "_pdf_export_output_path", Path("")) - LOGGER.error("PDF export failed: %s (%s)", output_path, message) - QMessageBox.warning(self, "导出失败", f"无法导出 PDF:\n{output_path}\n\n{message}") - self._cleanup_pdf_export() - - def _cleanup_pdf_export(self) -> None: - page = getattr(self, "_pdf_export_page", None) - if page is not None: - page.deleteLater() - self._pdf_export_page = None - self._pdf_export_stage = "" - - def export_current_html(self) -> None: - if self.current_file is None: - return - - default_name = self.current_file.with_suffix(".html").name - file_name, _ = QFileDialog.getSaveFileName( - self, - "导出当前文档为 HTML", - str(self.project_root / default_name), - "HTML Files (*.html *.htm)", - ) - if not file_name: - return - - output_path = Path(file_name) - if output_path.suffix.lower() not in {".html", ".htm"}: - output_path = output_path.with_suffix(".html") - - if self.current_file.suffix.lower() in {".md", ".markdown"} or is_code_document(self.current_file): - try: - content = self._render_document_file(self.current_file) - except (OSError, UnicodeDecodeError) as exc: - LOGGER.exception("Failed to render HTML export: %s", self.current_file) - QMessageBox.warning(self, "导出失败", f"无法渲染当前文档:\n{self.current_file}\n\n{exc}") - return - self._write_exported_html(output_path, content) - return - - self.status_label.setText(f"正在导出 HTML:{output_path}") - self.web_view.page().toHtml(lambda content, target=output_path: self._write_exported_html(target, content)) - - def _write_exported_html(self, output_path: Path, content: str) -> None: - try: - output_path.write_text(content, encoding="utf-8") - except OSError as exc: - LOGGER.exception("Failed to export HTML: %s", output_path) - QMessageBox.warning(self, "导出失败", f"无法写入 HTML 文件:\n{output_path}\n\n{exc}") - return - - LOGGER.info("HTML exported: %s", output_path) - self.status_label.setText(f"HTML 已导出:{output_path}") - - def export_current_docx(self) -> None: - if self.current_file is None: - return - labels = list(DOCX_EXPORT_ENGINES.values()) - label_to_engine = {label: engine for engine, label in DOCX_EXPORT_ENGINES.items()} - selected_label, accepted = QInputDialog.getItem( - self, - "选择 DOCX 导出方式", - "导出方式", - labels, - 0, - False, - ) - if not accepted: - return - engine = label_to_engine.get(selected_label, "pandoc") - default_name = self.current_file.with_suffix(".docx").name - file_name, _ = QFileDialog.getSaveFileName( - self, - "导出当前文档为 DOCX", - str(self.project_root / default_name), - "Word Documents (*.docx)", - ) - if not file_name: - return - self.export_docx_to_path(Path(file_name), engine=engine) - - def export_docx_to_path(self, output_path: Path, engine: str = "builtin") -> Path | None: - if self.current_file is None: - return None - if self.current_file.suffix.lower() not in {".md", ".markdown"}: - QMessageBox.warning(self, "导出失败", "DOCX 导出当前仅支持 Markdown 文档。") - return None - if output_path.suffix.lower() != ".docx": - output_path = output_path.with_suffix(".docx") - try: - source = self.current_file.read_text(encoding="utf-8") - style = self.custom_document_styles.get(self.document_style_id, {}) - export_markdown_to_docx( - source, output_path, engine=engine, source_path=self.current_file, - style_rules=style.get("rules", {}), - document_font_family=self.document_font_family, - document_font_size=self.document_font_size, - preset=self.document_style_id, - ) - except (OSError, zipfile.BadZipFile, DocxExportError) as exc: - LOGGER.exception("Failed to export DOCX: %s", output_path) - QMessageBox.warning(self, "导出失败", f"无法写入 DOCX 文件:\n{output_path}\n\n{exc}") - return None - - engine_label = DOCX_EXPORT_ENGINES.get(engine, DOCX_EXPORT_ENGINES["builtin"]) - LOGGER.info("DOCX exported via %s: %s", engine, output_path) - self.status_label.setText(f"DOCX 已导出({engine_label}):{output_path}") - return output_path - - def export_current_mhtml(self) -> None: - if self.current_file is None: - return - default_name = self.current_file.with_suffix(".mhtml").name - file_name, _ = QFileDialog.getSaveFileName( - self, - "导出当前页面为 MHTML", - str(self.project_root / default_name), - "MHTML Files (*.mhtml *.mht)", - ) - if not file_name: - return - self.export_mhtml_to_path(Path(file_name)) - - def export_mhtml_to_path(self, output_path: Path) -> Path | None: - if self.current_file is None: - return None - if output_path.suffix.lower() not in {".mhtml", ".mht"}: - output_path = output_path.with_suffix(".mhtml") - if self.current_file.suffix.lower() in {".md", ".markdown"} or is_code_document(self.current_file): - try: - content = self._render_document_file(self.current_file) - except (OSError, UnicodeDecodeError) as exc: - LOGGER.exception("Failed to render MHTML export: %s", self.current_file) - QMessageBox.warning(self, "导出失败", f"无法渲染当前文档:\n{self.current_file}\n\n{exc}") - return None - self._write_exported_mhtml(output_path, content) - else: - self.web_view.page().toHtml(lambda content, target=output_path: self._write_exported_mhtml(target, content)) - LOGGER.info("Exporting MHTML: %s", output_path) - self.status_label.setText(f"正在导出 MHTML:{output_path}") - return output_path - - def _write_exported_mhtml(self, output_path: Path, content: str) -> None: - if output_path.suffix.lower() not in {".mhtml", ".mht"}: - output_path = output_path.with_suffix(".mhtml") - output_path.parent.mkdir(parents=True, exist_ok=True) - message = MIMEMultipart("related", type="text/html") - message["Subject"] = self.current_file.name if self.current_file is not None else output_path.stem - message["MIME-Version"] = "1.0" - message.attach(MIMEText(content, "html", "utf-8")) - try: - output_path.write_text(message.as_string(policy=email_default_policy), encoding="utf-8") - except OSError as exc: - LOGGER.exception("Failed to export MHTML: %s", output_path) - QMessageBox.warning(self, "导出失败", f"无法写入 MHTML 文件:\n{output_path}\n\n{exc}") - return - LOGGER.info("MHTML exported: %s", output_path) - self.status_label.setText(f"MHTML 已导出:{output_path}") - def export_configuration(self) -> None: default_path = self.project_root / "mdhelper_config.json" file_name, _ = QFileDialog.getSaveFileName( @@ -3978,7 +3691,7 @@ class MainWindow(QMainWindow): return False return True - def _render_document_file(self, path: Path) -> str: + 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), @@ -3994,7 +3707,8 @@ class MainWindow(QMainWindow): math_engine=self.math_engine, ) - return self.renderer.render_file( + 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, @@ -4875,8 +4589,7 @@ class MainWindow(QMainWindow): self.status_label.setText(f"Markdown 文件树显示:{label}") def _filter_tree(self, query: str) -> None: - visible_paths = {entry.path for entry in self.entries if self.search_index.matches_entry(entry, query)} - matches = self.search_index.search(query) + visible_paths, matches = self.search_index.filter(query) self.search_results.clear() def apply_visibility(item: QTreeWidgetItem) -> bool: @@ -5643,6 +5356,14 @@ class MainWindow(QMainWindow): self._update_watched_paths() def closeEvent(self, event: QCloseEvent) -> None: + 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._startup_generation += 1 self._startup_scan_pending = False standby_host = self._standby_reader_host @@ -5658,6 +5379,38 @@ class MainWindow(QMainWindow): self._save_preferences() super().closeEvent(event) + def _confirm_window_close(self) -> bool: + editors = [self.tabs.widget(i) for i in range(self.tabs.count()) + if isinstance(self.tabs.widget(i), RichMarkdownEditorDialog)] + dirty = [editor for editor in editors if editor.has_unsaved_changes()] + # Persist the live text before opening a modal prompt, including background tabs. + for editor in dirty: + editor._auto_save_draft() + for editor in editors: + if editor not in dirty: + self._clear_editor_draft(editor.path) + self.settings.sync() + if dirty: + names = "\n".join(editor.path.name for editor in dirty) + choice = QMessageBox.question( + self, "保存修改后退出?", f"以下文档有未保存的修改:\n\n{names}", + QMessageBox.StandardButton.Save | QMessageBox.StandardButton.Discard | QMessageBox.StandardButton.Cancel, + QMessageBox.StandardButton.Save, + ) + if choice == QMessageBox.StandardButton.Save: + for editor in dirty: + if not self._save_editor_tab(editor, editor.path, editor.source_text(), editor.file_signature): + return False + elif choice == QMessageBox.StandardButton.Discard: + for editor in dirty: + self._clear_editor_draft(editor.path) + else: + return False + for editor in editors: + editor.draft_save_timer.stop() + editor.preview_refresh_timer.stop() + return True + def showEvent(self, event: QShowEvent) -> None: super().showEvent(event) QTimer.singleShot(0, self._apply_navigation_style) diff --git a/mdhelper/markdown_editor.py b/mdhelper/markdown_editor.py index 91d1ee7..652592c 100644 --- a/mdhelper/markdown_editor.py +++ b/mdhelper/markdown_editor.py @@ -6,7 +6,8 @@ import re from pathlib import Path from typing import Callable -from PySide6.QtCore import QRect, QSize, QTimer, QUrl, Qt, Signal +from PySide6.QtCore import QObject, QRect, QSize, QSignalBlocker, QTimer, QUrl, Qt, Signal, Slot +from PySide6.QtWebChannel import QWebChannel from PySide6.QtGui import ( QAction, QColor, @@ -69,6 +70,7 @@ class LineNumberArea(QWidget): class MarkdownSourceEditor(QPlainTextEdit): def __init__(self, parent: QWidget | None = None) -> None: super().__init__(parent) + self.image_handler = None self.line_number_background = QColor("#f3f5f8") self.line_number_foreground = QColor("#7a8494") self.current_line_background = QColor("#edf4ff") @@ -79,6 +81,15 @@ class MarkdownSourceEditor(QPlainTextEdit): self.update_line_number_area_width(0) self.highlight_current_line() + def canInsertFromMimeData(self, source: object) -> bool: + from .editor_assets import image_files + return bool(source.hasImage() or image_files(source)) or super().canInsertFromMimeData(source) + + def insertFromMimeData(self, source: object) -> None: + if callable(self.image_handler) and self.image_handler(source): + return + super().insertFromMimeData(source) + def apply_theme(self, dark: bool) -> None: if dark: self.line_number_background = QColor("#22272e") @@ -233,6 +244,12 @@ class MarkdownSyntaxHighlighter(QSyntaxHighlighter): +class PreviewScrollBridge(QObject): + @Slot(float) + def sourceLine(self, line: float) -> None: + self.parent()._sync_source_to_preview_line(line) + + class MarkdownEditorDialog(QDialog): save_requested = Signal(object, str, object) close_requested = Signal() @@ -306,6 +323,9 @@ class MarkdownEditorDialog(QDialog): self.view_mode_box.setCurrentIndex(2 if embedded else 0) self.view_mode_box.currentIndexChanged.connect(self._apply_view_mode) control_layout.addWidget(self.view_mode_box) + self.sync_scroll_checkbox = QCheckBox("同步滚动") + self.sync_scroll_checkbox.setChecked(True) + control_layout.addWidget(self.sync_scroll_checkbox) self.editor_find_box = QLineEdit() self.editor_find_box.setPlaceholderText("查找源码") @@ -348,6 +368,7 @@ class MarkdownEditorDialog(QDialog): self.splitter = QSplitter(Qt.Orientation.Horizontal) self.editor = MarkdownSourceEditor() + self.editor.image_handler = self._insert_image_mime self.editor.setPlainText(source) self.editor.setLineWrapMode(QPlainTextEdit.LineWrapMode.WidgetWidth) editor_font = QFont("Consolas") @@ -361,9 +382,17 @@ class MarkdownEditorDialog(QDialog): ) self.editor.textChanged.connect(self._on_editor_text_changed) self.editor.verticalScrollBar().valueChanged.connect(self._sync_preview_to_editor_scroll) + self.scroll_sync_timer = QTimer(self) + self.scroll_sync_timer.setSingleShot(True) + self.scroll_sync_timer.setInterval(40) + self.scroll_sync_timer.timeout.connect(self._sync_preview_to_source_line) self.splitter.addWidget(self.editor) self.preview = QWebEngineView() + self.preview_channel = QWebChannel(self.preview.page()) + self.preview_bridge = PreviewScrollBridge(self) + self.preview_channel.registerObject("mdhelperEditor", self.preview_bridge) + self.preview.page().setWebChannel(self.preview_channel) self.preview.loadFinished.connect(self._restore_preview_scroll) self._configure_preview_settings(self.preview.settings()) self.splitter.addWidget(self.preview) @@ -424,6 +453,9 @@ class MarkdownEditorDialog(QDialog): if dark: self.setStyleSheet( "QDialog { background: #1f242b; color: #dbe2ea; }" + "QLabel, QCheckBox, QToolButton { color: #dbe2ea; }" + "QTableWidget, QListWidget, QPlainTextEdit { background: #15191f; color: #dbe2ea; gridline-color: #444c56; }" + "QHeaderView::section { background: #2d333b; color: #dbe2ea; border: 1px solid #444c56; }" "QLineEdit, QComboBox { background: #15191f; color: #dbe2ea; border: 1px solid #3a4553; padding: 4px; }" "QToolBar { background: #22272e; border: 1px solid #3a4553; }" "QPushButton { background: #2d333b; color: #dbe2ea; border: 1px solid #444c56; padding: 4px 8px; }" @@ -482,9 +514,7 @@ class MarkdownEditorDialog(QDialog): ("B", "**{selection}**"), ("I", "*{selection}*"), ("代码", "```\n{selection}\n```"), - ("表格", "| 列1 | 列2 |\n| --- | --- |\n| 内容 | 内容 |"), ("链接", "[{selection}](target.md)"), - ("图片", "![{selection}](media/screenshot.png)"), ("提示", "> [!NOTE]\n> {selection}"), ("Mermaid", "```mermaid\ngraph TD\n A --> B\n```"), ("公式", "$${selection}$$"), @@ -494,6 +524,13 @@ class MarkdownEditorDialog(QDialog): action.triggered.connect(lambda checked=False, item=template: self.insert_template(item)) self.insert_toolbar.addAction(action) + for label, callback in [("表格", self._edit_table), ("图片", self._choose_images), + ("历史版本", self.show_history)]: + action = QAction(label, self) + action.triggered.connect(callback) + anchor = next(item for item in self.insert_toolbar.actions() if item.text() == "Mermaid") + self.insert_toolbar.insertAction(anchor, action) + self.convert_latex_formula_action = QAction("转换latex公式到md", self) self.convert_latex_formula_action.setToolTip("将文档中的 \\[ 和 \\] 转换为 $$") self.convert_latex_formula_action.triggered.connect(self.convert_latex_formulas_to_markdown) @@ -649,7 +686,7 @@ class MarkdownEditorDialog(QDialog): pattern = re.escape(query) if self.whole_word_checkbox.isChecked(): pattern = r"\b" + pattern + r"\b" - self._match_positions = [match.start() for match in re.finditer(pattern, text, flags)] + self._match_positions = [start for start, _ in self._qt_match_spans(text, re.finditer(pattern, text, flags))] cursor_pos = self.editor.textCursor().selectionStart() for index, position in enumerate(self._match_positions): if position >= cursor_pos: @@ -667,7 +704,7 @@ class MarkdownEditorDialog(QDialog): query = self.editor_find_box.text() cursor = self.editor.textCursor() cursor.setPosition(self._match_positions[self._current_match_index]) - cursor.setPosition(cursor.position() + len(query), QTextCursor.MoveMode.KeepAnchor) + cursor.setPosition(cursor.position() + self._qt_position(query, len(query)), QTextCursor.MoveMode.KeepAnchor) self.editor.setTextCursor(cursor) self.editor.ensureCursorVisible() self._update_find_status() @@ -717,9 +754,84 @@ class MarkdownEditorDialog(QDialog): pattern = re.escape(query) if self.whole_word_checkbox.isChecked(): pattern = r"\b" + pattern + r"\b" - self.editor.setPlainText(re.sub(pattern, replacement, self.source_text(), flags=flags)) + source = self.source_text() + matches = self._qt_match_spans(source, re.finditer(pattern, source, flags=flags)) + cursor = self.editor.textCursor() + cursor.beginEditBlock() + for start, end in reversed(matches): + cursor.setPosition(start) + cursor.setPosition(end, QTextCursor.MoveMode.KeepAnchor) + cursor.insertText(replacement) + cursor.endEditBlock() self._rebuild_find_matches() + @staticmethod + def _qt_match_spans(source: str, matches) -> list[tuple[int, int]]: + """Convert ordered, non-overlapping matches in one pass over UTF-16 text.""" + spans = [] + offset = position = 0 + for match in matches: + position += len(source[offset:match.start()].encode("utf-16-le")) // 2 + end = position + len(source[match.start():match.end()].encode("utf-16-le")) // 2 + spans.append((position, end)) + offset, position = match.end(), end + return spans + + @staticmethod + def _qt_position(source: str, offset: int) -> int: + return len(source[:offset].encode("utf-16-le")) // 2 + + def replace_source_undoable(self, source: str) -> None: + cursor = self.editor.textCursor() + cursor.beginEditBlock() + cursor.select(QTextCursor.SelectionType.Document) + cursor.insertText(source) + cursor.endEditBlock() + + def show_history(self) -> None: + from .file_versions import show_version_history + source = show_version_history(self, self.save_target_path, self.source_text()) + if source is not None: + self.replace_source_undoable(source) + + def _insert_image_mime(self, mime: object) -> bool: + from .editor_assets import image_markdown + try: + text = image_markdown(mime, self.save_target_path) + if text is None: + return False + self.editor.textCursor().insertText(text) + except (OSError, ValueError) as exc: + QMessageBox.warning(self, "图片插入失败", str(exc)) + return True + + def _choose_images(self) -> None: + from PySide6.QtCore import QMimeData + paths, _ = QFileDialog.getOpenFileNames(self, "插入图片", str(self.save_target_path.parent), + "图片 (*.png *.jpg *.jpeg *.gif *.webp *.bmp *.svg *.tif *.tiff)") + if paths: + mime = QMimeData() + mime.setUrls([QUrl.fromLocalFile(path) for path in paths]) + self._insert_image_mime(mime) + + def _edit_table(self) -> None: + from .table_editor import edit_table, table_at_line + source = self.source_text() + selected = table_at_line(source, self.editor.textCursor().blockNumber()) + table = edit_table(self, selected.rows if selected else None, selected.alignments if selected else None) + if table is None: + return + cursor = self.editor.textCursor() + cursor.beginEditBlock() + if selected: + cursor.setPosition(self._qt_position(source, selected.start)) + cursor.setPosition(self._qt_position(source, selected.end), QTextCursor.MoveMode.KeepAnchor) + cursor.insertText(table + "\n") + else: + cursor.insertText("\n\n" + table + "\n\n") + cursor.endEditBlock() + self.editor.setTextCursor(cursor) + def _configure_preview_settings(self, settings: QWebEngineSettings) -> None: attributes = QWebEngineSettings.WebAttribute settings.setAttribute(attributes.LocalContentCanAccessFileUrls, True) @@ -734,7 +846,7 @@ class MarkdownEditorDialog(QDialog): self.preview.setVisible(mode in {"preview", "split"}) if mode in {"preview", "split"} and self._preview_dirty: self._refresh_preview_now() - if mode == "split": + if mode == "split" and self.sync_scroll_checkbox.isChecked(): QTimer.singleShot(0, lambda: self._sync_preview_to_editor_scroll(self.editor.verticalScrollBar().value())) def _schedule_preview_refresh(self) -> None: @@ -745,7 +857,7 @@ class MarkdownEditorDialog(QDialog): def _refresh_preview_with_scroll_capture(self) -> None: mode = str(self.view_mode_box.currentData() or "source") - if mode == "split": + if mode == "split" and self.sync_scroll_checkbox.isChecked(): self._preview_scroll_ratio = self._editor_scroll_ratio() self._refresh_preview_now() return @@ -773,6 +885,7 @@ class MarkdownEditorDialog(QDialog): document_width_scale=self.document_width_scale, document_style_css=self.document_style_css, math_engine=self.math_engine, + source_map=True, ) base_path = str(self.save_target_path.parent.resolve()) + os.sep self.preview.setHtml(html_content, QUrl.fromLocalFile(base_path)) @@ -781,8 +894,8 @@ class MarkdownEditorDialog(QDialog): def _restore_preview_scroll(self, ok: bool) -> None: if not ok: return - if str(self.view_mode_box.currentData() or "source") == "split": - self._scroll_preview_to_ratio(self._preview_scroll_ratio) + if str(self.view_mode_box.currentData() or "source") == "split" and self.sync_scroll_checkbox.isChecked(): + self._sync_preview_to_source_line() return if self._preview_scroll_y > 0: script = f"(() => {{ window.scrollTo({{top: {self._preview_scroll_y}, behavior: 'instant'}}); }})();" @@ -794,10 +907,63 @@ class MarkdownEditorDialog(QDialog): def _sync_preview_to_editor_scroll(self, value: int) -> None: del value - if self._syncing_scroll or str(self.view_mode_box.currentData() or "source") != "split": + if self._syncing_scroll or not self.sync_scroll_checkbox.isChecked() or str(self.view_mode_box.currentData() or "source") != "split": return self._preview_scroll_ratio = self._editor_scroll_ratio() - self._scroll_preview_to_ratio(self._preview_scroll_ratio) + self.scroll_sync_timer.start() + + def _sync_preview_to_source_line(self) -> None: + if not isValid(self) or not self.sync_scroll_checkbox.isChecked() or self.view_mode_box.currentData() != "split": + return + block = self.editor.firstVisibleBlock() + line = block.blockNumber() + height = max(1.0, self.editor.blockBoundingRect(block).height()) + offset = -self.editor.blockBoundingGeometry(block).translated(self.editor.contentOffset()).top() / height + script = """(() => { + window.mdhelperProgrammaticScrollUntil = performance.now() + 200; + const line = %s; + const blocks = [...document.querySelectorAll('[data-source-line]')] + .filter(e => e.getBoundingClientRect().height > 0); + let target = null; + for (const e of blocks) { + const start = Number(e.dataset.sourceLine), end = Number(e.dataset.sourceEnd); + if (start <= line && (!target || start >= Number(target.dataset.sourceLine))) target = e; + } + if (!target) return; + const start = Number(target.dataset.sourceLine), end = Number(target.dataset.sourceEnd); + const fraction = Math.max(0, Math.min(1, (line - start) / Math.max(1, end - start))); + const rect = target.getBoundingClientRect(); + window.scrollTo({top: window.scrollY + rect.top + rect.height * fraction - 12, behavior: 'instant'}); + })();""" % json.dumps(line + max(0, offset)) + self.preview.page().runJavaScript(script) + + def _sync_source_to_preview_line(self, line: float) -> None: + if not self.sync_scroll_checkbox.isChecked() or self.view_mode_box.currentData() != "split": + return + block = self.editor.document().findBlockByNumber(max(0, min(int(line), self.editor.blockCount() - 1))) + if not block.isValid(): + return + document = self.editor.document() + key = (document.revision(), self.editor.viewport().width(), self.editor.font().toString()) + if getattr(self, "_visual_line_key", None) != key: + offsets = [0] + current = document.firstBlock() + layout = document.documentLayout() + while current.isValid(): + layout.ensureBlockLayout(current) + offsets.append(offsets[-1] + max(1, current.layout().lineCount())) + current = current.next() + self._visual_line_offsets = offsets + self._visual_line_key = key + offsets = self._visual_line_offsets + index = block.blockNumber() + position = offsets[index] + int((line - int(line)) * (offsets[index + 1] - offsets[index])) + bar = self.editor.verticalScrollBar() + self._syncing_scroll = True + try: + bar.setValue(position) + finally: + self._syncing_scroll = False def _scroll_preview_to_ratio(self, ratio: float) -> None: if not isValid(self) or not isValid(self.preview): @@ -828,11 +994,11 @@ class MarkdownEditorDialog(QDialog): target = Path(file_name) if target.suffix.lower() not in {".md", ".markdown"}: target = target.with_suffix(".md") - self.save_target_path = target.resolve() - self._update_dirty_title() if self.embedded: - self._emit_save_requested() + self.save_requested.emit(target.resolve(), self.source_text(), self.file_signature) else: + self.save_target_path = target.resolve() + self._update_dirty_title() self.accept() def accept(self) -> None: @@ -845,7 +1011,11 @@ class MarkdownEditorDialog(QDialog): self.path = path self.save_target_path = path self.file_signature = file_signature + if source != self.source_text(): + self.replace_source_undoable(source) self._original_source = source + self.draft_save_timer.stop() + self._preview_dirty = True self._update_dirty_title() def confirm_close(self) -> bool: diff --git a/mdhelper/markdown_renderer.py b/mdhelper/markdown_renderer.py index 360cb68..7f95df9 100644 --- a/mdhelper/markdown_renderer.py +++ b/mdhelper/markdown_renderer.py @@ -63,6 +63,25 @@ class MarkdownRenderer: self.markdown.core.ruler.push("mdhelper_heading_ids", self._add_heading_ids) self.markdown.core.ruler.push("mdhelper_admonitions", self._convert_admonitions) self.markdown.core.ruler.push("mdhelper_task_lists", self._convert_task_lists) + self.markdown.core.ruler.push("mdhelper_source_lines", self._add_source_lines) + for name in ("fence", "code_block", "math_block"): + original = self.markdown.renderer.rules[name] + def mapped(tokens, idx, options, env, render=original): + output = render(tokens, idx, options, env) + mapping = tokens[idx].map + if mapping and env.get("source_map"): + output = output.replace(" None: + if not state.env.get("source_map"): + return + for token in state.tokens: + if token.map and token.nesting == 1: + token.attrSet("data-source-line", str(token.map[0])) + token.attrSet("data-source-end", str(token.map[1])) def render_file( self, @@ -104,8 +123,9 @@ class MarkdownRenderer: document_font_size: int | None = None, document_style_css: str = "", math_engine: str = "katex", + source_map: bool = False, ) -> str: - env: dict[str, Any] = {"path": str(markdown_path), "headings": []} + env: dict[str, Any] = {"path": str(markdown_path), "headings": [], "source_map": source_map} body = self.markdown.render(source, env) return self._wrap_html( body=body, diff --git a/mdhelper/mhtml_export.py b/mdhelper/mhtml_export.py new file mode 100644 index 0000000..4a19477 --- /dev/null +++ b/mdhelper/mhtml_export.py @@ -0,0 +1,241 @@ +"""Save a rendered, self-contained browser 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)) + + +class MhtmlExportController: + def __init__(self, owner, output: Path, content: str, source_path: Path): + self.owner, self.output, self.content = owner, output.resolve(), content + 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("离线文档导出超时,请检查图片和公式资源。")) + + def start(self): + try: + self.output.parent.mkdir(parents=True, exist_ok=True) + 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.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() + except OSError as exc: + self.fail(str(exc)) + + def loaded(self, ok): + if self.finished: + return + if not ok: + self.fail("离线文档页面加载失败。") + return + self.progress.setLabelText("正在载入图片、公式和字体…") + self.wait_ready() + + 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) + + def ready(self, state): + if self.finished: + return + if isinstance(state, str) and state.startswith("missing:"): + self.fail("部分图片未能加载,未生成离线文档。请修复图片路径后重试。\n" + state[8:]) + elif state == "ready": + self.progress.setLabelText("正在封装离线资源…") + self.page.save(str(self.staged), QWebEngineDownloadRequest.SavePageFormat.MimeHtmlSaveFormat) + else: + QTimer.singleShot(100, self.wait_ready) + + def download_requested(self, request): + if self.finished or request.page() != self.page: + return + self.request = request + request.isFinishedChanged.connect(self.download_finished) + if request.state() == QWebEngineDownloadRequest.DownloadState.DownloadRequested: + request.accept() + self.download_finished() + + def download_finished(self): + if self.finished or self.request is None or not self.request.isFinished(): + return + if self.request.state() != QWebEngineDownloadRequest.DownloadState.DownloadCompleted: + self.fail("离线资源保存失败:" + self.request.interruptReasonString()) + return + try: + if not self.staged.exists() or not self.staged.stat().st_size: + raise OSError("浏览器未生成有效的离线文档。") + self.staged.write_bytes(portable_archive(self.staged.read_bytes())) + os.replace(self.staged, self.output) + except (OSError, ValueError, UnicodeError) as exc: + self.fail(str(exc)) + return + self.owner.status_label.setText(f"已导出:{self.output}") + self.cleanup() + + def cancel(self): + if not self.finished: + self.owner.status_label.setText("已取消 MHTML 导出,原有输出文件保持不变") + self.cleanup() + + def fail(self, message): + if not self.finished: + self.cleanup() + QMessageBox.warning(self.owner, "导出失败", message) + + def cleanup(self): + self.finished = True + self.timeout.stop() + if self.request is not None and not self.request.isFinished(): + self.request.cancel() + if self.page is not None: + self.page.triggerAction(QWebEnginePage.WebAction.Stop) + # Destroy the page before its profile, as required by Qt WebEngine. + self.page.destroyed.connect(self.profile.deleteLater) + self.page.deleteLater() + self.page = None + 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.py b/mdhelper/pdf_export.py index 008c921..9af30c3 100644 --- a/mdhelper/pdf_export.py +++ b/mdhelper/pdf_export.py @@ -10,15 +10,20 @@ from PySide6.QtCore import QMarginsF from PySide6.QtGui import QPageLayout, QPageSize from PySide6.QtWidgets import ( QDialog, + QCheckBox, + QComboBox, QDialogButtonBox, QDoubleSpinBox, QFormLayout, QLabel, + QLineEdit, + QSpinBox, QVBoxLayout, QWidget, ) from .markdown_utils import Heading +from .export_settings import PageSettings PDF_BODY_MARKER = "MDHELPER_PDF_BODY_START_7A61" @@ -33,23 +38,24 @@ class PdfMargins: right: float = 15.0 -def build_pdf_page_layout(margins: PdfMargins | None = None) -> QPageLayout: +def build_pdf_page_layout(margins: PdfMargins | PageSettings | None = None) -> QPageLayout: selected = margins or PdfMargins() return QPageLayout( - QPageSize(QPageSize.PageSizeId.A4), - QPageLayout.Orientation.Portrait, + QPageSize(getattr(QPageSize.PageSizeId, getattr(selected, "paper", "A4"))), + QPageLayout.Orientation.Landscape if getattr(selected, "landscape", False) else QPageLayout.Orientation.Portrait, QMarginsF(selected.left, selected.top, selected.right, selected.bottom), QPageLayout.Unit.Millimeter, ) class PdfExportSettingsDialog(QDialog): - def __init__(self, margins: PdfMargins, parent: QWidget | None = None) -> None: + def __init__(self, margins: PdfMargins | PageSettings, parent: QWidget | None = None) -> None: super().__init__(parent) - self.setWindowTitle("PDF 导出设置") + self.setWindowTitle("导出页面设置(PDF / Word)") self.setModal(True) + self.setMinimumWidth(480) - note = QLabel("纸张:A4;导出背景:白色;正文前自动生成带页码目录。") + note = QLabel("PDF 与 Word 共用这些设置。Word 目录页码由 Word 更新域后生成。\n启用页眉或页脚时,相应页边距至少为 12 mm,以免遮挡正文。") note.setWordWrap(True) self.top_spin = self._margin_spin(margins.top) @@ -58,10 +64,24 @@ class PdfExportSettingsDialog(QDialog): self.right_spin = self._margin_spin(margins.right) form = QFormLayout() + defaults = margins if isinstance(margins, PageSettings) else PageSettings() + self.paper_combo = QComboBox(); self.paper_combo.addItems(["A4", "A3", "Letter"]) + self.paper_combo.setCurrentText(defaults.paper) + self.landscape_check = QCheckBox("横向"); self.landscape_check.setChecked(defaults.landscape) + self.toc_check = QCheckBox("在正文前生成目录"); self.toc_check.setChecked(defaults.include_toc) + self.depth_spin = QSpinBox(); self.depth_spin.setRange(1, 6); self.depth_spin.setValue(defaults.toc_depth) + self.depth_spin.setEnabled(defaults.include_toc); self.toc_check.toggled.connect(self.depth_spin.setEnabled) + self.header_edit = QLineEdit(defaults.header); self.header_edit.setMaxLength(100) + self.footer_edit = QLineEdit(defaults.footer); self.footer_edit.setMaxLength(100) + self.numbers_check = QCheckBox("显示页码和总页数"); self.numbers_check.setChecked(defaults.page_numbers) + form.addRow("纸张", self.paper_combo); form.addRow("方向", self.landscape_check) form.addRow("上边距", self.top_spin) form.addRow("下边距", self.bottom_spin) form.addRow("左边距", self.left_spin) form.addRow("右边距", self.right_spin) + form.addRow("目录", self.toc_check); form.addRow("目录层级", self.depth_spin) + form.addRow("页眉", self.header_edit); form.addRow("页脚", self.footer_edit) + form.addRow("页码", self.numbers_check) buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) buttons.accepted.connect(self.accept) @@ -80,6 +100,14 @@ class PdfExportSettingsDialog(QDialog): right=float(self.right_spin.value()), ) + def page_settings(self) -> PageSettings: + margins = self.margins() + return PageSettings(paper=self.paper_combo.currentText(), landscape=self.landscape_check.isChecked(), + top=margins.top, bottom=margins.bottom, left=margins.left, right=margins.right, + include_toc=self.toc_check.isChecked(), toc_depth=self.depth_spin.value(), + header=self.header_edit.text(), footer=self.footer_edit.text(), + page_numbers=self.numbers_check.isChecked()).normalized() + def _margin_spin(self, value: float) -> QDoubleSpinBox: spin = QDoubleSpinBox() spin.setRange(0.0, 50.0) @@ -96,11 +124,17 @@ def build_pdf_export_html( page_numbers: dict[int, int] | None = None, *, include_page_markers: bool = True, + settings: PageSettings | None = None, ) -> str: - printable_headings = [heading for heading in headings if heading.level <= 3] + selected = settings or PageSettings() + # Export uses light paper independently of the application's reading theme. + html_document = html_document.replace('data-theme="dark"', 'data-theme="light"', 1) + printable_headings = [heading for heading in headings if heading.level <= selected.toc_depth] if selected.include_toc else [] marked_document = _insert_heading_markers(html_document, printable_headings) if include_page_markers else html_document - toc_html = _toc_html(printable_headings, page_numbers or {}) + toc_html = _toc_html(printable_headings, page_numbers or {}) if selected.include_toc else "" print_css = _print_css(len(printable_headings)) + usable_height = max(20, selected.size_mm()[1] - selected.top - selected.bottom - 2) + print_css += f"\n@media print {{ html {{ color-scheme: light !important; }} .reader img {{ max-height: {usable_height:g}mm; object-fit: contain; }} }}\n" marked_document = marked_document.replace("", f"{print_css}\n ", 1) body_class = ' class="pdf-export"' @@ -277,6 +311,9 @@ def _print_css(heading_count: int) -> str: }} .pdf-toc__item--level-2 {{ padding-left: 5mm; }} .pdf-toc__item--level-3 {{ padding-left: 10mm; }} + .pdf-toc__item--level-4 {{ padding-left: 15mm; }} + .pdf-toc__item--level-5 {{ padding-left: 20mm; }} + .pdf-toc__item--level-6 {{ padding-left: 25mm; }} .pdf-toc__text {{ max-width: 78%; }} .pdf-toc__dots {{ min-width: 8mm; diff --git a/mdhelper/resources/reader.js b/mdhelper/resources/reader.js index 9f4b4f1..93618ab 100644 --- a/mdhelper/resources/reader.js +++ b/mdhelper/resources/reader.js @@ -1,4 +1,5 @@ document.addEventListener("DOMContentLoaded", () => { + window.mdhelperRenderReady = false; const CODE_LINE_NUMBER_LIMIT = 240; const CODE_COLLAPSE_LIMIT = 18; const CODE_AUTO_COLLAPSE_LIMIT = 420; @@ -56,8 +57,7 @@ document.addEventListener("DOMContentLoaded", () => { return; } if (engine === "mathjax" && window.MathJax && window.MathJax.typesetPromise) { - window.MathJax.typesetPromise([reader]).catch(() => {}); - return; + return window.MathJax.typesetPromise([reader]).catch(() => {}); } if (engine === "katex" && window.renderMathInElement) { window.renderMathInElement(reader, { @@ -72,10 +72,12 @@ document.addEventListener("DOMContentLoaded", () => { } }; - renderMermaidDiagrams(); + const diagramsReady = renderMermaidDiagrams(); window.mdhelperSyncMathFontSize = syncMathFontSize; syncMathFontSize(); - renderMath(); + Promise.allSettled([diagramsReady, renderMath()]).then(() => { + window.mdhelperRenderReady = true; + }); document.querySelectorAll(".code-block").forEach((block) => { const code = block.querySelector("pre code"); @@ -445,6 +447,36 @@ document.addEventListener("DOMContentLoaded", () => { if (window.qt && window.qt.webChannelTransport) { new QWebChannel(window.qt.webChannelTransport, (channel) => { bridge = channel.objects.mdhelperBridge || null; + const editor = channel.objects.mdhelperEditor; + if (editor) { + // Only editor previews track user scrolling. Reader windows remain idle. + let intentUntil = 0, pending = null; + const intent = () => { intentUntil = performance.now() + 1200; }; + document.addEventListener("wheel", intent, {passive: true}); + document.addEventListener("pointerdown", intent, {passive: true}); + document.addEventListener("keydown", intent); + window.addEventListener("scroll", () => { + if (pending || performance.now() > intentUntil || + performance.now() < (window.mdhelperProgrammaticScrollUntil || 0)) return; + pending = setTimeout(() => { + pending = null; + const blocks = [...document.querySelectorAll('[data-source-line]')]; + let target = null, best = -Infinity; + for (const element of blocks) { + const rect = element.getBoundingClientRect(); + if (rect.height > 0 && rect.top <= 14 && rect.bottom > 12 && rect.top >= best) { + best = rect.top; target = element; + } + } + if (!target) target = blocks.find(e => e.getBoundingClientRect().top >= 0); + if (!target) return; + const rect = target.getBoundingClientRect(); + const start = Number(target.dataset.sourceLine), end = Number(target.dataset.sourceEnd); + const fraction = Math.max(0, Math.min(0.999, (12 - rect.top) / Math.max(1, rect.height))); + editor.sourceLine(start + fraction * Math.max(1, end - start)); + }, 50); + }, {passive: true}); + } }); } }); diff --git a/mdhelper/search.py b/mdhelper/search.py index 4006ce7..c8aeb08 100644 --- a/mdhelper/search.py +++ b/mdhelper/search.py @@ -18,12 +18,14 @@ class SearchMatch: class SearchIndex: def __init__(self, entries: list[DocumentEntry] | None = None) -> None: self._records: list[tuple[DocumentEntry, str, str]] = [] + self._records_by_path: dict[Path, tuple[DocumentEntry, str, str]] = {} self._body_cache: dict[Path, tuple[int, int, str]] = {} if entries: self.rebuild(entries) def rebuild(self, entries: list[DocumentEntry]) -> None: self._records = [(entry, entry.title, entry.relative_path) for entry in entries] + self._records_by_path = {record[0].path: record for record in self._records} current_paths = {entry.path for entry in entries} self._body_cache = {path: value for path, value in self._body_cache.items() if path in current_paths} @@ -32,20 +34,21 @@ class SearchIndex: if not normalized: return True - for indexed_entry, title, relative_path in self._records: - if indexed_entry.path == entry.path: - if normalized in self._haystack(title, relative_path, "").casefold(): - return True - return normalized in self._body_for(indexed_entry).casefold() - if normalized in self._haystack(entry.title, entry.relative_path, "").casefold(): + entry, title, relative_path = self._records_by_path.get(entry.path, (entry, entry.title, entry.relative_path)) + if normalized in self._haystack(title, relative_path, "").casefold(): return True return normalized in self._body_for(entry).casefold() def search(self, query: str, limit: int = 80) -> list[SearchMatch]: + return self.filter(query, limit, all_paths=False)[1] + + def filter(self, query: str, limit: int = 80, *, all_paths: bool = True) -> tuple[set[Path], list[SearchMatch]]: + """Find tree visibility and bounded result details without scanning twice.""" normalized = query.strip().casefold() if not normalized: - return [] + return ({entry.path for entry, _, _ in self._records} if all_paths else set()), [] + visible: set[Path] = set() matches: list[SearchMatch] = [] for entry, title, relative_path in self._records: result = _match_details(title, relative_path, "", normalized) @@ -54,6 +57,11 @@ class SearchIndex: if result is None: continue + visible.add(entry.path) + if len(matches) >= limit: + if not all_paths: + break + continue snippet, match_count, match_kind = result matches.append( SearchMatch( @@ -63,9 +71,9 @@ class SearchIndex: match_kind=match_kind, ) ) - if len(matches) >= limit: + if not all_paths and len(matches) >= limit: break - return matches + return visible, matches def _haystack(self, title: str, relative_path: str, body: str) -> str: return f"{title}\n{relative_path}\n{body}" diff --git a/mdhelper/table_editor.py b/mdhelper/table_editor.py new file mode 100644 index 0000000..2dce630 --- /dev/null +++ b/mdhelper/table_editor.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +import csv +import io +import re +from dataclasses import dataclass + +MAX_ROWS = 1000 +MAX_COLUMNS = 100 + + +def validate_table_size(rows: list[list[str]]) -> None: + if len(rows) > MAX_ROWS or any(len(row) > MAX_COLUMNS for row in rows): + raise ValueError(f"图形表格最多支持 {MAX_ROWS} 行(含表头)、{MAX_COLUMNS} 列。\n" + "未导入超限内容,原表格保持不变。请拆分表格或在源码中编辑。") + + +def parse_tsv(text: str) -> list[list[str]]: + rows = [] + for row in csv.reader(io.StringIO(text), delimiter="\t"): + if len(rows) >= MAX_ROWS or len(row) > MAX_COLUMNS: + raise ValueError(f"粘贴内容超过 {MAX_ROWS} 行或 {MAX_COLUMNS} 列,未导入任何内容。请拆分后重试。") + rows.append(row or [""]) + return rows + + +def format_table(rows: list[list[str]], alignments: list[str]) -> str: + count = max((len(row) for row in rows), default=1) + rows = rows or [["列1"]] + def line(row: list[str]) -> str: + cells = [row[i] if i < len(row) else "" for i in range(count)] + # Preserve existing escaped pipes; multiline spreadsheet cells become line breaks. + cells = [re.sub(r"(?")).strip() for cell in cells] + return "| " + " | ".join(cells) + " |" + separators = {"left": ":---", "center": ":---:", "right": "---:", "": "---"} + rule = [separators.get(alignments[i] if i < len(alignments) else "", "---") for i in range(count)] + return "\n".join([line(rows[0]), line(rule), *[line(row) for row in rows[1:]]]) + + +@dataclass +class TableSelection: + start: int + end: int + rows: list[list[str]] + alignments: list[str] + + +def table_at_line(source: str, line: int) -> TableSelection | None: + from markdown_it import MarkdownIt + tokens = MarkdownIt().enable("table").parse(source) + for i, token in enumerate(tokens): + if token.type != "table_open" or token.map is None or not token.map[0] <= line < token.map[1]: + continue + if token.level > 0: + return None + # Nested quote/list tables need their prefix retained; leave those to source editing. + start, end = token.map + source_lines = source.splitlines(keepends=True) + if source_lines[start].lstrip().startswith((">", "- ", "* ")): + return None + rows: list[list[str]] = [] + aligns: list[str] = [] + for child in tokens[i+1:]: + if child.type == "table_close": + break + if child.type == "tr_open": + rows.append([]) + elif child.type == "inline" and rows: + rows[-1].append(child.content) + elif child.type == "th_open": + aligns.append((child.attrGet("style") or "").removeprefix("text-align:")) + return TableSelection(sum(map(len, source_lines[:start])), sum(map(len, source_lines[:end])), rows, aligns) + return None + + +def edit_table(parent: object, rows: list[list[str]] | None = None, alignments: list[str] | None = None) -> str | None: + from PySide6.QtWidgets import (QApplication, QComboBox, QDialog, QDialogButtonBox, QHBoxLayout, + QLabel, QMessageBox, QPushButton, QSpinBox, QTableWidget, QTableWidgetItem, QVBoxLayout) + rows = rows or [["列1", "列2"], ["", ""], ["", ""]] + try: + validate_table_size(rows) + except ValueError as exc: + QMessageBox.warning(parent, "表格过大", str(exc)) + return None + alignment = list(alignments or [""] * max(map(len, rows))) + dialog = QDialog(parent) + dialog.setWindowTitle("编辑 Markdown 表格") + dialog.resize(820, 540) + layout = QVBoxLayout(dialog) + layout.addWidget(QLabel("第一行为表头;可直接编辑单元格,也可从 Excel 粘贴。应用后可整体撤销。")) + controls = QHBoxLayout() + row_count, column_count = QSpinBox(), QSpinBox() + row_count.setRange(1, MAX_ROWS) + column_count.setRange(1, MAX_COLUMNS) + row_count.setValue(len(rows)) + column_count.setValue(max(map(len, rows))) + controls.addWidget(QLabel("行数(含表头)")); controls.addWidget(row_count) + controls.addWidget(QLabel("列数")); controls.addWidget(column_count) + align = QComboBox() + for label, value in [("默认", ""), ("左对齐", "left"), ("居中", "center"), ("右对齐", "right")]: + align.addItem(label, value) + controls.addWidget(QLabel("当前列")); controls.addWidget(align) + layout.addLayout(controls) + table = QTableWidget(len(rows), max(map(len, rows))) + layout.addWidget(table) + + def populate(values: list[list[str]]) -> None: + table.clearContents() + row_count.setValue(len(values)); column_count.setValue(max(map(len, values))) + for r, row in enumerate(values): + for c, cell in enumerate(row): + table.setItem(r, c, QTableWidgetItem(cell)) + table.setCurrentCell(0, 0) + + def columns(value: int) -> None: + table.setColumnCount(value) + alignment.extend([""] * max(0, value - len(alignment))) + del alignment[value:] + row_count.valueChanged.connect(table.setRowCount) + column_count.valueChanged.connect(columns) + def selection(r: int, c: int, *_: object) -> None: + align.blockSignals(True) + align.setCurrentIndex(max(0, align.findData(alignment[c] if 0 <= c < len(alignment) else ""))) + align.blockSignals(False) + table.currentCellChanged.connect(selection) + def set_alignment() -> None: + if table.currentColumn() >= 0: + alignment[table.currentColumn()] = str(align.currentData()) + align.currentIndexChanged.connect(set_alignment) + populate(rows) + actions = QHBoxLayout() + def add_row() -> None: + if table.rowCount() < MAX_ROWS: + table.insertRow(max(1, table.currentRow() + 1)) + row_count.setValue(table.rowCount()) + def remove_row() -> None: + if table.rowCount() > 1 and table.currentRow() >= 0: + table.removeRow(table.currentRow()); row_count.setValue(table.rowCount()) + def add_column() -> None: + if table.columnCount() < MAX_COLUMNS: + index = max(0, table.currentColumn() + 1) + table.insertColumn(index); alignment.insert(index, ""); column_count.setValue(table.columnCount()) + def remove_column() -> None: + if table.columnCount() > 1 and table.currentColumn() >= 0: + alignment.pop(table.currentColumn()); table.removeColumn(table.currentColumn()); column_count.setValue(table.columnCount()) + def paste() -> None: + try: + values = parse_tsv(QApplication.clipboard().text()) + except (ValueError, csv.Error) as exc: + QMessageBox.warning(dialog, "无法粘贴表格", str(exc)) + return + if values: + populate(values) + for title, callback in [("插入行", add_row), ("删除行", remove_row), ("插入列", add_column), + ("删除列", remove_column), ("从 Excel 粘贴", paste)]: + button = QPushButton(title); button.clicked.connect(callback); actions.addWidget(button) + layout.addLayout(actions) + buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) + buttons.accepted.connect(dialog.accept); buttons.rejected.connect(dialog.reject) + layout.addWidget(buttons) + if dialog.exec() != QDialog.DialogCode.Accepted: + return None + result = [[table.item(r, c).text() if table.item(r, c) else "" for c in range(table.columnCount())] + for r in range(table.rowCount())] + return format_table(result, alignment) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..91c0ce3 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,21 @@ +"""Keep one QApplication alive, matching the desktop application's lifecycle.""" +import os + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +os.environ.setdefault("QTWEBENGINE_DISABLE_SANDBOX", "1") +os.environ.setdefault("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu --no-sandbox --log-level=3") + +import pytest +from PySide6.QtWidgets import QApplication +from PySide6.QtGui import QFontDatabase + + +@pytest.fixture(scope="session", autouse=True) +def qt_application(): + app = QApplication.instance() or QApplication([]) + # Windows' offscreen plugin has no system font database. Register the same + # font used by PDF headers so the test exercises real glyph embedding. + if os.name == "nt" and not QFontDatabase.families(): + QFontDatabase.addApplicationFont(os.path.join(os.environ.get("WINDIR", "C:/Windows"), "Fonts", "msyh.ttc")) + yield app + app.processEvents() diff --git a/tests/improvements_smoke.py b/tests/improvements_smoke.py new file mode 100644 index 0000000..fdd52fd --- /dev/null +++ b/tests/improvements_smoke.py @@ -0,0 +1,153 @@ +"""Real WebEngine, dialogs, cancellation and PDF integration checks.""" +from __future__ import annotations + +import os +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +os.environ.setdefault("QTWEBENGINE_DISABLE_SANDBOX", "1") +os.environ.setdefault("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu --no-sandbox --log-level=3") + +import sys +import tempfile +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +from PySide6.QtCore import QMimeData, QSettings, QTimer +from PySide6.QtGui import QColor, QFontDatabase, QImage, QTextCursor +from PySide6.QtWidgets import QApplication, QDialog, QMessageBox, QPushButton, QSpinBox, QTableWidget +from pypdf import PdfReader + +from mdhelper.main_window import MainWindow +from mdhelper.markdown_editor import MarkdownEditorDialog +from mdhelper.export_settings import PageSettings +from mdhelper.pdf_export import PdfExportSettingsDialog +from mdhelper.file_versions import VersionStore + + +def main(): + output = ROOT / "pack" / "output" / "improvements-qa" + output.mkdir(parents=True, exist_ok=True) + app = QApplication.instance() or QApplication([]) + if not QFontDatabase.families(): + QFontDatabase.addApplicationFont("C:/Windows/Fonts/msyh.ttc") + app.setQuitOnLastWindowClosed(False) + warnings = [] + QMessageBox.warning = staticmethod(lambda parent, title, text, *args: warnings.append(str(text))) + with tempfile.TemporaryDirectory(prefix="mdhelper-improvements-") as temporary: + directory = Path(temporary) + QSettings.setDefaultFormat(QSettings.Format.IniFormat) + QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.UserScope, str(directory / "settings")) + os.environ["MDHELPER_HISTORY_DIR"] = str(directory / "history") + path = directory / "报告.md" + path.write_text("# OLD_DISK\n\n旧内容", encoding="utf-8") + window = MainWindow(None, app_root=ROOT) + window.prepare_reader_before_show(); window.resize(1380, 900); window.show() + + def wait(condition, seconds=30): + end = time.monotonic() + seconds + while not condition() and time.monotonic() < end: + app.processEvents(); time.sleep(0.01) + assert condition(), "Integration check timed out" + + def js(script): + values = [] + editor.preview.page().runJavaScript(script, values.append) + wait(lambda: bool(values), 10) + return values[0] + + window.open_document(path) + window.edit_current_markdown() + editor = window.tabs.currentWidget() + assert isinstance(editor, MarkdownEditorDialog) + source = "# 最新报告 FRESH_EDITOR\n\n**中文加粗。**紧接正文。\n\n" + "\n\n".join(f"## 章节 {n}\n\n" + "用于检查段落和字体。" * 12 for n in range(1, 10)) + editor.replace_source_undoable(source) + image = QImage(300, 900, QImage.Format.Format_RGB32); image.fill(QColor("#b8d6ef")) + mime = QMimeData(); mime.setImageData(image) + cursor = editor.editor.textCursor(); cursor.setPosition(source.index("## 章节 3")); editor.editor.setTextCursor(cursor) + editor.editor.insertFromMimeData(mime) + editor.editor.textCursor().insertText("\n\n") + source = editor.source_text() + assert ".assets" in source + wait(lambda: not editor._preview_dirty) + wait(lambda: js("document.querySelectorAll('[data-source-line]').length") > 10) + cursor = editor.editor.textCursor(); cursor.movePosition(QTextCursor.MoveOperation.End) + editor.editor.setTextCursor(cursor); editor.editor.ensureCursorVisible() + wait(lambda: js("window.scrollY") > 200) + editor.sync_scroll_checkbox.setChecked(False) + before = js("window.scrollY") + editor.editor.verticalScrollBar().setValue(0) + end = time.monotonic() + .3 + while time.monotonic() < end: + app.processEvents(); time.sleep(.01) + assert abs(js("window.scrollY") - before) < 2 + editor.sync_scroll_checkbox.setChecked(True) + editor._sync_preview_to_source_line() + wait(lambda: js("window.scrollY") < 100) + # Wait until programmatic suppression expires, then emulate a preview scroll. + end = time.monotonic() + .25 + while time.monotonic() < end: + app.processEvents(); time.sleep(.01) + js("document.dispatchEvent(new WheelEvent('wheel')); window.scrollTo(0, document.querySelectorAll('h2')[5].offsetTop)") + wait(lambda: editor.editor.firstVisibleBlock().blockNumber() >= 15) + window.grab().save(str(output / "editor.png")) + + # Exercise table dialog controls, clipboard import and undo through the toolbar. + before_table = editor.source_text() + def table_dialog(): + dialog = QApplication.activeModalWidget() + assert isinstance(dialog, QDialog) + QApplication.clipboard().setText("项目\t数值\nA\t10\nB\t20") + next(b for b in dialog.findChildren(QPushButton) if b.text() == "从 Excel 粘贴").click() + next(b for b in dialog.findChildren(QPushButton) if b.text() == "插入列").click() + assert dialog.findChild(QTableWidget).columnCount() == 3 + dialog.grab().save(str(output / "table.png")); dialog.accept() + QTimer.singleShot(100, table_dialog); editor._edit_table() + assert "| 项目" in editor.source_text() + editor.editor.undo(); assert editor.source_text() == before_table + + assert window.save_markdown_source(path, source, reload_current=False) + assert VersionStore().versions(path)[0].read_text(encoding="utf-8") == "# OLD_DISK\n\n旧内容" + def history_dialog(): + dialog = QApplication.activeModalWidget() + dialog.grab().save(str(output / "history.png")); dialog.accept() + QTimer.singleShot(100, history_dialog); editor.show_history() + assert "OLD_DISK" in editor.source_text() + editor.editor.undo(); assert editor.source_text() == source + # Current editor text must win over saved disk in the following export. + editor.replace_source_undoable(source.replace("FRESH_EDITOR", "LATEST_UNSAVED")) + settings = PageSettings(paper="A4", landscape=True, include_toc=True, toc_depth=2, + header="测试报告 Header", footer="内部资料 Footer", page_numbers=True) + dialog = PdfExportSettingsDialog(settings) + dialog.show(); app.processEvents(); dialog.grab().save(str(output / "page-settings.png")); dialog.close() + target = output / "landscape.pdf" + target.write_bytes(b"old output") + window.export_pdf_to_path(target, settings) + window._pdf_controller.cancel() + assert target.read_bytes() == b"old output" + window.export_pdf_to_path(target, settings) + # Switching tabs must not change the active PDF snapshot or resource directory. + other = directory / "other.md"; other.write_text("# Other tab", encoding="utf-8") + window.open_document(other, new_tab=True) + wait(lambda: getattr(window, "_pdf_export_page", None) is None, 45) + assert not warnings, warnings + pdf = PdfReader(target) + text = "\n".join(page.extract_text() for page in pdf.pages) + assert "LATEST_UNSAVED" in text and "OLD_DISK" not in text + assert "Header" in text and "Footer" in text + assert float(pdf.pages[0].mediabox.width) > float(pdf.pages[0].mediabox.height) + assert len(pdf.pages) >= 2 + # Exercise background Word conversion and wait for the final atomic output. + window.tabs.setCurrentWidget(editor) + word = output / "report.docx" + window.export_docx_to_path(word, "pandoc", background=True, page_settings=settings) + wait(lambda: not window._export_jobs, 30) + assert word.exists() and not warnings, warnings + editor.mark_saved(path, editor.source_text(), window._file_signature(path)) + window.close(); app.processEvents() + print("Improvements integration passed: images, tables, history, bidirectional scroll, PDF cancel/retry/snapshot, page headers, background Word.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/reliability_smoke.py b/tests/reliability_smoke.py new file mode 100644 index 0000000..2da28c9 --- /dev/null +++ b/tests/reliability_smoke.py @@ -0,0 +1,126 @@ +"""Real WebEngine checks for independent preview scrolling and offline MHTML.""" +from __future__ import annotations + +import os +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +os.environ.setdefault("QTWEBENGINE_DISABLE_SANDBOX", "1") +os.environ.setdefault("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu --no-sandbox --log-level=3") + +import json +import sys +import tempfile +import time +from email import message_from_bytes +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +from PySide6.QtCore import QSettings, QUrl +from PySide6.QtGui import QImage, QColor +from PySide6.QtWebEngineCore import QWebEnginePage, QWebEngineProfile, QWebEngineUrlRequestInterceptor +from PySide6.QtWidgets import QApplication, QMessageBox +from mdhelper import main_window + + +def main(): + app = QApplication.instance() or QApplication([]) + app.setQuitOnLastWindowClosed(False) + warnings = [] + QMessageBox.warning = staticmethod(lambda *args: warnings.append(str(args[2]))) + QMessageBox.question = staticmethod(lambda *args: QMessageBox.StandardButton.Discard) + + def wait(condition, seconds=30): + end = time.monotonic() + seconds + while not condition() and time.monotonic() < end: + app.processEvents() + time.sleep(.01) + assert condition(), f"Timed out; warnings: {warnings}" + + def js(page, script): + values = [] + page.runJavaScript(script, 1, values.append) + wait(lambda: bool(values), 10) + return values[0] + + with tempfile.TemporaryDirectory(prefix="mdhelper-reliability-") as temporary: + root = Path(temporary) + settings = QSettings(str(root / "settings.ini"), QSettings.Format.IniFormat) + main_window.QSettings = lambda *args: settings + os.environ["MDHELPER_HISTORY_DIR"] = str(root / "history") + picture = root / "picture.png" + image = QImage(35, 27, QImage.Format.Format_RGB32) + image.fill(QColor("red")); assert image.save(str(picture)) + path = root / "note.md" + path.write_text("# Old disk", encoding="utf-8") + window = main_window.MainWindow(None, app_root=ROOT) + window.prepare_reader_before_show(); window.resize(1200, 800); window.show() + window.open_document(path); window.edit_current_markdown() + editor = window.tabs.currentWidget() + source = "# FRESH_EDITOR\n\n" + "\n\n".join("Paragraph " + str(i) + " content" * 30 for i in range(120)) + source += '\n\n![offline image](picture.png)\n\n$$x^2 + y^2 = z^2$$\n\n```mermaid\ngraph LR\n A-->B\n```\n' + editor.replace_source_undoable(source) + page = editor.preview.page() + wait(lambda: not editor._preview_dirty) + wait(lambda: float(js(page, "document.body ? document.body.scrollHeight : 0") or 0) > 5000) + editor.sync_scroll_checkbox.setChecked(False) + js(page, "window.scrollTo(0, 2500)") + wait(lambda: float(js(page, "window.scrollY") or 0) > 2000) + before = js(page, "window.scrollY") + loaded = [] + page.loadFinished.connect(loaded.append) + editor.replace_source_undoable(source + "\nlatest edit") + wait(lambda: bool(loaded)) + wait(lambda: abs(float(js(page, "window.scrollY") or 0) - before) < 3) + after = js(page, "window.scrollY") + output = root / "portable.mhtml" + window.export_mhtml_to_path(output) + wait(lambda: not window._mhtml_exports) + assert not warnings and output.exists(), warnings + message = message_from_bytes(output.read_bytes()) + types = [part.get_content_type() for part in message.walk()] + assert "image/png" in types and "text/css" in types, types + html = next(part.get_payload(decode=True) for part in message.walk() if part.get_content_type() == "text/html").decode("utf-8") + assert "FRESH_EDITOR" in html and "latest edit" in html and "Old disk" not in html + assert 'katex' in html and 'i.getAttribute('src'))?.naturalWidth,math:!!document.querySelector('.katex'),diagram:!!document.querySelector('svg'),font:document.fonts.status})")) + assert state == {"width": 35, "math": True, "diagram": True, "font": "loaded"}, (state, js(archive, "JSON.stringify([...document.images].map(i=>({src:i.src,width:i.naturalWidth,complete:i.complete,loading:i.loading})))"), archived_urls) + archive.destroyed.connect(profile.deleteLater); archive.deleteLater(); app.processEvents() + # Cancelling a new archive must leave an existing output untouched. + output.write_bytes(b"previous export") + window.export_mhtml_to_path(output) + next(iter(window._mhtml_exports)).cancel() + assert not window._mhtml_exports and output.read_bytes() == b"previous export" + assert not list(root.glob(".mdhelper-mhtml-*")) + window.export_mhtml_to_path(output) + wait(lambda: not window._mhtml_exports) + assert warnings and output.read_bytes() == b"previous export" + assert not list(root.glob(".mdhelper-mhtml-*")) + window.close(); app.processEvents() + print(json.dumps({"preview_before": before, "preview_after": after, "mhtml_parts": types, + "offline": state, "cancel_and_failure_preserve_output": True}, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_editor_improvements.py b/tests/test_editor_improvements.py new file mode 100644 index 0000000..b71cffa --- /dev/null +++ b/tests/test_editor_improvements.py @@ -0,0 +1,125 @@ +from __future__ import annotations + +import os +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +os.environ.setdefault("QTWEBENGINE_DISABLE_SANDBOX", "1") +os.environ.setdefault("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu --no-sandbox --log-level=3") + +from pathlib import Path +from urllib.parse import unquote +import pytest +from PySide6.QtCore import QMimeData, QUrl +from PySide6.QtGui import QColor, QImage, QTextCursor +from PySide6.QtWidgets import QApplication + +from mdhelper.editor_assets import image_markdown, store_image +from mdhelper.file_versions import VersionStore +from mdhelper.markdown_editor import MarkdownEditorDialog +from mdhelper.markdown_renderer import MarkdownRenderer +from mdhelper.table_editor import format_table, parse_tsv, table_at_line + + +@pytest.fixture(scope="module") +def app(): + return QApplication.instance() or QApplication([]) + + +@pytest.fixture +def editor(app, tmp_path): + widget = MarkdownEditorDialog(tmp_path / "note.md", "😀 old old", MarkdownRenderer(tmp_path), "light", 1, "", 16) + yield widget + widget.preview_refresh_timer.stop(); widget.draft_save_timer.stop() + widget.deleteLater(); app.processEvents() + + +def test_replace_all_is_single_undo_and_keeps_earlier_edits(editor): + cursor = editor.editor.textCursor(); cursor.movePosition(QTextCursor.MoveOperation.End) + cursor.insertText(" earlier") + editor.editor_find_box.setText("old") + editor.editor_replace_box.setText(r"C:\new\test") + editor.replace_all_in_editor() + assert editor.source_text() == "😀 C:\\new\\test C:\\new\\test earlier" + editor.editor.undo() + assert editor.source_text() == "😀 old old earlier" + editor.editor.undo() + assert editor.source_text() == "😀 old old" + editor.editor.redo(); editor.editor.redo() + assert r"C:\new\test" in editor.source_text() + + +def test_find_uses_utf16_positions(editor): + editor.editor_find_box.setText("old") + editor.find_next_in_editor() + assert editor.editor.textCursor().selectedText() == "old" + + +def test_restore_history_is_undoable(editor): + editor.replace_source_undoable("# 历史内容") + assert editor.has_unsaved_changes() + editor.editor.undo() + assert editor.source_text() == "😀 old old" + + +def test_version_retention_and_unchanged_save(tmp_path): + path = tmp_path / "note.md" + path.write_text("zero", encoding="utf-8") + store = VersionStore(tmp_path / "history", limit=3) + for number in range(1, 6): + store.save(path, str(number)) + assert [v.read_text() for v in store.versions(path)] == ["4", "3", "2"] + previous = store.versions(path) + store.save(path, "5") + assert store.versions(path) == previous + + +def test_failed_atomic_save_keeps_original_and_history(tmp_path, monkeypatch): + from mdhelper import file_versions + path = tmp_path / "note.md"; path.write_bytes(b"original\r\n") + store = VersionStore(tmp_path / "history") + replace = file_versions.os.replace + def failure(source, destination): + if Path(destination) == path: + raise OSError("simulated sharing violation") + replace(source, destination) + monkeypatch.setattr(file_versions.os, "replace", failure) + with pytest.raises(OSError): + store.save(path, "changed") + assert path.read_bytes() == b"original\r\n" + assert store.versions(path)[0].read_bytes() == b"original\r\n" + assert not list(tmp_path.glob("*.tmp")) + + +def test_clipboard_image_and_file_drop_use_relative_assets(app, tmp_path): + document = tmp_path / "报告 空格.md" + image = QImage(16, 12, QImage.Format.Format_ARGB32); image.fill(QColor("red")) + mime = QMimeData(); mime.setImageData(image) + markdown = image_markdown(mime, document) + url = markdown.split("](")[1][:-1] + target = tmp_path / unquote(url) + assert target.exists() and target.suffix == ".png" + assert image_markdown(mime, document) == markdown + assert len(list(target.parent.iterdir())) == 1 + files = QMimeData(); files.setUrls([QUrl.fromLocalFile(str(target))]) + assert image_markdown(files, document).endswith("](" + url + ")") + assert "file:" not in markdown and "%20" in markdown + + +def test_table_excel_multiline_escaped_pipe_and_alignment(): + rows = parse_tsv('Name\tValue\r\n"two\nlines"\t"a|b"\r\n') + output = format_table(rows, ["left", "right"]) + assert "two
lines" in output and "a\\|b" in output + assert "| :--- | ---: |" in output + selected = table_at_line("before\n\n" + output + "\n\nafter", 3) + assert selected is not None and len(selected.rows) == 2 + assert selected.alignments == ["left", "right"] + assert format_table(selected.rows, selected.alignments) == output + + +def test_source_map_is_only_in_editor_preview(tmp_path): + renderer = MarkdownRenderer(tmp_path) + source = "# Heading\n\nparagraph\n\n```python\nx = 1\n```\n" + normal = renderer.render_source(source, tmp_path / "x.md") + mapped = renderer.render_source(source, tmp_path / "x.md", source_map=True) + assert '

' in normal + assert 'data-source-line="2" data-source-end="3"' in mapped + assert 'data-source-line="4" data-source-end="7"' in mapped diff --git a/tests/test_export_improvements.py b/tests/test_export_improvements.py new file mode 100644 index 0000000..2f1f616 --- /dev/null +++ b/tests/test_export_improvements.py @@ -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('

a

', [Heading(1, "a", "a")], + include_page_markers=False, settings=settings) + assert '
' 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() diff --git a/tests/test_mhtml_export.py b/tests/test_mhtml_export.py new file mode 100644 index 0000000..729d237 --- /dev/null +++ b/tests/test_mhtml_export.py @@ -0,0 +1,46 @@ +from email import message_from_bytes, policy +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText +from email.mime.application import MIMEApplication +import base64 + +import pytest +from mdhelper.mhtml_export import portable_archive + + +def test_archive_embeds_fonts_and_uses_internal_resource_ids(tmp_path): + folder = tmp_path / ("long folder " * 4).strip() + folder.mkdir() + css_path = folder / "style.css" + font = folder / "字体.woff2" + font.write_bytes(b"font data") + image_url = (folder / "image.png").as_uri() + message = MIMEMultipart("related", type="text/html") + html = MIMEText(f'

text

', "html", "utf-8") + html["Content-Location"] = (folder / "index.html").as_uri() + css = MIMEText('@font-face{font-family:Demo;src:url("字体.woff2") format("woff2"),url(missing.woff)}', "css", "utf-8") + css["Content-Location"] = css_path.as_uri() + image = MIMEApplication(b"image bytes", "octet-stream") + image["Content-Location"] = image_url + for part in (html, css, image): + message.attach(part) + raw = portable_archive(message.as_bytes(policy=policy.SMTP.clone(max_line_length=0))) + archive = message_from_bytes(raw, policy=policy.default) + parts = archive.get_payload() + body = parts[0].get_payload(decode=True).decode() + css_text = parts[1].get_payload(decode=True).decode() + assert 'src="cid:mdhelper-' in body and 'href="cid:mdhelper-' in body + assert image_url not in body and '

text

' in body + assert base64.b64encode(font.read_bytes()).decode() in css_text + assert 'url("data:,")' in css_text + assert str(parts[0]["Content-Location"]) == html["Content-Location"] + assert b"=?utf-8?" not in raw + + +def test_unarchived_remote_css_dependency_fails_explicitly(): + message = MIMEMultipart("related", type="text/html") + css = MIMEText('@font-face{src:url(https://example.invalid/font.woff2)}', "css", "utf-8") + css["Content-Location"] = "https://example.invalid/style.css" + message.attach(css) + with pytest.raises(ValueError, match="font.woff2"): + portable_archive(message.as_bytes()) diff --git a/tests/test_reliability.py b/tests/test_reliability.py new file mode 100644 index 0000000..4e1656b --- /dev/null +++ b/tests/test_reliability.py @@ -0,0 +1,249 @@ +from pathlib import Path +import re +from urllib.parse import unquote, urlsplit + +import pytest +from PySide6.QtCore import QSettings, QTimer +from PySide6.QtWidgets import QApplication, QFileDialog, QMessageBox, QPushButton, QTableWidget + +from mdhelper import main_window +from mdhelper.document_tree import DocumentEntry +from mdhelper.editor_assets import relocate_images, store_image +from mdhelper.markdown_editor import MarkdownEditorDialog +from mdhelper.markdown_renderer import MarkdownRenderer +from mdhelper.search import SearchIndex +from mdhelper.table_editor import edit_table, format_table, parse_tsv + + +@pytest.fixture +def editing(tmp_path, monkeypatch, qt_application): + settings = QSettings(str(tmp_path / "settings.ini"), QSettings.Format.IniFormat) + monkeypatch.setattr(main_window, "QSettings", lambda *args: settings) + monkeypatch.setenv("MDHELPER_HISTORY_DIR", str(tmp_path / "history")) + monkeypatch.setattr(QMessageBox, "warning", lambda *args: QMessageBox.StandardButton.Cancel) + monkeypatch.setattr(QMessageBox, "question", lambda *args: QMessageBox.StandardButton.Cancel) + path = tmp_path / "original.md" + path.write_text("# Original", encoding="utf-8") + window = main_window.MainWindow(None, app_root=Path(__file__).resolve().parents[1]) + window.open_document(path) + window.edit_current_markdown() + editor = window.tabs.currentWidget() + yield window, editor, path + monkeypatch.setattr(QMessageBox, "question", lambda *args: QMessageBox.StandardButton.Discard) + window.close() + window.deleteLater() + qt_application.processEvents() + + +@pytest.mark.parametrize("choice", ["Save", "Discard", "Cancel"]) +def test_close_protects_live_text_before_draft_timer(editing, monkeypatch, choice): + window, editor, path = editing + editor.replace_source_undoable("# Latest changes") + assert editor.draft_save_timer.isActive() + calls = [] + def decide(*args): + calls.append(args) + assert window.editor_drafts[str(path)]["source"] == "# Latest changes" + return getattr(QMessageBox.StandardButton, choice) + monkeypatch.setattr(QMessageBox, "question", decide) + assert window.close() == (choice != "Cancel") + assert len(calls) == 1 + assert path.read_text(encoding="utf-8") == ("# Latest changes" if choice == "Save" else "# Original") + assert (str(path) in window.editor_drafts) == (choice == "Cancel") + if choice != "Cancel": + assert not editor.draft_save_timer.isActive() + + +def test_failed_close_save_keeps_window_and_recoverable_draft(editing, monkeypatch): + window, editor, path = editing + editor.replace_source_undoable("not saved") + monkeypatch.setattr(QMessageBox, "question", lambda *args: QMessageBox.StandardButton.Save) + from mdhelper.file_versions import VersionStore + def fail(*args): + raise OSError("simulated disk failure") + monkeypatch.setattr(VersionStore, "save", fail) + assert not window.close() + assert editor.has_unsaved_changes() + assert window.editor_drafts[str(path)]["source"] == "not saved" + assert path.read_text() == "# Original" + + +def test_close_saves_background_editors_without_changing_active_document(editing, monkeypatch, tmp_path): + window, first, path = editing + first.replace_source_undoable("first changes") + second_path = tmp_path / "second.md" + second_path.write_text("second original", encoding="utf-8") + window.open_document(second_path, new_tab=True) + window.edit_current_markdown() + second = window.tabs.currentWidget() + second.replace_source_undoable("second changes") + monkeypatch.setattr(QMessageBox, "question", lambda *args: QMessageBox.StandardButton.Cancel) + assert not window.close() + assert set(window.editor_drafts) == {str(path), str(second_path)} + assert window._save_editor_tab(first, path, first.source_text(), first.file_signature) + assert window.current_file == second_path + monkeypatch.setattr(QMessageBox, "question", lambda *args: QMessageBox.StandardButton.Save) + assert window.close() + assert path.read_text() == "first changes" and second_path.read_text() == "second changes" + assert not window.editor_drafts + + +def test_close_does_not_recover_draft_that_user_already_undid(editing, monkeypatch): + window, editor, path = editing + editor.replace_source_undoable("undone edit") + editor._auto_save_draft() + editor.editor.undo() + assert not editor.has_unsaved_changes() + def no_prompt(*args): + pytest.fail("clean editor must not prompt") + monkeypatch.setattr(QMessageBox, "question", no_prompt) + assert window.close() + assert str(path) not in window.editor_drafts + + +def test_save_as_changes_draft_ownership_only_after_success(editing, monkeypatch, tmp_path): + window, editor, original = editing + target = tmp_path / "elsewhere" / "copy.md" + editor.replace_source_undoable("save as") + monkeypatch.setattr(QFileDialog, "getSaveFileName", lambda *args: (str(target), "Markdown")) + save = window.save_markdown_source + monkeypatch.setattr(window, "save_markdown_source", lambda *args, **kwargs: False) + editor._choose_save_as_path() + assert editor.path == original and editor.save_target_path == original + assert window.current_file == original and editor.has_unsaved_changes() + monkeypatch.setattr(window, "save_markdown_source", save) + editor._choose_save_as_path() + assert editor.path == target and not editor.has_unsaved_changes() + editor.replace_source_undoable("new draft for B") + editor._auto_save_draft() + assert set(window.editor_drafts) == {str(target)} + assert window.editor_drafts[str(target)]["source"] == "new draft for B" + assert original.read_text() == "# Original" + + +def test_save_recreates_externally_deleted_file(editing): + window, editor, path = editing + editor.replace_source_undoable("recovered") + path.unlink() + assert window._save_editor_tab(editor, path, editor.source_text(), editor.file_signature) + assert path.read_text() == "recovered" + + +def test_save_as_missing_image_keeps_original_context(editing, tmp_path): + window, editor, original = editing + source = "![missing](missing.png)" + editor.replace_source_undoable(source) + target = tmp_path / "elsewhere" / "copy.md" + assert not window._save_editor_tab(editor, target, source, editor.file_signature) + assert editor.path == original and editor.source_text() == source + assert editor.has_unsaved_changes() and not target.exists() + assert original.read_text() == "# Original" + + +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") + editor.replace_source_undoable(source) + target = tmp_path / "elsewhere" / "copy.md" + assert window._save_editor_tab(editor, target, source, editor.file_signature) + saved = target.read_text(encoding="utf-8") + url = re.search(r'\]\(([^)]+)\)', saved)[1] + assert (target.parent / unquote(url)).read_bytes() == b"image bytes" + assert editor.source_text() == saved and not editor.has_unsaved_changes() + editor.editor.undo() + assert editor.source_text() == source and editor.has_unsaved_changes() + + +def test_relocate_parsed_images_preserves_examples_and_titles(tmp_path): + original = tmp_path / "original.md" + target = tmp_path / "new folder" / "copy.md" + (tmp_path / "image (1).png").write_bytes(b"image") + source = '''![inline]( "Title") +![ref][picture] + +[picture]: "Reference title" + +`![code](missing.png)` and \\![escaped](missing.png) + +```md +![fenced](missing.png) +``` + + ![indented](missing.png) + +src="ignored.png" + +''' + moved = relocate_images(source, original, target) + assert '`![code](missing.png)`' in moved and '\\![escaped](missing.png)' in moved + assert '![fenced](missing.png)' in moved and ' ![indented](missing.png)' in moved + assert '[picture]: "Reference title"' in moved + assert '' in moved + assert '"Title"' in moved and '"Reference title"' in moved + tokens = MarkdownRenderer(tmp_path).markdown.parse(moved) + images = [c for t in tokens for c in t.children or [] if c.type == "image"] + assert len(images) == 2 + for image in images: + assert (target.parent / unquote(urlsplit(image.attrGet("src")).path)).read_bytes() == b"image" + assert len(list((target.parent / "copy.assets").iterdir())) == 1 + assert 'src="copy.assets/' in moved + + +@pytest.mark.parametrize("content", ["\n".join(["x"] * 1001), "\t".join(["x"] * 101)]) +def test_table_limit_is_explicit_and_keeps_existing_cells(content, monkeypatch): + with pytest.raises(ValueError): + parse_tsv(content) + warnings, states = [], [] + monkeypatch.setattr(QMessageBox, "warning", lambda *args: warnings.append(args[2])) + def paste(): + dialog = QApplication.activeModalWidget() + QApplication.clipboard().setText(content) + next(b for b in dialog.findChildren(QPushButton) if b.text() == "从 Excel 粘贴").click() + table = dialog.findChild(QTableWidget) + states.append((table.rowCount(), table.columnCount(), table.item(0, 0).text())) + dialog.accept() + QTimer.singleShot(0, paste) + rows = [["original", "value"], ["a", "b"]] + assert edit_table(None, rows) == format_table(rows, []) + assert warnings and states == [(2, 2, "original")] + + +def test_existing_large_table_is_not_opened_or_truncated(monkeypatch): + warnings = [] + monkeypatch.setattr(QMessageBox, "warning", lambda *args: warnings.append(args[2])) + assert edit_table(None, [["x"] * 101]) is None + assert warnings + assert parse_tsv("\n") == [[""]] + + +def test_find_conversion_visits_each_character_once(): + class CountingText(str): + examined = 0 + def __getitem__(self, key): + value = super().__getitem__(key) + if isinstance(key, slice): + self.examined += len(value) + return value + source = CountingText("😀xx中 " * 10000) + spans = MarkdownEditorDialog._qt_match_spans(source, re.finditer("x", source)) + assert spans[:4] == [(2, 3), (3, 4), (8, 9), (9, 10)] + assert len(spans) == 20000 and source.examined <= len(source) + + +def test_directory_filter_visits_each_entry_once_and_keeps_all_hits(tmp_path, monkeypatch): + entries = [DocumentEntry(tmp_path / f"{i}.md", "no title match", f"{i}.md") for i in range(150)] + index = SearchIndex(entries) + calls = [] + monkeypatch.setattr(index, "_body_for", lambda entry: calls.append(entry.path) or "needle") + visible, results = index.filter("needle") + assert len(visible) == 150 and len(results) == 80 + assert len(calls) == len(set(calls)) == 150 + calls.clear() + assert index.filter("") == ({e.path for e in entries}, []) + assert not calls + # A direct entry lookup must not iterate the full index either. + class NoIteration(list): + def __iter__(self): + raise AssertionError("quadratic lookup") + index._records = NoIteration(index._records) + assert index.matches_entry(entries[-1], "needle")