Skip to main content

tilo_paths/
app.rs

1//! One app's locations, resolved by the backend for the target it runs on.
2
3use std::fmt::Write as _;
4use std::path::PathBuf;
5
6use crate::UserDir;
7use crate::caps::{Feature, Unsupported};
8use crate::location::{Location, VPath, VirtualRoot};
9
10/// The browser profile an app's web storage belongs to unless the host
11/// chose another with [`set_default_profile`], or a caller with
12/// [`AppPaths::with_profile`].
13pub const DEFAULT_PROFILE: &str = "default";
14
15static PROFILE: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);
16
17/// Make `profile` the one [`AppPaths::for_app`] resolves web storage in, for the
18/// rest of the process (on the web, the page). A browser host calls this once, with
19/// the profile it mounts, before any app resolves its paths.
20pub fn set_default_profile(profile: &str) {
21    *PROFILE.write_recover() = Some(component(profile));
22}
23
24#[must_use]
25pub fn default_profile() -> String {
26    PROFILE
27        .read_recover()
28        .clone()
29        .unwrap_or_else(|| DEFAULT_PROFILE.to_owned())
30}
31
32/// Where one app keeps its files, the same API on every target.
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct AppPaths {
35    app: String,
36    scope: Scope,
37}
38
39#[derive(Clone, Debug, PartialEq, Eq)]
40enum Scope {
41    System { profile: String },
42    Under(PathBuf),
43    Memory,
44}
45
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47enum Slot {
48    Data,
49    Config,
50    Cache,
51    State,
52    Runtime,
53}
54
55impl Slot {
56    const fn name(self) -> &'static str {
57        match self {
58            Self::Data => "data",
59            Self::Config => "config",
60            Self::Cache => "cache",
61            Self::State => "state",
62            Self::Runtime => "runtime",
63        }
64    }
65}
66
67const SCOPED: &str = "App paths scoped to one directory have no user folders, workspace or fonts.";
68
69impl AppPaths {
70    #[must_use]
71    pub fn for_app(id: &str) -> Self {
72        Self {
73            app: component(id),
74            scope: Scope::System {
75                profile: default_profile(),
76            },
77        }
78    }
79
80    #[must_use]
81    pub fn under(root: impl Into<PathBuf>, id: &str) -> Self {
82        Self {
83            app: component(id),
84            scope: Scope::Under(root.into()),
85        }
86    }
87
88    #[must_use]
89    pub fn memory(id: &str) -> Self {
90        Self {
91            app: component(id),
92            scope: Scope::Memory,
93        }
94    }
95
96    /// Keep web storage in `profile`'s tree; native per-user directories belong to one
97    /// profile already.
98    #[must_use]
99    pub fn with_profile(mut self, profile: &str) -> Self {
100        if let Scope::System { profile: current } = &mut self.scope {
101            *current = component(profile);
102        }
103        self
104    }
105
106    #[must_use]
107    pub fn id(&self) -> &str {
108        &self.app
109    }
110
111    #[must_use]
112    pub fn data(&self) -> Location {
113        self.storage(Slot::Data)
114    }
115
116    #[must_use]
117    pub fn config(&self) -> Location {
118        self.storage(Slot::Config)
119    }
120
121    #[must_use]
122    pub fn cache(&self) -> Location {
123        self.storage(Slot::Cache)
124    }
125
126    #[must_use]
127    pub fn state(&self) -> Location {
128        self.storage(Slot::State)
129    }
130
131    pub fn runtime(&self) -> Result<Location, Unsupported> {
132        match &self.scope {
133            Scope::System { .. } => system::runtime(&self.app),
134            Scope::Under(root) => Ok(under(root, &self.app, Slot::Runtime)),
135            Scope::Memory => Ok(memory(&self.app, Slot::Runtime)),
136        }
137    }
138
139    pub fn user_dir(&self, dir: UserDir) -> Result<Location, Unsupported> {
140        match self.scope {
141            Scope::System { .. } => system::user_dir(dir),
142            Scope::Under(_) | Scope::Memory => Err(scoped(Feature::UserDirs)),
143        }
144    }
145
146    /// The collaborative workspace the host mounted for this app:
147    /// `$TILO_WORKSPACE_ROOT` when absolute, else `/var/workspace` on a Tilo
148    /// Linux session (`$TILO_WORKSPACE_ID` set).
149    pub fn workspace_root(&self) -> Result<Location, Unsupported> {
150        match self.scope {
151            Scope::System { .. } => system::workspace_root(),
152            Scope::Under(_) | Scope::Memory => Err(scoped(Feature::WorkspaceRoot)),
153        }
154    }
155
156    /// The directory holding the Tilo font catalog: where the OS image
157    /// installs it on Linux, the app bundle's `Contents/Resources/fonts` on
158    /// macOS. Only the location is resolved; readers verify what they use.
159    pub fn font_root(&self) -> Result<Location, Unsupported> {
160        match self.scope {
161            Scope::System { .. } => system::font_root(),
162            Scope::Under(_) | Scope::Memory => Err(scoped(Feature::FontRoot)),
163        }
164    }
165
166    fn storage(&self, slot: Slot) -> Location {
167        match &self.scope {
168            Scope::System { profile } => system::storage(slot, &self.app, profile),
169            Scope::Under(root) => under(root, &self.app, slot),
170            Scope::Memory => memory(&self.app, slot),
171        }
172    }
173}
174
175const fn scoped(feature: Feature) -> Unsupported {
176    Unsupported {
177        feature,
178        reason: SCOPED,
179    }
180}
181
182fn under(root: &std::path::Path, app: &str, slot: Slot) -> Location {
183    Location::Native(root.join(app).join(slot.name()))
184}
185
186fn memory(app: &str, slot: Slot) -> Location {
187    Location::Virtual(
188        VirtualRoot::Memory,
189        VPath::from_components([app, slot.name()]),
190    )
191}
192
193/// `raw` as one path component, percent-escaping what a component cannot hold. The
194/// mapping is injective, since `%` is escaped too.
195fn component(raw: &str) -> String {
196    match raw {
197        "" => return "%".to_owned(),
198        "." => return "%2E".to_owned(),
199        ".." => return "%2E%2E".to_owned(),
200        _ => {}
201    }
202    let mut escaped = String::with_capacity(raw.len());
203    for character in raw.chars() {
204        if matches!(character, '/' | '\\' | ':' | '%') || character.is_control() {
205            let mut utf8 = [0; 4];
206            for byte in character.encode_utf8(&mut utf8).bytes() {
207                let _ = write!(escaped, "%{byte:02X}");
208            }
209        } else {
210            escaped.push(character);
211        }
212    }
213    escaped
214}
215
216#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
217mod system {
218    use std::ffi::OsString;
219    use std::path::PathBuf;
220
221    use super::{Slot, memory};
222    use crate::caps::{Feature, Unsupported};
223    use crate::location::Location;
224    use crate::{UserDir, absolute};
225
226    /// Where the Tilo image mounts the workspace when the launcher names one
227    /// by id only.
228    const DEFAULT_WORKSPACE_ROOT: Option<&str> = if cfg!(target_os = "linux") {
229        Some(crate::WORKSPACE_MOUNT)
230    } else {
231        None
232    };
233
234    pub(super) fn storage(slot: Slot, app: &str, _profile: &str) -> Location {
235        let base = match slot {
236            Slot::Data => crate::data_dir(),
237            Slot::Config => crate::config_dir(),
238            Slot::Cache => crate::cache_dir(),
239            Slot::State => crate::state_dir(),
240            Slot::Runtime => crate::runtime_dir(),
241        };
242        joined(base, app, slot)
243    }
244
245    pub(super) fn joined(base: Option<PathBuf>, app: &str, slot: Slot) -> Location {
246        base.map_or_else(
247            || memory(app, slot),
248            |base| Location::Native(base.join(app)),
249        )
250    }
251
252    pub(super) fn runtime(app: &str) -> Result<Location, Unsupported> {
253        crate::runtime_dir()
254            .map(|dir| Location::Native(dir.join(app)))
255            .ok_or(Unsupported {
256                feature: Feature::Runtime,
257                reason: "This session has no private runtime directory.",
258            })
259    }
260
261    pub(super) fn user_dir(dir: UserDir) -> Result<Location, Unsupported> {
262        dir.resolve().map(Location::Native).ok_or(Unsupported {
263            feature: Feature::UserDirs,
264            reason: "This folder is not set up for this user.",
265        })
266    }
267
268    pub(super) fn workspace_root() -> Result<Location, Unsupported> {
269        workspace_root_from(&|name| crate::var(name), DEFAULT_WORKSPACE_ROOT)
270    }
271
272    pub(super) fn workspace_root_from(
273        var: &dyn Fn(&str) -> Option<OsString>,
274        default: Option<&str>,
275    ) -> Result<Location, Unsupported> {
276        absolute(var("TILO_WORKSPACE_ROOT"))
277            .or_else(|| {
278                var("TILO_WORKSPACE_ID")
279                    .filter(|id| !id.is_empty())
280                    .and(default)
281                    .map(PathBuf::from)
282            })
283            .map(Location::Native)
284            .ok_or(Unsupported {
285                feature: Feature::WorkspaceRoot,
286                reason: "No workspace is mounted for this app.",
287            })
288    }
289
290    #[cfg(target_os = "macos")]
291    pub(super) fn font_root() -> Result<Location, Unsupported> {
292        std::env::current_exe()
293            .ok()
294            .as_deref()
295            .and_then(bundle_fonts)
296            .map(Location::Native)
297            .ok_or(Unsupported {
298                feature: Feature::FontRoot,
299                reason: "Fonts are bundled only when the app runs from its app bundle.",
300            })
301    }
302
303    #[cfg(all(unix, not(target_os = "macos")))]
304    #[expect(
305        clippy::unnecessary_wraps,
306        reason = "the signature every backend shares"
307    )]
308    pub(super) fn font_root() -> Result<Location, Unsupported> {
309        Ok(Location::Native(PathBuf::from("/usr/share/fonts/tilo")))
310    }
311
312    #[cfg(not(unix))]
313    pub(super) fn font_root() -> Result<Location, Unsupported> {
314        Err(Unsupported {
315            feature: Feature::FontRoot,
316            reason: "This system has no Tilo font catalog.",
317        })
318    }
319
320    /// `Contents/Resources/fonts` of the bundle whose `Contents/MacOS` holds
321    /// `exe`.
322    #[cfg(any(target_os = "macos", test))]
323    pub(super) fn bundle_fonts(exe: &std::path::Path) -> Option<PathBuf> {
324        let macos = exe.parent()?;
325        let contents = macos.parent()?;
326        (macos.file_name()? == "MacOS" && contents.file_name()? == "Contents")
327            .then(|| contents.join("Resources/fonts"))
328    }
329}
330
331#[cfg(any(all(target_arch = "wasm32", target_os = "unknown"), test))]
332mod web {
333    use super::{Slot, memory};
334    use crate::UserDir;
335    use crate::caps::{Feature, Unsupported, WEB_FONTS, WEB_USER_DIRS, WEB_WORKSPACE};
336    use crate::location::{Location, VPath, VirtualRoot};
337
338    pub(super) fn storage(slot: Slot, app: &str, profile: &str) -> Location {
339        Location::Virtual(
340            VirtualRoot::Opfs {
341                profile: profile.to_owned(),
342            },
343            VPath::from_components([app, slot.name()]),
344        )
345    }
346
347    #[expect(
348        clippy::unnecessary_wraps,
349        reason = "the signature every backend shares"
350    )]
351    pub(super) fn runtime(app: &str) -> Result<Location, Unsupported> {
352        Ok(memory(app, Slot::Runtime))
353    }
354
355    pub(super) const fn user_dir(_: UserDir) -> Result<Location, Unsupported> {
356        Err(Unsupported {
357            feature: Feature::UserDirs,
358            reason: WEB_USER_DIRS,
359        })
360    }
361
362    pub(super) const fn workspace_root() -> Result<Location, Unsupported> {
363        Err(Unsupported {
364            feature: Feature::WorkspaceRoot,
365            reason: WEB_WORKSPACE,
366        })
367    }
368
369    pub(super) const fn font_root() -> Result<Location, Unsupported> {
370        Err(Unsupported {
371            feature: Feature::FontRoot,
372            reason: WEB_FONTS,
373        })
374    }
375}
376
377use tilo_lock::RwLockRecover as _;
378#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
379use web as system;
380
381// Every backend's rules are pure, so the native test run checks them all.
382#[cfg(test)]
383#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
384mod tests {
385    use std::ffi::OsString;
386    use std::path::Path;
387
388    use super::*;
389
390    const ID: &str = "so.tilo.notes";
391
392    fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
393        move |name| {
394            pairs
395                .iter()
396                .find(|(key, _)| *key == name)
397                .map(|(_, value)| OsString::from(value))
398        }
399    }
400
401    fn native(path: &str) -> Location {
402        Location::Native(PathBuf::from(path))
403    }
404
405    #[cfg(unix)]
406    #[test]
407    fn linux_joins_the_id_onto_the_xdg_base_directories() {
408        use crate::xdg::Base;
409        use std::ffi::OsStr;
410
411        let home = Some(OsStr::new("/home/u"));
412        let resolve = |base: Base, value: Option<&str>, slot| {
413            system::joined(base.resolve_from(value.map(OsStr::new), home), ID, slot)
414        };
415        assert_eq!(
416            resolve(Base::Data, None, Slot::Data),
417            native("/home/u/.local/share/so.tilo.notes")
418        );
419        assert_eq!(
420            resolve(Base::Config, Some("/cfg"), Slot::Config),
421            native("/cfg/so.tilo.notes")
422        );
423        assert_eq!(
424            resolve(Base::Cache, Some("relative"), Slot::Cache),
425            native("/home/u/.cache/so.tilo.notes")
426        );
427        assert_eq!(
428            resolve(Base::State, None, Slot::State),
429            native("/home/u/.local/state/so.tilo.notes")
430        );
431        assert_eq!(
432            resolve(Base::Runtime, Some("/run/user/1000"), Slot::Runtime),
433            native("/run/user/1000/so.tilo.notes")
434        );
435    }
436
437    #[cfg(unix)]
438    #[test]
439    fn macos_joins_the_id_onto_the_library_folders() {
440        use crate::xdg::Base;
441
442        let tmpdir = [("TMPDIR", "/var/folders/ab/xyz/T/")];
443        let resolve = |base: Base, slot| {
444            let dir = crate::macos::base(base, &env(&tmpdir), || Some(PathBuf::from("/Users/u")));
445            system::joined(dir, ID, slot)
446        };
447        let support = native("/Users/u/Library/Application Support/so.tilo.notes");
448        assert_eq!(resolve(Base::Data, Slot::Data), support);
449        assert_eq!(resolve(Base::Config, Slot::Config), support);
450        assert_eq!(resolve(Base::State, Slot::State), support);
451        assert_eq!(
452            resolve(Base::Cache, Slot::Cache),
453            native("/Users/u/Library/Caches/so.tilo.notes")
454        );
455        assert_eq!(
456            resolve(Base::Runtime, Slot::Runtime),
457            native("/var/folders/ab/xyz/T/so.tilo.notes")
458        );
459    }
460
461    #[test]
462    fn a_missing_base_directory_keeps_storage_in_memory() {
463        let location = system::joined(None, ID, Slot::Data);
464        assert_eq!(location.to_string(), "memory:///so.tilo.notes/data");
465        assert!(location.native_path().is_err());
466    }
467
468    #[test]
469    fn the_web_keeps_storage_in_the_profiles_opfs_tree() {
470        for (slot, expected) in [
471            (Slot::Data, "opfs://default/so.tilo.notes/data"),
472            (Slot::Config, "opfs://default/so.tilo.notes/config"),
473            (Slot::Cache, "opfs://default/so.tilo.notes/cache"),
474            (Slot::State, "opfs://default/so.tilo.notes/state"),
475        ] {
476            assert_eq!(
477                web::storage(slot, ID, DEFAULT_PROFILE).to_string(),
478                expected
479            );
480        }
481        assert_eq!(
482            web::storage(Slot::Data, ID, "work").to_string(),
483            "opfs://work/so.tilo.notes/data"
484        );
485        assert_eq!(
486            web::runtime(ID).map(|location| location.to_string()),
487            Ok("memory:///so.tilo.notes/runtime".to_owned())
488        );
489    }
490
491    #[test]
492    fn the_web_has_no_user_folders_workspace_or_font_directory() {
493        assert_eq!(
494            web::user_dir(UserDir::Documents).map_err(|error| error.feature),
495            Err(Feature::UserDirs)
496        );
497        assert_eq!(
498            web::workspace_root().map_err(|error| error.feature),
499            Err(Feature::WorkspaceRoot)
500        );
501        assert_eq!(
502            web::font_root().map_err(|error| error.feature),
503            Err(Feature::FontRoot)
504        );
505        assert!(
506            web::storage(Slot::Data, ID, "default")
507                .native_path()
508                .is_err()
509        );
510    }
511
512    #[test]
513    fn the_workspace_root_comes_from_the_launcher() {
514        let resolve = |pairs: &[(&str, &str)], default| {
515            system::workspace_root_from(&env(pairs), default).ok()
516        };
517        let linux = Some("/var/workspace");
518        assert_eq!(
519            resolve(&[("TILO_WORKSPACE_ROOT", "/mnt/ws")], None),
520            Some(native("/mnt/ws"))
521        );
522        assert_eq!(
523            resolve(&[("TILO_WORKSPACE_ID", "w1")], linux),
524            Some(native("/var/workspace"))
525        );
526        assert_eq!(
527            resolve(
528                &[("TILO_WORKSPACE_ROOT", "rel"), ("TILO_WORKSPACE_ID", "w1")],
529                linux
530            ),
531            Some(native("/var/workspace")),
532            "a relative root is ignored"
533        );
534        assert_eq!(resolve(&[("TILO_WORKSPACE_ID", "w1")], None), None);
535        assert_eq!(resolve(&[("TILO_WORKSPACE_ID", "")], linux), None);
536        assert_eq!(resolve(&[], linux), None);
537    }
538
539    #[test]
540    fn macos_fonts_come_from_the_running_bundle() {
541        assert_eq!(
542            system::bundle_fonts(Path::new(
543                "/Applications/Tilo Notes.app/Contents/MacOS/notes"
544            )),
545            Some(PathBuf::from(
546                "/Applications/Tilo Notes.app/Contents/Resources/fonts"
547            ))
548        );
549        assert_eq!(
550            system::bundle_fonts(Path::new("/usr/local/bin/notes")),
551            None
552        );
553        assert_eq!(system::bundle_fonts(Path::new("notes")), None);
554    }
555
556    #[test]
557    fn scoped_paths_stay_below_their_root() {
558        let app = AppPaths::under("/sandbox", ID);
559        assert_eq!(app.data(), native("/sandbox/so.tilo.notes/data"));
560        assert_eq!(app.state(), native("/sandbox/so.tilo.notes/state"));
561        assert_eq!(app.runtime(), Ok(native("/sandbox/so.tilo.notes/runtime")));
562        assert!(app.user_dir(UserDir::Download).is_err());
563        assert!(app.workspace_root().is_err());
564        assert!(app.font_root().is_err());
565        assert_eq!(app.clone().with_profile("work"), app);
566
567        let memory = AppPaths::memory(ID);
568        assert_eq!(memory.cache().to_string(), "memory:///so.tilo.notes/cache");
569    }
570
571    #[test]
572    fn the_system_backend_agrees_with_the_per_user_directories() {
573        let app = AppPaths::for_app(ID);
574        for (location, base) in [
575            (app.data(), crate::data_dir()),
576            (app.config(), crate::config_dir()),
577            (app.cache(), crate::cache_dir()),
578            (app.state(), crate::state_dir()),
579        ] {
580            if let Some(base) = base {
581                assert_eq!(location, Location::Native(base.join(ID)));
582            }
583        }
584        assert_eq!(
585            app.runtime().ok(),
586            crate::runtime_dir().map(|dir| Location::Native(dir.join(ID)))
587        );
588    }
589
590    #[test]
591    fn ids_are_escaped_into_one_component() {
592        for (raw, expected) in [
593            (ID, ID),
594            ("tilo-chat", "tilo-chat"),
595            ("a/b", "a%2Fb"),
596            ("..\\x", "..%5Cx"),
597            ("50%", "50%25"),
598            ("c:\n", "c%3A%0A"),
599            (".", "%2E"),
600            ("..", "%2E%2E"),
601            ("", "%"),
602        ] {
603            assert_eq!(AppPaths::for_app(raw).id(), expected, "{raw:?}");
604        }
605        assert_eq!(
606            AppPaths::memory("../escape").data().to_string(),
607            "memory:///..%2Fescape/data"
608        );
609    }
610}