Files
md-preview/src/session.rs

241 lines
7.3 KiB
Rust

use std::fs;
use std::path::PathBuf;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DocumentTab {
pub id: u64,
pub path: PathBuf,
pub dirty: bool,
pub missing: bool,
pub edit_on_open: bool,
}
#[derive(Debug, Default)]
pub struct DocumentSession {
pub tabs: Vec<DocumentTab>,
pub active_id: Option<u64>,
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 == path) {
tab.missing = !tab.path.exists();
tab.edit_on_open |= edit_on_open;
self.active_id = Some(tab.id);
return tab.id;
}
self.next_id += 1;
let id = self.next_id;
self.tabs.push(DocumentTab {
id,
missing: !path.exists(),
path,
dirty: false,
edit_on_open,
});
self.active_id = Some(id);
id
}
pub fn activate(&mut self, id: u64) -> bool {
let Some(tab) = self.tabs.iter_mut().find(|tab| tab.id == id) else {
return false;
};
tab.missing = !tab.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
}
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<DocumentTab> {
let index = self.tabs.iter().position(|tab| tab.id == id)?;
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 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 == path) {
return false;
}
let Some(tab) = self.get_mut(id) else {
return false;
};
tab.path = path;
tab.missing = !tab.path.exists();
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].edit_on_open);
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<_>>(),
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);
}
#[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].path.to_string_lossy().to_string();
assert!(!stored.starts_with(r"\\?\"), "verbatim prefix leaked: {stored}");
assert!(session.tabs[0].path.ends_with("note.md"));
let _ = fs::remove_dir_all(dir);
}
}