tilo-paths 0.5.1

Per-user and per-app locations on Linux, macOS and the web: XDG base directories and xdg-user-dirs, the macOS Library folders, and virtual browser storage roots.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
//! One app's locations, resolved by the backend for the target it runs on.

use std::fmt::Write as _;
use std::path::PathBuf;

use crate::UserDir;
use crate::caps::{Feature, Unsupported};
use crate::location::{Location, VPath, VirtualRoot};

/// The browser profile an app's web storage belongs to unless the host
/// chose another with [`set_default_profile`], or a caller with
/// [`AppPaths::with_profile`].
pub const DEFAULT_PROFILE: &str = "default";

static PROFILE: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);

/// Make `profile` the one [`AppPaths::for_app`] resolves web storage in, for the
/// rest of the process (on the web, the page). A browser host calls this once, with
/// the profile it mounts, before any app resolves its paths.
pub fn set_default_profile(profile: &str) {
    *PROFILE.write_recover() = Some(component(profile));
}

#[must_use]
pub fn default_profile() -> String {
    PROFILE
        .read_recover()
        .clone()
        .unwrap_or_else(|| DEFAULT_PROFILE.to_owned())
}

/// Where one app keeps its files, the same API on every target.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AppPaths {
    app: String,
    scope: Scope,
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum Scope {
    System { profile: String },
    Under(PathBuf),
    Memory,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Slot {
    Data,
    Config,
    Cache,
    State,
    Runtime,
}

impl Slot {
    const fn name(self) -> &'static str {
        match self {
            Self::Data => "data",
            Self::Config => "config",
            Self::Cache => "cache",
            Self::State => "state",
            Self::Runtime => "runtime",
        }
    }
}

const SCOPED: &str = "App paths scoped to one directory have no user folders, workspace or fonts.";

impl AppPaths {
    #[must_use]
    pub fn for_app(id: &str) -> Self {
        Self {
            app: component(id),
            scope: Scope::System {
                profile: default_profile(),
            },
        }
    }

    #[must_use]
    pub fn under(root: impl Into<PathBuf>, id: &str) -> Self {
        Self {
            app: component(id),
            scope: Scope::Under(root.into()),
        }
    }

    #[must_use]
    pub fn memory(id: &str) -> Self {
        Self {
            app: component(id),
            scope: Scope::Memory,
        }
    }

    /// Keep web storage in `profile`'s tree; native per-user directories belong to one
    /// profile already.
    #[must_use]
    pub fn with_profile(mut self, profile: &str) -> Self {
        if let Scope::System { profile: current } = &mut self.scope {
            *current = component(profile);
        }
        self
    }

    #[must_use]
    pub fn id(&self) -> &str {
        &self.app
    }

    #[must_use]
    pub fn data(&self) -> Location {
        self.storage(Slot::Data)
    }

    #[must_use]
    pub fn config(&self) -> Location {
        self.storage(Slot::Config)
    }

    #[must_use]
    pub fn cache(&self) -> Location {
        self.storage(Slot::Cache)
    }

    #[must_use]
    pub fn state(&self) -> Location {
        self.storage(Slot::State)
    }

    pub fn runtime(&self) -> Result<Location, Unsupported> {
        match &self.scope {
            Scope::System { .. } => system::runtime(&self.app),
            Scope::Under(root) => Ok(under(root, &self.app, Slot::Runtime)),
            Scope::Memory => Ok(memory(&self.app, Slot::Runtime)),
        }
    }

    pub fn user_dir(&self, dir: UserDir) -> Result<Location, Unsupported> {
        match self.scope {
            Scope::System { .. } => system::user_dir(dir),
            Scope::Under(_) | Scope::Memory => Err(scoped(Feature::UserDirs)),
        }
    }

    /// The collaborative workspace the host mounted for this app:
    /// `$TILO_WORKSPACE_ROOT` when absolute, else `/var/workspace` on a Tilo
    /// Linux session (`$TILO_WORKSPACE_ID` set).
    pub fn workspace_root(&self) -> Result<Location, Unsupported> {
        match self.scope {
            Scope::System { .. } => system::workspace_root(),
            Scope::Under(_) | Scope::Memory => Err(scoped(Feature::WorkspaceRoot)),
        }
    }

    /// The directory holding the Tilo font catalog: where the OS image
    /// installs it on Linux, the app bundle's `Contents/Resources/fonts` on
    /// macOS. Only the location is resolved; readers verify what they use.
    pub fn font_root(&self) -> Result<Location, Unsupported> {
        match self.scope {
            Scope::System { .. } => system::font_root(),
            Scope::Under(_) | Scope::Memory => Err(scoped(Feature::FontRoot)),
        }
    }

    fn storage(&self, slot: Slot) -> Location {
        match &self.scope {
            Scope::System { profile } => system::storage(slot, &self.app, profile),
            Scope::Under(root) => under(root, &self.app, slot),
            Scope::Memory => memory(&self.app, slot),
        }
    }
}

const fn scoped(feature: Feature) -> Unsupported {
    Unsupported {
        feature,
        reason: SCOPED,
    }
}

fn under(root: &std::path::Path, app: &str, slot: Slot) -> Location {
    Location::Native(root.join(app).join(slot.name()))
}

fn memory(app: &str, slot: Slot) -> Location {
    Location::Virtual(
        VirtualRoot::Memory,
        VPath::from_components([app, slot.name()]),
    )
}

/// `raw` as one path component, percent-escaping what a component cannot hold. The
/// mapping is injective, since `%` is escaped too.
fn component(raw: &str) -> String {
    match raw {
        "" => return "%".to_owned(),
        "." => return "%2E".to_owned(),
        ".." => return "%2E%2E".to_owned(),
        _ => {}
    }
    let mut escaped = String::with_capacity(raw.len());
    for character in raw.chars() {
        if matches!(character, '/' | '\\' | ':' | '%') || character.is_control() {
            let mut utf8 = [0; 4];
            for byte in character.encode_utf8(&mut utf8).bytes() {
                let _ = write!(escaped, "%{byte:02X}");
            }
        } else {
            escaped.push(character);
        }
    }
    escaped
}

#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
mod system {
    use std::ffi::OsString;
    use std::path::PathBuf;

    use super::{Slot, memory};
    use crate::caps::{Feature, Unsupported};
    use crate::location::Location;
    use crate::{UserDir, absolute};

    /// Where the Tilo image mounts the workspace when the launcher names one
    /// by id only.
    const DEFAULT_WORKSPACE_ROOT: Option<&str> = if cfg!(target_os = "linux") {
        Some(crate::WORKSPACE_MOUNT)
    } else {
        None
    };

    pub(super) fn storage(slot: Slot, app: &str, _profile: &str) -> Location {
        let base = match slot {
            Slot::Data => crate::data_dir(),
            Slot::Config => crate::config_dir(),
            Slot::Cache => crate::cache_dir(),
            Slot::State => crate::state_dir(),
            Slot::Runtime => crate::runtime_dir(),
        };
        joined(base, app, slot)
    }

    pub(super) fn joined(base: Option<PathBuf>, app: &str, slot: Slot) -> Location {
        base.map_or_else(
            || memory(app, slot),
            |base| Location::Native(base.join(app)),
        )
    }

    pub(super) fn runtime(app: &str) -> Result<Location, Unsupported> {
        crate::runtime_dir()
            .map(|dir| Location::Native(dir.join(app)))
            .ok_or(Unsupported {
                feature: Feature::Runtime,
                reason: "This session has no private runtime directory.",
            })
    }

    pub(super) fn user_dir(dir: UserDir) -> Result<Location, Unsupported> {
        dir.resolve().map(Location::Native).ok_or(Unsupported {
            feature: Feature::UserDirs,
            reason: "This folder is not set up for this user.",
        })
    }

    pub(super) fn workspace_root() -> Result<Location, Unsupported> {
        workspace_root_from(&|name| crate::var(name), DEFAULT_WORKSPACE_ROOT)
    }

    pub(super) fn workspace_root_from(
        var: &dyn Fn(&str) -> Option<OsString>,
        default: Option<&str>,
    ) -> Result<Location, Unsupported> {
        absolute(var("TILO_WORKSPACE_ROOT"))
            .or_else(|| {
                var("TILO_WORKSPACE_ID")
                    .filter(|id| !id.is_empty())
                    .and(default)
                    .map(PathBuf::from)
            })
            .map(Location::Native)
            .ok_or(Unsupported {
                feature: Feature::WorkspaceRoot,
                reason: "No workspace is mounted for this app.",
            })
    }

    #[cfg(target_os = "macos")]
    pub(super) fn font_root() -> Result<Location, Unsupported> {
        std::env::current_exe()
            .ok()
            .as_deref()
            .and_then(bundle_fonts)
            .map(Location::Native)
            .ok_or(Unsupported {
                feature: Feature::FontRoot,
                reason: "Fonts are bundled only when the app runs from its app bundle.",
            })
    }

    #[cfg(all(unix, not(target_os = "macos")))]
    #[expect(
        clippy::unnecessary_wraps,
        reason = "the signature every backend shares"
    )]
    pub(super) fn font_root() -> Result<Location, Unsupported> {
        Ok(Location::Native(PathBuf::from("/usr/share/fonts/tilo")))
    }

    #[cfg(not(unix))]
    pub(super) fn font_root() -> Result<Location, Unsupported> {
        Err(Unsupported {
            feature: Feature::FontRoot,
            reason: "This system has no Tilo font catalog.",
        })
    }

    /// `Contents/Resources/fonts` of the bundle whose `Contents/MacOS` holds
    /// `exe`.
    #[cfg(any(target_os = "macos", test))]
    pub(super) fn bundle_fonts(exe: &std::path::Path) -> Option<PathBuf> {
        let macos = exe.parent()?;
        let contents = macos.parent()?;
        (macos.file_name()? == "MacOS" && contents.file_name()? == "Contents")
            .then(|| contents.join("Resources/fonts"))
    }
}

#[cfg(any(all(target_arch = "wasm32", target_os = "unknown"), test))]
mod web {
    use super::{Slot, memory};
    use crate::UserDir;
    use crate::caps::{Feature, Unsupported, WEB_FONTS, WEB_USER_DIRS, WEB_WORKSPACE};
    use crate::location::{Location, VPath, VirtualRoot};

    pub(super) fn storage(slot: Slot, app: &str, profile: &str) -> Location {
        Location::Virtual(
            VirtualRoot::Opfs {
                profile: profile.to_owned(),
            },
            VPath::from_components([app, slot.name()]),
        )
    }

    #[expect(
        clippy::unnecessary_wraps,
        reason = "the signature every backend shares"
    )]
    pub(super) fn runtime(app: &str) -> Result<Location, Unsupported> {
        Ok(memory(app, Slot::Runtime))
    }

    pub(super) const fn user_dir(_: UserDir) -> Result<Location, Unsupported> {
        Err(Unsupported {
            feature: Feature::UserDirs,
            reason: WEB_USER_DIRS,
        })
    }

    pub(super) const fn workspace_root() -> Result<Location, Unsupported> {
        Err(Unsupported {
            feature: Feature::WorkspaceRoot,
            reason: WEB_WORKSPACE,
        })
    }

    pub(super) const fn font_root() -> Result<Location, Unsupported> {
        Err(Unsupported {
            feature: Feature::FontRoot,
            reason: WEB_FONTS,
        })
    }
}

use tilo_lock::RwLockRecover as _;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
use web as system;

// Every backend's rules are pure, so the native test run checks them all.
#[cfg(test)]
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
mod tests {
    use std::ffi::OsString;
    use std::path::Path;

    use super::*;

    const ID: &str = "so.tilo.notes";

    fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
        move |name| {
            pairs
                .iter()
                .find(|(key, _)| *key == name)
                .map(|(_, value)| OsString::from(value))
        }
    }

    fn native(path: &str) -> Location {
        Location::Native(PathBuf::from(path))
    }

    #[cfg(unix)]
    #[test]
    fn linux_joins_the_id_onto_the_xdg_base_directories() {
        use crate::xdg::Base;
        use std::ffi::OsStr;

        let home = Some(OsStr::new("/home/u"));
        let resolve = |base: Base, value: Option<&str>, slot| {
            system::joined(base.resolve_from(value.map(OsStr::new), home), ID, slot)
        };
        assert_eq!(
            resolve(Base::Data, None, Slot::Data),
            native("/home/u/.local/share/so.tilo.notes")
        );
        assert_eq!(
            resolve(Base::Config, Some("/cfg"), Slot::Config),
            native("/cfg/so.tilo.notes")
        );
        assert_eq!(
            resolve(Base::Cache, Some("relative"), Slot::Cache),
            native("/home/u/.cache/so.tilo.notes")
        );
        assert_eq!(
            resolve(Base::State, None, Slot::State),
            native("/home/u/.local/state/so.tilo.notes")
        );
        assert_eq!(
            resolve(Base::Runtime, Some("/run/user/1000"), Slot::Runtime),
            native("/run/user/1000/so.tilo.notes")
        );
    }

    #[cfg(unix)]
    #[test]
    fn macos_joins_the_id_onto_the_library_folders() {
        use crate::xdg::Base;

        let tmpdir = [("TMPDIR", "/var/folders/ab/xyz/T/")];
        let resolve = |base: Base, slot| {
            let dir = crate::macos::base(base, &env(&tmpdir), || Some(PathBuf::from("/Users/u")));
            system::joined(dir, ID, slot)
        };
        let support = native("/Users/u/Library/Application Support/so.tilo.notes");
        assert_eq!(resolve(Base::Data, Slot::Data), support);
        assert_eq!(resolve(Base::Config, Slot::Config), support);
        assert_eq!(resolve(Base::State, Slot::State), support);
        assert_eq!(
            resolve(Base::Cache, Slot::Cache),
            native("/Users/u/Library/Caches/so.tilo.notes")
        );
        assert_eq!(
            resolve(Base::Runtime, Slot::Runtime),
            native("/var/folders/ab/xyz/T/so.tilo.notes")
        );
    }

    #[test]
    fn a_missing_base_directory_keeps_storage_in_memory() {
        let location = system::joined(None, ID, Slot::Data);
        assert_eq!(location.to_string(), "memory:///so.tilo.notes/data");
        assert!(location.native_path().is_err());
    }

    #[test]
    fn the_web_keeps_storage_in_the_profiles_opfs_tree() {
        for (slot, expected) in [
            (Slot::Data, "opfs://default/so.tilo.notes/data"),
            (Slot::Config, "opfs://default/so.tilo.notes/config"),
            (Slot::Cache, "opfs://default/so.tilo.notes/cache"),
            (Slot::State, "opfs://default/so.tilo.notes/state"),
        ] {
            assert_eq!(
                web::storage(slot, ID, DEFAULT_PROFILE).to_string(),
                expected
            );
        }
        assert_eq!(
            web::storage(Slot::Data, ID, "work").to_string(),
            "opfs://work/so.tilo.notes/data"
        );
        assert_eq!(
            web::runtime(ID).map(|location| location.to_string()),
            Ok("memory:///so.tilo.notes/runtime".to_owned())
        );
    }

    #[test]
    fn the_web_has_no_user_folders_workspace_or_font_directory() {
        assert_eq!(
            web::user_dir(UserDir::Documents).map_err(|error| error.feature),
            Err(Feature::UserDirs)
        );
        assert_eq!(
            web::workspace_root().map_err(|error| error.feature),
            Err(Feature::WorkspaceRoot)
        );
        assert_eq!(
            web::font_root().map_err(|error| error.feature),
            Err(Feature::FontRoot)
        );
        assert!(
            web::storage(Slot::Data, ID, "default")
                .native_path()
                .is_err()
        );
    }

    #[test]
    fn the_workspace_root_comes_from_the_launcher() {
        let resolve = |pairs: &[(&str, &str)], default| {
            system::workspace_root_from(&env(pairs), default).ok()
        };
        let linux = Some("/var/workspace");
        assert_eq!(
            resolve(&[("TILO_WORKSPACE_ROOT", "/mnt/ws")], None),
            Some(native("/mnt/ws"))
        );
        assert_eq!(
            resolve(&[("TILO_WORKSPACE_ID", "w1")], linux),
            Some(native("/var/workspace"))
        );
        assert_eq!(
            resolve(
                &[("TILO_WORKSPACE_ROOT", "rel"), ("TILO_WORKSPACE_ID", "w1")],
                linux
            ),
            Some(native("/var/workspace")),
            "a relative root is ignored"
        );
        assert_eq!(resolve(&[("TILO_WORKSPACE_ID", "w1")], None), None);
        assert_eq!(resolve(&[("TILO_WORKSPACE_ID", "")], linux), None);
        assert_eq!(resolve(&[], linux), None);
    }

    #[test]
    fn macos_fonts_come_from_the_running_bundle() {
        assert_eq!(
            system::bundle_fonts(Path::new(
                "/Applications/Tilo Notes.app/Contents/MacOS/notes"
            )),
            Some(PathBuf::from(
                "/Applications/Tilo Notes.app/Contents/Resources/fonts"
            ))
        );
        assert_eq!(
            system::bundle_fonts(Path::new("/usr/local/bin/notes")),
            None
        );
        assert_eq!(system::bundle_fonts(Path::new("notes")), None);
    }

    #[test]
    fn scoped_paths_stay_below_their_root() {
        let app = AppPaths::under("/sandbox", ID);
        assert_eq!(app.data(), native("/sandbox/so.tilo.notes/data"));
        assert_eq!(app.state(), native("/sandbox/so.tilo.notes/state"));
        assert_eq!(app.runtime(), Ok(native("/sandbox/so.tilo.notes/runtime")));
        assert!(app.user_dir(UserDir::Download).is_err());
        assert!(app.workspace_root().is_err());
        assert!(app.font_root().is_err());
        assert_eq!(app.clone().with_profile("work"), app);

        let memory = AppPaths::memory(ID);
        assert_eq!(memory.cache().to_string(), "memory:///so.tilo.notes/cache");
    }

    #[test]
    fn the_system_backend_agrees_with_the_per_user_directories() {
        let app = AppPaths::for_app(ID);
        for (location, base) in [
            (app.data(), crate::data_dir()),
            (app.config(), crate::config_dir()),
            (app.cache(), crate::cache_dir()),
            (app.state(), crate::state_dir()),
        ] {
            if let Some(base) = base {
                assert_eq!(location, Location::Native(base.join(ID)));
            }
        }
        assert_eq!(
            app.runtime().ok(),
            crate::runtime_dir().map(|dir| Location::Native(dir.join(ID)))
        );
    }

    #[test]
    fn ids_are_escaped_into_one_component() {
        for (raw, expected) in [
            (ID, ID),
            ("tilo-chat", "tilo-chat"),
            ("a/b", "a%2Fb"),
            ("..\\x", "..%5Cx"),
            ("50%", "50%25"),
            ("c:\n", "c%3A%0A"),
            (".", "%2E"),
            ("..", "%2E%2E"),
            ("", "%"),
        ] {
            assert_eq!(AppPaths::for_app(raw).id(), expected, "{raw:?}");
        }
        assert_eq!(
            AppPaths::memory("../escape").data().to_string(),
            "memory:///..%2Fescape/data"
        );
    }
}