fix: protect editor saves and clear failed restored tab state
This commit is contained in:
@@ -8,7 +8,7 @@ from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Callable, Protocol
|
||||
|
||||
from .file_versions import VersionStore
|
||||
from .file_versions import VersionStore, _UNCHECKED
|
||||
|
||||
FileSignature = tuple[int, int] | None
|
||||
DRAFTS_KEY = "editor/drafts"
|
||||
@@ -46,8 +46,8 @@ class DocumentStore:
|
||||
return relocate_images(source, original, target)
|
||||
|
||||
@staticmethod
|
||||
def save(path: Path, source: str) -> None:
|
||||
VersionStore().save(path, source)
|
||||
def save(path: Path, source: str, *, expected=_UNCHECKED) -> None:
|
||||
VersionStore().save(path, source, expected=expected)
|
||||
|
||||
|
||||
class DraftStore:
|
||||
|
||||
@@ -125,9 +125,15 @@ class VersionStore:
|
||||
def versions(self, path: Path) -> list[Path]:
|
||||
return sorted(self.directory(path).glob("*.md"), reverse=True)
|
||||
|
||||
def save(self, path: Path, source: str) -> None:
|
||||
def save(self, path: Path, source: str, *, expected=_UNCHECKED) -> None:
|
||||
data = source.encode("utf-8")
|
||||
previous = path.read_bytes() if path.exists() else None
|
||||
try:
|
||||
previous = path.read_bytes()
|
||||
except FileNotFoundError:
|
||||
previous = None
|
||||
snapshot = hashlib.sha256(previous).hexdigest() if previous is not None else None
|
||||
if expected is not _UNCHECKED and snapshot != expected:
|
||||
raise OSError(f'文件在比较后再次变化,已取消保存:{path}')
|
||||
if previous == data:
|
||||
return
|
||||
if previous is not None:
|
||||
@@ -136,7 +142,7 @@ class VersionStore:
|
||||
name = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000_000:09d}-{uuid.uuid4().hex[:6]}.md"
|
||||
atomic_write(self.directory(path) / name, previous)
|
||||
# A failed replacement leaves the original file and its history intact.
|
||||
atomic_write(path, data)
|
||||
atomic_write(path, data, expected=snapshot)
|
||||
for expired in self.versions(path)[self.limit:]:
|
||||
try:
|
||||
expired.unlink()
|
||||
|
||||
+41
-9
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import hashlib
|
||||
import copy
|
||||
import time
|
||||
import json
|
||||
@@ -2109,8 +2110,10 @@ class MainWindow(QMainWindow):
|
||||
original_path = editor.session.path
|
||||
target_path = target_path.resolve()
|
||||
disk_source = None
|
||||
disk_bytes = None
|
||||
try:
|
||||
disk_source = self._read_markdown_source(original_path)
|
||||
disk_bytes = original_path.read_bytes()
|
||||
disk_source = disk_bytes.decode('utf-8').replace('\r\n', '\n').replace('\r', '\n')
|
||||
unchanged = target_path == original_path and source == disk_source
|
||||
except (OSError, UnicodeError):
|
||||
unchanged = False
|
||||
@@ -2120,7 +2123,15 @@ class MainWindow(QMainWindow):
|
||||
self.status_label.setText("编辑内容未变化")
|
||||
return True
|
||||
|
||||
reviewed_disk = None
|
||||
# Carry the compared bytes all the way to the protected replacement.
|
||||
# In particular, image relocation must not open a new overwrite window.
|
||||
try:
|
||||
reviewed_disk = (disk_bytes,) if target_path == original_path else (target_path.read_bytes(),)
|
||||
except FileNotFoundError:
|
||||
reviewed_disk = (None,)
|
||||
except OSError as exc:
|
||||
QMessageBox.warning(self, "保存失败", str(exc))
|
||||
return False
|
||||
if target_path == original_path and (expected_signature != self._file_signature(target_path)
|
||||
or disk_source != editor.session.saved_source):
|
||||
from .save_conflict import resolve_save_conflict
|
||||
@@ -2217,12 +2228,14 @@ class MainWindow(QMainWindow):
|
||||
QMessageBox.warning(self, "保存失败", "只能保存 Markdown 文档。")
|
||||
return False
|
||||
|
||||
try:
|
||||
actual = path.read_bytes()
|
||||
except FileNotFoundError:
|
||||
actual = None
|
||||
except OSError as exc:
|
||||
QMessageBox.warning(self, "保存失败", str(exc))
|
||||
return False
|
||||
if reviewed_disk is not None:
|
||||
try:
|
||||
actual = path.read_bytes() if path.exists() else None
|
||||
except OSError as exc:
|
||||
QMessageBox.warning(self, "保存失败", str(exc))
|
||||
return False
|
||||
if actual != reviewed_disk[0]:
|
||||
QMessageBox.warning(self, "文件再次变化", "比较期间磁盘文件再次变化,本次保存已取消。请重新保存以查看最新差异。")
|
||||
return False
|
||||
@@ -2240,7 +2253,8 @@ class MainWindow(QMainWindow):
|
||||
|
||||
self.internal_save_paths.add(path)
|
||||
try:
|
||||
self.documents.save(path, source)
|
||||
expected = hashlib.sha256(actual).hexdigest() if actual is not None else None
|
||||
self.documents.save(path, source, expected=expected)
|
||||
except OSError as exc:
|
||||
self.internal_save_paths.discard(path)
|
||||
LOGGER.exception("Failed to save Markdown source: %s", path)
|
||||
@@ -4524,7 +4538,7 @@ class MainWindow(QMainWindow):
|
||||
state = host.workspace_state
|
||||
path = Path(state.path)
|
||||
if not path.is_file():
|
||||
host.welcome_view.setPlainText(f"文件已不存在:\n{path}")
|
||||
self._workspace_load_failed(host, f"文件已不存在:\n{path}")
|
||||
return
|
||||
# Replacing a restored reader with its editor must not activate and
|
||||
# load the neighbouring background tab during the intermediate removal.
|
||||
@@ -4538,6 +4552,10 @@ class MainWindow(QMainWindow):
|
||||
self.current_file = path
|
||||
if path.suffix.lower() in {".md", ".markdown"} or is_code_document(path):
|
||||
self.open_document(path, add_history=False, scroll_y=state.scroll)
|
||||
if host.reader_view.property('current_file') != str(path):
|
||||
host.workspace_state = state
|
||||
self._workspace_load_failed(host, f"无法加载文档:\n{path}\n请检查文件后重新选择此标签。")
|
||||
return
|
||||
elif path.suffix.lower() in {".html", ".htm", ".xhtml"}:
|
||||
self._open_webpage_file_now(path)
|
||||
else:
|
||||
@@ -4555,6 +4573,20 @@ class MainWindow(QMainWindow):
|
||||
QTimer.singleShot(0, editor, lambda: editor.editor.verticalScrollBar().setValue(state.source_scroll))
|
||||
self._on_tab_changed(self.tabs.currentIndex())
|
||||
|
||||
def _workspace_load_failed(self, host, message: str) -> None:
|
||||
# Keep the lazy state for a later retry, but never leave actions pointing
|
||||
# at the document that was active before the failed tab was selected.
|
||||
self.current_file = None
|
||||
self.current_fragment = self.pending_fragment = self.pending_find_text = ''
|
||||
self.pending_scroll_y = None
|
||||
host.welcome_view.setPlainText(message)
|
||||
host.stack.setCurrentWidget(host.welcome_view)
|
||||
self.setWindowTitle(f'{Path(host.workspace_state.path).name} - MDHelper')
|
||||
self.status_label.setText(message.splitlines()[0])
|
||||
self.toc_tree.clear()
|
||||
self._update_watched_paths()
|
||||
self._update_actions()
|
||||
|
||||
|
||||
@property
|
||||
def editor_drafts(self) -> dict:
|
||||
|
||||
Reference in New Issue
Block a user