feat: dedupe open documents and drop session restore

This commit is contained in:
2026-10-28 14:46:40 +08:00
parent 55d78485dd
commit e24733ad96
2 changed files with 108 additions and 135 deletions

View File

@@ -853,10 +853,6 @@ fn recent_files_path() -> PathBuf {
config_dir().join("recent-files.txt") config_dir().join("recent-files.txt")
} }
fn session_path() -> PathBuf {
config_dir().join("session.json")
}
fn tabs_json(session: &DocumentSession) -> String { fn tabs_json(session: &DocumentSession) -> String {
let tabs = session let tabs = session
.tabs .tabs
@@ -3633,16 +3629,54 @@ fn register_finder_extension() {
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
fn register_finder_extension() {} fn register_finder_extension() {}
fn persist_session(session: &DocumentSession) { fn find_open_path(app: &AppState, path: &Path) -> Option<(WindowId, u64)> {
if let Err(error) = session.save(&session_path()) { let normalized = session::normalize_path(path.to_path_buf());
eprintln!("Could not save tab session: {error}"); for (window_id, ws) in &app.windows {
let session = ws.session.lock().unwrap();
if let Some(tab) = session.tabs.iter().find(|tab| tab.path == normalized) {
return Some((*window_id, tab.id));
} }
} }
None
}
fn persist_window_session(ws: &WindowState) { fn focus_open_tab(
if ws.is_primary { app: &mut AppState,
persist_session(&ws.session.lock().unwrap()); window_id: WindowId,
tab_id: u64,
recent_files: &Arc<Mutex<Vec<PathBuf>>>,
strings: &Strings,
proxy: &EventLoopProxy<UserEvent>,
) {
app.active_window = window_id;
let Some(ws) = app.windows.get_mut(&window_id) else {
return;
};
ws.window.set_minimized(false);
ws.window.set_focus();
let mut session = ws.session.lock().unwrap();
let target_active = session.active_id == Some(tab_id);
let active_dirty = session.active().map(|tab| tab.dirty).unwrap_or(false);
if !target_active && active_dirty {
// Do not switch away from unsaved edits just to focus another tab.
return;
} }
if !session.activate(tab_id) {
return;
}
if target_active {
update_tabs(&ws.webview, &session);
return;
}
drop(session);
ws.render_active(recent_files, strings);
let path = ws
.session
.lock()
.unwrap()
.active()
.map(|tab| tab.path.clone());
install_file_watcher(&ws.watcher, proxy, &ws.last_self_write, window_id, path);
} }
fn update_tabs(webview: &WebView, session: &DocumentSession) { fn update_tabs(webview: &WebView, session: &DocumentSession) {
@@ -4158,7 +4192,7 @@ fn main() {
register_finder_extension(); register_finder_extension();
bench_log("after_register"); bench_log("after_register");
let mut initial_session = DocumentSession::load(&session_path()); let mut initial_session = DocumentSession::default();
for path in cli_paths { for path in cli_paths {
initial_session.open(path, edit_from_cli); initial_session.open(path, edit_from_cli);
} }
@@ -4204,7 +4238,6 @@ fn main() {
let initial_page = build_startup_page(&strings); let initial_page = build_startup_page(&strings);
let initial_flags = EnhanceFlags::default(); let initial_flags = EnhanceFlags::default();
persist_session(&initial_session);
let document_session = Arc::new(Mutex::new(initial_session)); let document_session = Arc::new(Mutex::new(initial_session));
let enhance_flags: Arc<Mutex<EnhanceFlags>> = Arc::new(Mutex::new(initial_flags)); let enhance_flags: Arc<Mutex<EnhanceFlags>> = Arc::new(Mutex::new(initial_flags));
let last_self_write: Arc<Mutex<Option<SelfWriteRecord>>> = Arc::new(Mutex::new(None)); let last_self_write: Arc<Mutex<Option<SelfWriteRecord>>> = Arc::new(Mutex::new(None));
@@ -4368,8 +4401,8 @@ fn main() {
} }
} }
TaoEvent::UserEvent(UserEvent::OpenPaths(paths, edit_on_open)) => { TaoEvent::UserEvent(UserEvent::OpenPaths(paths, edit_on_open)) => {
let window_id = app.active_window; let mut target_window = app.active_window;
let Some(ws) = app.windows.get_mut(&window_id) else { let Some(ws) = app.windows.get_mut(&target_window) else {
return; return;
}; };
if !ws.page_ready { if !ws.page_ready {
@@ -4379,21 +4412,42 @@ fn main() {
ws.window.set_minimized(false); ws.window.set_minimized(false);
ws.window.set_focus(); ws.window.set_focus();
if paths.is_empty() { return; } let paths = paths
.into_iter()
.filter(|path| is_supported_document(path))
.collect::<Vec<_>>();
if paths.is_empty() {
return;
}
for path in paths {
if let Some((window_id, tab_id)) = find_open_path(&app, &path) {
focus_open_tab(
&mut app,
window_id,
tab_id,
&recent_files,
&strings,
&proxy,
);
target_window = window_id;
continue;
}
let Some(ws) = app.windows.get_mut(&target_window) else {
return;
};
if !ws.page_ready {
ws.pending_launches.push((vec![path], edit_on_open));
continue;
}
let mut session = ws.session.lock().unwrap(); let mut session = ws.session.lock().unwrap();
let previous_active = session.active_id; let previous_active = session.active_id;
let preserve_active = session.active().map(|tab| tab.dirty).unwrap_or(false); let preserve_active = session.active().map(|tab| tab.dirty).unwrap_or(false);
for path in paths.into_iter().filter(|path| is_supported_document(path)) {
session.open(path, edit_on_open); session.open(path, edit_on_open);
}
if preserve_active { if preserve_active {
if let Some(id) = previous_active { if let Some(id) = previous_active {
session.activate(id); session.activate(id);
} }
} }
if ws.is_primary {
persist_session(&session);
}
if preserve_active { if preserve_active {
update_tabs(&ws.webview, &session); update_tabs(&ws.webview, &session);
} else { } else {
@@ -4401,7 +4455,14 @@ fn main() {
ws.render_active(&recent_files, &strings); ws.render_active(&recent_files, &strings);
} }
let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone()); let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path); install_file_watcher(
&ws.watcher,
&proxy,
&ws.last_self_write,
target_window,
path,
);
}
} }
TaoEvent::UserEvent(UserEvent::ActivateTab(window_id, id)) => { TaoEvent::UserEvent(UserEvent::ActivateTab(window_id, id)) => {
let Some(ws) = app.windows.get_mut(&window_id) else { let Some(ws) = app.windows.get_mut(&window_id) else {
@@ -4409,9 +4470,6 @@ fn main() {
}; };
let mut session = ws.session.lock().unwrap(); let mut session = ws.session.lock().unwrap();
if session.activate(id) { if session.activate(id) {
if ws.is_primary {
persist_session(&session);
}
drop(session); drop(session);
ws.render_active(&recent_files, &strings); ws.render_active(&recent_files, &strings);
let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone()); let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
@@ -4425,9 +4483,6 @@ fn main() {
let mut session = ws.session.lock().unwrap(); let mut session = ws.session.lock().unwrap();
let was_active = session.active_id == Some(id); let was_active = session.active_id == Some(id);
if session.close(id) { if session.close(id) {
if ws.is_primary {
persist_session(&session);
}
if was_active { if was_active {
drop(session); drop(session);
ws.render_active(&recent_files, &strings); ws.render_active(&recent_files, &strings);
@@ -4457,14 +4512,22 @@ fn main() {
.add_filter("Markdown", &["md", "markdown", "mdown", "mkd", "txt"]) .add_filter("Markdown", &["md", "markdown", "mdown", "mkd", "txt"])
.pick_file() .pick_file()
{ {
if let Some((other_id, other_tab)) = find_open_path(&app, &path) {
focus_open_tab(
&mut app,
other_id,
other_tab,
&recent_files,
&strings,
&proxy,
);
return;
}
let Some(ws) = app.windows.get_mut(&window_id) else { let Some(ws) = app.windows.get_mut(&window_id) else {
return; return;
}; };
let mut session = ws.session.lock().unwrap(); let mut session = ws.session.lock().unwrap();
if session.relocate(id, path) && session.activate(id) { if session.relocate(id, path) && session.activate(id) {
if ws.is_primary {
persist_session(&session);
}
drop(session); drop(session);
ws.render_active(&recent_files, &strings); ws.render_active(&recent_files, &strings);
let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone()); let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
@@ -4525,7 +4588,6 @@ fn main() {
} }
drop(session); drop(session);
ws.render_active(&recent_files, &strings); ws.render_active(&recent_files, &strings);
persist_window_session(ws);
} }
} }
TaoEvent::UserEvent(UserEvent::FileSaved(window_id, path)) => { TaoEvent::UserEvent(UserEvent::FileSaved(window_id, path)) => {
@@ -4561,9 +4623,6 @@ fn main() {
} }
} }
ws.dirty = session.active().map(|tab| tab.dirty).unwrap_or(false); ws.dirty = session.active().map(|tab| tab.dirty).unwrap_or(false);
if ws.is_primary {
persist_session(&session);
}
update_tabs(&ws.webview, &session); update_tabs(&ws.webview, &session);
update_window_title(&ws.window, &session); update_window_title(&ws.window, &session);
let pending_close = ws.pending_close; let pending_close = ws.pending_close;
@@ -4582,7 +4641,6 @@ fn main() {
if ws.pending_close { if ws.pending_close {
ws.pending_close = false; ws.pending_close = false;
if confirm_discard_unsaved(&error) { if confirm_discard_unsaved(&error) {
persist_window_session(ws);
close_window(&mut app, window_id, control_flow); close_window(&mut app, window_id, control_flow);
} }
} else { } else {
@@ -4652,7 +4710,6 @@ fn main() {
if ws.is_primary { if ws.is_primary {
save_window_geom(&ws.window); save_window_geom(&ws.window);
} }
persist_window_session(ws);
*control_flow = ControlFlow::Exit; *control_flow = ControlFlow::Exit;
} }
} }
@@ -4745,7 +4802,6 @@ fn main() {
"if(window.__mdPreviewSave)window.__mdPreviewSave();", "if(window.__mdPreviewSave)window.__mdPreviewSave();",
); );
} else if !ws.pending_close { } else if !ws.pending_close {
persist_window_session(ws);
close_window(&mut app, window_id, control_flow); close_window(&mut app, window_id, control_flow);
} }
} }

View File

@@ -1,7 +1,5 @@
use serde::{Deserialize, Serialize};
use std::fs; use std::fs;
use std::io; use std::path::PathBuf;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub struct DocumentTab { pub struct DocumentTab {
@@ -19,37 +17,7 @@ pub struct DocumentSession {
next_id: u64, next_id: u64,
} }
#[derive(Debug, Deserialize, Serialize)]
struct PersistedSession {
version: u8,
active: Option<usize>,
tabs: Vec<PathBuf>,
}
impl DocumentSession { impl DocumentSession {
pub fn load(path: &Path) -> Self {
let Ok(raw) = fs::read(path) else {
return Self::default();
};
let Ok(saved) = serde_json::from_slice::<PersistedSession>(&raw) else {
return Self::default();
};
if saved.version != 1 {
return Self::default();
}
let mut session = Self::default();
for path in saved.tabs {
session.open(path, false);
}
session.active_id = saved
.active
.and_then(|index| session.tabs.get(index))
.map(|tab| tab.id)
.or_else(|| session.tabs.last().map(|tab| tab.id));
session
}
pub fn open(&mut self, path: PathBuf, edit_on_open: bool) -> u64 { pub fn open(&mut self, path: PathBuf, edit_on_open: bool) -> u64 {
let path = normalize_path(path); let path = normalize_path(path);
if let Some(tab) = self.tabs.iter_mut().find(|tab| tab.path == path) { if let Some(tab) = self.tabs.iter_mut().find(|tab| tab.path == path) {
@@ -97,28 +65,6 @@ impl DocumentSession {
true true
} }
pub fn save(&self, path: &Path) -> io::Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let active = self
.active_id
.and_then(|id| self.tabs.iter().position(|tab| tab.id == id));
let saved = PersistedSession {
version: 1,
active,
tabs: self.tabs.iter().map(|tab| tab.path.clone()).collect(),
};
let body = serde_json::to_vec_pretty(&saved).map_err(io::Error::other)?;
let temporary = path.with_extension("json.tmp");
fs::write(&temporary, body)?;
#[cfg(target_os = "windows")]
if path.exists() {
fs::remove_file(path)?;
}
fs::rename(temporary, path)
}
pub fn active(&self) -> Option<&DocumentTab> { pub fn active(&self) -> Option<&DocumentTab> {
let id = self.active_id?; let id = self.active_id?;
self.tabs.iter().find(|tab| tab.id == id) self.tabs.iter().find(|tab| tab.id == id)
@@ -147,7 +93,7 @@ impl DocumentSession {
} }
} }
fn normalize_path(path: PathBuf) -> PathBuf { pub(crate) fn normalize_path(path: PathBuf) -> PathBuf {
let absolute = if path.is_absolute() { let absolute = if path.is_absolute() {
path path
} else { } else {
@@ -249,33 +195,4 @@ mod tests {
assert!(session.tabs[0].path.ends_with("note.md")); assert!(session.tabs[0].path.ends_with("note.md"));
let _ = fs::remove_dir_all(dir); let _ = fs::remove_dir_all(dir);
} }
#[test]
fn persisted_session_keeps_missing_tabs_and_active_order() {
let dir = temp_dir("roundtrip");
let state_path = dir.join("session.json");
let existing = dir.join("existing.md");
let missing = dir.join("missing.md");
fs::write(&existing, "# Existing").unwrap();
let mut session = DocumentSession::default();
session.open(existing.clone(), false);
session.open(missing.clone(), false);
session.save(&state_path).unwrap();
let restored = DocumentSession::load(&state_path);
assert_eq!(restored.tabs.len(), 2);
assert_eq!(
restored.tabs[0].path,
strip_verbatim(fs::canonicalize(existing).unwrap())
);
assert_eq!(
restored.tabs[1].path,
strip_verbatim(fs::canonicalize(&dir).unwrap()).join(missing.file_name().unwrap())
);
assert!(!restored.tabs[0].missing);
assert!(restored.tabs[1].missing);
assert_eq!(restored.active_id, restored.tabs.get(1).map(|tab| tab.id));
let _ = fs::remove_dir_all(dir);
}
} }