diff --git a/docs/architecture.md b/docs/architecture.md index 6abe14a..e4b7e02 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -9,6 +9,14 @@ 控件模块导入时不创建窗口或浏览器。欢迎页不启动 WebEngine;首次显示阅读器时使用固定的 `ReaderTabHost`,页面准备好后才切换内容。拆分模块时必须保留控件的父子关系、创建时机和显示顺序,不通过重新创建主窗口或重新挂载已显示浏览器来刷新内容。 +## 文档、标签与资源 + +- `DocumentSession` 是编辑中文档路径、保存基准和磁盘签名的唯一来源;修改状态由当前文本与保存基准比较得出。Qt 标签属性只是界面适配数据。 +- `DocumentStore` 负责读取、文件签名和历史版本保存;`DraftStore` 负责草稿持久化。 +- `DocumentCloseController` 统一关闭标签、关闭项目和退出软件的保存 / 放弃 / 取消流程。`TabController` 只在确认成功后移除控件,保留阅读器复用逻辑。 +- `document_resources.py` 统一解析 Markdown 与 HTML 引用,提供 URL、源码位置及安全修改片段。文档检查、导出检查、文件监听和图片迁移共用该结果;代码和注释不作为资源引用。 +- 图片迁移先生成 `ImageRelocation` 计划,读取和验证全部资源,再复制文件并保存文档。保存成功后才更新文档会话。 + ## 验证约定 每个重构阶段独立提交。运行单元测试,并按改动范围运行 `gui_smoke.py`、`improvements_smoke.py` 和 `reliability_smoke.py`。涉及浏览器生命周期的调整必须检查欢迎页、首次打开文件、标签切换以及预览滚动;涉及保存的调整必须检查保存失败、取消、另存为和后台标签。 diff --git a/mdhelper/doc_check.py b/mdhelper/doc_check.py index 50411b2..c9ef26b 100644 --- a/mdhelper/doc_check.py +++ b/mdhelper/doc_check.py @@ -1,16 +1,9 @@ from __future__ import annotations import argparse -import re from dataclasses import dataclass from pathlib import Path -from urllib.parse import unquote, urlsplit -from urllib.request import url2pathname - - -EXTERNAL_SCHEMES = {"http", "https", "mailto", "tel", "data", "qrc"} -MARKDOWN_LINK_PATTERN = re.compile(r"!?\[[^\]]*]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)") -HTML_LINK_PATTERN = re.compile(r"""(?:src|href)=["']([^"']+)["']""", flags=re.IGNORECASE) +from .document_resources import analyze_document, resolve_local_reference @dataclass(frozen=True) @@ -49,7 +42,7 @@ def check_documents(project_root: Path) -> list[LinkIssue]: def check_markdown_file(markdown_path: Path) -> list[LinkIssue]: issues: list[LinkIssue] = [] try: - lines = markdown_path.read_text(encoding="utf-8").splitlines() + source = markdown_path.read_text(encoding="utf-8") except (OSError, UnicodeDecodeError) as error: return [ LinkIssue( @@ -61,42 +54,20 @@ def check_markdown_file(markdown_path: Path) -> list[LinkIssue]: ) ] - for line_number, line in enumerate(lines, start=1): - for target in _extract_targets(line): - resolved = _resolve_local_target(markdown_path, target) - if resolved is not None and not resolved.exists(): - issues.append( - LinkIssue( - source=markdown_path, - line_number=line_number, - target=target, - resolved_path=resolved, - message="本地目标不存在", - ) - ) + for reference in analyze_document(source).references: + resolved = resolve_local_reference(markdown_path, reference.url) + if resolved is not None and not resolved.exists(): + issues.append(LinkIssue(markdown_path, reference.line, reference.url, resolved, "本地目标不存在")) return issues -def _extract_targets(line: str) -> list[str]: - targets = MARKDOWN_LINK_PATTERN.findall(line) - targets.extend(HTML_LINK_PATTERN.findall(line)) - return [target.strip().strip("<>") for target in targets if target.strip()] +def _extract_targets(source: str) -> list[str]: + return [reference.url for reference in analyze_document(source).references] def _resolve_local_target(markdown_path: Path, target: str) -> Path | None: - parsed = urlsplit(target) - if parsed.scheme in EXTERNAL_SCHEMES or parsed.path.startswith("#"): - return None - if parsed.scheme and parsed.scheme != "file": - return None - if not parsed.path: - return None - - if parsed.scheme == "file": - return Path(url2pathname(unquote(parsed.path))).resolve() - - return (markdown_path.parent / unquote(parsed.path)).resolve() + return resolve_local_reference(markdown_path, target) def main(argv: list[str] | None = None) -> int: diff --git a/mdhelper/document_resources.py b/mdhelper/document_resources.py new file mode 100644 index 0000000..74a6518 --- /dev/null +++ b/mdhelper/document_resources.py @@ -0,0 +1,163 @@ +"""Shared Markdown/HTML resource discovery with source spans for safe editing.""" +from __future__ import annotations + +import bisect +import re +from dataclasses import dataclass +from html import escape, unescape +from html.parser import HTMLParser +from pathlib import Path +from urllib.parse import unquote, urlsplit +from urllib.request import url2pathname + + +@dataclass(frozen=True) +class SourceEdit: + start: int + end: int + text: str + + +@dataclass(frozen=True) +class ResourceReference: + url: str + line: int + image: bool + start: int + end: int + syntax: str = "markdown" + label: str = "" + title: str = "" + + def edit_url(self, url: str) -> SourceEdit: + if self.syntax == "html": + text = '"' + escape(url, quote=True) + '"' + elif self.syntax == "reference": + title = ' "' + self.title.replace("\\", "\\\\").replace('"', '\\"') + '"' if self.title else "" + text = self.label + "(" + url + title + ")" + else: + text = url + return SourceEdit(self.start, self.end, text) + + +@dataclass +class DocumentAnalysis: + tokens: list + references: list[ResourceReference] + + +def resolve_local_reference(document: Path, url: str) -> Path | None: + parsed = urlsplit(url) + if not parsed.path or parsed.scheme not in {"", "file"}: + return None + if parsed.scheme == "file": + return Path(url2pathname(("//" + parsed.netloc if parsed.netloc else "") + parsed.path)).resolve() + if parsed.netloc: + return None + return (document.parent / unquote(parsed.path)).resolve() + + +def apply_source_edits(source: str, edits: list[SourceEdit]) -> str: + pieces, offset = [], 0 + for edit in sorted(edits, key=lambda item: item.start): + if edit.start < offset: + raise ValueError("Overlapping source edits") + pieces.extend((source[offset:edit.start], edit.text)) + offset = edit.end + return "".join([*pieces, source[offset:]]) + + +class _HtmlReferences(HTMLParser): + def __init__(self, raw, offset, line_number, references): + super().__init__(convert_charrefs=False) + self.document_offset, self.line_number, self.references = offset, line_number, references + self.lines = [0] + [m.end() for m in re.finditer("\n", raw)] + self.feed(raw) + + def handle_starttag(self, tag, attrs): + raw = self.get_starttag_text() + tag_end = re.match(r"<\s*[^\s/>]+", raw).end() + pattern = r'''([^\s=<>/]+)(?:\s*=\s*("[^"]*"|'[^']*'|[^\s>]+))?''' + line, column = self.getpos() + offset = self.document_offset + self.lines[line - 1] + column + tag_end + for match in re.finditer(pattern, raw[tag_end:]): + name, value = match[1].lower(), match[2] + if name not in {"src", "href"} or value is None: + continue + quoted = value[:1] in {"'", '"'} + url = unescape(value[1:-1] if quoted else value) + self.references.append(ResourceReference(url, self.line_number + line - 1, tag == "img" and name == "src", + offset + match.start(2), offset + match.end(2), "html")) + + +class _ResourceScanner: + def __init__(self, source: str): + from .markdown_renderer import MarkdownRenderer + self.source = source + self.parser = MarkdownRenderer(Path.cwd()).markdown + self.env = {} + self.tokens = self.parser.parse(source, self.env) + self.offsets = [0] + for line in source.splitlines(keepends=True): + self.offsets.append(self.offsets[-1] + len(line)) + self.references: list[ResourceReference] = [] + + def line_at(self, offset: int) -> int: + return bisect.bisect_right(self.offsets, offset) + + def masked_source(self) -> str: + masked, excluded = list(self.source), [] + for token in self.tokens: + if token.map and token.type in {"fence", "code_block", "math_block", "html_block"}: + start, end = (self.offsets[n] for n in token.map) + if token.type == "html_block": + _HtmlReferences(self.source[start:end], start, self.line_at(start), self.references) + excluded.append((start, end)) + for ref in self.env.get("references", {}).values(): + excluded.append(tuple(self.offsets[n] for n in ref["map"])) + for start, end in excluded: + masked[start:end] = ["\n" if c == "\n" else " " for c in self.source[start:end]] + return "".join(masked) + + def capture_destination(self, state, start, token, image): + label_end = self.parser.helpers.parseLinkLabel(state, start + int(image), False) + pos = label_end + 1 + url, title = token.attrGet("src" if image else "href") or "", token.attrGet("title") or "" + if pos < len(self.source) and self.source[pos] == "(": + pos += 1 + while self.source[pos].isspace(): + pos += 1 + destination = self.parser.helpers.parseLinkDestination(self.source, pos, len(self.source)) + reference = ResourceReference(url, self.line_at(start), image, pos, destination.pos) + else: + reference = ResourceReference(url, self.line_at(start), image, start, state.pos, "reference", + self.source[start:label_end + 1], title) + self.references.append(reference) + + def scan(self) -> DocumentAnalysis: + from markdown_it.rules_inline import image, link, html_inline + inline_source = self.masked_source() + def capture(rule, is_image): + def parse(state, silent): + start, token_start = state.pos, len(state.tokens) + matched = rule(state, silent) + if matched and not silent and state.src is inline_source: + token = next(t for t in state.tokens[token_start:] if t.type == ("image" if is_image else "link_open")) + self.capture_destination(state, start, token, is_image) + return matched + return parse + def capture_html(state, silent): + start = state.pos + matched = html_inline(state, silent) + if matched and not silent and state.src is inline_source: + _HtmlReferences(self.source[start:state.pos], start, self.line_at(start), self.references) + return matched + self.parser.inline.ruler.at("image", capture(image, True)) + self.parser.inline.ruler.at("link", capture(link, False)) + self.parser.inline.ruler.at("html_inline", capture_html) + self.parser.inline.parse(inline_source, self.parser, self.env, []) + return DocumentAnalysis(self.tokens, sorted(self.references, key=lambda r: r.start)) + + +def analyze_document(source: str) -> DocumentAnalysis: + return _ResourceScanner(source).scan() diff --git a/mdhelper/document_session.py b/mdhelper/document_session.py new file mode 100644 index 0000000..19ed7d7 --- /dev/null +++ b/mdhelper/document_session.py @@ -0,0 +1,126 @@ +"""Document identity and persistence, independent of Qt widgets.""" +from __future__ import annotations + +import json +import time +from dataclasses import dataclass +from enum import Enum +from pathlib import Path +from typing import Callable, Protocol + +from .file_versions import VersionStore + +FileSignature = tuple[int, int] | None +DRAFTS_KEY = "editor/drafts" + + +@dataclass +class DocumentSession: + path: Path + saved_source: str + signature: FileSignature = None + + def is_modified(self, source: str) -> bool: + return source != self.saved_source + + def mark_saved(self, path: Path, source: str, signature: FileSignature) -> None: + self.path, self.saved_source, self.signature = path.resolve(), source, signature + + +class DocumentStore: + @staticmethod + def read(path: Path) -> str: + return path.read_text(encoding="utf-8") + + @staticmethod + def signature(path: Path) -> FileSignature: + try: + stat = path.stat() + return stat.st_mtime_ns, stat.st_size + except OSError: + return None + + @staticmethod + def prepare_save(source: str, original: Path, target: Path) -> str: + from .editor_assets import relocate_images + return relocate_images(source, original, target) + + @staticmethod + def save(path: Path, source: str) -> None: + VersionStore().save(path, source) + + +class DraftStore: + def __init__(self, settings, documents: DocumentStore): + self.settings, self.documents = settings, documents + self.entries: dict[str, dict] = {} + + def save(self, path: Path, source: str) -> None: + path = path.resolve() + try: + current = self.documents.read(path) + except (OSError, UnicodeError): + current = "" + if current == source: + self.clear(path) + return + signature = self.documents.signature(path) + self.entries[str(path)] = { + "source": source, "saved_at": time.strftime("%Y-%m-%d %H:%M:%S"), + "file_mtime_ns": signature[0] if signature else 0, + "file_size": signature[1] if signature else 0, + } + self._persist() + + def clear(self, path: Path) -> None: + self.entries.pop(str(path.resolve()), None) + self._persist() + + def _persist(self) -> None: + self.settings.setValue(DRAFTS_KEY, json.dumps(self.entries, ensure_ascii=False)) + + def sync(self) -> None: + self.settings.sync() + + +class CloseChoice(Enum): + SAVE = "save" + DISCARD = "discard" + CANCEL = "cancel" + + +class EditorDocument(Protocol): + session: DocumentSession + def source_text(self) -> str: ... + def stop_background_work(self) -> None: ... + + +class DocumentCloseController: + """One policy for closing a tab, a project, or the application.""" + def __init__(self, drafts: DraftStore, choose: Callable[[list[Path]], CloseChoice], + save: Callable[[EditorDocument], bool]): + self.drafts, self.choose, self.save = drafts, choose, save + + def confirm(self, editors: list[EditorDocument]) -> bool: + dirty = [] + for editor in editors: + if editor.session.is_modified(editor.source_text()): + dirty.append(editor) + self.drafts.save(editor.session.path, editor.source_text()) + else: + self.drafts.clear(editor.session.path) + self.drafts.sync() + if dirty: + choice = self.choose([editor.session.path for editor in dirty]) + if choice is CloseChoice.CANCEL: + return False + if choice is CloseChoice.SAVE: + for editor in dirty: + if not self.save(editor): + return False + else: + for editor in dirty: + self.drafts.clear(editor.session.path) + for editor in editors: + editor.stop_background_work() + return True diff --git a/mdhelper/editor_assets.py b/mdhelper/editor_assets.py index cccdf96..5e791a6 100644 --- a/mdhelper/editor_assets.py +++ b/mdhelper/editor_assets.py @@ -1,135 +1,22 @@ from __future__ import annotations import hashlib -import re -from html import escape, unescape -from html.parser import HTMLParser +from dataclasses import dataclass from pathlib import Path from urllib.parse import quote, unquote, urlsplit, urlunsplit from .file_versions import atomic_write +from .document_resources import analyze_document, apply_source_edits, resolve_local_reference 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()) + plan = plan_image_relocation(source, original, target) + for destination, data in plan.files.items(): 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) + return plan.source def store_image(document: Path, data: bytes, suffix: str = ".png", label: str = "图片") -> str: @@ -169,3 +56,31 @@ def image_markdown(mime: object, document: Path) -> str | None: raise ValueError("无法读取剪贴板图片") return store_image(document, bytes(buffer.data()), label="截图") return None + + +@dataclass +class ImageRelocation: + source: str + files: dict[Path, bytes] + + +def plan_image_relocation(source: str, original: Path, target: Path) -> ImageRelocation: + """Read/validate every image before writing any destination resource.""" + if original.resolve().parent == target.resolve().parent: + return ImageRelocation(source, {}) + files, edits, copied = {}, [], {} + for reference in analyze_document(source).references: + if not reference.image: + continue + parts = urlsplit(reference.url) + if not parts.path or parts.scheme or parts.netloc or Path(unquote(parts.path)).is_absolute(): + continue + if reference.url not in copied: + resource = resolve_local_reference(original, reference.url) + data = resource.read_bytes() + destination = target.parent / (target.stem + ".assets") / (hashlib.sha256(data).hexdigest()[:24] + resource.suffix.lower()) + files[destination] = data + relative = quote(destination.relative_to(target.parent).as_posix(), safe="/") + copied[reference.url] = urlunsplit(("", "", relative, parts.query, parts.fragment)) + edits.append(reference.edit_url(copied[reference.url])) + return ImageRelocation(apply_source_edits(source, edits), files) diff --git a/mdhelper/export_check.py b/mdhelper/export_check.py index 74a94b8..b73c052 100644 --- a/mdhelper/export_check.py +++ b/mdhelper/export_check.py @@ -4,8 +4,8 @@ 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 +from urllib.parse import urlsplit +from .document_resources import analyze_document, resolve_local_reference @dataclass(frozen=True) @@ -15,8 +15,6 @@ class ExportIssue: 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: @@ -32,12 +30,15 @@ def check_export(source: str, path: Path, kind: str, css_source: str = "") -> li 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(): + local = resolve_local_reference(path, value) + if local is not None and 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) + analysis = analyze_document(source) + for reference in analysis.references: + target(reference.url, reference.line, reference.image) + tokens = analysis.tokens list_depth = 0 for token in tokens: line = token.map[0] + 1 if token.map else 0 @@ -54,22 +55,12 @@ def check_export(source: str, path: Path, kind: str, css_source: str = "") -> li 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": + if 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 diff --git a/mdhelper/main_window.py b/mdhelper/main_window.py index d770ae8..00d48fc 100644 --- a/mdhelper/main_window.py +++ b/mdhelper/main_window.py @@ -56,6 +56,9 @@ from .style_sync import normalize_payload, render_css from .text_io import DEFAULT_TEXT_PREVIEW_BYTES, read_text_with_fallback from .startup_scan import StartupScan from .export_workflow import ExportWorkflow +from .document_session import DocumentStore, DraftStore, DocumentCloseController, CloseChoice +from .document_resources import analyze_document, resolve_local_reference +from .tab_controller import TabController, document_path from .reader_widgets import ReaderPage, ReaderBridge, ReaderView, ReaderTabHost, CompactTreeDelegate from .video_player import VideoPlayerWidget from .ui_theme import navigation_theme, apply_title_bar_style @@ -204,9 +207,7 @@ LEGACY_THEME_BACKGROUND_VALUES = { def re_find_markdown_links(source: str) -> list[str]: - markdown_targets = re.findall(r"!?\[[^\]]*]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)", source) - html_targets = re.findall(r"""(?:src|href)=["']([^"']+)["']""", source, flags=re.IGNORECASE) - return markdown_targets + html_targets + return [reference.url for reference in analyze_document(source).references] @@ -245,6 +246,9 @@ class MainWindow(ExportWorkflow, QMainWindow): self._startup_initial_path = initial_path self._startup_prompt = prompt_for_project self.settings = QSettings("MDHelper", "MDHelper") + self.documents = DocumentStore() + self.drafts = DraftStore(self.settings, self.documents) + self.document_closer = DocumentCloseController(self.drafts, self._choose_editor_close, lambda editor: self._save_editor_tab(editor, editor.path, editor.source_text(), editor.file_signature)) self.document_file_groups = DEFAULT_DOCUMENT_FILE_GROUPS self.renderer = MarkdownRenderer(self.project_root) self.entries: list[DocumentEntry] = [] @@ -330,6 +334,7 @@ class MainWindow(ExportWorkflow, QMainWindow): if app is not None: app.setWindowIcon(icon) self._build_ui() + self.tab_controller = TabController(self.tabs, self.document_closer.confirm, self._release_tab_widget, self._ensure_welcome_if_empty, self._on_tab_changed) self.scroll_capture_timer.start() self._populate_tree() if not self._restore_window_state(): @@ -1370,7 +1375,7 @@ class MainWindow(ExportWorkflow, QMainWindow): return if isinstance(widget, RichMarkdownEditorDialog): - file_value = widget.property("current_file") or str(widget.save_target_path) + file_value = widget.session.path self.current_file = Path(str(file_value)).resolve() self.current_fragment = "" self.setWindowTitle(f"{self.current_file.name} - MDHelper") @@ -1380,7 +1385,7 @@ class MainWindow(ExportWorkflow, QMainWindow): return if isinstance(widget, VideoPlayerWidget): - file_value = widget.property("current_file") or str(widget.path) + file_value = document_path(widget) or str(widget.path) self.current_file = Path(str(file_value)).resolve() self.current_fragment = "" self.setWindowTitle(f"{self.current_file.name} - MDHelper") @@ -1419,27 +1424,10 @@ class MainWindow(ExportWorkflow, QMainWindow): return widget is not None and not bool(widget.property("is_welcome")) def _close_tab_indexes(self, indexes: list[int], show_welcome: bool = True) -> bool: - target_indexes = sorted({index for index in indexes if self._is_content_tab_index(index)}, reverse=True) - if not target_indexes: - if show_welcome: - self._ensure_welcome_if_empty() - return True - - for index in target_indexes: - widget = self.tabs.widget(index) - if isinstance(widget, RichMarkdownEditorDialog) and not widget.confirm_close(): - return False - - for index in target_indexes: - widget = self.tabs.widget(index) - self.tabs.removeTab(index) - self._release_tab_widget(widget) - - if show_welcome: - self._ensure_welcome_if_empty() - if self.tabs.count() > 0: - self._on_tab_changed(self.tabs.currentIndex()) - else: + indexes = [i for i in indexes if self._is_content_tab_index(i)] + if not self.tab_controller.close(indexes, show_welcome=show_welcome): + return False + if not self.tabs.count(): self.current_file = None self.current_fragment = "" self._update_actions() @@ -1481,15 +1469,8 @@ class MainWindow(ExportWorkflow, QMainWindow): menu.exec(tab_bar.mapToGlobal(position)) def _close_all_tabs(self, show_welcome: bool = True) -> bool: - for index in range(self.tabs.count() - 1, -1, -1): - widget = self.tabs.widget(index) - if isinstance(widget, RichMarkdownEditorDialog) and not widget.confirm_close(): - return False - - for index in range(self.tabs.count() - 1, -1, -1): - widget = self.tabs.widget(index) - self.tabs.removeTab(index) - self._release_tab_widget(widget) + if not self.tab_controller.close(list(range(self.tabs.count())), show_welcome=False): + return False self.current_file = None self.current_fragment = "" @@ -1502,12 +1483,7 @@ class MainWindow(ExportWorkflow, QMainWindow): self._ensure_welcome_if_empty() return True def _close_tab(self, index: int) -> None: - widget = self.tabs.widget(index) - if isinstance(widget, RichMarkdownEditorDialog) and not widget.confirm_close(): - return - self.tabs.removeTab(index) - self._release_tab_widget(widget) - self._ensure_welcome_if_empty() + self._close_tab_indexes([index]) def _render_local_file_page(self, path: Path) -> str: title = html.escape(path.name) @@ -2105,7 +2081,7 @@ class MainWindow(ExportWorkflow, QMainWindow): ) 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.close_confirmation = self.document_closer.confirm editor.editor.textChanged.connect(lambda widget=editor: self._on_editor_content_changed(widget)) editor.save_requested.connect(lambda target, text, signature, widget=editor: self._save_editor_tab(widget, Path(target), text, signature)) editor.close_requested.connect(lambda widget=editor: self._close_editor_tab(widget)) @@ -2143,8 +2119,7 @@ class MainWindow(ExportWorkflow, QMainWindow): source: str, expected_signature: tuple[int, int] | 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() + original_path = editor.session.path target_path = target_path.resolve() try: unchanged = target_path == original_path and source == self._read_markdown_source(original_path) @@ -2158,8 +2133,7 @@ class MainWindow(ExportWorkflow, QMainWindow): if target_path.parent != original_path.parent: try: - from .editor_assets import relocate_images - source = relocate_images(source, original_path, target_path) + source = self.documents.prepare_save(source, original_path, target_path) except (OSError, ValueError) as exc: QMessageBox.warning(self, "保存失败", f"无法复制文档图片:\n{exc}") return False @@ -2175,7 +2149,6 @@ class MainWindow(ExportWorkflow, QMainWindow): 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()) if self.tabs.currentWidget() is editor: @@ -2190,7 +2163,7 @@ class MainWindow(ExportWorkflow, QMainWindow): self._close_tab(index) def _read_markdown_source(self, path: Path) -> str: - return path.read_text(encoding="utf-8") + return self.documents.read(path) def _source_with_recovered_draft(self, path: Path, source: str) -> str: draft = self.editor_drafts.get(str(path.resolve())) @@ -2214,36 +2187,13 @@ class MainWindow(ExportWorkflow, QMainWindow): return source def _file_signature(self, path: Path) -> tuple[int, int] | None: - try: - stat = path.stat() - except OSError: - return None - return stat.st_mtime_ns, stat.st_size + return DocumentStore.signature(path) def _save_editor_draft(self, path: Path, source: str) -> None: - path = path.resolve() - try: - current_source = path.read_text(encoding="utf-8") - except (OSError, UnicodeDecodeError): - current_source = "" - - if source == current_source: - self._clear_editor_draft(path) - return - - signature = self._file_signature(path) - self.editor_drafts[str(path)] = { - "source": source, - "saved_at": time.strftime("%Y-%m-%d %H:%M:%S"), - "file_mtime_ns": signature[0] if signature else 0, - "file_size": signature[1] if signature else 0, - } - self.settings.setValue(EDITOR_DRAFTS_SETTING_KEY, json.dumps(self.editor_drafts, ensure_ascii=False)) - LOGGER.info("Markdown draft saved: %s", path) + self.drafts.save(path, source) def _clear_editor_draft(self, path: Path) -> None: - self.editor_drafts.pop(str(path.resolve()), None) - self.settings.setValue(EDITOR_DRAFTS_SETTING_KEY, json.dumps(self.editor_drafts, ensure_ascii=False)) + self.drafts.clear(path) def save_markdown_source( self, @@ -2272,8 +2222,7 @@ class MainWindow(ExportWorkflow, QMainWindow): self.internal_save_paths.add(path) try: - from .file_versions import VersionStore - VersionStore().save(path, source) + self.documents.save(path, source) except OSError as exc: self.internal_save_paths.discard(path) LOGGER.exception("Failed to save Markdown source: %s", path) @@ -3619,7 +3568,7 @@ class MainWindow(ExportWorkflow, QMainWindow): path = path.resolve() for index in range(self.tabs.count()): widget = self.tabs.widget(index) - file_value = widget.property("current_file") if widget is not None else None + file_value = document_path(widget) if widget is not None else None if not file_value: continue try: @@ -3729,7 +3678,7 @@ class MainWindow(ExportWorkflow, QMainWindow): indexes: list[int] = [] for index in range(self.tabs.count()): widget = self.tabs.widget(index) - file_value = widget.property("current_file") if widget is not None else None + file_value = document_path(widget) if widget is not None else None if not file_value: continue try: @@ -3747,7 +3696,7 @@ class MainWindow(ExportWorkflow, QMainWindow): paths: set[Path] = set() for index in range(self.tabs.count()): widget = self.tabs.widget(index) - file_value = widget.property("current_file") if widget is not None else None + file_value = document_path(widget) if widget is not None else None if not file_value: continue try: @@ -4422,7 +4371,7 @@ class MainWindow(ExportWorkflow, QMainWindow): widget = self.tabs.widget(index) if widget is None or bool(widget.property("is_welcome")): continue - file_value = widget.property("current_file") + file_value = document_path(widget) if not file_value: continue try: @@ -4506,19 +4455,11 @@ class MainWindow(ExportWorkflow, QMainWindow): def _referenced_local_paths(self, markdown_path: Path) -> set[Path]: try: source = markdown_path.read_text(encoding="utf-8") - except (OSError, UnicodeDecodeError): + except (OSError, UnicodeError): return set() - - paths: set[Path] = set() - for match in re_find_markdown_links(source): - target = match.strip() - parsed = urlsplit(target) - if parsed.scheme or not parsed.path or parsed.path.startswith("#"): - continue - local_path = (markdown_path.parent / unquote(parsed.path)).resolve() - if local_path.exists() and local_path.is_file(): - paths.add(local_path) - return paths + paths = {resolve_local_reference(markdown_path, reference.url) + for reference in analyze_document(source).references} + return {path for path in paths if path is not None and path.is_file()} def _on_watched_file_changed(self, changed_path: str) -> None: if not self.auto_refresh_enabled or self.auto_refresh_mode == "off": @@ -4657,37 +4598,25 @@ class MainWindow(ExportWorkflow, QMainWindow): self._save_preferences() super().closeEvent(event) + @property + def editor_drafts(self) -> dict: + return self.drafts.entries + + @editor_drafts.setter + def editor_drafts(self, entries: dict) -> None: + self.drafts.entries = entries + + def _choose_editor_close(self, paths: list[Path]) -> CloseChoice: + names = "\n".join(path.name for path in paths) + choice = QMessageBox.question(self, "保存修改?", f"以下文档有未保存的修改:\n\n{names}", + QMessageBox.StandardButton.Save | QMessageBox.StandardButton.Discard | QMessageBox.StandardButton.Cancel, + QMessageBox.StandardButton.Save) + return {QMessageBox.StandardButton.Save: CloseChoice.SAVE, + QMessageBox.StandardButton.Discard: CloseChoice.DISCARD}.get(choice, CloseChoice.CANCEL) + 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 + return self.document_closer.confirm([self.tabs.widget(i) for i in range(self.tabs.count()) + if isinstance(self.tabs.widget(i), RichMarkdownEditorDialog)]) def showEvent(self, event: QShowEvent) -> None: super().showEvent(event) diff --git a/mdhelper/markdown_editor.py b/mdhelper/markdown_editor.py index 652592c..579f143 100644 --- a/mdhelper/markdown_editor.py +++ b/mdhelper/markdown_editor.py @@ -1,4 +1,5 @@ from __future__ import annotations +from .document_session import DocumentSession import os import json @@ -277,8 +278,8 @@ class MarkdownEditorDialog(QDialog): self.embedded = embedded if embedded: self.setWindowFlag(Qt.WindowType.Widget, True) - self.path = path - self.save_target_path = path + self.session = DocumentSession(path.resolve(), source if original_source is None else original_source, file_signature) + self._save_as_target: Path | None = None self.renderer = renderer self.theme = theme self.font_scale = font_scale @@ -287,7 +288,6 @@ class MarkdownEditorDialog(QDialog): self.document_width_scale = document_width_scale self.document_style_css = document_style_css self.math_engine = math_engine - self.file_signature = file_signature self.draft_callback = draft_callback self._preview_dirty = True self._preview_scroll_y = 0 @@ -297,7 +297,6 @@ class MarkdownEditorDialog(QDialog): self._current_match_index = -1 self.setWindowTitle(f"编辑 Markdown - {path.name}") self.setMinimumSize(1120, 720) - self._original_source = source if original_source is None else original_source layout = QVBoxLayout(self) layout.setContentsMargins(12, 12, 12, 12) @@ -440,11 +439,31 @@ class MarkdownEditorDialog(QDialog): self._rebuild_find_matches() self._apply_view_mode() + @property + def path(self) -> Path: + return self.session.path + + @property + def file_signature(self): + return self.session.signature + + @property + def save_target_path(self) -> Path: + return self._save_as_target or self.session.path + + @save_target_path.setter + def save_target_path(self, path: Path) -> None: + self._save_as_target = path + + def stop_background_work(self) -> None: + self.draft_save_timer.stop() + self.preview_refresh_timer.stop() + def source_text(self) -> str: return self.editor.toPlainText() def has_unsaved_changes(self) -> bool: - return self.source_text() != self._original_source + return self.session.is_modified(self.source_text()) def apply_theme(self, dark: bool) -> None: self.editor.apply_theme(dark) @@ -1008,17 +1027,17 @@ class MarkdownEditorDialog(QDialog): self.save_requested.emit(self.save_target_path, self.source_text(), self.file_signature) def mark_saved(self, path: Path, source: str, file_signature: tuple[int, int] | None) -> None: - self.path = path - self.save_target_path = path - self.file_signature = file_signature + self.session.mark_saved(path, source, file_signature) + self._save_as_target = None 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: + if self.embedded and callable(getattr(self, "close_confirmation", None)): + return self.close_confirmation([self]) if not self.has_unsaved_changes(): return True choice = QMessageBox.question( diff --git a/mdhelper/tab_controller.py b/mdhelper/tab_controller.py new file mode 100644 index 0000000..7ff7cb5 --- /dev/null +++ b/mdhelper/tab_controller.py @@ -0,0 +1,31 @@ +"""Tab ownership and close orchestration; never recreates a browser widget.""" +from __future__ import annotations +from pathlib import Path + + +def document_path(widget) -> Path | None: + if widget is None or bool(widget.property("is_welcome")): + return None + session = getattr(widget, "session", None) + value = session.path if session is not None else widget.property("current_file") + return Path(str(value)).resolve() if value else None + + +class TabController: + def __init__(self, tabs, confirm, release, show_welcome, changed): + self.tabs, self.confirm, self.release = tabs, confirm, release + self.show_welcome, self.changed = show_welcome, changed + + def close(self, indexes: list[int], *, show_welcome=True) -> bool: + widgets = [self.tabs.widget(i) for i in sorted(set(indexes), reverse=True) + if 0 <= i < self.tabs.count()] + if not self.confirm([widget for widget in widgets if hasattr(widget, "session")]): + return False + for widget in widgets: + self.tabs.removeTab(self.tabs.indexOf(widget)) + self.release(widget) + if show_welcome: + self.show_welcome() + if self.tabs.count(): + self.changed(self.tabs.currentIndex()) + return True diff --git a/tests/test_document_resources.py b/tests/test_document_resources.py new file mode 100644 index 0000000..68dfc50 --- /dev/null +++ b/tests/test_document_resources.py @@ -0,0 +1,45 @@ +from pathlib import Path + +from mdhelper.doc_check import check_markdown_file +from mdhelper.document_resources import analyze_document, apply_source_edits, resolve_local_reference +from mdhelper.editor_assets import plan_image_relocation +from mdhelper.export_check import check_export +from mdhelper.main_window import MainWindow + + +def test_resource_consumers_agree_on_examples_and_references(tmp_path): + path = tmp_path / "note.md" + source = '```md\n![example](missing-code.png)\n```\n\n![real][picture]\n\n[picture]: real.png\n' + path.write_text(source, encoding="utf-8") + (tmp_path / "real.png").write_bytes(b"image") + assert [(r.url, r.line) for r in analyze_document(source).references] == [("real.png", 5)] + assert check_markdown_file(path) == [] + assert check_export(source, path, "html") == [] + assert MainWindow._referenced_local_paths(None, path) == {tmp_path / "real.png"} + + +def test_images_inside_links_and_html_attributes_have_correct_spans(tmp_path): + source = '[![alt](image.png "title")](guide.md)\n\n\'src="fake.png"\'\n' + references = analyze_document(source).references + assert [(r.url, r.image) for r in references] == [("image.png", True), ("guide.md", False), ("real.png", True)] + edits = [r.edit_url("new.png") for r in references if r.image] + assert apply_source_edits(source, edits) == source.replace('](image.png', '](new.png').replace('src="real.png"','src="new.png"') + + +def test_relocation_plan_does_not_write_before_all_resources_validate(tmp_path): + original, target = tmp_path / "original.md", tmp_path / "new" / "copy.md" + (tmp_path / "one.png").write_bytes(b"image") + import pytest + with pytest.raises(OSError): + plan_image_relocation('![one](one.png)\n![missing](missing.png)', original, target) + assert not target.parent.exists() + plan = plan_image_relocation('![one](one.png)', original, target) + assert plan.files and not target.parent.exists() + + +def test_file_url_and_encoded_relative_path_resolve_once(tmp_path): + path = tmp_path / "note.md" + asset = tmp_path / "100%20图片.png" + assert resolve_local_reference(path, asset.as_uri()) == asset + assert resolve_local_reference(path, "100%2520%E5%9B%BE%E7%89%87.png") == asset + assert resolve_local_reference(path, "https://example.com/image.png") is None diff --git a/tests/test_reliability.py b/tests/test_reliability.py index 4e1656b..62dbf50 100644 --- a/tests/test_reliability.py +++ b/tests/test_reliability.py @@ -101,6 +101,22 @@ def test_close_does_not_recover_draft_that_user_already_undid(editing, monkeypat assert str(path) not in window.editor_drafts +@pytest.mark.parametrize("operation", ["tab", "all", "project"]) +def test_all_close_routes_use_save_discard_cancel(editing, monkeypatch, operation): + window, editor, path = editing + editor.replace_source_undoable("pending changes") + actions = {"tab": lambda: window._close_tab(window.tabs.indexOf(editor)), + "all": window._close_all_tabs, "project": window.close_project_folder} + monkeypatch.setattr(QMessageBox, "question", lambda *args: QMessageBox.StandardButton.Cancel) + actions[operation]() + assert window.tabs.indexOf(editor) >= 0 and path.read_text() == "# Original" + assert window.editor_drafts[str(path)]["source"] == "pending changes" + monkeypatch.setattr(QMessageBox, "question", lambda *args: QMessageBox.StandardButton.Save) + actions[operation]() + assert window.tabs.indexOf(editor) == -1 and path.read_text() == "pending changes" + assert not 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"