use std::fs; use std::path::{Path, PathBuf}; #[derive(Clone, Debug, PartialEq)] pub struct DocumentTab { pub id: u64, /// `None` marks the built-in Home tab; Home has no file on disk. pub path: Option, pub dirty: bool, pub missing: bool, /// Edit mode belongs to the tab, so switching tabs restores the mode the /// tab was left in instead of carrying one global mode across documents. pub editing: bool, /// Viewport position as a 0.0 (top) ..= 1.0 (bottom) fraction. Stores a /// ratio rather than pixels so zoom and reflow do not move the reader. pub scroll_ratio: f32, } impl DocumentTab { pub fn is_home(&self) -> bool { self.path.is_none() } pub fn file_path(&self) -> Option<&Path> { self.path.as_deref() } } #[derive(Debug, Default)] pub struct DocumentSession { pub tabs: Vec, pub active_id: Option, next_id: u64, } impl DocumentSession { pub fn open(&mut self, path: PathBuf, edit_on_open: bool) -> u64 { let path = normalize_path(path); if let Some(tab) = self .tabs .iter_mut() .find(|tab| tab.path.as_deref() == Some(path.as_path())) { tab.missing = !path.exists(); tab.editing |= edit_on_open; self.active_id = Some(tab.id); return tab.id; } self.next_id += 1; let id = self.next_id; let missing = !path.exists(); self.tabs.push(DocumentTab { id, path: Some(path), dirty: false, missing, editing: edit_on_open, scroll_ratio: 0.0, }); self.active_id = Some(id); id } /// Append and activate a Home tab (the in-app "new tab page"). pub fn open_home(&mut self) -> u64 { self.next_id += 1; let id = self.next_id; self.tabs.push(DocumentTab { id, path: None, dirty: false, missing: false, editing: false, scroll_ratio: 0.0, }); self.active_id = Some(id); id } /// Open `path`, turning the active Home tab into the document when possible /// (browser-style navigation). Falls back to appending a tab otherwise. pub fn open_reusing_home(&mut self, path: PathBuf, edit_on_open: bool) -> u64 { let Some(active_id) = self.active_id else { return self.open(path, edit_on_open); }; if !self .tabs .iter() .any(|tab| tab.id == active_id && tab.is_home()) { return self.open(path, edit_on_open); } let path = normalize_path(path); if let Some(existing) = self .tabs .iter_mut() .find(|tab| tab.id != active_id && tab.path.as_deref() == Some(path.as_path())) { existing.missing = !path.exists(); existing.editing |= edit_on_open; let existing_id = existing.id; // The blank tab did its job; drop it the way a browser would. self.tabs.retain(|tab| tab.id != active_id); self.active_id = Some(existing_id); return existing_id; } let missing = !path.exists(); let tab = self .tabs .iter_mut() .find(|tab| tab.id == active_id) .expect("active tab disappeared"); tab.path = Some(path); tab.missing = missing; tab.dirty = false; tab.editing = edit_on_open; tab.scroll_ratio = 0.0; active_id } pub fn activate(&mut self, id: u64) -> bool { let Some(tab) = self.tabs.iter_mut().find(|tab| tab.id == id) else { return false; }; if let Some(path) = tab.path.as_deref() { tab.missing = !path.exists(); } self.active_id = Some(id); true } pub fn close(&mut self, id: u64) -> bool { let Some(index) = self.tabs.iter().position(|tab| tab.id == id) else { return false; }; let was_active = self.active_id == Some(id); self.tabs.remove(index); if was_active { self.active_id = self .tabs .get(index) .or_else(|| index.checked_sub(1).and_then(|i| self.tabs.get(i))) .map(|tab| tab.id); } true } /// Close a tab and leave a fresh Home tab behind when it was the last one. pub fn close_with_home_fallback(&mut self, id: u64) -> bool { if !self.close(id) { return false; } if self.tabs.is_empty() { self.open_home(); } true } pub fn with_tab(tab: DocumentTab) -> Self { let id = tab.id; Self { tabs: vec![tab], active_id: Some(id), next_id: id, } } pub fn detach(&mut self, id: u64) -> Option { let index = self.tabs.iter().position(|tab| tab.id == id)?; if self.tabs[index].is_home() { return None; } let was_active = self.active_id == Some(id); let tab = self.tabs.remove(index); if was_active { self.active_id = self .tabs .get(index) .or_else(|| index.checked_sub(1).and_then(|i| self.tabs.get(i))) .map(|tab| tab.id); } Some(tab) } pub fn active(&self) -> Option<&DocumentTab> { let id = self.active_id?; self.tabs.iter().find(|tab| tab.id == id) } pub fn active_mut(&mut self) -> Option<&mut DocumentTab> { let id = self.active_id?; self.tabs.iter_mut().find(|tab| tab.id == id) } pub fn active_path(&self) -> Option<&Path> { self.active().and_then(DocumentTab::file_path) } pub fn active_is_home(&self) -> bool { self.active().is_some_and(DocumentTab::is_home) } /// Remember the viewport of the active tab (0.0 top .. 1.0 bottom). pub fn set_active_scroll_ratio(&mut self, ratio: f32) { if !ratio.is_finite() { return; } if let Some(tab) = self.active_mut() { tab.scroll_ratio = ratio.clamp(0.0, 1.0); } } /// Store the viewport by tab id; late scroll reports must not land on a tab /// that was activated in the meantime. pub fn set_tab_scroll_ratio(&mut self, id: u64, ratio: f32) { if !ratio.is_finite() { return; } if let Some(tab) = self.get_mut(id) { tab.scroll_ratio = ratio.clamp(0.0, 1.0); } } pub fn set_tab_editing(&mut self, id: u64, editing: bool) { if let Some(tab) = self.get_mut(id) { tab.editing = editing; } } pub fn get_mut(&mut self, id: u64) -> Option<&mut DocumentTab> { self.tabs.iter_mut().find(|tab| tab.id == id) } pub fn relocate(&mut self, id: u64, path: PathBuf) -> bool { let path = normalize_path(path); if self .tabs .iter() .any(|tab| tab.id != id && tab.path.as_deref() == Some(path.as_path())) { return false; } let missing = !path.exists(); let Some(tab) = self.get_mut(id) else { return false; }; if tab.is_home() { return false; } tab.path = Some(path); tab.missing = missing; true } } pub(crate) fn normalize_path(path: PathBuf) -> PathBuf { let absolute = if path.is_absolute() { path } else { std::env::current_dir().unwrap_or_default().join(path) }; let resolved = fs::canonicalize(&absolute).unwrap_or_else(|_| { absolute .parent() .and_then(|parent| fs::canonicalize(parent).ok()) .and_then(|parent| absolute.file_name().map(|name| parent.join(name))) .unwrap_or(absolute) }); strip_verbatim(resolved) } /// Windows canonicalize returns verbatim paths. Strip that prefix so session /// and recent-file entries stay readable and usable by other tools. pub(crate) fn strip_verbatim(path: PathBuf) -> PathBuf { #[cfg(target_os = "windows")] { let text = path.to_string_lossy().into_owned(); if let Some(rest) = text.strip_prefix(r"\\?\UNC\") { return PathBuf::from(format!(r"\\{rest}")); } if let Some(rest) = text.strip_prefix(r"\\?\") { return PathBuf::from(rest.to_string()); } } path } #[cfg(test)] mod tests { use super::*; use std::fs; use std::time::{SystemTime, UNIX_EPOCH}; 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-session-{name}-{}-{unique}", std::process::id() )); fs::create_dir_all(&dir).unwrap(); dir } #[test] fn opening_the_same_path_activates_without_duplicate() { let dir = temp_dir("dedupe"); let file = dir.join("note.md"); fs::write(&file, "# Note").unwrap(); let mut session = DocumentSession::default(); let first = session.open(file.clone(), false); let second = session.open(file.clone(), true); assert_eq!(first, second); assert_eq!(session.tabs.len(), 1); assert_eq!(session.active_id, Some(first)); assert!(session.tabs[0].editing); let _ = fs::remove_dir_all(dir); } #[test] fn closing_active_tab_selects_the_next_neighbor() { let dir = temp_dir("close"); let mut session = DocumentSession::default(); let first = session.open(dir.join("one.md"), false); let second = session.open(dir.join("two.md"), false); let third = session.open(dir.join("three.md"), false); assert!(session.activate(second)); assert!(session.close(second)); assert_eq!(session.active_id, Some(third)); assert_eq!( session.tabs.iter().map(|tab| tab.id).collect::>(), vec![first, third] ); let _ = fs::remove_dir_all(dir); } #[test] fn detaching_a_tab_keeps_source_and_adopts_it_in_new_session() { let dir = temp_dir("detach"); let mut session = DocumentSession::default(); let first = session.open(dir.join("one.md"), false); let second = session.open(dir.join("two.md"), false); session.activate(first); let moved = session.detach(second).unwrap(); assert_eq!(session.active_id, Some(first)); assert_eq!(session.tabs.len(), 1); let adopted = DocumentSession::with_tab(moved); assert_eq!(adopted.active_id, Some(second)); assert_eq!(adopted.tabs.len(), 1); assert_eq!(adopted.tabs[0].id, second); let _ = fs::remove_dir_all(dir); } #[test] fn home_tab_is_a_tab_without_a_file_path() { let mut session = DocumentSession::default(); let home = session.open_home(); assert_eq!(session.active_id, Some(home)); assert_eq!(session.tabs.len(), 1); assert!(session.tabs[0].is_home()); assert_eq!(session.active_path(), None); assert!(session.active_is_home()); } #[test] fn opening_a_file_from_home_reuses_the_home_tab() { let dir = temp_dir("home-reuse"); let file = dir.join("note.md"); fs::write(&file, "# Note").unwrap(); let mut session = DocumentSession::default(); let home = session.open_home(); let opened = session.open_reusing_home(file.clone(), true); assert_eq!(opened, home); assert_eq!(session.tabs.len(), 1); assert!(!session.tabs[0].is_home()); assert_eq!(session.tabs[0].file_path(), Some(file.as_path())); assert!(session.tabs[0].editing); let _ = fs::remove_dir_all(dir); } #[test] fn opening_an_already_open_file_from_home_drops_the_blank_tab() { let dir = temp_dir("home-dedupe"); let first = dir.join("one.md"); fs::write(&first, "one").unwrap(); let mut session = DocumentSession::default(); let first_id = session.open(first.clone(), false); let home = session.open_home(); let opened = session.open_reusing_home(first, false); assert_eq!(opened, first_id); assert_eq!(session.tabs.len(), 1); assert_eq!(session.active_id, Some(first_id)); assert!(!session.tabs.iter().any(|tab| tab.id == home)); let _ = fs::remove_dir_all(dir); } #[test] fn home_tab_cannot_be_detached_or_relocated() { let dir = temp_dir("home-guard"); let mut session = DocumentSession::default(); let home = session.open_home(); assert!(session.detach(home).is_none()); assert!(!session.relocate(home, dir.join("note.md"))); assert_eq!(session.tabs.len(), 1); let _ = fs::remove_dir_all(dir); } #[test] fn closing_the_last_file_leaves_a_home_tab() { let dir = temp_dir("close-home"); let file = dir.join("note.md"); fs::write(&file, "").unwrap(); let mut session = DocumentSession::default(); let file_id = session.open(file, false); assert!(session.close_with_home_fallback(file_id)); assert_eq!(session.tabs.len(), 1); assert!(session.active().unwrap().is_home()); assert_eq!(session.active_id, Some(session.tabs[0].id)); let _ = fs::remove_dir_all(dir); } #[test] fn edit_mode_and_scroll_position_are_remembered_per_tab() { let dir = temp_dir("per-tab-view"); let mut session = DocumentSession::default(); let first = session.open(dir.join("one.md"), true); session.set_active_scroll_ratio(0.75); let second = session.open(dir.join("two.md"), false); assert_ne!(first, second); assert!(!session.active().unwrap().editing); assert_eq!(session.active().unwrap().scroll_ratio, 0.0); assert!(session.activate(first)); assert!(session.active().unwrap().editing); assert_eq!(session.active().unwrap().scroll_ratio, 0.75); // Late reports address the tab by id, not by whichever tab is active. session.set_tab_scroll_ratio(second, 0.4); assert!(session.activate(second)); assert_eq!(session.active().unwrap().scroll_ratio, 0.4); assert!(!session.active().unwrap().editing); let _ = fs::remove_dir_all(dir); } #[cfg(target_os = "windows")] #[test] fn opened_paths_drop_windows_verbatim_prefix() { let dir = temp_dir("verbatim"); let file = dir.join("note.md"); fs::write(&file, "# Note").unwrap(); let mut session = DocumentSession::default(); session.open(file.clone(), false); let stored = session.tabs[0] .file_path() .unwrap() .to_string_lossy() .to_string(); assert!( !stored.starts_with(r"\\?\"), "verbatim prefix leaked: {stored}" ); assert!(session.tabs[0].file_path().unwrap().ends_with("note.md")); let _ = fs::remove_dir_all(dir); } }