tilo-paths 0.5.0

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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
//! Where per-user data, configuration, state, cache and runtime files live.
//!
//! [`AppPaths::for_app`] gives an app its data, config, cache, state and runtime
//! locations, the user's folders, the workspace and the font catalog, on every
//! target; the functions here are the same base directories for code without an app.

use std::ffi::OsString;
use std::path::PathBuf;

mod app;
mod caps;
pub mod desktop_service;
mod location;
pub mod login;
pub mod machine;
pub mod session;

pub use app::{AppPaths, DEFAULT_PROFILE, default_profile, set_default_profile};
pub use caps::{Availability, Feature, Unsupported, availability, available};
pub use location::{InvalidVPath, Location, VPath, VirtualRoot};
pub use machine::Reach;

/// Where a Tilo Linux session mounts the collaborative workspace, and the
/// root every member's documents name workspace files under, whatever
/// this device mounts. [`AppPaths::workspace_root`] says whether (and where)
/// this process has one mounted.
pub const WORKSPACE_MOUNT: &str = "/var/workspace";

/// The file a Tilo Linux session writes the people and devices it certifies
/// to: what an app showing who a file is shared with names them from.
pub const TRUSTED_IDENTITIES: &str = "/run/tilo/identity-projection/trusted-identities.json";

/// The runtime publishers this device accepts, one hex Ed25519 key per line, `#` comments: the
/// list the system ships beside the code that reads it. A Linux image ships it in `/etc/tilo`; on
/// a Mac it is in the resources of the Tilo.app whose executable is running, sealed by the app's
/// signature as that executable is. An executable outside an app bundle reads the image's path,
/// which a Mac does not have, so it trusts no runtime.
#[must_use]
pub fn runtime_publishers() -> PathBuf {
    const FILE: &str = "runtime-bundle-trusted-publishers.txt";
    #[cfg(target_os = "macos")]
    if let Some(contents) = std::env::current_exe()
        .and_then(std::fs::canonicalize)
        .ok()
        .and_then(|exe| Some(exe.parent()?.parent()?.to_path_buf()))
        .filter(|contents| contents.join("Info.plist").is_file())
    {
        return contents.join("Resources").join(FILE);
    }
    PathBuf::from("/etc/tilo").join(FILE)
}

/// The directory, at the root of the device's files, that holds one tree per
/// workspace: `<files>/.workspaces/<workspace id>`. The device's files are
/// one namespace (`fs` serves one per device); a workspace's own files are
/// the tree under its id, so its access checks (`FsPath` grants, which scope
/// by path prefix) cover each tree as they cover any folder.
pub const WORKSPACE_TREES_DIR: &str = ".workspaces";

/// The tree of the workspace `id`'s own files under the device's files at
/// `files`: [`WORKSPACE_TREES_DIR`]`/<id>`. `None` for an id that is not one
/// path component of `[A-Za-z0-9_-]`, 1 to 128 bytes, so no id names a
/// directory outside its own tree.
#[must_use]
pub fn workspace_tree(files: &std::path::Path, id: &str) -> Option<PathBuf> {
    is_workspace_tree_id(id).then(|| files.join(WORKSPACE_TREES_DIR).join(id))
}

#[must_use]
pub fn is_workspace_tree_id(id: &str) -> bool {
    (1..=128).contains(&id.len())
        && id
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}

#[must_use]
pub fn workspace_root() -> Option<PathBuf> {
    let location = AppPaths::for_app("workspace").workspace_root().ok()?;
    location
        .native_path()
        .ok()
        .map(std::path::Path::to_path_buf)
}

#[must_use]
pub fn language_packs_dir() -> Option<PathBuf> {
    xdg::data_home().map(|data| data.join("tilo").join("language-packs"))
}

/// The language a locale names, as a language pack is named: its language
/// subtag, lower case (`de` of `de`, `de-DE`, `de_DE.UTF-8@euro`). One pack
/// holds a language's catalogues whatever region, encoding or modifier a
/// locale adds, so a choice, the pack's directory and its package id meet at
/// this one name. Empty when no language is named.
///
/// This is the one rule for "which language is this tag": every reader of a
/// language tag — the packs, the toolkits, history, desktop entries — asks
/// here, so a language picked anywhere matches everywhere.
#[must_use]
pub fn language_of(tag: &str) -> String {
    tag.trim()
        .split(['-', '_', '.', '@'])
        .next()
        .unwrap_or_default()
        .to_ascii_lowercase()
}

/// The BCP 47 tag a locale names: the POSIX `de_DE.UTF-8@euro`, the
/// `LANGUAGE` list `de_AT:en_US` and the BCP 47 `de-DE` all name `de-DE`.
/// The encoding and the modifier name no language, a list's first entry is
/// the language, and a tag spells the `_` a POSIX locale uses as `-`.
#[must_use]
pub fn locale_tag(locale: &str) -> String {
    locale
        .split(':')
        .next()
        .unwrap_or_default()
        .split(['.', '@'])
        .next()
        .unwrap_or_default()
        .trim()
        .replace('_', "-")
}

/// Whether `tag` names a language: `C`, `POSIX`, `C.UTF-8` and an empty
/// value name none, so their text is read untranslated.
#[must_use]
pub fn names_language(tag: &str) -> bool {
    !matches!(language_of(tag).as_str(), "" | "c" | "posix")
}

/// The position in `candidates` (language tags, in the order the caller
/// prefers them) of the one a reader of `locale` reads best: their own tag
/// (`de-DE` for `de_DE.UTF-8`), else another region of their language
/// (`de-DE` for `de-AT`). `None` when neither is there or `locale` names no
/// language. This is the one rule for which tag a reader gets, so every
/// catalogue, name and window picks the same one.
#[must_use]
pub fn matching<'a>(
    locale: &str,
    mut candidates: impl Iterator<Item = &'a str> + Clone,
) -> Option<usize> {
    if !names_language(locale) {
        return None;
    }
    let tag = locale_tag(locale);
    let language = language_of(locale);
    let mut exact = candidates.clone();
    exact
        .position(|candidate| locale_tag(candidate).eq_ignore_ascii_case(&tag))
        .or_else(|| candidates.position(|candidate| language_of(candidate) == language))
}

/// The user's home directory: `$HOME` when set and non-empty, the account
/// database's entry when `$HOME` is unset (on Unix), and `None` for an empty
/// `$HOME` — an empty value names no directory, and resolving relative to the
/// working directory would scatter state wherever the process started. On
/// Windows it is the profile known folder, never an environment variable.
#[must_use]
pub fn home() -> Option<PathBuf> {
    #[cfg(windows)]
    {
        platform::home()
    }
    #[cfg(not(windows))]
    {
        home_from(&|name| var(name), std::env::home_dir)
    }
}

#[cfg(not(windows))]
fn home_from(
    var: &dyn Fn(&str) -> Option<OsString>,
    account_home: impl FnOnce() -> Option<PathBuf>,
) -> Option<PathBuf> {
    #[cfg(unix)]
    match var("HOME") {
        Some(home) if home.is_empty() => None,
        Some(home) => Some(PathBuf::from(home)),
        None => account_home().filter(|home| !home.as_os_str().is_empty()),
    }
    #[cfg(not(unix))]
    {
        let _ = var;
        account_home().filter(|home| !home.as_os_str().is_empty())
    }
}

/// `$name` as a directory, following the XDG rule for every base-directory
/// variable: honoured only when set, non-empty and absolute.
#[must_use]
pub fn env_dir(name: &str) -> Option<PathBuf> {
    absolute(var(name))
}

thread_local! {
    static PROFILE_ROOT: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
}

/// Keeps a thread's per-user folders below one root until it is dropped:
/// see [`scope_profile`].
#[must_use = "the scope ends when the guard is dropped"]
pub struct ProfileScope {
    earlier: Option<PathBuf>,
}

impl Drop for ProfileScope {
    fn drop(&mut self) {
        PROFILE_ROOT.with(|root| *root.borrow_mut() = self.earlier.take());
    }
}

/// From now until the guard drops, this thread's home is `root`: [`home`],
/// the per-user base folders, [`env_dir`] of the XDG variables and
/// [`AppPaths::for_app`] all resolve below it, whatever the process
/// environment says, and no workspace is mounted. A host that runs a
/// member (an agent) on its own thread gives it a profile apart from
/// the host user's this way. Threads the scoped thread starts do not
/// inherit it.
pub fn scope_profile(root: impl Into<PathBuf>) -> ProfileScope {
    let earlier = PROFILE_ROOT.with(|scoped| scoped.borrow_mut().replace(root.into()));
    ProfileScope { earlier }
}

pub fn unscoped<R>(work: impl FnOnce() -> R) -> R {
    let _scope = ProfileScope {
        earlier: PROFILE_ROOT.with(|root| root.borrow_mut().take()),
    };
    work()
}

#[must_use]
pub fn scoped_profile() -> Option<PathBuf> {
    PROFILE_ROOT.with(|root| root.borrow().clone())
}

fn var(name: &str) -> Option<OsString> {
    let Some(root) = scoped_profile() else {
        return std::env::var_os(name);
    };
    let below = match name {
        "HOME" => "",
        "XDG_DATA_HOME" => ".local/share",
        "XDG_CONFIG_HOME" => ".config",
        "XDG_STATE_HOME" => ".local/state",
        "XDG_CACHE_HOME" => ".cache",
        "XDG_RUNTIME_DIR" => "run",
        "TMPDIR" => "tmp",
        name if name.starts_with("TILO_WORKSPACE") => return None,
        name if name.starts_with("XDG_") && name.ends_with("_DIR") => return None,
        _ => return std::env::var_os(name),
    };
    Some(root.join(below).into_os_string())
}

fn absolute(value: Option<OsString>) -> Option<PathBuf> {
    // An empty path is not absolute, so this also rejects empty values.
    value.map(PathBuf::from).filter(|path| path.is_absolute())
}

pub mod xdg {
    use std::ffi::{OsStr, OsString};
    use std::path::PathBuf;

    use super::{absolute, home};

    #[must_use]
    pub fn data_home() -> Option<PathBuf> {
        Base::Data.resolve(&env, home)
    }

    #[must_use]
    pub fn config_home() -> Option<PathBuf> {
        Base::Config.resolve(&env, home)
    }

    #[must_use]
    pub fn state_home() -> Option<PathBuf> {
        Base::State.resolve(&env, home)
    }

    #[must_use]
    pub fn cache_home() -> Option<PathBuf> {
        Base::Cache.resolve(&env, home)
    }

    /// `$XDG_RUNTIME_DIR`. The spec defines no fallback: a substitute would
    /// lack its guarantees (owner-only, removed at logout), so `None` makes
    /// callers decide what to do without one.
    #[must_use]
    pub fn runtime_dir() -> Option<PathBuf> {
        Base::Runtime.resolve(&env, home)
    }

    /// [`runtime_dir`], else where the platform keeps it without the
    /// variable: `/run/user/<euid>` as systemd-logind creates it, the per-user
    /// `$TMPDIR` on macOS, the per-user `%TEMP%` on Windows. For callers that
    /// must name a per-user socket or file even in a session started without
    /// `$XDG_RUNTIME_DIR`.
    #[cfg(any(unix, windows))]
    #[must_use]
    pub fn runtime_dir_or_default() -> PathBuf {
        runtime_dir().unwrap_or_else(|| {
            #[cfg(any(target_os = "macos", windows))]
            {
                std::env::temp_dir()
            }
            #[cfg(all(unix, not(target_os = "macos")))]
            {
                PathBuf::from(format!("/run/user/{}", rustix::process::geteuid().as_raw()))
            }
        })
    }

    /// Where this login's Tilo services bind their sockets: one directory in
    /// the runtime directory, so a socket found here belongs to this user and
    /// is gone when their login ends.
    #[cfg(any(unix, windows))]
    #[must_use]
    pub fn services_dir() -> PathBuf {
        runtime_dir_or_default().join("tilo/services")
    }

    #[cfg(any(unix, windows))]
    #[must_use]
    pub fn service_socket(name: &str) -> PathBuf {
        services_dir().join(format!("{name}.sock"))
    }

    /// `$XDG_DATA_DIRS` in preference order, else `/usr/local/share` and
    /// `/usr/share`. Relative and empty entries are ignored, as the spec
    /// requires.
    #[must_use]
    pub fn data_dirs() -> Vec<PathBuf> {
        search_path(
            env("XDG_DATA_DIRS").as_deref(),
            &["/usr/local/share", "/usr/share"],
        )
    }

    /// `$XDG_CONFIG_DIRS` in preference order, else `/etc/xdg`. Relative and
    /// empty entries are ignored, as the spec requires.
    #[must_use]
    pub fn config_dirs() -> Vec<PathBuf> {
        search_path(env("XDG_CONFIG_DIRS").as_deref(), &["/etc/xdg"])
    }

    fn env(name: &str) -> Option<OsString> {
        super::var(name)
    }

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

    impl Base {
        #[must_use]
        pub const fn env_var(self) -> &'static str {
            match self {
                Self::Data => "XDG_DATA_HOME",
                Self::Config => "XDG_CONFIG_HOME",
                Self::State => "XDG_STATE_HOME",
                Self::Cache => "XDG_CACHE_HOME",
                Self::Runtime => "XDG_RUNTIME_DIR",
            }
        }

        const fn home_default(self) -> Option<&'static str> {
            match self {
                Self::Data => Some(".local/share"),
                Self::Config => Some(".config"),
                Self::State => Some(".local/state"),
                Self::Cache => Some(".cache"),
                Self::Runtime => None,
            }
        }

        /// Resolve from explicit values of the variable and `$HOME` instead of
        /// the process environment — for callers that take them as parameters
        /// so tests need not mutate the environment. The variable counts only
        /// when non-empty and absolute; an empty `home` counts as unset.
        #[must_use]
        pub fn resolve_from(self, value: Option<&OsStr>, home: Option<&OsStr>) -> Option<PathBuf> {
            self.resolve(&|_| value.map(OsStr::to_os_string), || {
                home.filter(|home| !home.is_empty()).map(PathBuf::from)
            })
        }

        pub(crate) fn resolve(
            self,
            var: &dyn Fn(&str) -> Option<OsString>,
            home: impl FnOnce() -> Option<PathBuf>,
        ) -> Option<PathBuf> {
            absolute(var(self.env_var())).or_else(|| {
                let default = self.home_default()?;
                Some(home()?.join(default))
            })
        }
    }

    pub(crate) fn search_path(value: Option<&OsStr>, default: &[&str]) -> Vec<PathBuf> {
        let listed: Vec<PathBuf> = value
            .map(|value| {
                std::env::split_paths(value)
                    .filter(|path| path.is_absolute())
                    .collect()
            })
            .unwrap_or_default();
        // An unset, empty or entirely invalid list means the defaults.
        if listed.is_empty() {
            default.iter().map(PathBuf::from).collect()
        } else {
            listed
        }
    }
}

/// The platform's per-user data directory: [`xdg::data_home`] on Linux and
/// other Unix, `~/Library/Application Support` on macOS, `%APPDATA%` on
/// Windows.
#[must_use]
pub fn data_dir() -> Option<PathBuf> {
    platform::data()
}

/// The platform's per-user local (non-roaming) data directory:
/// [`xdg::data_home`] on Linux and other Unix, `~/Library/Application Support`
/// on macOS, `%LOCALAPPDATA%` on Windows.
#[must_use]
pub fn data_local_dir() -> Option<PathBuf> {
    platform::data_local()
}

/// The platform's per-user configuration directory: [`xdg::config_home`] on
/// Linux and other Unix, `~/Library/Application Support` on macOS,
/// `%APPDATA%` on Windows.
#[must_use]
pub fn config_dir() -> Option<PathBuf> {
    platform::config()
}

/// The platform's per-user state directory: [`xdg::state_home`] on Linux and
/// other Unix, `~/Library/Application Support` on macOS (which keeps state
/// beside data); Windows defines none.
#[must_use]
pub fn state_dir() -> Option<PathBuf> {
    platform::state()
}

/// The per-user Tilo profile root: `$XDG_CONFIG_HOME/tilo`, else
/// `$HOME/.config/tilo` on Linux and other Unix, the platform's configuration
/// directory elsewhere.
#[must_use]
pub fn profile_root() -> Option<PathBuf> {
    Some(xdg::config_home()?.join("tilo"))
}

/// The platform's per-user cache directory: [`xdg::cache_home`] on Linux and
/// other Unix, `~/Library/Caches` on macOS, `%LOCALAPPDATA%` on Windows.
#[must_use]
pub fn cache_dir() -> Option<PathBuf> {
    platform::cache()
}

/// The per-login runtime directory: [`xdg::runtime_dir`] on Linux and other
/// Unix, the per-user `$TMPDIR` on macOS when it is absolute; Windows defines
/// none.
#[must_use]
pub fn runtime_dir() -> Option<PathBuf> {
    platform::runtime()
}

/// The system's shared temporary directory (`$TMPDIR` or `/tmp`,
/// `%TEMP%`), and `None` where there is no native file system (the web),
/// where `std::env::temp_dir` panics instead. For scratch files that must
/// have a native path; an app's own scratch space is [`AppPaths::runtime`].
#[must_use]
pub fn temp_dir() -> Option<PathBuf> {
    (available(Feature::NativePaths)).then(std::env::temp_dir)
}

/// A temporary directory kept in memory, where the platform has one
/// (`/dev/shm` on Linux): for scratch data that is synced like a person's
/// but deleted moments later (a test's profile), whose syncs then cost
/// nothing instead of waiting on a shared disk. `None` elsewhere.
#[must_use]
pub fn memory_temp_dir() -> Option<PathBuf> {
    if !cfg!(target_os = "linux") {
        return None;
    }
    Some(PathBuf::from("/dev/shm")).filter(|directory| directory.is_dir())
}

/// Directories the system and the user install fonts into, most general
/// first, whether or not they exist: the system font trees on Linux and
/// other Unix (not the user's own), `/System/Library/Fonts`, `/Library/Fonts` and
/// `~/Library/Fonts` on macOS, the Windows font folder, and none on the web.
/// For code that reads font files itself (a document renderer's fallback
/// fonts, a confined helper's read grant).
#[must_use]
pub fn system_font_dirs() -> Vec<PathBuf> {
    platform::font_dirs()
}

#[cfg(all(unix, not(target_os = "macos")))]
mod platform {
    use std::path::PathBuf;

    use super::{UserDir, home, xdg};

    pub fn data() -> Option<PathBuf> {
        xdg::data_home()
    }
    pub fn data_local() -> Option<PathBuf> {
        xdg::data_home()
    }
    pub fn config() -> Option<PathBuf> {
        xdg::config_home()
    }
    pub fn state() -> Option<PathBuf> {
        xdg::state_home()
    }
    pub fn cache() -> Option<PathBuf> {
        xdg::cache_home()
    }
    pub fn runtime() -> Option<PathBuf> {
        xdg::runtime_dir()
    }
    pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
        dir.resolve_for_home(&home()?)
    }
    pub fn font_dirs() -> Vec<PathBuf> {
        [
            "/usr/share/fonts",
            "/usr/local/share/fonts",
            "/usr/share/X11/fonts/Type1",
            "/usr/share/X11/fonts/TTF",
        ]
        .into_iter()
        .map(PathBuf::from)
        .collect()
    }
}

#[cfg(target_os = "macos")]
mod platform {
    use std::path::PathBuf;

    use super::xdg::Base;
    use super::{UserDir, home, macos};

    fn base(base: Base) -> Option<PathBuf> {
        macos::base(base, &|name| crate::var(name), home)
    }

    pub fn data() -> Option<PathBuf> {
        base(Base::Data)
    }
    pub fn data_local() -> Option<PathBuf> {
        data()
    }
    pub fn config() -> Option<PathBuf> {
        base(Base::Config)
    }
    pub fn state() -> Option<PathBuf> {
        base(Base::State)
    }
    pub fn cache() -> Option<PathBuf> {
        base(Base::Cache)
    }
    pub fn runtime() -> Option<PathBuf> {
        base(Base::Runtime)
    }
    pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
        Some(macos::user_dir(dir, &home()?))
    }
    pub fn font_dirs() -> Vec<PathBuf> {
        let mut dirs = vec![
            PathBuf::from("/System/Library/Fonts"),
            PathBuf::from("/Library/Fonts"),
        ];
        dirs.extend(home().map(|home| home.join("Library/Fonts")));
        dirs
    }
}

/// The macOS per-user locations as functions of the environment and home
/// directory, so the Linux test run checks them too.
#[cfg(any(target_os = "macos", all(test, unix)))]
mod macos {
    use std::ffi::OsString;
    use std::path::{Path, PathBuf};

    use super::xdg::Base;
    use super::{UserDir, absolute};

    /// Data, configuration and state share `~/Library/Application Support`,
    /// which is where macOS keeps an app's durable files; caches go to
    /// `~/Library/Caches`. The runtime directory is `$TMPDIR`, the per-user,
    /// owner-only directory launchd assigns below `/var/folders` and the
    /// system cleans up. It counts only when absolute: the shared `/tmp`
    /// lacks those guarantees, so there is no fallback.
    pub(crate) fn base(
        base: Base,
        var: &dyn Fn(&str) -> Option<OsString>,
        home: impl FnOnce() -> Option<PathBuf>,
    ) -> Option<PathBuf> {
        match base {
            Base::Data | Base::Config | Base::State => {
                Some(home()?.join("Library/Application Support"))
            }
            Base::Cache => Some(home()?.join("Library/Caches")),
            Base::Runtime => absolute(var("TMPDIR")),
        }
    }

    pub(crate) fn user_dir(dir: UserDir, home: &Path) -> PathBuf {
        home.join(match dir {
            UserDir::Videos => "Movies",
            other => other.conventional_name(),
        })
    }
}

#[cfg(windows)]
mod platform {
    use std::ffi::OsString;
    use std::os::windows::ffi::OsStringExt;
    use std::path::PathBuf;

    use windows_sys::Win32::System::Com::CoTaskMemFree;
    use windows_sys::Win32::UI::Shell::{
        FOLDERID_Desktop, FOLDERID_Documents, FOLDERID_Downloads, FOLDERID_LocalAppData,
        FOLDERID_Music, FOLDERID_Pictures, FOLDERID_Profile, FOLDERID_Public,
        FOLDERID_RoamingAppData, FOLDERID_Templates, FOLDERID_Videos, SHGetKnownFolderPath,
    };
    use windows_sys::core::{GUID, PWSTR};

    use super::UserDir;

    fn known_folder(id: &GUID) -> Option<PathBuf> {
        let mut raw: PWSTR = std::ptr::null_mut();
        // SAFETY: `id` is a valid GUID reference, a null token selects the
        // current user, and `raw` is a valid out-pointer the call fills with
        // a CoTaskMem-allocated, NUL-terminated wide string (or leaves null).
        let status = unsafe { SHGetKnownFolderPath(id, 0, std::ptr::null_mut(), &raw mut raw) };
        let path = (status == 0 && !raw.is_null()).then(|| {
            let mut len = 0_usize;
            // SAFETY: on success `raw` points to a NUL-terminated wide string;
            // every offset read here is at or before its terminator.
            while unsafe { *raw.add(len) } != 0 {
                len = len.saturating_add(1);
            }
            // SAFETY: the `len` units before the terminator were just read.
            let wide = unsafe { std::slice::from_raw_parts(raw, len) };
            PathBuf::from(OsString::from_wide(wide))
        });
        // SAFETY: the buffer is owned by us after the call, whether or not it
        // succeeded; freeing null is a no-op.
        unsafe { CoTaskMemFree(raw.cast()) };
        path.filter(|path| !path.as_os_str().is_empty())
    }

    pub fn home() -> Option<PathBuf> {
        known_folder(&FOLDERID_Profile)
    }
    pub fn data() -> Option<PathBuf> {
        known_folder(&FOLDERID_RoamingAppData)
    }
    pub fn data_local() -> Option<PathBuf> {
        known_folder(&FOLDERID_LocalAppData)
    }
    pub fn config() -> Option<PathBuf> {
        data()
    }
    pub fn state() -> Option<PathBuf> {
        None
    }
    pub fn cache() -> Option<PathBuf> {
        data_local()
    }
    pub fn runtime() -> Option<PathBuf> {
        None
    }
    pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
        known_folder(match dir {
            UserDir::Desktop => &FOLDERID_Desktop,
            UserDir::Documents => &FOLDERID_Documents,
            UserDir::Download => &FOLDERID_Downloads,
            UserDir::Music => &FOLDERID_Music,
            UserDir::Pictures => &FOLDERID_Pictures,
            UserDir::Videos => &FOLDERID_Videos,
            UserDir::Templates => &FOLDERID_Templates,
            UserDir::PublicShare => &FOLDERID_Public,
        })
    }
    pub fn font_dirs() -> Vec<PathBuf> {
        super::env_dir("WINDIR")
            .map(|windows| windows.join("Fonts"))
            .into_iter()
            .collect()
    }
}

#[cfg(not(any(unix, windows)))]
mod platform {
    use std::path::PathBuf;

    use super::{UserDir, env_dir, home};

    pub fn data() -> Option<PathBuf> {
        env_dir("APPDATA")
    }
    pub fn data_local() -> Option<PathBuf> {
        env_dir("LOCALAPPDATA")
    }
    pub fn config() -> Option<PathBuf> {
        data()
    }
    pub fn state() -> Option<PathBuf> {
        None
    }
    pub fn cache() -> Option<PathBuf> {
        env_dir("LOCALAPPDATA")
    }
    pub fn runtime() -> Option<PathBuf> {
        None
    }
    pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
        Some(home()?.join(dir.conventional_name()))
    }
    pub fn font_dirs() -> Vec<PathBuf> {
        Vec::new()
    }
}

/// One of the user's well-known content directories (Documents, Downloads, …).
///
/// On Linux and other Unix these follow `xdg-user-dirs`: `$XDG_<NAME>_DIR` when
/// set, non-empty and absolute, else the entry in
/// `$XDG_CONFIG_HOME/user-dirs.dirs`, which is where a localized desktop
/// records `~/Dokumente` instead of `~/Documents`. An entry pointing at `$HOME`
/// itself means the directory is disabled and resolves to `None`, as does a
/// missing entry. macOS and Windows use their conventional folders below the
/// home directory.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum UserDir {
    Desktop,
    Documents,
    Download,
    Music,
    Pictures,
    Videos,
    Templates,
    PublicShare,
}

impl UserDir {
    #[must_use]
    pub const fn env_var(self) -> &'static str {
        match self {
            Self::Desktop => "XDG_DESKTOP_DIR",
            Self::Documents => "XDG_DOCUMENTS_DIR",
            Self::Download => "XDG_DOWNLOAD_DIR",
            Self::Music => "XDG_MUSIC_DIR",
            Self::Pictures => "XDG_PICTURES_DIR",
            Self::Videos => "XDG_VIDEOS_DIR",
            Self::Templates => "XDG_TEMPLATES_DIR",
            Self::PublicShare => "XDG_PUBLICSHARE_DIR",
        }
    }

    /// The folder name the platform conventionally uses below the home
    /// directory (English, not localized). macOS and Windows resolve to it;
    /// on XDG platforms it is only a hint for callers that need a default.
    #[must_use]
    pub const fn conventional_name(self) -> &'static str {
        match self {
            Self::Desktop => "Desktop",
            Self::Documents => "Documents",
            Self::Download => "Downloads",
            Self::Music => "Music",
            Self::Pictures => "Pictures",
            #[cfg(target_os = "macos")]
            Self::Videos => "Movies",
            #[cfg(not(target_os = "macos"))]
            Self::Videos => "Videos",
            Self::Templates => "Templates",
            Self::PublicShare => "Public",
        }
    }

    #[must_use]
    pub fn resolve(self) -> Option<PathBuf> {
        platform::user_dir(self)
    }

    /// The directory the environment alone names: `$XDG_<NAME>_DIR` when set,
    /// non-empty and absolute. Reads no `user-dirs.dirs`, so a caller that
    /// must not read files (an app's startup) can still honour the variable.
    #[must_use]
    pub fn from_environment(self) -> Option<PathBuf> {
        absolute(var(self.env_var()))
    }

    #[must_use]
    pub fn resolve_for_home(self, home: &std::path::Path) -> Option<PathBuf> {
        let config_home = xdg::Base::Config
            .resolve_from(var("XDG_CONFIG_HOME").as_deref(), Some(home.as_os_str()))?;
        let file = std::fs::read(config_home.join("user-dirs.dirs")).ok();
        self.resolve_from(var(self.env_var()).as_deref(), file.as_deref(), home)
    }

    /// Resolve from an explicit variable value and `user-dirs.dirs` contents
    /// instead of the process environment and file system. The variable counts
    /// only when non-empty and absolute.
    #[must_use]
    pub fn resolve_from(
        self,
        value: Option<&std::ffi::OsStr>,
        user_dirs: Option<&[u8]>,
        home: &std::path::Path,
    ) -> Option<PathBuf> {
        absolute(value.map(std::ffi::OsStr::to_os_string))
            .or_else(|| user_dirs_entry(user_dirs?, self.env_var(), home))
    }
}

/// The value of `key` in a `user-dirs.dirs` file.
///
/// The file is a shell fragment, but `xdg-user-dirs-update` writes only
/// `KEY="$HOME/relative"` or `KEY="/absolute"`, so exactly those two forms are
/// accepted; a value of `"$HOME/"` disables the directory. The last matching
/// line wins, as it would when the file is sourced.
fn user_dirs_entry(contents: &[u8], key: &str, home: &std::path::Path) -> Option<PathBuf> {
    let mut found = None;
    for line in contents.split(|&byte| byte == b'\n') {
        let Some(separator) = line.iter().position(|&byte| byte == b'=') else {
            continue;
        };
        let (name, value) = line.split_at(separator);
        if trim_blank(name) != key.as_bytes() {
            continue;
        }
        let value = trim_blank(value.get(1..).unwrap_or_default());
        let Some(value) = value
            .strip_prefix(b"\"")
            .and_then(|value| value.strip_suffix(b"\""))
        else {
            continue;
        };
        found = if value == b"$HOME/" || value == b"$HOME" {
            None
        } else if let Some(relative) = value.strip_prefix(b"$HOME/") {
            Some(home.join(path_from_bytes(shell_unescape(relative))))
        } else if value.starts_with(b"/") {
            Some(path_from_bytes(shell_unescape(value)))
        } else {
            continue;
        };
    }
    found
}

fn trim_blank(bytes: &[u8]) -> &[u8] {
    let blank = |byte: &u8| *byte == b' ' || *byte == b'\t' || *byte == b'\r';
    let start = bytes
        .iter()
        .position(|byte| !blank(byte))
        .unwrap_or(bytes.len());
    let end = bytes
        .iter()
        .rposition(|byte| !blank(byte))
        .map_or(start, |last| last.saturating_add(1));
    bytes.get(start..end).unwrap_or_default()
}

/// Undo POSIX double-quote escaping: a backslash quotes only `$`, `` ` ``,
/// `"`, `\` and a newline, and is kept literally before anything else.
fn shell_unescape(escaped: &[u8]) -> Vec<u8> {
    let mut unescaped = Vec::with_capacity(escaped.len());
    let mut bytes = escaped.iter().copied().peekable();
    while let Some(byte) = bytes.next() {
        if byte == b'\\'
            && let Some(&next) = bytes.peek()
            && matches!(next, b'$' | b'`' | b'"' | b'\\' | b'\n')
        {
            unescaped.push(next);
            bytes.next();
        } else {
            unescaped.push(byte);
        }
    }
    unescaped
}

#[cfg(unix)]
fn path_from_bytes(bytes: Vec<u8>) -> PathBuf {
    use std::os::unix::ffi::OsStringExt;
    PathBuf::from(OsString::from_vec(bytes))
}

#[cfg(not(unix))]
fn path_from_bytes(bytes: Vec<u8>) -> PathBuf {
    match String::from_utf8(bytes) {
        Ok(text) => PathBuf::from(text),
        Err(error) => PathBuf::from(String::from_utf8_lossy(error.as_bytes()).into_owned()),
    }
}

#[must_use]
pub fn desktop_dir() -> Option<PathBuf> {
    UserDir::Desktop.resolve()
}

#[must_use]
pub fn document_dir() -> Option<PathBuf> {
    UserDir::Documents.resolve()
}

#[must_use]
pub fn download_dir() -> Option<PathBuf> {
    UserDir::Download.resolve()
}

#[must_use]
pub fn audio_dir() -> Option<PathBuf> {
    UserDir::Music.resolve()
}

#[must_use]
pub fn picture_dir() -> Option<PathBuf> {
    UserDir::Pictures.resolve()
}

#[must_use]
pub fn video_dir() -> Option<PathBuf> {
    UserDir::Videos.resolve()
}

/// One app's subdirectories of the per-user base directories, e.g.
/// `AppDirs::new("tilo-chat").data()` is `~/.local/share/tilo-chat` on Linux.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AppDirs<'a> {
    name: &'a str,
}

impl<'a> AppDirs<'a> {
    #[must_use]
    pub const fn new(name: &'a str) -> Self {
        Self { name }
    }

    #[must_use]
    pub fn data(&self) -> Option<PathBuf> {
        Some(data_dir()?.join(self.name))
    }

    #[must_use]
    pub fn config(&self) -> Option<PathBuf> {
        Some(config_dir()?.join(self.name))
    }

    #[must_use]
    pub fn state(&self) -> Option<PathBuf> {
        Some(state_dir()?.join(self.name))
    }

    #[must_use]
    pub fn cache(&self) -> Option<PathBuf> {
        Some(cache_dir()?.join(self.name))
    }

    #[must_use]
    pub fn runtime(&self) -> Option<PathBuf> {
        Some(runtime_dir()?.join(self.name))
    }
}

#[cfg(test)]
mod tests {
    use super::xdg::Base;
    #[cfg(unix)]
    use super::xdg::search_path;
    use super::*;
    #[cfg(unix)]
    use std::ffi::OsStr;

    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))
        }
    }

    #[cfg(unix)]
    fn home_is(path: &str) -> impl FnOnce() -> Option<PathBuf> + '_ {
        move || Some(PathBuf::from(path))
    }

    #[test]
    fn a_locale_names_one_language_however_it_is_spelled() {
        for (locale, language, tag, named) in [
            ("de", "de", "de", true),
            ("de-DE", "de", "de-DE", true),
            ("de_DE", "de", "de-DE", true),
            ("de_DE.UTF-8", "de", "de-DE", true),
            ("de_DE.UTF-8@euro", "de", "de-DE", true),
            ("de.UTF-8", "de", "de", true),
            (" de-DE ", "de", "de-DE", true),
            ("DE-de", "de", "DE-de", true),
            ("de_AT:en_US", "de", "de-AT", true),
            ("en-US", "en", "en-US", true),
            ("es-419", "es", "es-419", true),
            ("zh-Hant-TW", "zh", "zh-Hant-TW", true),
            ("C", "c", "C", false),
            ("C.UTF-8", "c", "C", false),
            ("POSIX", "posix", "POSIX", false),
            ("", "", "", false),
        ] {
            assert_eq!(language_of(locale), language, "{locale:?}");
            assert_eq!(locale_tag(locale), tag, "{locale:?}");
            assert_eq!(names_language(locale), named, "{locale:?}");
        }
    }

    #[test]
    fn a_reader_is_served_by_its_own_tag_or_another_region_of_its_language() {
        for (locale, candidates, want) in [
            ("de-DE", &["en-US", "de-DE"][..], Some(1)),
            ("de_DE.UTF-8", &["en-US", "de-DE"], Some(1)),
            ("de-AT", &["en-US", "de-DE"], Some(1)),
            ("de", &["de-DE", "de"], Some(1)),
            ("en-US", &["de-DE", "en-US"], Some(1)),
            ("fr-FR", &["de-DE", "en-US"], None),
            ("fr-FR", &[], None),
            ("C", &["de-DE"], None),
            ("", &["de-DE"], None),
        ] {
            assert_eq!(
                matching(locale, candidates.iter().copied()),
                want,
                "{locale:?}"
            );
        }
    }

    #[cfg(unix)]
    #[test]
    #[allow(
        clippy::too_many_lines,
        reason = "each phase keeps one former test's body verbatim"
    )]
    fn base_directories_follow_absolute_variables_or_home_defaults() {
        {
            let vars = [
                ("XDG_DATA_HOME", "/data"),
                ("XDG_CONFIG_HOME", "/config"),
                ("XDG_STATE_HOME", "/state"),
                ("XDG_CACHE_HOME", "/cache"),
                ("XDG_RUNTIME_DIR", "/run/user/1000"),
            ];
            let var = env(&vars);
            for (base, expected) in [
                (Base::Data, "/data"),
                (Base::Config, "/config"),
                (Base::State, "/state"),
                (Base::Cache, "/cache"),
                (Base::Runtime, "/run/user/1000"),
            ] {
                assert_eq!(
                    base.resolve(&var, home_is("/home/u")),
                    Some(PathBuf::from(expected))
                );
            }
        }
        {
            let var = env(&[]);
            for (base, expected) in [
                (Base::Data, Some("/home/u/.local/share")),
                (Base::Config, Some("/home/u/.config")),
                (Base::State, Some("/home/u/.local/state")),
                (Base::Cache, Some("/home/u/.cache")),
                (Base::Runtime, None),
            ] {
                assert_eq!(
                    base.resolve(&var, home_is("/home/u")),
                    expected.map(PathBuf::from),
                    "{base:?}"
                );
            }
        }
        {
            for value in ["relative/data", "", "./data", "~/data"] {
                let vars = [("XDG_DATA_HOME", value), ("XDG_RUNTIME_DIR", value)];
                let var = env(&vars);
                assert_eq!(
                    Base::Data.resolve(&var, home_is("/home/u")),
                    Some(PathBuf::from("/home/u/.local/share")),
                    "{value:?}"
                );
                assert_eq!(
                    Base::Runtime.resolve(&var, home_is("/home/u")),
                    None,
                    "{value:?}"
                );
            }
        }
        {
            let home = Some(OsStr::new("/home/u"));
            assert_eq!(
                Base::State.resolve_from(Some(OsStr::new("/state")), home),
                Some(PathBuf::from("/state"))
            );
            for invalid in [None, Some(OsStr::new("")), Some(OsStr::new("rel"))] {
                assert_eq!(
                    Base::State.resolve_from(invalid, home),
                    Some(PathBuf::from("/home/u/.local/state"))
                );
            }
            assert_eq!(Base::State.resolve_from(None, Some(OsStr::new(""))), None);
            assert_eq!(Base::Runtime.resolve_from(None, home), None);
            assert_eq!(Base::Config.env_var(), "XDG_CONFIG_HOME");
        }
        {
            let account = || Some(PathBuf::from("/var/home/account"));
            assert_eq!(
                home_from(&env(&[("HOME", "/home/u")]), account),
                Some(PathBuf::from("/home/u"))
            );
            assert_eq!(home_from(&env(&[("HOME", "")]), account), None);
            assert_eq!(
                home_from(&env(&[]), account),
                Some(PathBuf::from("/var/home/account"))
            );
            assert_eq!(home_from(&env(&[]), || Some(PathBuf::new())), None);
        }
        {
            let defaults = ["/usr/local/share", "/usr/share"];
            let expected_defaults: Vec<PathBuf> = defaults.iter().map(PathBuf::from).collect();
            assert_eq!(search_path(None, &defaults), expected_defaults);
            assert_eq!(
                search_path(Some(OsStr::new("")), &defaults),
                expected_defaults
            );
            assert_eq!(
                search_path(Some(OsStr::new("relative:also/relative")), &defaults),
                expected_defaults
            );
            assert_eq!(
                search_path(
                    Some(OsStr::new("/opt/share::relative:/usr/share")),
                    &defaults
                ),
                vec![PathBuf::from("/opt/share"), PathBuf::from("/usr/share")]
            );
        }
    }

    #[test]
    fn app_and_user_dir_names_follow_the_spec_without_a_home() {
        {
            assert_eq!(Base::Config.resolve(&env(&[]), || None), None);
            #[cfg(unix)]
            assert_eq!(
                Base::Config.resolve(&env(&[("XDG_CONFIG_HOME", "/cfg")]), || None),
                Some(PathBuf::from("/cfg"))
            );
        }
        {
            assert_eq!(UserDir::Download.env_var(), "XDG_DOWNLOAD_DIR");
            assert_eq!(UserDir::PublicShare.env_var(), "XDG_PUBLICSHARE_DIR");
            assert_eq!(UserDir::Download.conventional_name(), "Downloads");
        }
        {
            let app = AppDirs::new("tilo-example");
            for (joined, base) in [
                (app.data(), data_dir()),
                (app.config(), config_dir()),
                (app.state(), state_dir()),
                (app.cache(), cache_dir()),
                (app.runtime(), runtime_dir()),
            ] {
                assert_eq!(joined, base.map(|base| base.join("tilo-example")));
            }
        }
    }

    #[cfg(unix)]
    const USER_DIRS: &[u8] = b"# This file is written by xdg-user-dirs-update\n\
XDG_DESKTOP_DIR=\"$HOME/Schreibtisch\"\n\
XDG_DOWNLOAD_DIR=\"$HOME/Downloads\"\n\
  XDG_DOCUMENTS_DIR = \"$HOME/Dokumente\"  \n\
XDG_MUSIC_DIR=\"/srv/music\"\n\
XDG_PICTURES_DIR=\"$HOME/\"\n\
XDG_VIDEOS_DIR=$HOME/Videos\n\
XDG_TEMPLATES_DIR=\"relative/templates\"\n\
XDG_PUBLICSHARE_DIR=\"$HOME/My \\\"Public\\\" \\$hare\"\n";

    #[cfg(unix)]
    #[test]
    fn user_dirs_files_resolve_below_home_and_yield_to_variables() {
        {
            let home = std::path::Path::new("/home/u");
            let resolve = |dir: UserDir| dir.resolve_from(None, Some(USER_DIRS), home);
            assert_eq!(
                resolve(UserDir::Desktop),
                Some(PathBuf::from("/home/u/Schreibtisch"))
            );
            assert_eq!(
                resolve(UserDir::Download),
                Some(PathBuf::from("/home/u/Downloads"))
            );
            assert_eq!(
                resolve(UserDir::Documents),
                Some(PathBuf::from("/home/u/Dokumente")),
                "blanks around the key and value are not part of either"
            );
            assert_eq!(resolve(UserDir::Music), Some(PathBuf::from("/srv/music")));
            assert_eq!(
                resolve(UserDir::PublicShare),
                Some(PathBuf::from("/home/u/My \"Public\" $hare")),
                "double-quote escapes are undone"
            );
        }
        {
            let home = std::path::Path::new("/home/u");
            for dir in [UserDir::Pictures, UserDir::Videos, UserDir::Templates] {
                assert_eq!(
                    dir.resolve_from(None, Some(USER_DIRS), home),
                    None,
                    "{dir:?}"
                );
            }
            assert_eq!(UserDir::Desktop.resolve_from(None, None, home), None);
            assert_eq!(UserDir::Desktop.resolve_from(None, Some(b""), home), None);
        }
        {
            let home = std::path::Path::new("/home/u");
            assert_eq!(
                UserDir::Download.resolve_from(Some(OsStr::new("/data/dl")), Some(USER_DIRS), home),
                Some(PathBuf::from("/data/dl"))
            );
            for ignored in ["", "relative/dl"] {
                assert_eq!(
                    UserDir::Download.resolve_from(
                        Some(OsStr::new(ignored)),
                        Some(USER_DIRS),
                        home
                    ),
                    Some(PathBuf::from("/home/u/Downloads")),
                    "{ignored:?}"
                );
            }
        }
    }

    #[cfg(unix)]
    #[test]
    fn the_last_matching_line_wins() {
        let home = std::path::Path::new("/home/u");
        let file = b"XDG_DESKTOP_DIR=\"$HOME/One\"\nXDG_DESKTOP_DIR=\"$HOME/Two\"\n";
        assert_eq!(
            UserDir::Desktop.resolve_from(None, Some(file), home),
            Some(PathBuf::from("/home/u/Two"))
        );
    }

    #[cfg(unix)]
    #[test]
    fn macos_keeps_data_config_and_state_in_application_support() {
        let tmpdir = [("TMPDIR", "/var/folders/ab/xyz/T/")];
        let var = env(&tmpdir);
        for (base, expected) in [
            (Base::Data, "/Users/u/Library/Application Support"),
            (Base::Config, "/Users/u/Library/Application Support"),
            (Base::State, "/Users/u/Library/Application Support"),
            (Base::Cache, "/Users/u/Library/Caches"),
            (Base::Runtime, "/var/folders/ab/xyz/T/"),
        ] {
            assert_eq!(
                macos::base(base, &var, home_is("/Users/u")),
                Some(PathBuf::from(expected)),
                "{base:?}"
            );
        }
    }

    #[cfg(unix)]
    #[test]
    fn macos_runtime_needs_an_absolute_tmpdir_and_ignores_xdg() {
        for value in ["", "tmp", "./T"] {
            let vars = [("TMPDIR", value), ("XDG_RUNTIME_DIR", "/run/user/501")];
            assert_eq!(
                macos::base(Base::Runtime, &env(&vars), home_is("/Users/u")),
                None,
                "{value:?}"
            );
        }
        assert_eq!(
            macos::base(Base::Data, &env(&[("XDG_DATA_HOME", "/data")]), || None),
            None,
            "without a home only the runtime directory can resolve"
        );
    }

    #[cfg(unix)]
    #[test]
    fn macos_user_dirs_are_the_english_folders_below_home() {
        let home = std::path::Path::new("/Users/u");
        assert_eq!(macos::user_dir(UserDir::Videos, home), home.join("Movies"));
        assert_eq!(
            macos::user_dir(UserDir::Download, home),
            home.join("Downloads")
        );
        assert_eq!(
            macos::user_dir(UserDir::Documents, home),
            home.join("Documents")
        );
    }

    #[test]
    fn a_workspace_tree_is_one_component_under_the_files_root() {
        let files = std::path::Path::new("/var/workspace");
        let id = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
        assert_eq!(
            workspace_tree(files, id),
            Some(files.join(".workspaces").join(id))
        );
        for bad in [
            "",
            ".",
            "..",
            "a/b",
            "../x",
            "a.b",
            "a\0b",
            &"x".repeat(129),
        ] {
            assert_eq!(workspace_tree(files, bad), None, "{bad:?}");
        }
    }
}