refactor(files): move file IO, watcher and link helpers into files.rs

This commit is contained in:
2026-11-06 07:23:51 +08:00
parent d78d1aa722
commit 1208386452
3 changed files with 487 additions and 459 deletions

458
src/files.rs Normal file
View File

@@ -0,0 +1,458 @@
//! File-system side effects: the recent-files list, saving the active tab,
//! the single-file watcher, supported document types, local-link resolution
//! and Explorer integration.
use notify::{Event, RecursiveMode, Watcher};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use tao::event_loop::EventLoopProxy;
use tao::window::WindowId;
use crate::session::{self, DocumentSession};
use crate::UserEvent;
pub const MAX_RECENT_FILES: usize = 8;
#[derive(Debug)]
pub struct SelfWriteRecord {
pub path: PathBuf,
pub content: String,
}
fn recent_files_path() -> PathBuf {
crate::config::config_dir().join("recent-files.txt")
}
pub fn load_recent_files() -> Vec<PathBuf> {
let Ok(txt) = fs::read_to_string(recent_files_path()) else {
return Vec::new();
};
let mut files = Vec::new();
for line in txt.lines() {
if line.is_empty() {
continue;
}
let path = session::strip_verbatim(PathBuf::from(line));
if !path.exists() || files.iter().any(|p| p == &path) {
continue;
}
files.push(path);
if files.len() == MAX_RECENT_FILES {
break;
}
}
files
}
fn save_recent_files(files: &[PathBuf]) {
let dir = crate::config::config_dir();
let _ = fs::create_dir_all(&dir);
let body = files
.iter()
.take(MAX_RECENT_FILES)
.map(|p| p.to_string_lossy())
.collect::<Vec<_>>()
.join("\n");
let _ = fs::write(dir.join("recent-files.txt"), body);
}
pub fn remember_recent_file(files: &Arc<Mutex<Vec<PathBuf>>>, path: &Path) {
let mut recent = files.lock().unwrap();
recent.retain(|p| p != path);
recent.insert(0, path.to_path_buf());
recent.truncate(MAX_RECENT_FILES);
save_recent_files(&recent);
}
pub fn forget_recent_file(files: &Arc<Mutex<Vec<PathBuf>>>, path: &Path) -> bool {
let mut recent = files.lock().unwrap();
let original_len = recent.len();
recent.retain(|p| p != path);
if recent.len() == original_len {
return false;
}
save_recent_files(&recent);
true
}
pub fn is_supported_document(path: &Path) -> bool {
path.extension()
.map(|extension| {
matches!(
extension.to_string_lossy().to_ascii_lowercase().as_str(),
"md" | "markdown" | "mdown" | "mkd"
)
})
.unwrap_or(false)
}
pub fn reveal_in_explorer(path: &Path) -> bool {
let mut command = std::process::Command::new("explorer.exe");
if path.is_file() {
command.arg("/select,").arg(path);
} else if let Some(parent) = path.parent().filter(|parent| parent.is_dir()) {
command.arg(parent);
} else {
return false;
}
command.spawn().is_ok()
}
pub fn resolve_document_link(value: &str, active: Option<&Path>) -> Option<PathBuf> {
let url = match url::Url::parse(value) {
Ok(url) => url,
Err(url::ParseError::RelativeUrlWithoutBase) => {
url::Url::from_file_path(active?).ok()?.join(value).ok()?
}
Err(_) => return None,
};
local_document_path_from_url(url.as_str())
}
pub fn local_document_path_from_url(value: &str) -> Option<PathBuf> {
let url = url::Url::parse(value).ok()?;
if url.scheme() != "file" {
return None;
}
let path = url.to_file_path().ok()?;
if !path.is_file() || !is_supported_document(&path) {
return None;
}
fs::canonicalize(path).ok()
}
pub fn watch_scope_for_file(path: &Path) -> &Path {
path.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or(path)
}
fn event_path_matches_file(event_path: &Path, target: &Path) -> bool {
event_path == target
|| (target.file_name().is_some()
&& event_path.file_name() == target.file_name()
&& event_path.parent() == target.parent())
}
pub fn event_should_reload_file(ev: &Event, target: &Path) -> bool {
if ev.need_rescan() {
return true;
}
if !(ev.kind.is_modify() || ev.kind.is_create() || ev.kind.is_remove()) {
return false;
}
ev.paths
.iter()
.any(|event_path| event_path_matches_file(event_path, target))
}
/// Watch the active file's directory and turn real external changes into
/// `FileChanged` events. Watches only the parent directory, so sibling edits
/// still arrive and get filtered by [`event_should_reload_file`].
pub fn install_file_watcher(
holder: &Arc<Mutex<Option<notify::RecommendedWatcher>>>,
proxy: &EventLoopProxy<UserEvent>,
last_self_write: &Arc<Mutex<Option<SelfWriteRecord>>>,
window_id: WindowId,
path: Option<PathBuf>,
) {
let mut current = holder.lock().unwrap();
*current = None;
*last_self_write.lock().unwrap() = None;
let Some(path) = path else {
return;
};
let mut observed_content = fs::read(&path).ok();
let target_path = path.clone();
let callback_path = path.clone();
let proxy = proxy.clone();
let last_self_write = Arc::clone(last_self_write);
if let Ok(mut watcher) = notify::recommended_watcher(move |result: Result<Event, _>| {
if let Ok(event) = result {
if event_should_reload_file(&event, &callback_path) {
let content = fs::read(&callback_path).ok();
let mut last_self_write = last_self_write.lock().unwrap();
if file_content_should_reload(
&callback_path,
content,
&mut observed_content,
&mut last_self_write,
) {
let _ =
proxy.send_event(UserEvent::FileChanged(window_id, callback_path.clone()));
}
}
}
}) {
let scope = watch_scope_for_file(&target_path);
if scope.exists() && watcher.watch(scope, RecursiveMode::NonRecursive).is_ok() {
*current = Some(watcher);
}
}
}
pub fn file_content_should_reload(
path: &Path,
content: Option<Vec<u8>>,
observed: &mut Option<Vec<u8>>,
last_self_write: &mut Option<SelfWriteRecord>,
) -> bool {
if content == *observed {
return false;
}
let is_self_write = last_self_write.as_ref().is_some_and(|record| {
record.path == path && content.as_deref() == Some(record.content.as_bytes())
});
*observed = content;
if is_self_write {
return false;
}
// A subsequent revert to our old snapshot is a real change too.
if observed.is_some() {
*last_self_write = None;
}
true
}
pub fn self_write_still_matches_disk(record: Option<&SelfWriteRecord>, path: &Path) -> bool {
let Some(record) = record else {
return false;
};
record.path == path
&& fs::read(path)
.map(|content| content == record.content.as_bytes())
.unwrap_or(false)
}
pub fn should_protect_external_change(webview_dirty: bool, session_dirty: bool) -> bool {
webview_dirty || session_dirty
}
pub fn normalize_new_markdown_path(mut path: PathBuf) -> PathBuf {
if !is_supported_document(&path) {
path.set_extension("md");
}
path
}
/// Write the active tab's file and remember the write as our own so the file
/// watcher does not treat it as an external change. Returns false when nothing
/// was written (no active file, or the write failed and SaveFailed was sent).
pub fn save_active_file(
session: &Arc<Mutex<DocumentSession>>,
last_self_write: &Arc<Mutex<Option<SelfWriteRecord>>>,
proxy: &EventLoopProxy<UserEvent>,
window_id: WindowId,
content: &str,
) -> bool {
let Some(path) = session.lock().unwrap().active_path().map(Path::to_path_buf) else {
return false;
};
*last_self_write.lock().unwrap() = Some(SelfWriteRecord {
path: path.clone(),
content: content.to_string(),
});
match fs::write(&path, content) {
Ok(()) => {
let _ = proxy.send_event(UserEvent::FileSaved(window_id, path));
true
}
Err(error) => {
let _ = proxy.send_event(UserEvent::SaveFailed(window_id, path, error.to_string()));
false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::temp_dir;
use notify::EventKind;
#[test]
fn only_markdown_extensions_are_supported_documents() {
for name in ["note.md", "note.MARKDOWN", "note.mdown", "note.mkd"] {
assert!(is_supported_document(Path::new(name)), "{name}");
}
for name in ["note.txt", "note.html", "note", "note.md.bak"] {
assert!(!is_supported_document(Path::new(name)), "{name}");
}
}
#[test]
fn file_urls_only_open_existing_supported_documents() {
let dir = temp_dir("document-links");
let linked = dir.join("含 空格.md");
let unsupported = dir.join("page.html");
fs::write(&linked, "# Linked").unwrap();
fs::write(&unsupported, "<h1>Page</h1>").unwrap();
let linked_url = url::Url::from_file_path(&linked).unwrap().to_string();
let unsupported_url = url::Url::from_file_path(&unsupported).unwrap().to_string();
let missing_url = url::Url::from_file_path(dir.join("missing.md"))
.unwrap()
.to_string();
assert_eq!(
local_document_path_from_url(&format!("{linked_url}#section")),
Some(fs::canonicalize(&linked).unwrap())
);
assert_eq!(local_document_path_from_url(&unsupported_url), None);
assert_eq!(local_document_path_from_url(&missing_url), None);
assert_eq!(
local_document_path_from_url("https://example.com/readme.md"),
None
);
let _ = fs::remove_dir_all(dir);
}
#[test]
fn document_links_resolve_against_active_file_without_webview_base() {
let dir = temp_dir("relative-doc-links");
fs::create_dir_all(dir.join("folder")).unwrap();
let active = dir.join("folder/current.md");
let linked = dir.join("含 空格.md");
fs::write(&linked, "# Linked").unwrap();
let expected = Some(fs::canonicalize(&linked).unwrap());
assert_eq!(
resolve_document_link("../含%20空格.md#section", Some(&active)),
expected
);
assert_eq!(
resolve_document_link("../含 空格.md", Some(&active)),
expected
);
assert_eq!(resolve_document_link("missing.md", Some(&active)), None);
assert_eq!(
resolve_document_link("https://example.com/file.md", Some(&active)),
None
);
assert_eq!(resolve_document_link("../", Some(&active)), None);
assert_eq!(resolve_document_link("relative.md", None), None);
}
#[test]
fn new_markdown_path_keeps_markdown_extensions_and_replaces_other_extensions() {
assert_eq!(
normalize_new_markdown_path(PathBuf::from("/tmp/plan")),
PathBuf::from("/tmp/plan.md")
);
assert_eq!(
normalize_new_markdown_path(PathBuf::from("/tmp/plan.markdown")),
PathBuf::from("/tmp/plan.markdown")
);
assert_eq!(
normalize_new_markdown_path(PathBuf::from("/tmp/plan.txt")),
PathBuf::from("/tmp/plan.md")
);
}
#[test]
fn vim_style_target_rewrite_events_reload_current_file() {
let target = PathBuf::from("/tmp/note.md");
let ev = Event::new(EventKind::Create(notify::event::CreateKind::File))
.add_path(PathBuf::from("/tmp/note.md"));
assert!(event_should_reload_file(&ev, &target));
}
#[test]
fn sibling_file_events_do_not_reload_current_file() {
let target = PathBuf::from("/tmp/note.md");
let ev = Event::new(EventKind::Modify(notify::event::ModifyKind::Data(
notify::event::DataChange::Any,
)))
.add_path(PathBuf::from("/tmp/other.md"));
assert!(!event_should_reload_file(&ev, &target));
}
#[test]
fn self_write_suppression_checks_disk_content_not_only_time() {
let dir = temp_dir("self-write-suppression");
let path = dir.join("note.md");
fs::write(&path, "saved by app").unwrap();
let record = SelfWriteRecord {
path: path.clone(),
content: "saved by app".to_string(),
};
assert!(self_write_still_matches_disk(Some(&record), &path));
fs::write(&path, "external edit").unwrap();
assert!(!self_write_still_matches_disk(Some(&record), &path));
}
#[test]
fn sync_events_ignore_identical_bytes_but_detect_external_edits_and_reverts() {
let path = PathBuf::from("note.md");
let mut observed = Some(b"initial".to_vec());
let mut own = Some(SelfWriteRecord {
path: path.clone(),
content: "saved".to_string(),
});
assert!(!file_content_should_reload(
&path,
Some(b"initial".to_vec()),
&mut observed,
&mut own
));
assert!(!file_content_should_reload(
&path,
Some(b"saved".to_vec()),
&mut observed,
&mut own
));
for _ in 0..100 {
assert!(!file_content_should_reload(
&path,
Some(b"saved".to_vec()),
&mut observed,
&mut own
));
}
assert!(file_content_should_reload(
&path,
Some(b"external".to_vec()),
&mut observed,
&mut own
));
assert!(file_content_should_reload(
&path,
Some(b"saved".to_vec()),
&mut observed,
&mut own
));
assert!(file_content_should_reload(
&path,
None,
&mut observed,
&mut own
));
assert!(file_content_should_reload(
&path,
Some(b"saved".to_vec()),
&mut observed,
&mut own
));
}
#[test]
fn external_change_protection_uses_dirty_state_from_either_side() {
assert!(!should_protect_external_change(false, false));
assert!(should_protect_external_change(true, false));
assert!(should_protect_external_change(false, true));
assert!(should_protect_external_change(true, true));
}
#[test]
fn file_watch_scope_is_parent_directory() {
let target = PathBuf::from("/tmp/note.md");
assert_eq!(watch_scope_for_file(&target), Path::new("/tmp"));
}
}