Files

242 lines
9.3 KiB
Python

"""File monitoring and refresh decisions, with explicit UI callbacks."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from PySide6.QtCore import QObject, QFileSystemWatcher, QTimer
from .document_resources import analyze_document, resolve_local_reference
@dataclass(frozen=True)
class WatchContext:
root: Callable[[], Path | None]
mode: Callable[[], str]
open_paths: Callable[[], set[Path]]
is_document: Callable[[Path], bool]
renaming: Callable[[], bool]
refresh_tabs: Callable[[set[Path]], None]
refresh_tree: Callable[[], None]
class FileWatchService(QObject):
def __init__(self, parent: QObject, context: WatchContext, signature: Callable):
super().__init__(parent)
self.context, self.signature = context, signature
self.internal_save_paths: set[Path] = set()
self.watched_file_signatures: dict[Path, tuple[int, int] | None] = {}
self.pending_changed_files: set[Path] = set()
self.pending_directory_refresh = False
self.file_watcher = QFileSystemWatcher(self)
self.file_watcher.fileChanged.connect(self.on_file_changed)
self.file_watcher.directoryChanged.connect(self.on_directory_changed)
self.refresh_timer = QTimer(self)
self.refresh_timer.setSingleShot(True)
self.refresh_timer.setInterval(1000)
self.refresh_timer.timeout.connect(self.refresh_changed_documents)
self.tree_refresh_timer = QTimer(self)
self.tree_refresh_timer.setSingleShot(True)
self.tree_refresh_timer.setInterval(1000)
self.tree_refresh_timer.timeout.connect(context.refresh_tree)
def reset(self) -> None:
self.refresh_timer.stop()
self.tree_refresh_timer.stop()
self.pending_changed_files.clear()
self.pending_directory_refresh = False
self.internal_save_paths.clear()
self.watched_file_signatures.clear()
paths = self.file_watcher.files() + self.file_watcher.directories()
if paths:
self.file_watcher.removePaths(paths)
def update_paths(self) -> None:
watched_files = self.file_watcher.files()
watched_dirs = self.file_watcher.directories()
if watched_files:
self.file_watcher.removePaths(watched_files)
if watched_dirs:
self.file_watcher.removePaths(watched_dirs)
root = self.context.root()
if root is None or self.context.mode() == "off":
return
paths: set[Path] = set()
directories: set[Path] = set()
docs_dir = root / "docs"
media_dir = root / "media"
if self.allows("directory"):
directories.add(root)
if self.allows("directory") and docs_dir.exists():
directories.add(docs_dir)
if self.allows("resource") and media_dir.exists():
directories.add(media_dir)
sample = root / "sample.md"
if sample.exists():
paths.add(sample.resolve())
open_paths = self.context.open_paths()
for open_path in open_paths:
paths.add(open_path)
if (
self.allows("current")
or self.allows("resource")
or self.allows("directory")
):
directories.add(open_path.parent)
if self.allows("resource") and open_path.suffix.lower() in {".md", ".markdown"}:
paths.update(self.referenced_local_paths(open_path))
normalized_paths = {path.resolve() for path in paths if path.exists() and path.is_file()}
self.watched_file_signatures = {
path: self.watched_file_signatures.get(path, self.signature(path))
for path in normalized_paths
}
file_paths = [str(path) for path in normalized_paths]
dir_paths = [str(path) for path in directories if path.exists() and path.is_dir()]
if file_paths:
self.file_watcher.addPaths(file_paths)
if dir_paths:
self.file_watcher.addPaths(dir_paths)
def file_changed_since_last_check(self, path: Path) -> bool:
had_previous = path in self.watched_file_signatures
previous = self.watched_file_signatures.get(path)
current = self.signature(path)
self.watched_file_signatures[path] = current
if not had_previous:
return False
return previous != current
def allows(self, target: str) -> bool:
if self.context.mode() == "off":
return False
if target == "current":
return self.context.mode() in {"current", "resources", "all"}
if target == "resource":
return self.context.mode() in {"resources", "all"}
if target == "directory":
return self.context.mode() == "all"
return False
def references_for_documents(self, document_paths: set[Path]) -> dict[Path, set[Path]]:
if not self.allows("resource"):
return {}
return {
path: self.referenced_local_paths(path)
for path in document_paths
if path.suffix.lower() in {".md", ".markdown"} and path.exists()
}
def affected_documents(
self,
changed_paths: set[Path],
open_paths: set[Path] | None = None,
reference_paths_by_document: dict[Path, set[Path]] | None = None,
) -> set[Path]:
if not changed_paths:
return set()
active_open_paths = open_paths or self.context.open_paths()
references = (
reference_paths_by_document
if reference_paths_by_document is not None
else self.references_for_documents(active_open_paths)
)
affected = active_open_paths & changed_paths
if self.allows("resource"):
for document_path, reference_paths in references.items():
if reference_paths & changed_paths:
affected.add(document_path)
return affected
@staticmethod
def referenced_local_paths(markdown_path: Path) -> set[Path]:
try:
source = markdown_path.read_text(encoding="utf-8")
except (OSError, UnicodeError):
return set()
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_file_changed(self, changed_path: str) -> None:
if self.context.mode() == "off":
return
changed = Path(changed_path).resolve()
if changed in self.internal_save_paths:
self.internal_save_paths.discard(changed)
self.watched_file_signatures[changed] = self.signature(changed)
self.update_paths()
return
if not self.file_changed_since_last_check(changed):
self.update_paths()
return
self.pending_changed_files.add(changed)
if self.affected_documents({changed}):
self.refresh_timer.start()
elif self.allows("directory") and self.context.is_document(changed):
self.pending_directory_refresh = True
self.tree_refresh_timer.start()
def on_directory_changed(self, changed_path: str) -> None:
root = self.context.root()
if self.context.mode() == "off" or root is None:
return
if self.context.renaming():
return
changed = Path(changed_path).resolve()
docs_dir = (root / "docs").resolve()
if self.allows("directory") and changed in {root, docs_dir}:
self.pending_directory_refresh = True
self.tree_refresh_timer.start()
open_paths = self.context.open_paths()
watched_content_dirs = {path.parent.resolve() for path in open_paths}
if self.allows("resource"):
watched_content_dirs.add((root / "media").resolve())
if changed in watched_content_dirs:
self.refresh_timer.start()
def refresh_changed_documents(self) -> None:
open_paths = {path for path in self.context.open_paths() if path.exists()}
if not open_paths:
self.pending_changed_files.clear()
self.update_paths()
return
reference_paths_by_document = self.references_for_documents(open_paths)
refresh_paths = set(open_paths)
for reference_paths in reference_paths_by_document.values():
refresh_paths.update(reference_paths)
signature_changed_paths = {
path
for path in refresh_paths
if path.exists() and self.file_changed_since_last_check(path)
}
changed_paths = {
path.resolve()
for path in self.pending_changed_files
if path.exists()
} | signature_changed_paths
affected_documents = self.affected_documents(
changed_paths,
open_paths=open_paths,
reference_paths_by_document=reference_paths_by_document,
)
self.pending_changed_files.clear()
if affected_documents:
self.context.refresh_tabs(affected_documents)
if (
self.allows("directory")
and any(self.context.is_document(path) for path in affected_documents)
):
self.context.refresh_tree()
else:
self.update_paths()