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"" + + +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)"), - ("图片", ""), ("提示", "> [!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("