Skip to main content

oxinav_core/
session.rs

1//! What the app remembers between runs, and its on-disk format.
2//!
3//! Like `bookmarks`, the store owns the format — parsing and rendering the
4//! text — while the app owns where that text lives and when it is read or
5//! written. That split keeps every rule here testable without a config file
6//! to point at.
7
8use std::path::PathBuf;
9
10use crate::pane::SortKey;
11
12/// The two themes the app can actually be in. Kept as a domain enum rather
13/// than an Iced type so the format stays in this crate.
14#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
15pub enum ThemeMode {
16    #[default]
17    Dark,
18    Light,
19}
20
21impl ThemeMode {
22    pub fn label(self) -> &'static str {
23        match self {
24            ThemeMode::Dark => "dark",
25            ThemeMode::Light => "light",
26        }
27    }
28
29    pub fn from_label(label: &str) -> Option<Self> {
30        match label.trim() {
31            l if l.eq_ignore_ascii_case("dark") => Some(ThemeMode::Dark),
32            l if l.eq_ignore_ascii_case("light") => Some(ThemeMode::Light),
33            _ => None,
34        }
35    }
36}
37
38/// A pane's sort order: which column, and which direction.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub struct SortSpec {
41    pub key: SortKey,
42    pub reversed: bool,
43}
44
45impl Default for SortSpec {
46    fn default() -> Self {
47        Self {
48            key: SortKey::Name,
49            reversed: false,
50        }
51    }
52}
53
54/// The state restored on the next launch.
55///
56/// The directories are `Option` because this crate has no business inventing
57/// a fallback: "nothing was saved" is a different answer from "start here",
58/// and only the app knows what home means. The remaining fields have real
59/// domain defaults, the same ones `Pane::new` already uses.
60#[derive(Debug, Clone, Default, PartialEq, Eq)]
61pub struct Session {
62    pub left: Option<PathBuf>,
63    pub right: Option<PathBuf>,
64    pub theme: ThemeMode,
65    pub show_hidden: bool,
66    pub left_sort: SortSpec,
67    pub right_sort: SortSpec,
68}
69
70impl Session {
71    pub fn new() -> Self {
72        Self::default()
73    }
74
75    /// Render for storage: one `key<TAB>value` per line.
76    ///
77    /// Tab-separated for the same reason bookmarks are: a path may contain
78    /// almost any character but not a tab or newline, so no escaping — and
79    /// therefore no escaping bugs — is needed.
80    pub fn to_text(&self) -> String {
81        let mut out = String::new();
82        let mut line = |key: &str, value: &str| {
83            out.push_str(key);
84            out.push('\t');
85            out.push_str(value);
86            out.push('\n');
87        };
88
89        if let Some(path) = &self.left {
90            line("left", &path.to_string_lossy());
91        }
92        if let Some(path) = &self.right {
93            line("right", &path.to_string_lossy());
94        }
95        line("theme", self.theme.label());
96        line("hidden", bool_label(self.show_hidden));
97        line("left-sort", self.left_sort.key.label());
98        line("left-sort-reversed", bool_label(self.left_sort.reversed));
99        line("right-sort", self.right_sort.key.label());
100        line("right-sort-reversed", bool_label(self.right_sort.reversed));
101
102        out
103    }
104
105    /// Parse stored text. Unknown keys and unreadable values are skipped
106    /// rather than failing the whole file: a corrupt line should cost one
107    /// setting, not the whole session.
108    pub fn from_text(text: &str) -> Self {
109        let mut session = Self::new();
110
111        for line in text.lines() {
112            let line = line.trim_end_matches('\r');
113            let Some((key, value)) = line.split_once('\t') else {
114                continue;
115            };
116
117            match key.trim() {
118                "left" if !value.is_empty() => session.left = Some(PathBuf::from(value)),
119                "right" if !value.is_empty() => session.right = Some(PathBuf::from(value)),
120                "theme" => {
121                    if let Some(theme) = ThemeMode::from_label(value) {
122                        session.theme = theme;
123                    }
124                }
125                "hidden" => {
126                    if let Some(on) = parse_bool(value) {
127                        session.show_hidden = on;
128                    }
129                }
130                "left-sort" => {
131                    if let Some(key) = SortKey::from_label(value) {
132                        session.left_sort.key = key;
133                    }
134                }
135                "left-sort-reversed" => {
136                    if let Some(on) = parse_bool(value) {
137                        session.left_sort.reversed = on;
138                    }
139                }
140                "right-sort" => {
141                    if let Some(key) = SortKey::from_label(value) {
142                        session.right_sort.key = key;
143                    }
144                }
145                "right-sort-reversed" => {
146                    if let Some(on) = parse_bool(value) {
147                        session.right_sort.reversed = on;
148                    }
149                }
150                _ => {}
151            }
152        }
153
154        session
155    }
156}
157
158fn bool_label(value: bool) -> &'static str {
159    if value {
160        "true"
161    } else {
162        "false"
163    }
164}
165
166fn parse_bool(value: &str) -> Option<bool> {
167    match value.trim() {
168        v if v.eq_ignore_ascii_case("true") => Some(true),
169        v if v.eq_ignore_ascii_case("false") => Some(false),
170        _ => None,
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177    use std::path::Path;
178
179    fn populated() -> Session {
180        Session {
181            left: Some(PathBuf::from("/home/me/code")),
182            right: Some(PathBuf::from("/etc")),
183            theme: ThemeMode::Light,
184            show_hidden: true,
185            left_sort: SortSpec {
186                key: SortKey::Size,
187                reversed: true,
188            },
189            right_sort: SortSpec {
190                key: SortKey::Modified,
191                reversed: false,
192            },
193        }
194    }
195
196    #[test]
197    fn a_populated_session_round_trips() {
198        let session = populated();
199
200        assert_eq!(Session::from_text(&session.to_text()), session);
201    }
202
203    #[test]
204    fn the_default_session_round_trips() {
205        let session = Session::default();
206
207        assert_eq!(Session::from_text(&session.to_text()), session);
208    }
209
210    #[test]
211    fn the_default_has_no_directories_and_todays_view_settings() {
212        let session = Session::default();
213
214        assert_eq!(session.left, None);
215        assert_eq!(session.right, None);
216        assert_eq!(session.theme, ThemeMode::Dark);
217        assert!(!session.show_hidden);
218        assert_eq!(
219            session.left_sort,
220            SortSpec {
221                key: SortKey::Name,
222                reversed: false
223            }
224        );
225        assert_eq!(session.right_sort, session.left_sort);
226    }
227
228    #[test]
229    fn empty_text_parses_to_the_default() {
230        assert_eq!(Session::from_text(""), Session::default());
231    }
232
233    #[test]
234    fn paths_with_spaces_survive_the_round_trip() {
235        let mut session = Session::new();
236        session.left = Some(PathBuf::from("/a b/My Documents"));
237
238        let restored = Session::from_text(&session.to_text());
239
240        assert_eq!(
241            restored.left.as_deref(),
242            Some(Path::new("/a b/My Documents"))
243        );
244    }
245
246    #[test]
247    fn unknown_keys_and_malformed_lines_cost_only_themselves() {
248        let text = "left\t/keep\nno-tab-here\n\nsomething-new\tvalue\nhidden\ttrue\n";
249
250        let session = Session::from_text(text);
251
252        assert_eq!(session.left.as_deref(), Some(Path::new("/keep")));
253        assert!(session.show_hidden);
254    }
255
256    #[test]
257    fn an_unreadable_value_falls_back_for_that_field_alone() {
258        let text = "theme\tpurple\nhidden\tmaybe\nleft-sort\tcolour\nright-sort\tsize\n";
259
260        let session = Session::from_text(text);
261
262        assert_eq!(session.theme, ThemeMode::Dark);
263        assert!(!session.show_hidden);
264        assert_eq!(session.left_sort.key, SortKey::Name);
265        // The one readable value still lands.
266        assert_eq!(session.right_sort.key, SortKey::Size);
267    }
268
269    #[test]
270    fn an_empty_path_is_treated_as_unset() {
271        let session = Session::from_text("left\t\n");
272
273        assert_eq!(session.left, None);
274    }
275
276    #[test]
277    fn carriage_returns_are_tolerated() {
278        let session = Session::from_text("left\t/a\r\ntheme\tlight\r\n");
279
280        assert_eq!(session.left.as_deref(), Some(Path::new("/a")));
281        assert_eq!(session.theme, ThemeMode::Light);
282    }
283
284    #[test]
285    fn values_are_case_insensitive() {
286        let session = Session::from_text("theme\tLIGHT\nhidden\tTrue\nleft-sort\tSize\n");
287
288        assert_eq!(session.theme, ThemeMode::Light);
289        assert!(session.show_hidden);
290        assert_eq!(session.left_sort.key, SortKey::Size);
291    }
292}