Files
MDHelper/mdhelper/document_session.py
T

127 lines
3.9 KiB
Python
Raw Normal View History

"""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