Skip to main content

tilo_paths/
lib.rs

1//! Where per-user data, configuration, state, cache and runtime files live.
2//!
3//! [`AppPaths::for_app`] gives an app its data, config, cache, state and runtime
4//! locations, the user's folders, the workspace and the font catalog, on every
5//! target; the functions here are the same base directories for code without an app.
6
7use std::ffi::OsString;
8use std::path::PathBuf;
9
10mod app;
11mod caps;
12pub mod desktop_service;
13mod location;
14pub mod login;
15pub mod machine;
16pub mod session;
17
18pub use app::{AppPaths, DEFAULT_PROFILE, default_profile, set_default_profile};
19pub use caps::{Availability, Feature, Unsupported, availability, available};
20pub use location::{InvalidVPath, Location, VPath, VirtualRoot};
21pub use machine::Reach;
22
23/// Where a Tilo Linux session mounts the collaborative workspace, and the
24/// root every member's documents name workspace files under, whatever
25/// this device mounts. [`AppPaths::workspace_root`] says whether (and where)
26/// this process has one mounted.
27pub const WORKSPACE_MOUNT: &str = "/var/workspace";
28
29/// The file a Tilo Linux session writes the people and devices it certifies
30/// to: what an app showing who a file is shared with names them from.
31pub const TRUSTED_IDENTITIES: &str = "/run/tilo/identity-projection/trusted-identities.json";
32
33/// The runtime publishers this device accepts, one hex Ed25519 key per line, `#` comments: the
34/// list the system ships beside the code that reads it. A Linux image ships it in `/etc/tilo`; on
35/// a Mac it is in the resources of the Tilo.app whose executable is running, sealed by the app's
36/// signature as that executable is. An executable outside an app bundle reads the image's path,
37/// which a Mac does not have, so it trusts no runtime.
38#[must_use]
39pub fn runtime_publishers() -> PathBuf {
40    const FILE: &str = "runtime-bundle-trusted-publishers.txt";
41    #[cfg(target_os = "macos")]
42    if let Some(contents) = std::env::current_exe()
43        .and_then(std::fs::canonicalize)
44        .ok()
45        .and_then(|exe| Some(exe.parent()?.parent()?.to_path_buf()))
46        .filter(|contents| contents.join("Info.plist").is_file())
47    {
48        return contents.join("Resources").join(FILE);
49    }
50    PathBuf::from("/etc/tilo").join(FILE)
51}
52
53/// The directory, at the root of the device's files, that holds one tree per
54/// workspace: `<files>/.workspaces/<workspace id>`. The device's files are
55/// one namespace (`fs` serves one per device); a workspace's own files are
56/// the tree under its id, so its access checks (`FsPath` grants, which scope
57/// by path prefix) cover each tree as they cover any folder.
58pub const WORKSPACE_TREES_DIR: &str = ".workspaces";
59
60/// The tree of the workspace `id`'s own files under the device's files at
61/// `files`: [`WORKSPACE_TREES_DIR`]`/<id>`. `None` for an id that is not one
62/// path component of `[A-Za-z0-9_-]`, 1 to 128 bytes, so no id names a
63/// directory outside its own tree.
64#[must_use]
65pub fn workspace_tree(files: &std::path::Path, id: &str) -> Option<PathBuf> {
66    is_workspace_tree_id(id).then(|| files.join(WORKSPACE_TREES_DIR).join(id))
67}
68
69#[must_use]
70pub fn is_workspace_tree_id(id: &str) -> bool {
71    (1..=128).contains(&id.len())
72        && id
73            .bytes()
74            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
75}
76
77#[must_use]
78pub fn workspace_root() -> Option<PathBuf> {
79    let location = AppPaths::for_app("workspace").workspace_root().ok()?;
80    location
81        .native_path()
82        .ok()
83        .map(std::path::Path::to_path_buf)
84}
85
86#[must_use]
87pub fn language_packs_dir() -> Option<PathBuf> {
88    xdg::data_home().map(|data| data.join("tilo").join("language-packs"))
89}
90
91/// The language a locale names, as a language pack is named: its language
92/// subtag, lower case (`de` of `de`, `de-DE`, `de_DE.UTF-8@euro`). One pack
93/// holds a language's catalogues whatever region, encoding or modifier a
94/// locale adds, so a choice, the pack's directory and its package id meet at
95/// this one name. Empty when no language is named.
96///
97/// This is the one rule for "which language is this tag": every reader of a
98/// language tag — the packs, the toolkits, history, desktop entries — asks
99/// here, so a language picked anywhere matches everywhere.
100#[must_use]
101pub fn language_of(tag: &str) -> String {
102    tag.trim()
103        .split(['-', '_', '.', '@'])
104        .next()
105        .unwrap_or_default()
106        .to_ascii_lowercase()
107}
108
109/// The BCP 47 tag a locale names: the POSIX `de_DE.UTF-8@euro`, the
110/// `LANGUAGE` list `de_AT:en_US` and the BCP 47 `de-DE` all name `de-DE`.
111/// The encoding and the modifier name no language, a list's first entry is
112/// the language, and a tag spells the `_` a POSIX locale uses as `-`.
113#[must_use]
114pub fn locale_tag(locale: &str) -> String {
115    locale
116        .split(':')
117        .next()
118        .unwrap_or_default()
119        .split(['.', '@'])
120        .next()
121        .unwrap_or_default()
122        .trim()
123        .replace('_', "-")
124}
125
126/// Whether `tag` names a language: `C`, `POSIX`, `C.UTF-8` and an empty
127/// value name none, so their text is read untranslated.
128#[must_use]
129pub fn names_language(tag: &str) -> bool {
130    !matches!(language_of(tag).as_str(), "" | "c" | "posix")
131}
132
133/// The position in `candidates` (language tags, in the order the caller
134/// prefers them) of the one a reader of `locale` reads best: their own tag
135/// (`de-DE` for `de_DE.UTF-8`), else another region of their language
136/// (`de-DE` for `de-AT`). `None` when neither is there or `locale` names no
137/// language. This is the one rule for which tag a reader gets, so every
138/// catalogue, name and window picks the same one.
139#[must_use]
140pub fn matching<'a>(
141    locale: &str,
142    mut candidates: impl Iterator<Item = &'a str> + Clone,
143) -> Option<usize> {
144    if !names_language(locale) {
145        return None;
146    }
147    let tag = locale_tag(locale);
148    let language = language_of(locale);
149    let mut exact = candidates.clone();
150    exact
151        .position(|candidate| locale_tag(candidate).eq_ignore_ascii_case(&tag))
152        .or_else(|| candidates.position(|candidate| language_of(candidate) == language))
153}
154
155/// The user's home directory: `$HOME` when set and non-empty, the account
156/// database's entry when `$HOME` is unset (on Unix), and `None` for an empty
157/// `$HOME` — an empty value names no directory, and resolving relative to the
158/// working directory would scatter state wherever the process started. On
159/// Windows it is the profile known folder, never an environment variable.
160#[must_use]
161pub fn home() -> Option<PathBuf> {
162    #[cfg(windows)]
163    {
164        platform::home()
165    }
166    #[cfg(not(windows))]
167    {
168        home_from(&|name| var(name), std::env::home_dir)
169    }
170}
171
172#[cfg(not(windows))]
173fn home_from(
174    var: &dyn Fn(&str) -> Option<OsString>,
175    account_home: impl FnOnce() -> Option<PathBuf>,
176) -> Option<PathBuf> {
177    #[cfg(unix)]
178    match var("HOME") {
179        Some(home) if home.is_empty() => None,
180        Some(home) => Some(PathBuf::from(home)),
181        None => account_home().filter(|home| !home.as_os_str().is_empty()),
182    }
183    #[cfg(not(unix))]
184    {
185        let _ = var;
186        account_home().filter(|home| !home.as_os_str().is_empty())
187    }
188}
189
190/// `$name` as a directory, following the XDG rule for every base-directory
191/// variable: honoured only when set, non-empty and absolute.
192#[must_use]
193pub fn env_dir(name: &str) -> Option<PathBuf> {
194    absolute(var(name))
195}
196
197thread_local! {
198    static PROFILE_ROOT: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
199}
200
201/// Keeps a thread's per-user folders below one root until it is dropped:
202/// see [`scope_profile`].
203#[must_use = "the scope ends when the guard is dropped"]
204pub struct ProfileScope {
205    earlier: Option<PathBuf>,
206}
207
208impl Drop for ProfileScope {
209    fn drop(&mut self) {
210        PROFILE_ROOT.with(|root| *root.borrow_mut() = self.earlier.take());
211    }
212}
213
214/// From now until the guard drops, this thread's home is `root`: [`home`],
215/// the per-user base folders, [`env_dir`] of the XDG variables and
216/// [`AppPaths::for_app`] all resolve below it, whatever the process
217/// environment says, and no workspace is mounted. A host that runs a
218/// member (an agent) on its own thread gives it a profile apart from
219/// the host user's this way. Threads the scoped thread starts do not
220/// inherit it.
221pub fn scope_profile(root: impl Into<PathBuf>) -> ProfileScope {
222    let earlier = PROFILE_ROOT.with(|scoped| scoped.borrow_mut().replace(root.into()));
223    ProfileScope { earlier }
224}
225
226pub fn unscoped<R>(work: impl FnOnce() -> R) -> R {
227    let _scope = ProfileScope {
228        earlier: PROFILE_ROOT.with(|root| root.borrow_mut().take()),
229    };
230    work()
231}
232
233#[must_use]
234pub fn scoped_profile() -> Option<PathBuf> {
235    PROFILE_ROOT.with(|root| root.borrow().clone())
236}
237
238fn var(name: &str) -> Option<OsString> {
239    let Some(root) = scoped_profile() else {
240        return std::env::var_os(name);
241    };
242    let below = match name {
243        "HOME" => "",
244        "XDG_DATA_HOME" => ".local/share",
245        "XDG_CONFIG_HOME" => ".config",
246        "XDG_STATE_HOME" => ".local/state",
247        "XDG_CACHE_HOME" => ".cache",
248        "XDG_RUNTIME_DIR" => "run",
249        "TMPDIR" => "tmp",
250        name if name.starts_with("TILO_WORKSPACE") => return None,
251        name if name.starts_with("XDG_") && name.ends_with("_DIR") => return None,
252        _ => return std::env::var_os(name),
253    };
254    Some(root.join(below).into_os_string())
255}
256
257fn absolute(value: Option<OsString>) -> Option<PathBuf> {
258    // An empty path is not absolute, so this also rejects empty values.
259    value.map(PathBuf::from).filter(|path| path.is_absolute())
260}
261
262pub mod xdg {
263    use std::ffi::{OsStr, OsString};
264    use std::path::PathBuf;
265
266    use super::{absolute, home};
267
268    #[must_use]
269    pub fn data_home() -> Option<PathBuf> {
270        Base::Data.resolve(&env, home)
271    }
272
273    #[must_use]
274    pub fn config_home() -> Option<PathBuf> {
275        Base::Config.resolve(&env, home)
276    }
277
278    #[must_use]
279    pub fn state_home() -> Option<PathBuf> {
280        Base::State.resolve(&env, home)
281    }
282
283    #[must_use]
284    pub fn cache_home() -> Option<PathBuf> {
285        Base::Cache.resolve(&env, home)
286    }
287
288    /// `$XDG_RUNTIME_DIR`. The spec defines no fallback: a substitute would
289    /// lack its guarantees (owner-only, removed at logout), so `None` makes
290    /// callers decide what to do without one.
291    #[must_use]
292    pub fn runtime_dir() -> Option<PathBuf> {
293        Base::Runtime.resolve(&env, home)
294    }
295
296    /// [`runtime_dir`], else where the platform keeps it without the
297    /// variable: `/run/user/<euid>` as systemd-logind creates it, the per-user
298    /// `$TMPDIR` on macOS, the per-user `%TEMP%` on Windows. For callers that
299    /// must name a per-user socket or file even in a session started without
300    /// `$XDG_RUNTIME_DIR`.
301    #[cfg(any(unix, windows))]
302    #[must_use]
303    pub fn runtime_dir_or_default() -> PathBuf {
304        runtime_dir().unwrap_or_else(|| {
305            #[cfg(any(target_os = "macos", windows))]
306            {
307                std::env::temp_dir()
308            }
309            #[cfg(all(unix, not(target_os = "macos")))]
310            {
311                PathBuf::from(format!("/run/user/{}", rustix::process::geteuid().as_raw()))
312            }
313        })
314    }
315
316    /// Where this login's Tilo services bind their sockets: one directory in
317    /// the runtime directory, so a socket found here belongs to this user and
318    /// is gone when their login ends.
319    #[cfg(any(unix, windows))]
320    #[must_use]
321    pub fn services_dir() -> PathBuf {
322        runtime_dir_or_default().join("tilo/services")
323    }
324
325    #[cfg(any(unix, windows))]
326    #[must_use]
327    pub fn service_socket(name: &str) -> PathBuf {
328        services_dir().join(format!("{name}.sock"))
329    }
330
331    /// `$XDG_DATA_DIRS` in preference order, else `/usr/local/share` and
332    /// `/usr/share`. Relative and empty entries are ignored, as the spec
333    /// requires.
334    #[must_use]
335    pub fn data_dirs() -> Vec<PathBuf> {
336        search_path(
337            env("XDG_DATA_DIRS").as_deref(),
338            &["/usr/local/share", "/usr/share"],
339        )
340    }
341
342    /// `$XDG_CONFIG_DIRS` in preference order, else `/etc/xdg`. Relative and
343    /// empty entries are ignored, as the spec requires.
344    #[must_use]
345    pub fn config_dirs() -> Vec<PathBuf> {
346        search_path(env("XDG_CONFIG_DIRS").as_deref(), &["/etc/xdg"])
347    }
348
349    fn env(name: &str) -> Option<OsString> {
350        super::var(name)
351    }
352
353    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
354    pub enum Base {
355        Data,
356        Config,
357        State,
358        Cache,
359        Runtime,
360    }
361
362    impl Base {
363        #[must_use]
364        pub const fn env_var(self) -> &'static str {
365            match self {
366                Self::Data => "XDG_DATA_HOME",
367                Self::Config => "XDG_CONFIG_HOME",
368                Self::State => "XDG_STATE_HOME",
369                Self::Cache => "XDG_CACHE_HOME",
370                Self::Runtime => "XDG_RUNTIME_DIR",
371            }
372        }
373
374        const fn home_default(self) -> Option<&'static str> {
375            match self {
376                Self::Data => Some(".local/share"),
377                Self::Config => Some(".config"),
378                Self::State => Some(".local/state"),
379                Self::Cache => Some(".cache"),
380                Self::Runtime => None,
381            }
382        }
383
384        /// Resolve from explicit values of the variable and `$HOME` instead of
385        /// the process environment — for callers that take them as parameters
386        /// so tests need not mutate the environment. The variable counts only
387        /// when non-empty and absolute; an empty `home` counts as unset.
388        #[must_use]
389        pub fn resolve_from(self, value: Option<&OsStr>, home: Option<&OsStr>) -> Option<PathBuf> {
390            self.resolve(&|_| value.map(OsStr::to_os_string), || {
391                home.filter(|home| !home.is_empty()).map(PathBuf::from)
392            })
393        }
394
395        pub(crate) fn resolve(
396            self,
397            var: &dyn Fn(&str) -> Option<OsString>,
398            home: impl FnOnce() -> Option<PathBuf>,
399        ) -> Option<PathBuf> {
400            absolute(var(self.env_var())).or_else(|| {
401                let default = self.home_default()?;
402                Some(home()?.join(default))
403            })
404        }
405    }
406
407    pub(crate) fn search_path(value: Option<&OsStr>, default: &[&str]) -> Vec<PathBuf> {
408        let listed: Vec<PathBuf> = value
409            .map(|value| {
410                std::env::split_paths(value)
411                    .filter(|path| path.is_absolute())
412                    .collect()
413            })
414            .unwrap_or_default();
415        // An unset, empty or entirely invalid list means the defaults.
416        if listed.is_empty() {
417            default.iter().map(PathBuf::from).collect()
418        } else {
419            listed
420        }
421    }
422}
423
424/// The platform's per-user data directory: [`xdg::data_home`] on Linux and
425/// other Unix, `~/Library/Application Support` on macOS, `%APPDATA%` on
426/// Windows.
427#[must_use]
428pub fn data_dir() -> Option<PathBuf> {
429    platform::data()
430}
431
432/// The platform's per-user local (non-roaming) data directory:
433/// [`xdg::data_home`] on Linux and other Unix, `~/Library/Application Support`
434/// on macOS, `%LOCALAPPDATA%` on Windows.
435#[must_use]
436pub fn data_local_dir() -> Option<PathBuf> {
437    platform::data_local()
438}
439
440/// The platform's per-user configuration directory: [`xdg::config_home`] on
441/// Linux and other Unix, `~/Library/Application Support` on macOS,
442/// `%APPDATA%` on Windows.
443#[must_use]
444pub fn config_dir() -> Option<PathBuf> {
445    platform::config()
446}
447
448/// The platform's per-user state directory: [`xdg::state_home`] on Linux and
449/// other Unix, `~/Library/Application Support` on macOS (which keeps state
450/// beside data); Windows defines none.
451#[must_use]
452pub fn state_dir() -> Option<PathBuf> {
453    platform::state()
454}
455
456/// The per-user Tilo profile root: `$XDG_CONFIG_HOME/tilo`, else
457/// `$HOME/.config/tilo` on Linux and other Unix, the platform's configuration
458/// directory elsewhere.
459#[must_use]
460pub fn profile_root() -> Option<PathBuf> {
461    Some(xdg::config_home()?.join("tilo"))
462}
463
464/// The platform's per-user cache directory: [`xdg::cache_home`] on Linux and
465/// other Unix, `~/Library/Caches` on macOS, `%LOCALAPPDATA%` on Windows.
466#[must_use]
467pub fn cache_dir() -> Option<PathBuf> {
468    platform::cache()
469}
470
471/// The per-login runtime directory: [`xdg::runtime_dir`] on Linux and other
472/// Unix, the per-user `$TMPDIR` on macOS when it is absolute; Windows defines
473/// none.
474#[must_use]
475pub fn runtime_dir() -> Option<PathBuf> {
476    platform::runtime()
477}
478
479/// The system's shared temporary directory (`$TMPDIR` or `/tmp`,
480/// `%TEMP%`), and `None` where there is no native file system (the web),
481/// where `std::env::temp_dir` panics instead. For scratch files that must
482/// have a native path; an app's own scratch space is [`AppPaths::runtime`].
483#[must_use]
484pub fn temp_dir() -> Option<PathBuf> {
485    (available(Feature::NativePaths)).then(std::env::temp_dir)
486}
487
488/// A temporary directory kept in memory, where the platform has one
489/// (`/dev/shm` on Linux): for scratch data that is synced like a person's
490/// but deleted moments later (a test's profile), whose syncs then cost
491/// nothing instead of waiting on a shared disk. `None` elsewhere.
492#[must_use]
493pub fn memory_temp_dir() -> Option<PathBuf> {
494    if !cfg!(target_os = "linux") {
495        return None;
496    }
497    Some(PathBuf::from("/dev/shm")).filter(|directory| directory.is_dir())
498}
499
500/// Directories the system and the user install fonts into, most general
501/// first, whether or not they exist: the system font trees on Linux and
502/// other Unix (not the user's own), `/System/Library/Fonts`, `/Library/Fonts` and
503/// `~/Library/Fonts` on macOS, the Windows font folder, and none on the web.
504/// For code that reads font files itself (a document renderer's fallback
505/// fonts, a confined helper's read grant).
506#[must_use]
507pub fn system_font_dirs() -> Vec<PathBuf> {
508    platform::font_dirs()
509}
510
511#[cfg(all(unix, not(target_os = "macos")))]
512mod platform {
513    use std::path::PathBuf;
514
515    use super::{UserDir, home, xdg};
516
517    pub fn data() -> Option<PathBuf> {
518        xdg::data_home()
519    }
520    pub fn data_local() -> Option<PathBuf> {
521        xdg::data_home()
522    }
523    pub fn config() -> Option<PathBuf> {
524        xdg::config_home()
525    }
526    pub fn state() -> Option<PathBuf> {
527        xdg::state_home()
528    }
529    pub fn cache() -> Option<PathBuf> {
530        xdg::cache_home()
531    }
532    pub fn runtime() -> Option<PathBuf> {
533        xdg::runtime_dir()
534    }
535    pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
536        dir.resolve_for_home(&home()?)
537    }
538    pub fn font_dirs() -> Vec<PathBuf> {
539        [
540            "/usr/share/fonts",
541            "/usr/local/share/fonts",
542            "/usr/share/X11/fonts/Type1",
543            "/usr/share/X11/fonts/TTF",
544        ]
545        .into_iter()
546        .map(PathBuf::from)
547        .collect()
548    }
549}
550
551#[cfg(target_os = "macos")]
552mod platform {
553    use std::path::PathBuf;
554
555    use super::xdg::Base;
556    use super::{UserDir, home, macos};
557
558    fn base(base: Base) -> Option<PathBuf> {
559        macos::base(base, &|name| crate::var(name), home)
560    }
561
562    pub fn data() -> Option<PathBuf> {
563        base(Base::Data)
564    }
565    pub fn data_local() -> Option<PathBuf> {
566        data()
567    }
568    pub fn config() -> Option<PathBuf> {
569        base(Base::Config)
570    }
571    pub fn state() -> Option<PathBuf> {
572        base(Base::State)
573    }
574    pub fn cache() -> Option<PathBuf> {
575        base(Base::Cache)
576    }
577    pub fn runtime() -> Option<PathBuf> {
578        base(Base::Runtime)
579    }
580    pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
581        Some(macos::user_dir(dir, &home()?))
582    }
583    pub fn font_dirs() -> Vec<PathBuf> {
584        let mut dirs = vec![
585            PathBuf::from("/System/Library/Fonts"),
586            PathBuf::from("/Library/Fonts"),
587        ];
588        dirs.extend(home().map(|home| home.join("Library/Fonts")));
589        dirs
590    }
591}
592
593/// The macOS per-user locations as functions of the environment and home
594/// directory, so the Linux test run checks them too.
595#[cfg(any(target_os = "macos", all(test, unix)))]
596mod macos {
597    use std::ffi::OsString;
598    use std::path::{Path, PathBuf};
599
600    use super::xdg::Base;
601    use super::{UserDir, absolute};
602
603    /// Data, configuration and state share `~/Library/Application Support`,
604    /// which is where macOS keeps an app's durable files; caches go to
605    /// `~/Library/Caches`. The runtime directory is `$TMPDIR`, the per-user,
606    /// owner-only directory launchd assigns below `/var/folders` and the
607    /// system cleans up. It counts only when absolute: the shared `/tmp`
608    /// lacks those guarantees, so there is no fallback.
609    pub(crate) fn base(
610        base: Base,
611        var: &dyn Fn(&str) -> Option<OsString>,
612        home: impl FnOnce() -> Option<PathBuf>,
613    ) -> Option<PathBuf> {
614        match base {
615            Base::Data | Base::Config | Base::State => {
616                Some(home()?.join("Library/Application Support"))
617            }
618            Base::Cache => Some(home()?.join("Library/Caches")),
619            Base::Runtime => absolute(var("TMPDIR")),
620        }
621    }
622
623    pub(crate) fn user_dir(dir: UserDir, home: &Path) -> PathBuf {
624        home.join(match dir {
625            UserDir::Videos => "Movies",
626            other => other.conventional_name(),
627        })
628    }
629}
630
631#[cfg(windows)]
632mod platform {
633    use std::ffi::OsString;
634    use std::os::windows::ffi::OsStringExt;
635    use std::path::PathBuf;
636
637    use windows_sys::Win32::System::Com::CoTaskMemFree;
638    use windows_sys::Win32::UI::Shell::{
639        FOLDERID_Desktop, FOLDERID_Documents, FOLDERID_Downloads, FOLDERID_LocalAppData,
640        FOLDERID_Music, FOLDERID_Pictures, FOLDERID_Profile, FOLDERID_Public,
641        FOLDERID_RoamingAppData, FOLDERID_Templates, FOLDERID_Videos, SHGetKnownFolderPath,
642    };
643    use windows_sys::core::{GUID, PWSTR};
644
645    use super::UserDir;
646
647    fn known_folder(id: &GUID) -> Option<PathBuf> {
648        let mut raw: PWSTR = std::ptr::null_mut();
649        // SAFETY: `id` is a valid GUID reference, a null token selects the
650        // current user, and `raw` is a valid out-pointer the call fills with
651        // a CoTaskMem-allocated, NUL-terminated wide string (or leaves null).
652        let status = unsafe { SHGetKnownFolderPath(id, 0, std::ptr::null_mut(), &raw mut raw) };
653        let path = (status == 0 && !raw.is_null()).then(|| {
654            let mut len = 0_usize;
655            // SAFETY: on success `raw` points to a NUL-terminated wide string;
656            // every offset read here is at or before its terminator.
657            while unsafe { *raw.add(len) } != 0 {
658                len = len.saturating_add(1);
659            }
660            // SAFETY: the `len` units before the terminator were just read.
661            let wide = unsafe { std::slice::from_raw_parts(raw, len) };
662            PathBuf::from(OsString::from_wide(wide))
663        });
664        // SAFETY: the buffer is owned by us after the call, whether or not it
665        // succeeded; freeing null is a no-op.
666        unsafe { CoTaskMemFree(raw.cast()) };
667        path.filter(|path| !path.as_os_str().is_empty())
668    }
669
670    pub fn home() -> Option<PathBuf> {
671        known_folder(&FOLDERID_Profile)
672    }
673    pub fn data() -> Option<PathBuf> {
674        known_folder(&FOLDERID_RoamingAppData)
675    }
676    pub fn data_local() -> Option<PathBuf> {
677        known_folder(&FOLDERID_LocalAppData)
678    }
679    pub fn config() -> Option<PathBuf> {
680        data()
681    }
682    pub fn state() -> Option<PathBuf> {
683        None
684    }
685    pub fn cache() -> Option<PathBuf> {
686        data_local()
687    }
688    pub fn runtime() -> Option<PathBuf> {
689        None
690    }
691    pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
692        known_folder(match dir {
693            UserDir::Desktop => &FOLDERID_Desktop,
694            UserDir::Documents => &FOLDERID_Documents,
695            UserDir::Download => &FOLDERID_Downloads,
696            UserDir::Music => &FOLDERID_Music,
697            UserDir::Pictures => &FOLDERID_Pictures,
698            UserDir::Videos => &FOLDERID_Videos,
699            UserDir::Templates => &FOLDERID_Templates,
700            UserDir::PublicShare => &FOLDERID_Public,
701        })
702    }
703    pub fn font_dirs() -> Vec<PathBuf> {
704        super::env_dir("WINDIR")
705            .map(|windows| windows.join("Fonts"))
706            .into_iter()
707            .collect()
708    }
709}
710
711#[cfg(not(any(unix, windows)))]
712mod platform {
713    use std::path::PathBuf;
714
715    use super::{UserDir, env_dir, home};
716
717    pub fn data() -> Option<PathBuf> {
718        env_dir("APPDATA")
719    }
720    pub fn data_local() -> Option<PathBuf> {
721        env_dir("LOCALAPPDATA")
722    }
723    pub fn config() -> Option<PathBuf> {
724        data()
725    }
726    pub fn state() -> Option<PathBuf> {
727        None
728    }
729    pub fn cache() -> Option<PathBuf> {
730        env_dir("LOCALAPPDATA")
731    }
732    pub fn runtime() -> Option<PathBuf> {
733        None
734    }
735    pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
736        Some(home()?.join(dir.conventional_name()))
737    }
738    pub fn font_dirs() -> Vec<PathBuf> {
739        Vec::new()
740    }
741}
742
743/// One of the user's well-known content directories (Documents, Downloads, …).
744///
745/// On Linux and other Unix these follow `xdg-user-dirs`: `$XDG_<NAME>_DIR` when
746/// set, non-empty and absolute, else the entry in
747/// `$XDG_CONFIG_HOME/user-dirs.dirs`, which is where a localized desktop
748/// records `~/Dokumente` instead of `~/Documents`. An entry pointing at `$HOME`
749/// itself means the directory is disabled and resolves to `None`, as does a
750/// missing entry. macOS and Windows use their conventional folders below the
751/// home directory.
752#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
753pub enum UserDir {
754    Desktop,
755    Documents,
756    Download,
757    Music,
758    Pictures,
759    Videos,
760    Templates,
761    PublicShare,
762}
763
764impl UserDir {
765    #[must_use]
766    pub const fn env_var(self) -> &'static str {
767        match self {
768            Self::Desktop => "XDG_DESKTOP_DIR",
769            Self::Documents => "XDG_DOCUMENTS_DIR",
770            Self::Download => "XDG_DOWNLOAD_DIR",
771            Self::Music => "XDG_MUSIC_DIR",
772            Self::Pictures => "XDG_PICTURES_DIR",
773            Self::Videos => "XDG_VIDEOS_DIR",
774            Self::Templates => "XDG_TEMPLATES_DIR",
775            Self::PublicShare => "XDG_PUBLICSHARE_DIR",
776        }
777    }
778
779    /// The folder name the platform conventionally uses below the home
780    /// directory (English, not localized). macOS and Windows resolve to it;
781    /// on XDG platforms it is only a hint for callers that need a default.
782    #[must_use]
783    pub const fn conventional_name(self) -> &'static str {
784        match self {
785            Self::Desktop => "Desktop",
786            Self::Documents => "Documents",
787            Self::Download => "Downloads",
788            Self::Music => "Music",
789            Self::Pictures => "Pictures",
790            #[cfg(target_os = "macos")]
791            Self::Videos => "Movies",
792            #[cfg(not(target_os = "macos"))]
793            Self::Videos => "Videos",
794            Self::Templates => "Templates",
795            Self::PublicShare => "Public",
796        }
797    }
798
799    #[must_use]
800    pub fn resolve(self) -> Option<PathBuf> {
801        platform::user_dir(self)
802    }
803
804    /// The directory the environment alone names: `$XDG_<NAME>_DIR` when set,
805    /// non-empty and absolute. Reads no `user-dirs.dirs`, so a caller that
806    /// must not read files (an app's startup) can still honour the variable.
807    #[must_use]
808    pub fn from_environment(self) -> Option<PathBuf> {
809        absolute(var(self.env_var()))
810    }
811
812    #[must_use]
813    pub fn resolve_for_home(self, home: &std::path::Path) -> Option<PathBuf> {
814        let config_home = xdg::Base::Config
815            .resolve_from(var("XDG_CONFIG_HOME").as_deref(), Some(home.as_os_str()))?;
816        let file = std::fs::read(config_home.join("user-dirs.dirs")).ok();
817        self.resolve_from(var(self.env_var()).as_deref(), file.as_deref(), home)
818    }
819
820    /// Resolve from an explicit variable value and `user-dirs.dirs` contents
821    /// instead of the process environment and file system. The variable counts
822    /// only when non-empty and absolute.
823    #[must_use]
824    pub fn resolve_from(
825        self,
826        value: Option<&std::ffi::OsStr>,
827        user_dirs: Option<&[u8]>,
828        home: &std::path::Path,
829    ) -> Option<PathBuf> {
830        absolute(value.map(std::ffi::OsStr::to_os_string))
831            .or_else(|| user_dirs_entry(user_dirs?, self.env_var(), home))
832    }
833}
834
835/// The value of `key` in a `user-dirs.dirs` file.
836///
837/// The file is a shell fragment, but `xdg-user-dirs-update` writes only
838/// `KEY="$HOME/relative"` or `KEY="/absolute"`, so exactly those two forms are
839/// accepted; a value of `"$HOME/"` disables the directory. The last matching
840/// line wins, as it would when the file is sourced.
841fn user_dirs_entry(contents: &[u8], key: &str, home: &std::path::Path) -> Option<PathBuf> {
842    let mut found = None;
843    for line in contents.split(|&byte| byte == b'\n') {
844        let Some(separator) = line.iter().position(|&byte| byte == b'=') else {
845            continue;
846        };
847        let (name, value) = line.split_at(separator);
848        if trim_blank(name) != key.as_bytes() {
849            continue;
850        }
851        let value = trim_blank(value.get(1..).unwrap_or_default());
852        let Some(value) = value
853            .strip_prefix(b"\"")
854            .and_then(|value| value.strip_suffix(b"\""))
855        else {
856            continue;
857        };
858        found = if value == b"$HOME/" || value == b"$HOME" {
859            None
860        } else if let Some(relative) = value.strip_prefix(b"$HOME/") {
861            Some(home.join(path_from_bytes(shell_unescape(relative))))
862        } else if value.starts_with(b"/") {
863            Some(path_from_bytes(shell_unescape(value)))
864        } else {
865            continue;
866        };
867    }
868    found
869}
870
871fn trim_blank(bytes: &[u8]) -> &[u8] {
872    let blank = |byte: &u8| *byte == b' ' || *byte == b'\t' || *byte == b'\r';
873    let start = bytes
874        .iter()
875        .position(|byte| !blank(byte))
876        .unwrap_or(bytes.len());
877    let end = bytes
878        .iter()
879        .rposition(|byte| !blank(byte))
880        .map_or(start, |last| last.saturating_add(1));
881    bytes.get(start..end).unwrap_or_default()
882}
883
884/// Undo POSIX double-quote escaping: a backslash quotes only `$`, `` ` ``,
885/// `"`, `\` and a newline, and is kept literally before anything else.
886fn shell_unescape(escaped: &[u8]) -> Vec<u8> {
887    let mut unescaped = Vec::with_capacity(escaped.len());
888    let mut bytes = escaped.iter().copied().peekable();
889    while let Some(byte) = bytes.next() {
890        if byte == b'\\'
891            && let Some(&next) = bytes.peek()
892            && matches!(next, b'$' | b'`' | b'"' | b'\\' | b'\n')
893        {
894            unescaped.push(next);
895            bytes.next();
896        } else {
897            unescaped.push(byte);
898        }
899    }
900    unescaped
901}
902
903#[cfg(unix)]
904fn path_from_bytes(bytes: Vec<u8>) -> PathBuf {
905    use std::os::unix::ffi::OsStringExt;
906    PathBuf::from(OsString::from_vec(bytes))
907}
908
909#[cfg(not(unix))]
910fn path_from_bytes(bytes: Vec<u8>) -> PathBuf {
911    match String::from_utf8(bytes) {
912        Ok(text) => PathBuf::from(text),
913        Err(error) => PathBuf::from(String::from_utf8_lossy(error.as_bytes()).into_owned()),
914    }
915}
916
917#[must_use]
918pub fn desktop_dir() -> Option<PathBuf> {
919    UserDir::Desktop.resolve()
920}
921
922#[must_use]
923pub fn document_dir() -> Option<PathBuf> {
924    UserDir::Documents.resolve()
925}
926
927#[must_use]
928pub fn download_dir() -> Option<PathBuf> {
929    UserDir::Download.resolve()
930}
931
932#[must_use]
933pub fn audio_dir() -> Option<PathBuf> {
934    UserDir::Music.resolve()
935}
936
937#[must_use]
938pub fn picture_dir() -> Option<PathBuf> {
939    UserDir::Pictures.resolve()
940}
941
942#[must_use]
943pub fn video_dir() -> Option<PathBuf> {
944    UserDir::Videos.resolve()
945}
946
947/// One app's subdirectories of the per-user base directories, e.g.
948/// `AppDirs::new("tilo-chat").data()` is `~/.local/share/tilo-chat` on Linux.
949#[derive(Clone, Copy, Debug, PartialEq, Eq)]
950pub struct AppDirs<'a> {
951    name: &'a str,
952}
953
954impl<'a> AppDirs<'a> {
955    #[must_use]
956    pub const fn new(name: &'a str) -> Self {
957        Self { name }
958    }
959
960    #[must_use]
961    pub fn data(&self) -> Option<PathBuf> {
962        Some(data_dir()?.join(self.name))
963    }
964
965    #[must_use]
966    pub fn config(&self) -> Option<PathBuf> {
967        Some(config_dir()?.join(self.name))
968    }
969
970    #[must_use]
971    pub fn state(&self) -> Option<PathBuf> {
972        Some(state_dir()?.join(self.name))
973    }
974
975    #[must_use]
976    pub fn cache(&self) -> Option<PathBuf> {
977        Some(cache_dir()?.join(self.name))
978    }
979
980    #[must_use]
981    pub fn runtime(&self) -> Option<PathBuf> {
982        Some(runtime_dir()?.join(self.name))
983    }
984}
985
986#[cfg(test)]
987mod tests {
988    use super::xdg::Base;
989    #[cfg(unix)]
990    use super::xdg::search_path;
991    use super::*;
992    #[cfg(unix)]
993    use std::ffi::OsStr;
994
995    fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
996        move |name| {
997            pairs
998                .iter()
999                .find(|(key, _)| *key == name)
1000                .map(|(_, value)| OsString::from(value))
1001        }
1002    }
1003
1004    #[cfg(unix)]
1005    fn home_is(path: &str) -> impl FnOnce() -> Option<PathBuf> + '_ {
1006        move || Some(PathBuf::from(path))
1007    }
1008
1009    #[test]
1010    fn a_locale_names_one_language_however_it_is_spelled() {
1011        for (locale, language, tag, named) in [
1012            ("de", "de", "de", true),
1013            ("de-DE", "de", "de-DE", true),
1014            ("de_DE", "de", "de-DE", true),
1015            ("de_DE.UTF-8", "de", "de-DE", true),
1016            ("de_DE.UTF-8@euro", "de", "de-DE", true),
1017            ("de.UTF-8", "de", "de", true),
1018            (" de-DE ", "de", "de-DE", true),
1019            ("DE-de", "de", "DE-de", true),
1020            ("de_AT:en_US", "de", "de-AT", true),
1021            ("en-US", "en", "en-US", true),
1022            ("es-419", "es", "es-419", true),
1023            ("zh-Hant-TW", "zh", "zh-Hant-TW", true),
1024            ("C", "c", "C", false),
1025            ("C.UTF-8", "c", "C", false),
1026            ("POSIX", "posix", "POSIX", false),
1027            ("", "", "", false),
1028        ] {
1029            assert_eq!(language_of(locale), language, "{locale:?}");
1030            assert_eq!(locale_tag(locale), tag, "{locale:?}");
1031            assert_eq!(names_language(locale), named, "{locale:?}");
1032        }
1033    }
1034
1035    #[test]
1036    fn a_reader_is_served_by_its_own_tag_or_another_region_of_its_language() {
1037        for (locale, candidates, want) in [
1038            ("de-DE", &["en-US", "de-DE"][..], Some(1)),
1039            ("de_DE.UTF-8", &["en-US", "de-DE"], Some(1)),
1040            ("de-AT", &["en-US", "de-DE"], Some(1)),
1041            ("de", &["de-DE", "de"], Some(1)),
1042            ("en-US", &["de-DE", "en-US"], Some(1)),
1043            ("fr-FR", &["de-DE", "en-US"], None),
1044            ("fr-FR", &[], None),
1045            ("C", &["de-DE"], None),
1046            ("", &["de-DE"], None),
1047        ] {
1048            assert_eq!(
1049                matching(locale, candidates.iter().copied()),
1050                want,
1051                "{locale:?}"
1052            );
1053        }
1054    }
1055
1056    #[cfg(unix)]
1057    #[test]
1058    #[allow(
1059        clippy::too_many_lines,
1060        reason = "each phase keeps one former test's body verbatim"
1061    )]
1062    fn base_directories_follow_absolute_variables_or_home_defaults() {
1063        {
1064            let vars = [
1065                ("XDG_DATA_HOME", "/data"),
1066                ("XDG_CONFIG_HOME", "/config"),
1067                ("XDG_STATE_HOME", "/state"),
1068                ("XDG_CACHE_HOME", "/cache"),
1069                ("XDG_RUNTIME_DIR", "/run/user/1000"),
1070            ];
1071            let var = env(&vars);
1072            for (base, expected) in [
1073                (Base::Data, "/data"),
1074                (Base::Config, "/config"),
1075                (Base::State, "/state"),
1076                (Base::Cache, "/cache"),
1077                (Base::Runtime, "/run/user/1000"),
1078            ] {
1079                assert_eq!(
1080                    base.resolve(&var, home_is("/home/u")),
1081                    Some(PathBuf::from(expected))
1082                );
1083            }
1084        }
1085        {
1086            let var = env(&[]);
1087            for (base, expected) in [
1088                (Base::Data, Some("/home/u/.local/share")),
1089                (Base::Config, Some("/home/u/.config")),
1090                (Base::State, Some("/home/u/.local/state")),
1091                (Base::Cache, Some("/home/u/.cache")),
1092                (Base::Runtime, None),
1093            ] {
1094                assert_eq!(
1095                    base.resolve(&var, home_is("/home/u")),
1096                    expected.map(PathBuf::from),
1097                    "{base:?}"
1098                );
1099            }
1100        }
1101        {
1102            for value in ["relative/data", "", "./data", "~/data"] {
1103                let vars = [("XDG_DATA_HOME", value), ("XDG_RUNTIME_DIR", value)];
1104                let var = env(&vars);
1105                assert_eq!(
1106                    Base::Data.resolve(&var, home_is("/home/u")),
1107                    Some(PathBuf::from("/home/u/.local/share")),
1108                    "{value:?}"
1109                );
1110                assert_eq!(
1111                    Base::Runtime.resolve(&var, home_is("/home/u")),
1112                    None,
1113                    "{value:?}"
1114                );
1115            }
1116        }
1117        {
1118            let home = Some(OsStr::new("/home/u"));
1119            assert_eq!(
1120                Base::State.resolve_from(Some(OsStr::new("/state")), home),
1121                Some(PathBuf::from("/state"))
1122            );
1123            for invalid in [None, Some(OsStr::new("")), Some(OsStr::new("rel"))] {
1124                assert_eq!(
1125                    Base::State.resolve_from(invalid, home),
1126                    Some(PathBuf::from("/home/u/.local/state"))
1127                );
1128            }
1129            assert_eq!(Base::State.resolve_from(None, Some(OsStr::new(""))), None);
1130            assert_eq!(Base::Runtime.resolve_from(None, home), None);
1131            assert_eq!(Base::Config.env_var(), "XDG_CONFIG_HOME");
1132        }
1133        {
1134            let account = || Some(PathBuf::from("/var/home/account"));
1135            assert_eq!(
1136                home_from(&env(&[("HOME", "/home/u")]), account),
1137                Some(PathBuf::from("/home/u"))
1138            );
1139            assert_eq!(home_from(&env(&[("HOME", "")]), account), None);
1140            assert_eq!(
1141                home_from(&env(&[]), account),
1142                Some(PathBuf::from("/var/home/account"))
1143            );
1144            assert_eq!(home_from(&env(&[]), || Some(PathBuf::new())), None);
1145        }
1146        {
1147            let defaults = ["/usr/local/share", "/usr/share"];
1148            let expected_defaults: Vec<PathBuf> = defaults.iter().map(PathBuf::from).collect();
1149            assert_eq!(search_path(None, &defaults), expected_defaults);
1150            assert_eq!(
1151                search_path(Some(OsStr::new("")), &defaults),
1152                expected_defaults
1153            );
1154            assert_eq!(
1155                search_path(Some(OsStr::new("relative:also/relative")), &defaults),
1156                expected_defaults
1157            );
1158            assert_eq!(
1159                search_path(
1160                    Some(OsStr::new("/opt/share::relative:/usr/share")),
1161                    &defaults
1162                ),
1163                vec![PathBuf::from("/opt/share"), PathBuf::from("/usr/share")]
1164            );
1165        }
1166    }
1167
1168    #[test]
1169    fn app_and_user_dir_names_follow_the_spec_without_a_home() {
1170        {
1171            assert_eq!(Base::Config.resolve(&env(&[]), || None), None);
1172            #[cfg(unix)]
1173            assert_eq!(
1174                Base::Config.resolve(&env(&[("XDG_CONFIG_HOME", "/cfg")]), || None),
1175                Some(PathBuf::from("/cfg"))
1176            );
1177        }
1178        {
1179            assert_eq!(UserDir::Download.env_var(), "XDG_DOWNLOAD_DIR");
1180            assert_eq!(UserDir::PublicShare.env_var(), "XDG_PUBLICSHARE_DIR");
1181            assert_eq!(UserDir::Download.conventional_name(), "Downloads");
1182        }
1183        {
1184            let app = AppDirs::new("tilo-example");
1185            for (joined, base) in [
1186                (app.data(), data_dir()),
1187                (app.config(), config_dir()),
1188                (app.state(), state_dir()),
1189                (app.cache(), cache_dir()),
1190                (app.runtime(), runtime_dir()),
1191            ] {
1192                assert_eq!(joined, base.map(|base| base.join("tilo-example")));
1193            }
1194        }
1195    }
1196
1197    #[cfg(unix)]
1198    const USER_DIRS: &[u8] = b"# This file is written by xdg-user-dirs-update\n\
1199XDG_DESKTOP_DIR=\"$HOME/Schreibtisch\"\n\
1200XDG_DOWNLOAD_DIR=\"$HOME/Downloads\"\n\
1201  XDG_DOCUMENTS_DIR = \"$HOME/Dokumente\"  \n\
1202XDG_MUSIC_DIR=\"/srv/music\"\n\
1203XDG_PICTURES_DIR=\"$HOME/\"\n\
1204XDG_VIDEOS_DIR=$HOME/Videos\n\
1205XDG_TEMPLATES_DIR=\"relative/templates\"\n\
1206XDG_PUBLICSHARE_DIR=\"$HOME/My \\\"Public\\\" \\$hare\"\n";
1207
1208    #[cfg(unix)]
1209    #[test]
1210    fn user_dirs_files_resolve_below_home_and_yield_to_variables() {
1211        {
1212            let home = std::path::Path::new("/home/u");
1213            let resolve = |dir: UserDir| dir.resolve_from(None, Some(USER_DIRS), home);
1214            assert_eq!(
1215                resolve(UserDir::Desktop),
1216                Some(PathBuf::from("/home/u/Schreibtisch"))
1217            );
1218            assert_eq!(
1219                resolve(UserDir::Download),
1220                Some(PathBuf::from("/home/u/Downloads"))
1221            );
1222            assert_eq!(
1223                resolve(UserDir::Documents),
1224                Some(PathBuf::from("/home/u/Dokumente")),
1225                "blanks around the key and value are not part of either"
1226            );
1227            assert_eq!(resolve(UserDir::Music), Some(PathBuf::from("/srv/music")));
1228            assert_eq!(
1229                resolve(UserDir::PublicShare),
1230                Some(PathBuf::from("/home/u/My \"Public\" $hare")),
1231                "double-quote escapes are undone"
1232            );
1233        }
1234        {
1235            let home = std::path::Path::new("/home/u");
1236            for dir in [UserDir::Pictures, UserDir::Videos, UserDir::Templates] {
1237                assert_eq!(
1238                    dir.resolve_from(None, Some(USER_DIRS), home),
1239                    None,
1240                    "{dir:?}"
1241                );
1242            }
1243            assert_eq!(UserDir::Desktop.resolve_from(None, None, home), None);
1244            assert_eq!(UserDir::Desktop.resolve_from(None, Some(b""), home), None);
1245        }
1246        {
1247            let home = std::path::Path::new("/home/u");
1248            assert_eq!(
1249                UserDir::Download.resolve_from(Some(OsStr::new("/data/dl")), Some(USER_DIRS), home),
1250                Some(PathBuf::from("/data/dl"))
1251            );
1252            for ignored in ["", "relative/dl"] {
1253                assert_eq!(
1254                    UserDir::Download.resolve_from(
1255                        Some(OsStr::new(ignored)),
1256                        Some(USER_DIRS),
1257                        home
1258                    ),
1259                    Some(PathBuf::from("/home/u/Downloads")),
1260                    "{ignored:?}"
1261                );
1262            }
1263        }
1264    }
1265
1266    #[cfg(unix)]
1267    #[test]
1268    fn the_last_matching_line_wins() {
1269        let home = std::path::Path::new("/home/u");
1270        let file = b"XDG_DESKTOP_DIR=\"$HOME/One\"\nXDG_DESKTOP_DIR=\"$HOME/Two\"\n";
1271        assert_eq!(
1272            UserDir::Desktop.resolve_from(None, Some(file), home),
1273            Some(PathBuf::from("/home/u/Two"))
1274        );
1275    }
1276
1277    #[cfg(unix)]
1278    #[test]
1279    fn macos_keeps_data_config_and_state_in_application_support() {
1280        let tmpdir = [("TMPDIR", "/var/folders/ab/xyz/T/")];
1281        let var = env(&tmpdir);
1282        for (base, expected) in [
1283            (Base::Data, "/Users/u/Library/Application Support"),
1284            (Base::Config, "/Users/u/Library/Application Support"),
1285            (Base::State, "/Users/u/Library/Application Support"),
1286            (Base::Cache, "/Users/u/Library/Caches"),
1287            (Base::Runtime, "/var/folders/ab/xyz/T/"),
1288        ] {
1289            assert_eq!(
1290                macos::base(base, &var, home_is("/Users/u")),
1291                Some(PathBuf::from(expected)),
1292                "{base:?}"
1293            );
1294        }
1295    }
1296
1297    #[cfg(unix)]
1298    #[test]
1299    fn macos_runtime_needs_an_absolute_tmpdir_and_ignores_xdg() {
1300        for value in ["", "tmp", "./T"] {
1301            let vars = [("TMPDIR", value), ("XDG_RUNTIME_DIR", "/run/user/501")];
1302            assert_eq!(
1303                macos::base(Base::Runtime, &env(&vars), home_is("/Users/u")),
1304                None,
1305                "{value:?}"
1306            );
1307        }
1308        assert_eq!(
1309            macos::base(Base::Data, &env(&[("XDG_DATA_HOME", "/data")]), || None),
1310            None,
1311            "without a home only the runtime directory can resolve"
1312        );
1313    }
1314
1315    #[cfg(unix)]
1316    #[test]
1317    fn macos_user_dirs_are_the_english_folders_below_home() {
1318        let home = std::path::Path::new("/Users/u");
1319        assert_eq!(macos::user_dir(UserDir::Videos, home), home.join("Movies"));
1320        assert_eq!(
1321            macos::user_dir(UserDir::Download, home),
1322            home.join("Downloads")
1323        );
1324        assert_eq!(
1325            macos::user_dir(UserDir::Documents, home),
1326            home.join("Documents")
1327        );
1328    }
1329
1330    #[test]
1331    fn a_workspace_tree_is_one_component_under_the_files_root() {
1332        let files = std::path::Path::new("/var/workspace");
1333        let id = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
1334        assert_eq!(
1335            workspace_tree(files, id),
1336            Some(files.join(".workspaces").join(id))
1337        );
1338        for bad in [
1339            "",
1340            ".",
1341            "..",
1342            "a/b",
1343            "../x",
1344            "a.b",
1345            "a\0b",
1346            &"x".repeat(129),
1347        ] {
1348            assert_eq!(workspace_tree(files, bad), None, "{bad:?}");
1349        }
1350    }
1351}