refactor(files): move file IO, watcher and link helpers into files.rs
This commit is contained in:
458
src/files.rs
Normal file
458
src/files.rs
Normal 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"));
|
||||
}
|
||||
}
|
||||
470
src/main.rs
470
src/main.rs
@@ -2,11 +2,15 @@
|
||||
|
||||
mod config;
|
||||
mod escape;
|
||||
mod files;
|
||||
mod instance;
|
||||
mod markdown;
|
||||
mod page;
|
||||
mod session;
|
||||
|
||||
#[cfg(test)]
|
||||
mod testutil;
|
||||
|
||||
#[cfg(test)]
|
||||
use config::clamp_zoom;
|
||||
use config::{
|
||||
@@ -15,7 +19,12 @@ use config::{
|
||||
show_warning_dialog, ThemeChoice,
|
||||
};
|
||||
use escape::{escape_js, html_escape_attr, html_escape_text};
|
||||
use notify::{Event, RecursiveMode, Watcher};
|
||||
use files::{
|
||||
forget_recent_file, install_file_watcher, is_supported_document, load_recent_files,
|
||||
local_document_path_from_url, normalize_new_markdown_path, remember_recent_file,
|
||||
resolve_document_link, reveal_in_explorer, save_active_file, self_write_still_matches_disk,
|
||||
should_protect_external_change, SelfWriteRecord, MAX_RECENT_FILES,
|
||||
};
|
||||
use session::DocumentSession;
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
@@ -37,12 +46,6 @@ use page::build_page;
|
||||
|
||||
const ICON_BYTES: &[u8] = include_bytes!("../assets/icon.ico");
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SelfWriteRecord {
|
||||
path: PathBuf,
|
||||
content: String,
|
||||
}
|
||||
|
||||
/// The page drives these over IPC today; the menu-style variants are kept for
|
||||
/// keyboard paths that are not wired up on Windows yet (Ctrl+W/E/F, Quit).
|
||||
#[allow(dead_code)]
|
||||
@@ -227,12 +230,6 @@ const HLJS_EXTRA_LANGS: &str = concat!(
|
||||
const KATEX_JS: &str = include_str!("../assets/katex/katex.min.js");
|
||||
const KATEX_CSS: &str = include_str!("../assets/katex/katex.inline.css");
|
||||
const MERMAID_JS: &str = include_str!("../assets/mermaid/mermaid.min.js");
|
||||
const MAX_RECENT_FILES: usize = 8;
|
||||
|
||||
fn recent_files_path() -> PathBuf {
|
||||
config_dir().join("recent-files.txt")
|
||||
}
|
||||
|
||||
fn tabs_json(session: &DocumentSession) -> String {
|
||||
let tabs = session
|
||||
.tabs
|
||||
@@ -273,58 +270,6 @@ fn missing_preview_html(tab_id: u64, path: &Path, s: &Strings) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
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 = 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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
fn base_href_for_file(path: &Path) -> Option<String> {
|
||||
let dir = path.parent()?;
|
||||
url::Url::from_directory_path(dir)
|
||||
@@ -499,33 +444,6 @@ fn home_preview_html(s: &Strings, recent_files: &[PathBuf]) -> String {
|
||||
html
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
/// Decode embedded icon.ico to an RGBA tao Icon for the window chrome.
|
||||
fn load_window_icon() -> Option<tao::window::Icon> {
|
||||
let img = image::load_from_memory_with_format(ICON_BYTES, image::ImageFormat::Ico).ok()?;
|
||||
@@ -534,148 +452,6 @@ fn load_window_icon() -> Option<tao::window::Icon> {
|
||||
tao::window::Icon::from_rgba(rgba.into_raw(), w, h).ok()
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
fn should_protect_external_change(webview_dirty: bool, session_dirty: bool) -> bool {
|
||||
webview_dirty || session_dirty
|
||||
}
|
||||
|
||||
fn normalize_new_markdown_path(mut path: PathBuf) -> PathBuf {
|
||||
let is_markdown = path
|
||||
.extension()
|
||||
.and_then(|extension| extension.to_str())
|
||||
.map(|extension| {
|
||||
matches!(
|
||||
extension.to_ascii_lowercase().as_str(),
|
||||
"md" | "markdown" | "mdown" | "mkd"
|
||||
)
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if !is_markdown {
|
||||
path.set_extension("md");
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
fn find_open_path(app: &AppState, path: &Path) -> Option<(WindowId, u64)> {
|
||||
let normalized = session::normalize_path(path.to_path_buf());
|
||||
for (window_id, ws) in &app.windows {
|
||||
@@ -737,35 +513,6 @@ fn focus_open_tab(
|
||||
true
|
||||
}
|
||||
|
||||
/// 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).
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn update_tabs(webview: &WebView, session: &DocumentSession) {
|
||||
let state = tabs_json(session);
|
||||
let _ = webview.evaluate_script(&format!("if(window.__setTabs)window.__setTabs({state});"));
|
||||
@@ -2061,19 +1808,7 @@ fn main() {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use notify::EventKind;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
fn temp_test_dir(name: &str) -> PathBuf {
|
||||
let unique = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("md-preview-{name}-{}-{unique}", std::process::id()));
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
use crate::testutil::temp_dir as temp_test_dir;
|
||||
|
||||
#[test]
|
||||
fn large_document_startup_stays_below_webview2_html_limit() {
|
||||
@@ -2311,68 +2046,6 @@ mod tests {
|
||||
assert!(html.contains("<hr />"));
|
||||
}
|
||||
|
||||
#[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_test_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_test_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 generated_heading_ids_support_cjk_anchor_links() {
|
||||
let html = md_to_html("1. [需求概述](#需求概述)\n\n## 需求概述");
|
||||
@@ -2637,22 +2310,6 @@ mod tests {
|
||||
assert!(empty_handler.contains("setEditMode(false)"));
|
||||
}
|
||||
|
||||
#[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 page_expands_multi_column_tables() {
|
||||
let strings = Strings::english();
|
||||
@@ -2705,109 +2362,4 @@ mod tests {
|
||||
assert!(json.contains(r#""home":true"#), "{json}");
|
||||
assert!(json.contains(r#""path":"""#), "{json}");
|
||||
}
|
||||
|
||||
#[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_test_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"));
|
||||
}
|
||||
}
|
||||
|
||||
18
src/testutil.rs
Normal file
18
src/testutil.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
//! Test-only helpers shared by the module test suites.
|
||||
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// Create a unique scratch directory under the platform temp dir (the test
|
||||
/// runner points TEMP/TMP at `target\tmp`).
|
||||
pub fn temp_dir(name: &str) -> PathBuf {
|
||||
let unique = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("md-preview-{name}-{}-{unique}", std::process::id()));
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
Reference in New Issue
Block a user