From 9af74df77579c19889aef4089963e2b0e51c354b Mon Sep 17 00:00:00 2001 From: shen Date: Thu, 5 Nov 2026 10:51:45 +0800 Subject: [PATCH] fix: protect transaction conflicts and correct editor navigation --- mdhelper/batch_documents.py | 15 +++- mdhelper/editor_find.py | 32 +++---- mdhelper/rename_references.py | 17 +++- mdhelper/style_panel.py | 11 +-- tests/test_interaction_revision_056.py | 114 +++++++++++++++++++++++++ 5 files changed, 161 insertions(+), 28 deletions(-) create mode 100644 tests/test_interaction_revision_056.py diff --git a/mdhelper/batch_documents.py b/mdhelper/batch_documents.py index 8984c5b..7525cce 100644 --- a/mdhelper/batch_documents.py +++ b/mdhelper/batch_documents.py @@ -126,6 +126,8 @@ def publish_outputs(outputs: dict[Path, Path], expected: dict, backup: Path, can if destination.exists(): copy = backup / f"previous-{index}" shutil.copyfile(destination, copy) + if fingerprint(copy) != expected[destination]: + raise OSError(f"导出期间目标文件发生变化,已停止替换:{destination}") originals[destination] = copy else: originals[destination] = None @@ -133,13 +135,20 @@ def publish_outputs(outputs: dict[Path, Path], expected: dict, backup: Path, can try: for destination, staged in outputs.items(): check_cancelled(cancel) - atomic_write(destination, staged.read_bytes()) - written.append(destination) + data = staged.read_bytes() + # Conversion and backup of other files can take time. Validate the + # destination again immediately before publishing this particular file. + if fingerprint(destination) != expected[destination]: + raise OSError(f"导出期间目标文件发生变化,已停止替换:{destination}") + atomic_write(destination, data) + written.append((destination, hashlib.sha256(data).hexdigest())) check_cancelled(cancel) except Exception as error: failures = [] - for destination in reversed(written): + for destination, published in reversed(written): try: + if fingerprint(destination) != published: + raise OSError(f"目标文件已被外部修改,保留当前内容:{destination}") if originals[destination] is None: destination.unlink(missing_ok=True) else: atomic_write(destination, originals[destination].read_bytes()) except OSError as rollback: diff --git a/mdhelper/editor_find.py b/mdhelper/editor_find.py index 6b24b66..5c89bda 100644 --- a/mdhelper/editor_find.py +++ b/mdhelper/editor_find.py @@ -1,6 +1,7 @@ """Find/replace state and UTF-16 cursor positions, independent of the dialog.""" from __future__ import annotations import re +from bisect import bisect_left from PySide6.QtGui import QTextCursor from PySide6.QtWidgets import QPlainTextEdit, QLineEdit, QCheckBox, QLabel @@ -13,11 +14,13 @@ class EditorFindController: self.match_case_checkbox, self.whole_word_checkbox = match_case, whole_word self.find_status_label = status self._match_positions: list[int] = [] + self._match_spans: list[tuple[int, int]] = [] self._current_match_index = -1 def _rebuild_find_matches(self) -> None: query = self.editor_find_box.text() self._match_positions = [] + self._match_spans = [] self._current_match_index = -1 if not query: self.find_status_label.setText("0/0") @@ -28,14 +31,12 @@ class EditorFindController: 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._match_spans = self._qt_match_spans(text, re.finditer(pattern, text, flags)) + self._match_positions = [start for start, _ in self._match_spans] + cursor = self.editor.textCursor() + selection = (cursor.selectionStart(), cursor.selectionEnd()) + if cursor.hasSelection() and selection in self._match_spans: + self._current_match_index = self._match_spans.index(selection) self._update_find_status() @@ -44,10 +45,10 @@ class EditorFindController: 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) + start, end = self._match_spans[self._current_match_index] + cursor.setPosition(start) + cursor.setPosition(end, QTextCursor.MoveMode.KeepAnchor) self.editor.setTextCursor(cursor) self.editor.ensureCursorVisible() self._update_find_status() @@ -65,7 +66,7 @@ class EditorFindController: if not self._match_positions: self._rebuild_find_matches() if self._match_positions: - self._select_match(self._current_match_index + 1) + self._select_match(bisect_left(self._match_positions, self.editor.textCursor().selectionEnd())) def find_previous_in_editor(self) -> None: @@ -74,7 +75,7 @@ class EditorFindController: if not self._match_positions: self._rebuild_find_matches() if self._match_positions: - self._select_match(self._current_match_index - 1) + self._select_match(bisect_left(self._match_positions, self.editor.textCursor().selectionStart()) - 1) def replace_current_in_editor(self) -> None: @@ -83,9 +84,8 @@ class EditorFindController: 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: + self._rebuild_find_matches() + if cursor.hasSelection() and (cursor.selectionStart(), cursor.selectionEnd()) in self._match_spans: cursor.insertText(self.editor_replace_box.text()) self._rebuild_find_matches() return diff --git a/mdhelper/rename_references.py b/mdhelper/rename_references.py index be5c12c..9067ddf 100644 --- a/mdhelper/rename_references.py +++ b/mdhelper/rename_references.py @@ -69,9 +69,11 @@ def plan_rename(root: Path, source: Path, target: Path, buffers=None) -> RenameP def execute_rename(plan: RenamePlan, backup_root: Path | None = None) -> Path: if plan.target.exists(): raise FileExistsError(plan.target) - for path, original in plan.originals.items(): - if path.read_bytes() != original: - raise OSError(f"文件在预览后已变化,请重新重命名:{path.name}") + def check_originals(): + for path, original in plan.originals.items(): + if path.read_bytes() != original: + raise OSError(f"文件在预览后已变化,请重新重命名:{path.name}") + check_originals() base = backup_root or Path(os.environ.get("LOCALAPPDATA", str(Path.home()))) / "MDHelper" / "rename-backups" backup = base / (time.strftime("%Y%m%d-%H%M%S-") + uuid.uuid4().hex[:8]) manifest = {"source": str(plan.source), "target": str(plan.target), "files": {}} @@ -82,21 +84,28 @@ def execute_rename(plan: RenamePlan, backup_root: Path | None = None) -> Path: atomic_write(backup / "manifest.json", json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8")) written, renamed = [], False try: + check_originals() plan.source.rename(plan.target) renamed = True for path, data in plan.replacements.items(): destination = plan.target if path == plan.source else path + if destination.read_bytes() != plan.originals[path]: + raise OSError(f"文件在重命名期间已变化,保留当前内容:{destination.name}") atomic_write(destination, data) written.append(path) except OSError as exc: failures = [] for path in reversed(written): try: - atomic_write(plan.target if path == plan.source else path, plan.originals[path]) + destination = plan.target if path == plan.source else path + if destination.read_bytes() != plan.replacements[path]: + raise OSError(f"文件已被外部修改,保留当前内容:{destination.name}") + atomic_write(destination, plan.originals[path]) except OSError as rollback_error: failures.append(str(rollback_error)) if renamed: try: + if plan.source.exists(): raise FileExistsError(plan.source) plan.target.rename(plan.source) except OSError as rollback_error: failures.append(str(rollback_error)) diff --git a/mdhelper/style_panel.py b/mdhelper/style_panel.py index 8095654..ad26751 100644 --- a/mdhelper/style_panel.py +++ b/mdhelper/style_panel.py @@ -50,7 +50,8 @@ class StylePanel(QDockWidget): line = editor.editor.textCursor().blockNumber() active = next((region for region in reversed(self.regions) if region.start <= line < region.end), None) self.current.setText(('当前段落:' + style_name(active.style, rules) + - ('\n包含:' + '、'.join(style_name(k, rules) for k in active.characters) if active.characters else '')) if active else '阅读模式:双击条目修改统一外观。') + ('\n包含:' + '、'.join(style_name(k, rules) for k in active.characters) if active.characters else '')) if active else + ('当前行:空白或未识别的样式。' if editor else '阅读模式:双击条目修改统一外观。')) listing_key = (key, repr(rules), window.document_style_id, window.document_font_size, window.document_font_family, self.filter.currentIndex()) if force or listing_key != self.list_key: selected = self.listing.currentItem().data(Qt.ItemDataRole.UserRole) if self.listing.currentItem() else None @@ -66,10 +67,10 @@ class StylePanel(QDockWidget): self.listing.addItem(item) if target == selected: self.listing.setCurrentItem(item) self.list_key = listing_key - if active: - for index in range(self.listing.count()): - item = self.listing.item(index) - item.setBackground(QColor('#dceaf8') if item.data(Qt.ItemDataRole.UserRole) in (active.style, *active.characters) else QColor('transparent')) + highlighted = (active.style, *active.characters) if active else () + for index in range(self.listing.count()): + item = self.listing.item(index) + item.setBackground(QColor('#dceaf8') if item.data(Qt.ItemDataRole.UserRole) in highlighted else QColor('transparent')) def edit_selected(self, *_): item = self.listing.currentItem() diff --git a/tests/test_interaction_revision_056.py b/tests/test_interaction_revision_056.py new file mode 100644 index 0000000..f4e8d4f --- /dev/null +++ b/tests/test_interaction_revision_056.py @@ -0,0 +1,114 @@ +"""Conflicts during transactions, cursor-based search and empty style regions.""" +import pytest +from PySide6.QtCore import QSettings, Qt +from PySide6.QtGui import QTextCursor +from mdhelper import batch_documents as batch, rename_references as rename, main_window +from mdhelper.markdown_editor import MarkdownEditorDialog +from mdhelper.markdown_renderer import MarkdownRenderer + + +@pytest.mark.parametrize('changed', ['next', 'rollback', 'created']) +def test_batch_preserves_external_changes_between_writes(tmp_path, monkeypatch, changed): + first, second = tmp_path / 'first.out', tmp_path / 'second.out' + staged = tmp_path / 'stage'; staged.write_bytes(b'exported') + first.write_bytes(b'original') + if changed != 'created': second.write_bytes(b'original') + expected = {p: batch.fingerprint(p) for p in (first, second)} + write = batch.atomic_write + def concurrent_write(path, data): + write(path, data) + if path == first and data == b'exported': + second.write_bytes(b'external second') + if changed == 'rollback': first.write_bytes(b'external first') + monkeypatch.setattr(batch, 'atomic_write', concurrent_write) + with pytest.raises(OSError, match='输出恢复失败' if changed == 'rollback' else '发生变化'): + batch.publish_outputs({first: staged, second: staged}, expected, tmp_path) + assert second.read_bytes() == b'external second' + assert first.read_bytes() == (b'external first' if changed == 'rollback' else b'original') + assert (tmp_path / 'previous-0').read_bytes() == b'original' + + +@pytest.mark.parametrize('when', ['backup', 'write', 'rollback']) +def test_rename_preserves_external_edits_during_transaction(tmp_path, monkeypatch, when): + source, target, ref = (tmp_path / name for name in ('old.md', 'new.md', 'ref.md')) + source.write_text('[self](old.md)', encoding='utf8') + ref.write_text('[ref](old.md)', encoding='utf8') + plan = rename.plan_rename(tmp_path, source, target) + write = rename.atomic_write + def concurrent_write(path, data): + write(path, data) + if (when == 'backup' and path.name == 'manifest.json') or (when != 'backup' and path == target): + ref.write_bytes(b'external ref') + if when == 'rollback': target.write_bytes(b'external source') + monkeypatch.setattr(rename, 'atomic_write', concurrent_write) + with pytest.raises(OSError, match='恢复未完全成功' if when == 'rollback' else '已变化'): + rename.execute_rename(plan, tmp_path / 'backups') + assert ref.read_bytes() == b'external ref' + assert not target.exists() + assert source.read_bytes() == (b'external source' if when == 'rollback' else plan.originals[source]) + + +@pytest.fixture +def editor(qt_application, tmp_path): + dialog = MarkdownEditorDialog(tmp_path / 'note.md', '', MarkdownRenderer(tmp_path), 'light', 1, '', 16) + yield dialog + dialog.mark_saved(tmp_path / 'note.md', dialog.source_text(), None) + dialog.close(); dialog.deleteLater() + + +def select(editor, start, end=None): + cursor = editor.textCursor(); cursor.setPosition(start) + if end is not None: cursor.setPosition(end, QTextCursor.MoveMode.KeepAnchor) + editor.setTextCursor(cursor) + + +def test_whole_word_replace_rejects_manually_selected_substring(editor): + editor.editor.setPlainText('catalog cat') + editor.editor_find_box.setText('cat'); editor.whole_word_checkbox.setChecked(True) + editor.editor_replace_box.setText('dog'); select(editor.editor, 0, 3) + editor.editor_replace_button.click() + assert editor.source_text() == 'catalog cat' + assert editor.editor.textCursor().selectionStart() == 8 + editor.editor_replace_button.click() + assert editor.source_text() == 'catalog dog' + editor.editor.undo(); assert editor.source_text() == 'catalog cat' + + +def test_previous_wraps_and_follows_manual_cursor_changes(editor): + editor.editor.setPlainText('cat cat cat'); select(editor.editor, 0) + editor.editor_find_box.setText('cat'); editor.editor_find_previous_button.click() + assert editor.editor.textCursor().selectionStart() == 8 + assert editor.find_status_label.text() == '3/3' + editor.editor_find_previous_button.click(); assert editor.editor.textCursor().selectionStart() == 4 + editor.editor_find_next_button.click(); assert editor.editor.textCursor().selectionStart() == 8 + select(editor.editor, 4); editor.editor_find_previous_button.click() + assert editor.editor.textCursor().selectionStart() == 0 + select(editor.editor, 4); editor.editor_find_next_button.click() + assert editor.editor.textCursor().selectionStart() == 4 + + +def test_replace_uses_same_unicode_case_matching_as_find(editor): + editor.editor.setPlainText('🙂 ſ cat') + editor.editor_find_box.setText('s'); editor.editor_replace_box.setText('X') + editor.editor_find_next_button.click(); editor.editor_replace_button.click() + assert editor.source_text() == '🙂 X cat' + + +def test_style_panel_clears_highlight_on_blank_editor_line(qt_application, tmp_path, monkeypatch): + settings = QSettings(str(tmp_path / 'settings.ini'), QSettings.Format.IniFormat) + monkeypatch.setattr(main_window, 'QSettings', lambda *_: settings) + note = tmp_path / 'note.md'; note.write_text('# Heading\n\nBody', encoding='utf8') + window = main_window.MainWindow(tmp_path) + try: + window.open_document(note); window.edit_current_markdown(); window.show_style_panel() + panel = window.style_panel; panel.refresh(force=True) + assert '标题 1' in panel.current.text() + select(window.tabs.currentWidget().editor, 10); panel.refresh() + assert '当前行' in panel.current.text() and '阅读模式' not in panel.current.text() + assert all(panel.listing.item(i).background().color().alpha() == 0 for i in range(panel.listing.count())) + select(window.tabs.currentWidget().editor, 11); panel.refresh() + assert '正文' in panel.current.text() + active = [panel.listing.item(i).data(Qt.ItemDataRole.UserRole) for i in range(panel.listing.count()) + if panel.listing.item(i).background().color().alpha()] + assert active == ['paragraph'] + finally: window.close()