diff --git a/docs/architecture.md b/docs/architecture.md index 0fd4153..96401bf 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -27,6 +27,10 @@ `preferences.py` 定义 `ReaderPreferences` 和 `ApplicationConfiguration`。本地设置与 JSON 导入共用字段、取值检查和旧版迁移规则;`ConfigurationStore` 负责持久化。页面设置保留旧版 PDF 页边距的读取方式。窗口几何状态和草稿仍由各自的界面、文档组件管理。内置文档样式集中在 `style_presets.py`。 +## 编辑器边界 + +`markdown_editor.py` 组装编辑界面并连接文档会话。`editor_widgets.py` 负责源码控件、行号和语法高亮;`EditorFindController` 管理查找位置及可撤销替换;`EditorPreviewController` 管理预览刷新、滚动映射、桥接信号和计时器。预览控制器接收明确的控件与渲染回调,不读取主窗口或文档存储。关闭编辑器时同时停止预览刷新与滚动计时器。 + ## 验证约定 每个重构阶段独立提交。运行单元测试,并按改动范围运行 `gui_smoke.py`、`improvements_smoke.py` 和 `reliability_smoke.py`。涉及浏览器生命周期的调整必须检查欢迎页、首次打开文件、标签切换以及预览滚动;涉及保存的调整必须检查保存失败、取消、另存为和后台标签。 diff --git a/mdhelper/editor_find.py b/mdhelper/editor_find.py new file mode 100644 index 0000000..6b24b66 --- /dev/null +++ b/mdhelper/editor_find.py @@ -0,0 +1,134 @@ +"""Find/replace state and UTF-16 cursor positions, independent of the dialog.""" +from __future__ import annotations +import re +from PySide6.QtGui import QTextCursor +from PySide6.QtWidgets import QPlainTextEdit, QLineEdit, QCheckBox, QLabel + + +class EditorFindController: + def __init__(self, editor: QPlainTextEdit, query: QLineEdit, replacement: QLineEdit, + match_case: QCheckBox, whole_word: QCheckBox, status: QLabel): + self.editor = editor + self.editor_find_box, self.editor_replace_box = query, replacement + self.match_case_checkbox, self.whole_word_checkbox = match_case, whole_word + self.find_status_label = status + self._match_positions: list[int] = [] + self._current_match_index = -1 + + def _rebuild_find_matches(self) -> None: + query = self.editor_find_box.text() + self._match_positions = [] + self._current_match_index = -1 + if not query: + self.find_status_label.setText("0/0") + return + + text = self.editor.toPlainText() + flags = 0 if self.match_case_checkbox.isChecked() else re.IGNORECASE + pattern = re.escape(query) + if self.whole_word_checkbox.isChecked(): + pattern = r"\b" + pattern + r"\b" + 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: + self._current_match_index = index - 1 + break + else: + self._current_match_index = len(self._match_positions) - 1 + self._update_find_status() + + + def _select_match(self, index: int) -> None: + if not self._match_positions: + self._update_find_status() + return + self._current_match_index = index % len(self._match_positions) + query = self.editor_find_box.text() + cursor = self.editor.textCursor() + cursor.setPosition(self._match_positions[self._current_match_index]) + cursor.setPosition(cursor.position() + self._qt_position(query, len(query)), QTextCursor.MoveMode.KeepAnchor) + self.editor.setTextCursor(cursor) + self.editor.ensureCursorVisible() + self._update_find_status() + + + def _update_find_status(self) -> None: + total = len(self._match_positions) + current = self._current_match_index + 1 if total and self._current_match_index >= 0 else 0 + self.find_status_label.setText(f"{current}/{total}") + + + def find_next_in_editor(self) -> None: + if not self.editor_find_box.text(): + return + if not self._match_positions: + self._rebuild_find_matches() + if self._match_positions: + self._select_match(self._current_match_index + 1) + + + def find_previous_in_editor(self) -> None: + if not self.editor_find_box.text(): + return + if not self._match_positions: + self._rebuild_find_matches() + if self._match_positions: + self._select_match(self._current_match_index - 1) + + + def replace_current_in_editor(self) -> None: + query = self.editor_find_box.text() + if not query: + return + + cursor = self.editor.textCursor() + selected = cursor.selectedText().replace("\u2029", "\n") + matches = selected == query if self.match_case_checkbox.isChecked() else selected.lower() == query.lower() + if cursor.hasSelection() and matches: + cursor.insertText(self.editor_replace_box.text()) + self._rebuild_find_matches() + return + self.find_next_in_editor() + + + def replace_all_in_editor(self) -> None: + query = self.editor_find_box.text() + if not query: + return + + replacement = self.editor_replace_box.text() + flags = 0 if self.match_case_checkbox.isChecked() else re.IGNORECASE + pattern = re.escape(query) + if self.whole_word_checkbox.isChecked(): + pattern = r"\b" + pattern + r"\b" + source = self.editor.toPlainText() + 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 + + diff --git a/mdhelper/editor_preview.py b/mdhelper/editor_preview.py new file mode 100644 index 0000000..bf18708 --- /dev/null +++ b/mdhelper/editor_preview.py @@ -0,0 +1,207 @@ +"""Own preview refresh, scroll mapping, and their timers without owning a window.""" +from __future__ import annotations +import json +from collections.abc import Callable +from PySide6.QtCore import QObject, QTimer, QUrl, Slot +from PySide6.QtWebChannel import QWebChannel +from PySide6.QtWebEngineWidgets import QWebEngineView +from PySide6.QtWidgets import QPlainTextEdit, QComboBox, QCheckBox +from shiboken6 import isValid + +class PreviewScrollBridge(QObject): + @Slot(float) + def sourceLine(self, line: float) -> None: + self.parent()._sync_source_to_preview_line(line) + + +class EditorPreviewController(QObject): + def __init__(self, parent: QObject, editor: QPlainTextEdit, preview: QWebEngineView, + mode: QComboBox, sync: QCheckBox, render: Callable[[], tuple[str, QUrl]]): + super().__init__(parent) + self.editor, self.preview = editor, preview + self.view_mode_box, self.sync_scroll_checkbox = mode, sync + self.render = render + self._preview_dirty = True + self._preview_scroll_y = 0 + self._preview_scroll_ratio = 0.0 + self._syncing_scroll = False + self.preview_refresh_timer = QTimer(self) + self.preview_refresh_timer.setSingleShot(True) + self.preview_refresh_timer.setInterval(350) + self.preview_refresh_timer.timeout.connect(self._refresh_preview_with_scroll_capture) + 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) + editor.verticalScrollBar().valueChanged.connect(self._sync_preview_to_editor_scroll) + self.channel = QWebChannel(preview.page()) + self.bridge = PreviewScrollBridge(self) + self.channel.registerObject('mdhelperEditor', self.bridge) + preview.page().setWebChannel(self.channel) + preview.loadFinished.connect(self._restore_preview_scroll) + + def stop(self) -> None: + self.preview_refresh_timer.stop() + self.scroll_sync_timer.stop() + + def _apply_view_mode(self) -> None: + mode = str(self.view_mode_box.currentData() or "source") + self.editor.setVisible(mode in {"source", "split"}) + self.preview.setVisible(mode in {"preview", "split"}) + if mode in {"preview", "split"} and self._preview_dirty: + self._refresh_preview_now() + 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: + self._preview_dirty = True + mode = str(self.view_mode_box.currentData() or "source") + if mode in {"preview", "split"}: + self.preview_refresh_timer.start() + + + def _refresh_preview_with_scroll_capture(self) -> None: + mode = str(self.view_mode_box.currentData() or "source") + if mode == "split" and self.sync_scroll_checkbox.isChecked(): + self._preview_scroll_ratio = self._editor_scroll_ratio() + self._refresh_preview_now() + return + self.preview.page().runJavaScript("Math.max(0, window.scrollY || 0)", self._store_scroll_and_refresh_preview) + + + def _store_scroll_and_refresh_preview(self, scroll_y: object) -> None: + if not isValid(self) or not isValid(self.preview): + return + try: + self._preview_scroll_y = max(0, int(float(scroll_y or 0))) + except (TypeError, ValueError): + self._preview_scroll_y = 0 + self._refresh_preview_now() + + + def _refresh_preview_now(self) -> None: + if not isValid(self) or not isValid(self.preview): + return + html, base_url = self.render() + self.preview.setHtml(html, base_url) + self._preview_dirty = False + + def _restore_preview_scroll(self, ok: bool) -> None: + if not ok: + return + 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'}}); }})();" + self.preview.page().runJavaScript(script) + + + def _editor_scroll_ratio(self) -> float: + maximum = max(1, self.editor.verticalScrollBar().maximum()) + return max(0.0, min(1.0, self.editor.verticalScrollBar().value() / maximum)) + + + def _sync_preview_to_editor_scroll(self, value: int) -> None: + del value + 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_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): + return + script = ( + "(() => {" + "const ratio = %0.6f;" + "const maxY = Math.max(0, document.documentElement.scrollHeight - window.innerHeight);" + "window.scrollTo({top: Math.round(maxY * ratio), behavior: 'instant'});" + "})();" + % ratio + ) + self._syncing_scroll = True + self.preview.page().runJavaScript(script, lambda result=None: self._clear_scroll_sync()) + + + def _clear_scroll_sync(self) -> None: + self._syncing_scroll = False + + + def _scroll_preview_to_heading(self, slug: str) -> None: + if not isValid(self) or not isValid(self.preview): + return + script = ( + "(() => {" + "const id = " + f"{json.dumps(slug)}" + ";" + "const selector = window.CSS && CSS.escape ? `[id=\"${CSS.escape(id)}\"]` : '';" + "const target = document.getElementById(id) || (selector ? document.querySelector(selector) : null);" + "if (target) {" + " target.scrollIntoView({block: 'start', behavior: 'auto'});" + " const scroller = document.scrollingElement || document.documentElement || document.body;" + " scroller.scrollTop = Math.max(0, scroller.scrollTop - 12);" + "}" + "})();" + ) + self.preview.page().runJavaScript(script) + + diff --git a/mdhelper/editor_widgets.py b/mdhelper/editor_widgets.py new file mode 100644 index 0000000..8ecac16 --- /dev/null +++ b/mdhelper/editor_widgets.py @@ -0,0 +1,195 @@ +"""Reusable Markdown source widgets; no document or browser lifecycle.""" +from __future__ import annotations +import re +from PySide6.QtCore import QRect, QSize, Qt +from PySide6.QtGui import QColor, QFont, QPainter, QSyntaxHighlighter, QTextCharFormat, QTextFormat +from PySide6.QtWidgets import QPlainTextEdit, QTextEdit, QWidget + +class LineNumberArea(QWidget): + def __init__(self, editor: "MarkdownSourceEditor") -> None: + super().__init__(editor) + self.editor = editor + + def sizeHint(self) -> QSize: + return QSize(self.editor.line_number_area_width(), 0) + + def paintEvent(self, event: object) -> None: + self.editor.line_number_area_paint_event(event) + + +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") + self.line_number_area = LineNumberArea(self) + self.blockCountChanged.connect(self.update_line_number_area_width) + self.updateRequest.connect(self.update_line_number_area) + self.cursorPositionChanged.connect(self.highlight_current_line) + 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") + self.line_number_foreground = QColor("#8b949e") + self.current_line_background = QColor("#273447") + self.setStyleSheet( + "QPlainTextEdit { background: #1f242b; color: #dbe2ea; " + "selection-background-color: #2f6feb; selection-color: #ffffff; }" + ) + else: + self.line_number_background = QColor("#f3f5f8") + self.line_number_foreground = QColor("#7a8494") + self.current_line_background = QColor("#edf4ff") + self.setStyleSheet("") + self.line_number_area.update() + self.highlight_current_line() + + def line_number_area_width(self) -> int: + digits = max(2, len(str(max(1, self.blockCount())))) + return 12 + self.fontMetrics().horizontalAdvance("9") * digits + + def update_line_number_area_width(self, new_block_count: int) -> None: + del new_block_count + self.setViewportMargins(self.line_number_area_width(), 0, 0, 0) + + def update_line_number_area(self, rect: QRect, dy: int) -> None: + if dy: + self.line_number_area.scroll(0, dy) + else: + self.line_number_area.update(0, rect.y(), self.line_number_area.width(), rect.height()) + + if rect.contains(self.viewport().rect()): + self.update_line_number_area_width(0) + + def resizeEvent(self, event: object) -> None: + super().resizeEvent(event) + content_rect = self.contentsRect() + self.line_number_area.setGeometry( + QRect(content_rect.left(), content_rect.top(), self.line_number_area_width(), content_rect.height()) + ) + + def line_number_area_paint_event(self, event: object) -> None: + painter = QPainter(self.line_number_area) + painter.fillRect(event.rect(), self.line_number_background) + + block = self.firstVisibleBlock() + block_number = block.blockNumber() + top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top()) + bottom = top + int(self.blockBoundingRect(block).height()) + + while block.isValid() and top <= event.rect().bottom(): + if block.isVisible() and bottom >= event.rect().top(): + painter.setPen(self.line_number_foreground) + painter.drawText( + 0, + top, + self.line_number_area.width() - 6, + self.fontMetrics().height(), + Qt.AlignmentFlag.AlignRight, + str(block_number + 1), + ) + + block = block.next() + top = bottom + bottom = top + int(self.blockBoundingRect(block).height()) + block_number += 1 + + def highlight_current_line(self) -> None: + selection = QTextEdit.ExtraSelection() + selection.format.setBackground(self.current_line_background) + selection.format.setProperty(QTextFormat.Property.FullWidthSelection, True) + selection.cursor = self.textCursor() + selection.cursor.clearSelection() + self.setExtraSelections([selection]) + + +class MarkdownSyntaxHighlighter(QSyntaxHighlighter): + def __init__(self, document: object, dark: bool = False) -> None: + super().__init__(document) + self.dark = dark + self._rebuild_rules() + + def apply_theme(self, dark: bool) -> None: + self.dark = dark + self._rebuild_rules() + self.rehighlight() + + def _rebuild_rules(self) -> None: + if self.dark: + heading = "#79c0ff" + link = "#58a6ff" + strong = "#f0f6fc" + accent = "#d2a8ff" + code = "#ffa657" + media = "#7ee787" + quote = "#8b949e" + fence = "#ffab70" + block_code = "#c9d1d9" + else: + heading = "#1f6feb" + link = "#0969da" + strong = "#24292f" + accent = "#8250df" + code = "#bf3989" + media = "#1a7f37" + quote = "#6e7781" + fence = "#953800" + block_code = "#57606a" + + self.rules = [ + (re.compile(r"^#{1,6}\s+.+$"), self._format(heading, bold=True)), + (re.compile(r"^\s*[-*+]\s+"), self._format(link)), + (re.compile(r"^\s*\d+\.\s+"), self._format(link)), + (re.compile(r"\*\*[^*]+\*\*"), self._format(strong, bold=True)), + (re.compile(r"(?\s?.*$"), self._format(quote, italic=True)), + (re.compile(r"^\s{0,3}---+\s*$"), self._format(quote)), + ] + self.code_format = self._format(block_code) + self.fence_format = self._format(fence, bold=True) + + def _format(self, color: str, bold: bool = False, italic: bool = False, underline: bool = False) -> QTextCharFormat: + text_format = QTextCharFormat() + text_format.setForeground(QColor(color)) + if bold: + text_format.setFontWeight(QFont.Weight.Bold) + if italic: + text_format.setFontItalic(True) + if underline: + text_format.setFontUnderline(True) + return text_format + + def highlightBlock(self, text: str) -> None: + in_fence = self.previousBlockState() == 1 + if text.strip().startswith("```"): + self.setFormat(0, len(text), self.fence_format) + self.setCurrentBlockState(0 if in_fence else 1) + return + + if in_fence: + self.setFormat(0, len(text), self.code_format) + self.setCurrentBlockState(1) + return + + self.setCurrentBlockState(0) + for pattern, text_format in self.rules: + for match in pattern.finditer(text): + self.setFormat(match.start(), match.end() - match.start(), text_format) + + diff --git a/mdhelper/markdown_editor.py b/mdhelper/markdown_editor.py index 579f143..e373b23 100644 --- a/mdhelper/markdown_editor.py +++ b/mdhelper/markdown_editor.py @@ -1,25 +1,20 @@ from __future__ import annotations from .document_session import DocumentSession +from .editor_widgets import LineNumberArea, MarkdownSourceEditor, MarkdownSyntaxHighlighter +from .editor_find import EditorFindController +from .editor_preview import EditorPreviewController import os -import json import re from pathlib import Path from typing import Callable -from PySide6.QtCore import QObject, QRect, QSize, QSignalBlocker, QTimer, QUrl, Qt, Signal, Slot -from PySide6.QtWebChannel import QWebChannel +from PySide6.QtCore import QTimer, QUrl, Qt, Signal from PySide6.QtGui import ( QAction, - QColor, QFont, QKeySequence, - QPainter, - QSyntaxHighlighter, - QTextCharFormat, QTextCursor, - QTextDocument, - QTextFormat, ) from PySide6.QtWebEngineCore import QWebEngineSettings from PySide6.QtWebEngineWidgets import QWebEngineView @@ -31,17 +26,14 @@ from PySide6.QtWidgets import ( QHBoxLayout, QLabel, QLineEdit, - QMenu, QMessageBox, QPlainTextEdit, QPushButton, QSplitter, - QTextEdit, QToolBar, QVBoxLayout, QWidget, ) -from shiboken6 import isValid from .markdown_renderer import MarkdownRenderer from .markdown_utils import slugify_heading @@ -56,201 +48,6 @@ def convert_latex_display_delimiters(source: str) -> tuple[str, int]: return source.replace("\\[", "$$").replace("\\]", "$$"), replacement_count -class LineNumberArea(QWidget): - def __init__(self, editor: "MarkdownSourceEditor") -> None: - super().__init__(editor) - self.editor = editor - - def sizeHint(self) -> QSize: - return QSize(self.editor.line_number_area_width(), 0) - - def paintEvent(self, event: object) -> None: - self.editor.line_number_area_paint_event(event) - - -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") - self.line_number_area = LineNumberArea(self) - self.blockCountChanged.connect(self.update_line_number_area_width) - self.updateRequest.connect(self.update_line_number_area) - self.cursorPositionChanged.connect(self.highlight_current_line) - 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") - self.line_number_foreground = QColor("#8b949e") - self.current_line_background = QColor("#273447") - self.setStyleSheet( - "QPlainTextEdit { background: #1f242b; color: #dbe2ea; " - "selection-background-color: #2f6feb; selection-color: #ffffff; }" - ) - else: - self.line_number_background = QColor("#f3f5f8") - self.line_number_foreground = QColor("#7a8494") - self.current_line_background = QColor("#edf4ff") - self.setStyleSheet("") - self.line_number_area.update() - self.highlight_current_line() - - def line_number_area_width(self) -> int: - digits = max(2, len(str(max(1, self.blockCount())))) - return 12 + self.fontMetrics().horizontalAdvance("9") * digits - - def update_line_number_area_width(self, new_block_count: int) -> None: - del new_block_count - self.setViewportMargins(self.line_number_area_width(), 0, 0, 0) - - def update_line_number_area(self, rect: QRect, dy: int) -> None: - if dy: - self.line_number_area.scroll(0, dy) - else: - self.line_number_area.update(0, rect.y(), self.line_number_area.width(), rect.height()) - - if rect.contains(self.viewport().rect()): - self.update_line_number_area_width(0) - - def resizeEvent(self, event: object) -> None: - super().resizeEvent(event) - content_rect = self.contentsRect() - self.line_number_area.setGeometry( - QRect(content_rect.left(), content_rect.top(), self.line_number_area_width(), content_rect.height()) - ) - - def line_number_area_paint_event(self, event: object) -> None: - painter = QPainter(self.line_number_area) - painter.fillRect(event.rect(), self.line_number_background) - - block = self.firstVisibleBlock() - block_number = block.blockNumber() - top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top()) - bottom = top + int(self.blockBoundingRect(block).height()) - - while block.isValid() and top <= event.rect().bottom(): - if block.isVisible() and bottom >= event.rect().top(): - painter.setPen(self.line_number_foreground) - painter.drawText( - 0, - top, - self.line_number_area.width() - 6, - self.fontMetrics().height(), - Qt.AlignmentFlag.AlignRight, - str(block_number + 1), - ) - - block = block.next() - top = bottom - bottom = top + int(self.blockBoundingRect(block).height()) - block_number += 1 - - def highlight_current_line(self) -> None: - selection = QTextEdit.ExtraSelection() - selection.format.setBackground(self.current_line_background) - selection.format.setProperty(QTextFormat.Property.FullWidthSelection, True) - selection.cursor = self.textCursor() - selection.cursor.clearSelection() - self.setExtraSelections([selection]) - - -class MarkdownSyntaxHighlighter(QSyntaxHighlighter): - def __init__(self, document: object, dark: bool = False) -> None: - super().__init__(document) - self.dark = dark - self._rebuild_rules() - - def apply_theme(self, dark: bool) -> None: - self.dark = dark - self._rebuild_rules() - self.rehighlight() - - def _rebuild_rules(self) -> None: - if self.dark: - heading = "#79c0ff" - link = "#58a6ff" - strong = "#f0f6fc" - accent = "#d2a8ff" - code = "#ffa657" - media = "#7ee787" - quote = "#8b949e" - fence = "#ffab70" - block_code = "#c9d1d9" - else: - heading = "#1f6feb" - link = "#0969da" - strong = "#24292f" - accent = "#8250df" - code = "#bf3989" - media = "#1a7f37" - quote = "#6e7781" - fence = "#953800" - block_code = "#57606a" - - self.rules = [ - (re.compile(r"^#{1,6}\s+.+$"), self._format(heading, bold=True)), - (re.compile(r"^\s*[-*+]\s+"), self._format(link)), - (re.compile(r"^\s*\d+\.\s+"), self._format(link)), - (re.compile(r"\*\*[^*]+\*\*"), self._format(strong, bold=True)), - (re.compile(r"(?\s?.*$"), self._format(quote, italic=True)), - (re.compile(r"^\s{0,3}---+\s*$"), self._format(quote)), - ] - self.code_format = self._format(block_code) - self.fence_format = self._format(fence, bold=True) - - def _format(self, color: str, bold: bool = False, italic: bool = False, underline: bool = False) -> QTextCharFormat: - text_format = QTextCharFormat() - text_format.setForeground(QColor(color)) - if bold: - text_format.setFontWeight(QFont.Weight.Bold) - if italic: - text_format.setFontItalic(True) - if underline: - text_format.setFontUnderline(True) - return text_format - - def highlightBlock(self, text: str) -> None: - in_fence = self.previousBlockState() == 1 - if text.strip().startswith("```"): - self.setFormat(0, len(text), self.fence_format) - self.setCurrentBlockState(0 if in_fence else 1) - return - - if in_fence: - self.setFormat(0, len(text), self.code_format) - self.setCurrentBlockState(1) - return - - self.setCurrentBlockState(0) - for pattern, text_format in self.rules: - for match in pattern.finditer(text): - self.setFormat(match.start(), match.end() - match.start(), text_format) - - - -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() @@ -289,12 +86,6 @@ class MarkdownEditorDialog(QDialog): self.document_style_css = document_style_css self.math_engine = math_engine self.draft_callback = draft_callback - self._preview_dirty = True - self._preview_scroll_y = 0 - self._preview_scroll_ratio = 0.0 - self._syncing_scroll = False - self._match_positions: list[int] = [] - self._current_match_index = -1 self.setWindowTitle(f"编辑 Markdown - {path.name}") self.setMinimumSize(1120, 720) @@ -356,10 +147,6 @@ class MarkdownEditorDialog(QDialog): control_layout.addWidget(self.find_status_label) layout.addLayout(control_layout) - self.preview_refresh_timer = QTimer(self) - self.preview_refresh_timer.setSingleShot(True) - self.preview_refresh_timer.setInterval(350) - self.preview_refresh_timer.timeout.connect(self._refresh_preview_with_scroll_capture) self.draft_save_timer = QTimer(self) self.draft_save_timer.setSingleShot(True) self.draft_save_timer.setInterval(5000) @@ -380,19 +167,14 @@ class MarkdownEditorDialog(QDialog): else None ) 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.preview_controller = EditorPreviewController( + self, self.editor, self.preview, self.view_mode_box, self.sync_scroll_checkbox, self._render_preview) + self.find_controller = EditorFindController( + self.editor, self.editor_find_box, self.editor_replace_box, + self.match_case_checkbox, self.whole_word_checkbox, self.find_status_label) self._configure_preview_settings(self.preview.settings()) self.splitter.addWidget(self.preview) self.splitter.setSizes([560, 560]) @@ -439,6 +221,70 @@ class MarkdownEditorDialog(QDialog): self._rebuild_find_matches() self._apply_view_mode() + @property + def _preview_dirty(self) -> bool: + return self.preview_controller._preview_dirty + + @_preview_dirty.setter + def _preview_dirty(self, value: bool) -> None: + self.preview_controller._preview_dirty = value + + @property + def _preview_scroll_ratio(self) -> float: + return self.preview_controller._preview_scroll_ratio + + @property + def preview_refresh_timer(self) -> QTimer: + return self.preview_controller.preview_refresh_timer + + def _render_preview(self) -> tuple[str, QUrl]: + html = self.renderer.render_source( + self.source_text(), self.save_target_path, + theme=self.theme, font_scale=self.font_scale, + document_font_family=self.document_font_family, document_font_size=self.document_font_size, + document_width_scale=self.document_width_scale, document_style_css=self.document_style_css, + math_engine=self.math_engine, source_map=True) + return html, QUrl.fromLocalFile(str(self.save_target_path.parent.resolve()) + os.sep) + + def _rebuild_find_matches(self) -> None: + self.find_controller._rebuild_find_matches() + + def find_next_in_editor(self) -> None: + self.find_controller.find_next_in_editor() + + def find_previous_in_editor(self) -> None: + self.find_controller.find_previous_in_editor() + + def replace_current_in_editor(self) -> None: + self.find_controller.replace_current_in_editor() + + def replace_all_in_editor(self) -> None: + self.find_controller.replace_all_in_editor() + + def _apply_view_mode(self) -> None: + self.preview_controller._apply_view_mode() + + def _schedule_preview_refresh(self) -> None: + self.preview_controller._schedule_preview_refresh() + + def _refresh_preview_with_scroll_capture(self) -> None: + self.preview_controller._refresh_preview_with_scroll_capture() + + def _refresh_preview_now(self) -> None: + self.preview_controller._refresh_preview_now() + + def _sync_preview_to_source_line(self) -> None: + self.preview_controller._sync_preview_to_source_line() + + def _sync_preview_to_editor_scroll(self, value: int) -> None: + self.preview_controller._sync_preview_to_editor_scroll(value) + + def _scroll_preview_to_heading(self, slug: str) -> None: + self.preview_controller._scroll_preview_to_heading(slug) + + _qt_match_spans = staticmethod(EditorFindController._qt_match_spans) + _qt_position = staticmethod(EditorFindController._qt_position) + @property def path(self) -> Path: return self.session.path @@ -457,7 +303,7 @@ class MarkdownEditorDialog(QDialog): def stop_background_work(self) -> None: self.draft_save_timer.stop() - self.preview_refresh_timer.stop() + self.preview_controller.stop() def source_text(self) -> str: return self.editor.toPlainText() @@ -634,24 +480,6 @@ class MarkdownEditorDialog(QDialog): return None - def _scroll_preview_to_heading(self, slug: str) -> None: - if not isValid(self) or not isValid(self.preview): - return - script = ( - "(() => {" - "const id = " - f"{json.dumps(slug)}" - ";" - "const selector = window.CSS && CSS.escape ? `[id=\"${CSS.escape(id)}\"]` : '';" - "const target = document.getElementById(id) || (selector ? document.querySelector(selector) : null);" - "if (target) {" - " target.scrollIntoView({block: 'start', behavior: 'auto'});" - " const scroller = document.scrollingElement || document.documentElement || document.body;" - " scroller.scrollTop = Math.max(0, scroller.scrollTop - 12);" - "}" - "})();" - ) - self.preview.page().runJavaScript(script) def _on_editor_text_changed(self) -> None: self._schedule_preview_refresh() @@ -684,121 +512,6 @@ class MarkdownEditorDialog(QDialog): if self.has_unsaved_changes() and callable(self.draft_callback): self.draft_callback(self.source_text()) - def _find_flags(self) -> QTextDocument.FindFlag: - flags = QTextDocument.FindFlag(0) - if self.match_case_checkbox.isChecked(): - flags |= QTextDocument.FindFlag.FindCaseSensitively - if self.whole_word_checkbox.isChecked(): - flags |= QTextDocument.FindFlag.FindWholeWords - return flags - - def _rebuild_find_matches(self) -> None: - query = self.editor_find_box.text() - self._match_positions = [] - self._current_match_index = -1 - if not query: - self.find_status_label.setText("0/0") - return - - text = self.source_text() - flags = 0 if self.match_case_checkbox.isChecked() else re.IGNORECASE - pattern = re.escape(query) - if self.whole_word_checkbox.isChecked(): - pattern = r"\b" + pattern + r"\b" - 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: - self._current_match_index = index - 1 - break - else: - self._current_match_index = len(self._match_positions) - 1 - self._update_find_status() - - def _select_match(self, index: int) -> None: - if not self._match_positions: - self._update_find_status() - return - self._current_match_index = index % len(self._match_positions) - query = self.editor_find_box.text() - cursor = self.editor.textCursor() - cursor.setPosition(self._match_positions[self._current_match_index]) - cursor.setPosition(cursor.position() + self._qt_position(query, len(query)), QTextCursor.MoveMode.KeepAnchor) - self.editor.setTextCursor(cursor) - self.editor.ensureCursorVisible() - self._update_find_status() - - def _update_find_status(self) -> None: - total = len(self._match_positions) - current = self._current_match_index + 1 if total and self._current_match_index >= 0 else 0 - self.find_status_label.setText(f"{current}/{total}") - - def find_next_in_editor(self) -> None: - if not self.editor_find_box.text(): - return - if not self._match_positions: - self._rebuild_find_matches() - if self._match_positions: - self._select_match(self._current_match_index + 1) - - def find_previous_in_editor(self) -> None: - if not self.editor_find_box.text(): - return - if not self._match_positions: - self._rebuild_find_matches() - if self._match_positions: - self._select_match(self._current_match_index - 1) - - def replace_current_in_editor(self) -> None: - query = self.editor_find_box.text() - if not query: - return - - cursor = self.editor.textCursor() - selected = cursor.selectedText().replace("\u2029", "\n") - matches = selected == query if self.match_case_checkbox.isChecked() else selected.lower() == query.lower() - if cursor.hasSelection() and matches: - cursor.insertText(self.editor_replace_box.text()) - self._rebuild_find_matches() - return - self.find_next_in_editor() - - def replace_all_in_editor(self) -> None: - query = self.editor_find_box.text() - if not query: - return - - replacement = self.editor_replace_box.text() - flags = 0 if self.match_case_checkbox.isChecked() else re.IGNORECASE - pattern = re.escape(query) - if self.whole_word_checkbox.isChecked(): - pattern = r"\b" + pattern + r"\b" - 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() @@ -859,147 +572,6 @@ class MarkdownEditorDialog(QDialog): settings.setAttribute(attributes.FullScreenSupportEnabled, True) settings.setAttribute(attributes.JavascriptEnabled, True) - def _apply_view_mode(self) -> None: - mode = str(self.view_mode_box.currentData() or "source") - self.editor.setVisible(mode in {"source", "split"}) - self.preview.setVisible(mode in {"preview", "split"}) - if mode in {"preview", "split"} and self._preview_dirty: - self._refresh_preview_now() - 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: - self._preview_dirty = True - mode = str(self.view_mode_box.currentData() or "source") - if mode in {"preview", "split"}: - self.preview_refresh_timer.start() - - def _refresh_preview_with_scroll_capture(self) -> None: - mode = str(self.view_mode_box.currentData() or "source") - if mode == "split" and self.sync_scroll_checkbox.isChecked(): - self._preview_scroll_ratio = self._editor_scroll_ratio() - self._refresh_preview_now() - return - self.preview.page().runJavaScript("Math.max(0, window.scrollY || 0)", self._store_scroll_and_refresh_preview) - - def _store_scroll_and_refresh_preview(self, scroll_y: object) -> None: - if not isValid(self) or not isValid(self.preview): - return - try: - self._preview_scroll_y = max(0, int(float(scroll_y or 0))) - except (TypeError, ValueError): - self._preview_scroll_y = 0 - self._refresh_preview_now() - - def _refresh_preview_now(self) -> None: - if not isValid(self) or not isValid(self.preview): - return - html_content = self.renderer.render_source( - self.source_text(), - self.save_target_path, - theme=self.theme, - font_scale=self.font_scale, - document_font_family=self.document_font_family, - document_font_size=self.document_font_size, - 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)) - self._preview_dirty = False - - def _restore_preview_scroll(self, ok: bool) -> None: - if not ok: - return - 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'}}); }})();" - self.preview.page().runJavaScript(script) - - def _editor_scroll_ratio(self) -> float: - maximum = max(1, self.editor.verticalScrollBar().maximum()) - return max(0.0, min(1.0, self.editor.verticalScrollBar().value() / maximum)) - - def _sync_preview_to_editor_scroll(self, value: int) -> None: - del value - 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_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): - return - script = ( - "(() => {" - "const ratio = %0.6f;" - "const maxY = Math.max(0, document.documentElement.scrollHeight - window.innerHeight);" - "window.scrollTo({top: Math.round(maxY * ratio), behavior: 'instant'});" - "})();" - % ratio - ) - self._syncing_scroll = True - self.preview.page().runJavaScript(script, lambda result=None: self._clear_scroll_sync()) - - def _clear_scroll_sync(self) -> None: - self._syncing_scroll = False def _choose_save_as_path(self) -> None: file_name, _ = QFileDialog.getSaveFileName( diff --git a/tests/test_editor_find.py b/tests/test_editor_find.py new file mode 100644 index 0000000..2d0d5a0 --- /dev/null +++ b/tests/test_editor_find.py @@ -0,0 +1,29 @@ +from PySide6.QtGui import QTextCursor +from PySide6.QtWidgets import QPlainTextEdit, QLineEdit, QCheckBox, QLabel + +from mdhelper.editor_find import EditorFindController + + +def test_find_replace_keeps_unicode_word_boundaries_and_undo(qt_application): + editor = QPlainTextEdit() + original = "🙂 alpha ALPHA alphabet\nalpha" + editor.setPlainText(original) + editor.moveCursor(QTextCursor.MoveOperation.End) + editor.insertPlainText(" extra") + query, replacement = QLineEdit("alpha"), QLineEdit("猫😀") + match_case, whole_word, status = QCheckBox(), QCheckBox(), QLabel() + whole_word.setChecked(True) + finder = EditorFindController(editor, query, replacement, match_case, whole_word, status) + editor.textChanged.connect(finder._rebuild_find_matches) + finder._rebuild_find_matches() + finder.find_next_in_editor() + assert editor.textCursor().selectedText() == "alpha" + assert status.text() == "1/3" + finder.replace_all_in_editor() + assert editor.toPlainText() == "🙂 猫😀 猫😀 alphabet\n猫😀 extra" + assert status.text() == "0/0" + editor.undo() + assert editor.toPlainText() == original + " extra" + editor.undo() + assert editor.toPlainText() == original +