forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

recent.rs236 lines, 8.3 KiBHistoryRawDownload
1//! The last projects opened or saved, newest first, kept in `$XDG_STATE_HOME/edith/recent`
2//! (one absolute path per line, at most [`MAX`]). The File menu's Open recent reads it, and
3//! so will the welcome screen: [`list`] is the one API for both.
4
5use std::path::{Path, PathBuf};
6
7/// How many projects the list holds.
8pub(crate) const MAX: usize = 10;
9
10/// Why a listed project cannot be opened right now.
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub(crate) enum Missing {
13 /// The folder is there, the file is not: moved, renamed or deleted.
14 Moved,
15 /// The folder is gone too: an unplugged drive, an unmounted share.
16 Folder,
17}
18
19impl Missing {
20 pub(crate) fn reason(self) -> &'static str {
21 match self {
22 Missing::Moved => "File moved or deleted",
23 Missing::Folder => "Folder not found",
24 }
25 }
26}
27
28/// One row of the list.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub(crate) struct Recent {
31 pub(crate) path: PathBuf,
32 /// The file name without `.edith`.
33 pub(crate) name: String,
34 /// The folder it sits in, with the home folder written `~`.
35 pub(crate) folder: String,
36 /// `None` when the file is there.
37 pub(crate) missing: Option<Missing>,
38}
39
40/// The recent projects, newest first, each checked against the disk.
41pub(crate) fn list() -> Vec<Recent> {
42 read(&file()).into_iter().map(|p| describe(p, home().as_deref())).collect()
43}
44
45/// Puts `project` at the top of the list (moving it there if it was already in it).
46/// Best effort: a list that cannot be written costs the menu a row and nothing else.
47pub(crate) fn push(project: &Path) {
48 push_to(&file(), project);
49}
50
51/// Empties the list. The projects themselves are not touched.
52pub(crate) fn clear() {
53 let _ = std::fs::remove_file(file());
54}
55
56fn describe(path: PathBuf, home: Option<&Path>) -> Recent {
57 let name = path.file_stem().map_or_else(|| "Untitled".to_string(), |s| s.to_string_lossy().into_owned());
58 let dir = path.parent().unwrap_or(Path::new("/"));
59 let folder = match home.and_then(|h| dir.strip_prefix(h).ok()) {
60 Some(rest) if rest.as_os_str().is_empty() => "~".to_string(),
61 Some(rest) => format!("~/{}", rest.display()),
62 None => dir.display().to_string(),
63 };
64 let missing = match (path.is_file(), dir.is_dir()) {
65 (true, _) => None,
66 (false, true) => Some(Missing::Moved),
67 (false, false) => Some(Missing::Folder),
68 };
69 Recent { path, name, folder, missing }
70}
71
72/// `folder` cut from the left to at most `max` characters, at a slash when it can: the end of a
73/// path is the part that tells folders apart.
74pub(crate) fn tail(folder: &str, max: usize) -> String {
75 let n = folder.chars().count();
76 if n <= max {
77 return folder.to_string();
78 }
79 let cut: String = folder.chars().skip(n - (max - 1)).collect();
80 match cut.find('/') {
81 Some(at) if at + 1 < cut.len() => format!("…{}", &cut[at..]),
82 _ => format!("…{cut}"),
83 }
84}
85
86/// `folder` shortened to at most `max` characters by dropping the middle: the first folder
87/// (`~`) stays, then `…`, then as many of the last folders as fit -- the two ends are the
88/// parts that say where a folder is and which one it is.
89pub(crate) fn middle(folder: &str, max: usize) -> String {
90 if folder.chars().count() <= max {
91 return folder.to_string();
92 }
93 let parts: Vec<&str> = folder.split('/').collect();
94 let head = parts.first().copied().unwrap_or("");
95 let mut tail: Vec<&str> = Vec::new();
96 for part in parts.iter().skip(1).rev() {
97 let mut next = tail.clone();
98 next.insert(0, part);
99 let text = format!("{head}/…/{}", next.join("/"));
100 if text.chars().count() > max {
101 break;
102 }
103 tail = next;
104 }
105 match tail.is_empty() {
106 true => self::tail(folder, max),
107 false => format!("{head}/…/{}", tail.join("/")),
108 }
109}
110
111/// A path as the person sees it: the home folder written `~`, and cut from the left to fit.
112pub(crate) fn short_path(path: &Path, max: usize) -> String {
113 let shown = match home().as_deref().and_then(|h| path.strip_prefix(h).ok()) {
114 Some(rest) => format!("~/{}", rest.display()),
115 None => path.display().to_string(),
116 };
117 tail(&shown, max)
118}
119
120fn home() -> Option<PathBuf> {
121 std::env::var_os("HOME").filter(|h| !h.is_empty()).map(PathBuf::from)
122}
123
124fn file() -> PathBuf {
125 // A test never touches the person's real list.
126 if cfg!(test) {
127 return std::env::temp_dir().join(format!("edith-test-recent-{}", std::process::id()));
128 }
129 crate::Player::autosave_state_dir().map_or_else(|| PathBuf::from("recent"), |d| d.join("recent"))
130}
131
132fn read(file: &Path) -> Vec<PathBuf> {
133 let Ok(text) = std::fs::read_to_string(file) else {
134 return Vec::new();
135 };
136 let mut out: Vec<PathBuf> = Vec::new();
137 for line in text.lines().map(str::trim).filter(|l| !l.is_empty()) {
138 let p = PathBuf::from(line);
139 if p.is_absolute() && !out.contains(&p) {
140 out.push(p);
141 }
142 }
143 out.truncate(MAX);
144 out
145}
146
147fn push_to(file: &Path, project: &Path) {
148 // The path as a person would find it; a project not yet on disk cannot be reopened.
149 let Ok(path) = project.canonicalize() else {
150 return;
151 };
152 if path.to_string_lossy().contains('\n') {
153 return;
154 }
155 let mut all = read(file);
156 all.retain(|p| p != &path);
157 all.insert(0, path);
158 all.truncate(MAX);
159 let text: String = all.iter().map(|p| format!("{}\n", p.display())).collect();
160 if let Some(dir) = file.parent() {
161 let _ = std::fs::create_dir_all(dir);
162 }
163 // Written whole beside the list and renamed over it: a crash leaves the old list.
164 let part = file.with_extension("part");
165 if std::fs::write(&part, text).is_ok() {
166 let _ = std::fs::rename(&part, file);
167 }
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173
174 fn dir(name: &str) -> PathBuf {
175 let d = std::env::temp_dir().join(format!("edith-recent-{name}-{}", std::process::id()));
176 let _ = std::fs::remove_dir_all(&d);
177 std::fs::create_dir_all(&d).unwrap();
178 d
179 }
180
181 #[test]
182 fn a_long_folder_loses_its_middle_and_keeps_both_ends() {
183 let f = "~/Documents/Code/Rust/edith/projects/holiday";
184 assert_eq!(middle(f, 80), f);
185 let m = middle(f, 26);
186 assert!(m.starts_with("~/…/") && m.ends_with("projects/holiday"), "{m}");
187 assert!(m.chars().count() <= 26, "{m}");
188 assert!(middle("/very/long/folder/name", 5).chars().count() <= 5);
189 }
190
191 #[test]
192 fn newest_first_deduplicated_and_capped() {
193 let d = dir("cap");
194 let list = d.join("state/recent");
195 let mut made = Vec::new();
196 for n in 0..12 {
197 let p = d.join(format!("p{n}.edith"));
198 std::fs::write(&p, "x").unwrap();
199 push_to(&list, &p);
200 made.push(p.canonicalize().unwrap());
201 }
202 let got = read(&list);
203 assert_eq!(got.len(), MAX);
204 assert_eq!(got[0], made[11]);
205 push_to(&list, &d.join("p5.edith"));
206 let got = read(&list);
207 assert_eq!((got[0].clone(), got.len()), (made[5].clone(), MAX));
208 assert_eq!(got.iter().filter(|p| **p == made[5]).count(), 1);
209 // A path that is not on disk is not listed.
210 push_to(&list, &d.join("nothing.edith"));
211 assert_eq!(read(&list), got);
212 }
213
214 #[test]
215 fn long_folders_keep_their_end() {
216 assert_eq!(tail("~/films", 20), "~/films");
217 let t = tail("/home/me/Documents/Projects/summer/trip", 24);
218 assert!(t.starts_with('…') && t.ends_with("summer/trip") && t.chars().count() <= 24, "{t}");
219 }
220
221 #[test]
222 fn rows_say_why_a_project_is_missing_and_shorten_home() {
223 let d = dir("rows");
224 let home = d.join("home");
225 std::fs::create_dir_all(home.join("films")).unwrap();
226 let here = home.join("films/a.edith");
227 std::fs::write(&here, "x").unwrap();
228 let r = describe(here, Some(&home));
229 assert_eq!((r.name.as_str(), r.folder.as_str(), r.missing), ("a", "~/films", None));
230 let moved = describe(home.join("films/b.edith"), Some(&home));
231 assert_eq!(moved.missing, Some(Missing::Moved));
232 let gone = describe(d.join("usb/c.edith"), Some(&home));
233 assert_eq!(gone.missing, Some(Missing::Folder));
234 assert_eq!(describe(home.join("d.edith"), Some(&home)).folder, "~");
235 }
236}