1use std::ffi::OsString;
8use std::path::PathBuf;
9
10mod app;
11mod caps;
12pub mod desktop_service;
13mod location;
14pub mod login;
15pub mod session;
16
17pub use app::{AppPaths, DEFAULT_PROFILE, default_profile, set_default_profile};
18pub use caps::{Availability, Feature, Unsupported, availability, available};
19pub use location::{InvalidVPath, Location, VPath, VirtualRoot};
20
21pub const WORKSPACE_MOUNT: &str = "/var/workspace";
26
27pub const TRUSTED_IDENTITIES: &str = "/run/tilo/identity-projection/trusted-identities.json";
30
31#[must_use]
37pub fn runtime_publishers() -> PathBuf {
38 const FILE: &str = "runtime-bundle-trusted-publishers.txt";
39 #[cfg(target_os = "macos")]
40 if let Some(contents) = std::env::current_exe()
41 .and_then(std::fs::canonicalize)
42 .ok()
43 .and_then(|exe| Some(exe.parent()?.parent()?.to_path_buf()))
44 .filter(|contents| contents.join("Info.plist").is_file())
45 {
46 return contents.join("Resources").join(FILE);
47 }
48 PathBuf::from("/etc/tilo").join(FILE)
49}
50
51pub const WORKSPACE_TREES_DIR: &str = ".workspaces";
57
58#[must_use]
63pub fn workspace_tree(files: &std::path::Path, id: &str) -> Option<PathBuf> {
64 is_workspace_tree_id(id).then(|| files.join(WORKSPACE_TREES_DIR).join(id))
65}
66
67#[must_use]
68pub fn is_workspace_tree_id(id: &str) -> bool {
69 (1..=128).contains(&id.len())
70 && id
71 .bytes()
72 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
73}
74
75#[must_use]
76pub fn workspace_root() -> Option<PathBuf> {
77 let location = AppPaths::for_app("workspace").workspace_root().ok()?;
78 location
79 .native_path()
80 .ok()
81 .map(std::path::Path::to_path_buf)
82}
83
84#[must_use]
85pub fn language_packs_dir() -> Option<PathBuf> {
86 xdg::data_home().map(|data| data.join("tilo").join("language-packs"))
87}
88
89#[must_use]
99pub fn language_of(tag: &str) -> String {
100 tag.trim()
101 .split(['-', '_', '.', '@'])
102 .next()
103 .unwrap_or_default()
104 .to_ascii_lowercase()
105}
106
107#[must_use]
112pub fn locale_tag(locale: &str) -> String {
113 locale
114 .split(':')
115 .next()
116 .unwrap_or_default()
117 .split(['.', '@'])
118 .next()
119 .unwrap_or_default()
120 .trim()
121 .replace('_', "-")
122}
123
124#[must_use]
127pub fn names_language(tag: &str) -> bool {
128 !matches!(language_of(tag).as_str(), "" | "c" | "posix")
129}
130
131#[must_use]
138pub fn matching<'a>(
139 locale: &str,
140 mut candidates: impl Iterator<Item = &'a str> + Clone,
141) -> Option<usize> {
142 if !names_language(locale) {
143 return None;
144 }
145 let tag = locale_tag(locale);
146 let language = language_of(locale);
147 let mut exact = candidates.clone();
148 exact
149 .position(|candidate| locale_tag(candidate).eq_ignore_ascii_case(&tag))
150 .or_else(|| candidates.position(|candidate| language_of(candidate) == language))
151}
152
153#[must_use]
159pub fn home() -> Option<PathBuf> {
160 #[cfg(windows)]
161 {
162 platform::home()
163 }
164 #[cfg(not(windows))]
165 {
166 home_from(&|name| var(name), std::env::home_dir)
167 }
168}
169
170#[cfg(not(windows))]
171fn home_from(
172 var: &dyn Fn(&str) -> Option<OsString>,
173 account_home: impl FnOnce() -> Option<PathBuf>,
174) -> Option<PathBuf> {
175 #[cfg(unix)]
176 match var("HOME") {
177 Some(home) if home.is_empty() => None,
178 Some(home) => Some(PathBuf::from(home)),
179 None => account_home().filter(|home| !home.as_os_str().is_empty()),
180 }
181 #[cfg(not(unix))]
182 {
183 let _ = var;
184 account_home().filter(|home| !home.as_os_str().is_empty())
185 }
186}
187
188#[must_use]
191pub fn env_dir(name: &str) -> Option<PathBuf> {
192 absolute(var(name))
193}
194
195thread_local! {
196 static PROFILE_ROOT: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
197}
198
199#[must_use = "the scope ends when the guard is dropped"]
202pub struct ProfileScope {
203 earlier: Option<PathBuf>,
204}
205
206impl Drop for ProfileScope {
207 fn drop(&mut self) {
208 PROFILE_ROOT.with(|root| *root.borrow_mut() = self.earlier.take());
209 }
210}
211
212pub fn scope_profile(root: impl Into<PathBuf>) -> ProfileScope {
220 let earlier = PROFILE_ROOT.with(|scoped| scoped.borrow_mut().replace(root.into()));
221 ProfileScope { earlier }
222}
223
224pub fn unscoped<R>(work: impl FnOnce() -> R) -> R {
225 let _scope = ProfileScope {
226 earlier: PROFILE_ROOT.with(|root| root.borrow_mut().take()),
227 };
228 work()
229}
230
231#[must_use]
232pub fn scoped_profile() -> Option<PathBuf> {
233 PROFILE_ROOT.with(|root| root.borrow().clone())
234}
235
236#[must_use]
240pub fn var(name: &str) -> Option<OsString> {
241 let Some(root) = scoped_profile() else {
242 return std::env::var_os(name);
243 };
244 let below = match name {
245 "HOME" => "",
246 "XDG_DATA_HOME" => ".local/share",
247 "XDG_CONFIG_HOME" => ".config",
248 "XDG_STATE_HOME" => ".local/state",
249 "XDG_CACHE_HOME" => ".cache",
250 "XDG_RUNTIME_DIR" => "run",
251 "TMPDIR" => "tmp",
252 name if name.starts_with("TILO_WORKSPACE") => return None,
253 name if name.starts_with("XDG_") && name.ends_with("_DIR") => return None,
254 _ => return std::env::var_os(name),
255 };
256 Some(root.join(below).into_os_string())
257}
258
259fn absolute(value: Option<OsString>) -> Option<PathBuf> {
260 value.map(PathBuf::from).filter(|path| path.is_absolute())
262}
263
264pub mod xdg {
265 use std::ffi::{OsStr, OsString};
266 use std::path::PathBuf;
267
268 use super::{absolute, home};
269
270 #[must_use]
271 pub fn data_home() -> Option<PathBuf> {
272 Base::Data.resolve(&env, home)
273 }
274
275 #[must_use]
276 pub fn config_home() -> Option<PathBuf> {
277 Base::Config.resolve(&env, home)
278 }
279
280 #[must_use]
281 pub fn state_home() -> Option<PathBuf> {
282 Base::State.resolve(&env, home)
283 }
284
285 #[must_use]
286 pub fn cache_home() -> Option<PathBuf> {
287 Base::Cache.resolve(&env, home)
288 }
289
290 #[must_use]
294 pub fn runtime_dir() -> Option<PathBuf> {
295 Base::Runtime.resolve(&env, home)
296 }
297
298 #[cfg(any(unix, windows))]
304 #[must_use]
305 pub fn runtime_dir_or_default() -> PathBuf {
306 runtime_dir().unwrap_or_else(|| {
307 #[cfg(any(target_os = "macos", windows))]
308 {
309 std::env::temp_dir()
310 }
311 #[cfg(all(unix, not(target_os = "macos")))]
312 {
313 PathBuf::from(format!("/run/user/{}", rustix::process::geteuid().as_raw()))
314 }
315 })
316 }
317
318 #[cfg(any(unix, windows))]
322 #[must_use]
323 pub fn services_dir() -> PathBuf {
324 runtime_dir_or_default().join("tilo/services")
325 }
326
327 #[cfg(any(unix, windows))]
328 #[must_use]
329 pub fn service_socket(name: &str) -> PathBuf {
330 services_dir().join(format!("{name}.sock"))
331 }
332
333 #[must_use]
337 pub fn data_dirs() -> Vec<PathBuf> {
338 search_path(
339 env("XDG_DATA_DIRS").as_deref(),
340 &["/usr/local/share", "/usr/share"],
341 )
342 }
343
344 #[must_use]
347 pub fn config_dirs() -> Vec<PathBuf> {
348 search_path(env("XDG_CONFIG_DIRS").as_deref(), &["/etc/xdg"])
349 }
350
351 fn env(name: &str) -> Option<OsString> {
352 super::var(name)
353 }
354
355 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
356 pub enum Base {
357 Data,
358 Config,
359 State,
360 Cache,
361 Runtime,
362 }
363
364 impl Base {
365 #[must_use]
366 pub const fn env_var(self) -> &'static str {
367 match self {
368 Self::Data => "XDG_DATA_HOME",
369 Self::Config => "XDG_CONFIG_HOME",
370 Self::State => "XDG_STATE_HOME",
371 Self::Cache => "XDG_CACHE_HOME",
372 Self::Runtime => "XDG_RUNTIME_DIR",
373 }
374 }
375
376 const fn home_default(self) -> Option<&'static str> {
377 match self {
378 Self::Data => Some(".local/share"),
379 Self::Config => Some(".config"),
380 Self::State => Some(".local/state"),
381 Self::Cache => Some(".cache"),
382 Self::Runtime => None,
383 }
384 }
385
386 #[must_use]
391 pub fn resolve_from(self, value: Option<&OsStr>, home: Option<&OsStr>) -> Option<PathBuf> {
392 self.resolve(&|_| value.map(OsStr::to_os_string), || {
393 home.filter(|home| !home.is_empty()).map(PathBuf::from)
394 })
395 }
396
397 pub(crate) fn resolve(
398 self,
399 var: &dyn Fn(&str) -> Option<OsString>,
400 home: impl FnOnce() -> Option<PathBuf>,
401 ) -> Option<PathBuf> {
402 absolute(var(self.env_var())).or_else(|| {
403 let default = self.home_default()?;
404 Some(home()?.join(default))
405 })
406 }
407 }
408
409 pub(crate) fn search_path(value: Option<&OsStr>, default: &[&str]) -> Vec<PathBuf> {
410 let listed: Vec<PathBuf> = value
411 .map(|value| {
412 std::env::split_paths(value)
413 .filter(|path| path.is_absolute())
414 .collect()
415 })
416 .unwrap_or_default();
417 if listed.is_empty() {
419 default.iter().map(PathBuf::from).collect()
420 } else {
421 listed
422 }
423 }
424}
425
426#[must_use]
430pub fn data_dir() -> Option<PathBuf> {
431 platform::data()
432}
433
434#[must_use]
438pub fn data_local_dir() -> Option<PathBuf> {
439 platform::data_local()
440}
441
442pub const APPS_DATA_DIR_ENV: &str = "TILO_APPS_DATA_DIR";
445
446pub const COMPUTER_APPS_DIR: &str = "/var/lib/tilo/apps";
450
451#[must_use]
460pub fn device_data_dir() -> Option<PathBuf> {
461 absolute(var(APPS_DATA_DIR_ENV))
462 .or_else(|| {
463 let computer = PathBuf::from(COMPUTER_APPS_DIR);
464 computer.is_dir().then_some(computer)
465 })
466 .or_else(|| Some(xdg::data_home()?.join("tilo-apps")))
467}
468
469#[must_use]
473pub fn config_dir() -> Option<PathBuf> {
474 platform::config()
475}
476
477#[must_use]
482pub fn state_dir() -> Option<PathBuf> {
483 platform::state()
484}
485
486#[must_use]
490pub fn profile_root() -> Option<PathBuf> {
491 Some(xdg::config_home()?.join("tilo"))
492}
493
494#[must_use]
497pub fn cache_dir() -> Option<PathBuf> {
498 platform::cache()
499}
500
501#[must_use]
505pub fn runtime_dir() -> Option<PathBuf> {
506 platform::runtime()
507}
508
509#[must_use]
514pub fn temp_dir() -> Option<PathBuf> {
515 (available(Feature::NativePaths)).then(std::env::temp_dir)
516}
517
518#[must_use]
523pub fn memory_temp_dir() -> Option<PathBuf> {
524 if !cfg!(target_os = "linux") {
525 return None;
526 }
527 Some(PathBuf::from("/dev/shm")).filter(|directory| directory.is_dir())
528}
529
530#[must_use]
537pub fn system_font_dirs() -> Vec<PathBuf> {
538 platform::font_dirs()
539}
540
541#[cfg(all(unix, not(target_os = "macos")))]
542mod platform {
543 use std::path::PathBuf;
544
545 use super::{UserDir, home, xdg};
546
547 pub fn data() -> Option<PathBuf> {
548 xdg::data_home()
549 }
550 pub fn data_local() -> Option<PathBuf> {
551 xdg::data_home()
552 }
553 pub fn config() -> Option<PathBuf> {
554 xdg::config_home()
555 }
556 pub fn state() -> Option<PathBuf> {
557 xdg::state_home()
558 }
559 pub fn cache() -> Option<PathBuf> {
560 xdg::cache_home()
561 }
562 pub fn runtime() -> Option<PathBuf> {
563 xdg::runtime_dir()
564 }
565 pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
566 dir.resolve_for_home(&home()?)
567 }
568 pub fn font_dirs() -> Vec<PathBuf> {
569 [
570 "/usr/share/fonts",
571 "/usr/local/share/fonts",
572 "/usr/share/X11/fonts/Type1",
573 "/usr/share/X11/fonts/TTF",
574 ]
575 .into_iter()
576 .map(PathBuf::from)
577 .collect()
578 }
579}
580
581#[cfg(target_os = "macos")]
582mod platform {
583 use std::path::PathBuf;
584
585 use super::xdg::Base;
586 use super::{UserDir, home, macos};
587
588 fn base(base: Base) -> Option<PathBuf> {
589 macos::base(base, &|name| crate::var(name), home)
590 }
591
592 pub fn data() -> Option<PathBuf> {
593 base(Base::Data)
594 }
595 pub fn data_local() -> Option<PathBuf> {
596 data()
597 }
598 pub fn config() -> Option<PathBuf> {
599 base(Base::Config)
600 }
601 pub fn state() -> Option<PathBuf> {
602 base(Base::State)
603 }
604 pub fn cache() -> Option<PathBuf> {
605 base(Base::Cache)
606 }
607 pub fn runtime() -> Option<PathBuf> {
608 base(Base::Runtime)
609 }
610 pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
611 Some(macos::user_dir(dir, &home()?))
612 }
613 pub fn font_dirs() -> Vec<PathBuf> {
614 let mut dirs = vec![
615 PathBuf::from("/System/Library/Fonts"),
616 PathBuf::from("/Library/Fonts"),
617 ];
618 dirs.extend(home().map(|home| home.join("Library/Fonts")));
619 dirs
620 }
621}
622
623#[cfg(any(target_os = "macos", all(test, unix)))]
626mod macos {
627 use std::ffi::OsString;
628 use std::path::PathBuf;
629
630 use super::absolute;
631 use super::xdg::Base;
632
633 pub(crate) fn base(
640 base: Base,
641 var: &dyn Fn(&str) -> Option<OsString>,
642 home: impl FnOnce() -> Option<PathBuf>,
643 ) -> Option<PathBuf> {
644 match base {
645 Base::Data | Base::Config | Base::State => {
646 Some(home()?.join("Library/Application Support"))
647 }
648 Base::Cache => Some(home()?.join("Library/Caches")),
649 Base::Runtime => absolute(var("TMPDIR")),
650 }
651 }
652
653 #[cfg(target_os = "macos")]
654 pub(crate) fn user_dir(dir: super::UserDir, home: &std::path::Path) -> PathBuf {
655 home.join(match dir {
656 super::UserDir::Videos => "Movies",
657 other => other.conventional_name(),
658 })
659 }
660}
661
662#[cfg(windows)]
663mod platform {
664 use std::ffi::OsString;
665 use std::os::windows::ffi::OsStringExt;
666 use std::path::PathBuf;
667
668 use windows_sys::Win32::System::Com::CoTaskMemFree;
669 use windows_sys::Win32::UI::Shell::{
670 FOLDERID_Desktop, FOLDERID_Documents, FOLDERID_Downloads, FOLDERID_LocalAppData,
671 FOLDERID_Music, FOLDERID_Pictures, FOLDERID_Profile, FOLDERID_Public,
672 FOLDERID_RoamingAppData, FOLDERID_Templates, FOLDERID_Videos, SHGetKnownFolderPath,
673 };
674 use windows_sys::core::{GUID, PWSTR};
675
676 use super::UserDir;
677
678 fn known_folder(id: &GUID) -> Option<PathBuf> {
679 let mut raw: PWSTR = std::ptr::null_mut();
680 let status = unsafe { SHGetKnownFolderPath(id, 0, std::ptr::null_mut(), &raw mut raw) };
684 let path = (status == 0 && !raw.is_null()).then(|| {
685 let mut len = 0_usize;
686 while unsafe { *raw.add(len) } != 0 {
689 len = len.saturating_add(1);
690 }
691 let wide = unsafe { std::slice::from_raw_parts(raw, len) };
693 PathBuf::from(OsString::from_wide(wide))
694 });
695 unsafe { CoTaskMemFree(raw.cast()) };
698 path.filter(|path| !path.as_os_str().is_empty())
699 }
700
701 pub fn home() -> Option<PathBuf> {
702 known_folder(&FOLDERID_Profile)
703 }
704 pub fn data() -> Option<PathBuf> {
705 known_folder(&FOLDERID_RoamingAppData)
706 }
707 pub fn data_local() -> Option<PathBuf> {
708 known_folder(&FOLDERID_LocalAppData)
709 }
710 pub fn config() -> Option<PathBuf> {
711 data()
712 }
713 pub fn state() -> Option<PathBuf> {
714 data_local()
715 }
716 pub fn cache() -> Option<PathBuf> {
717 data_local()
718 }
719 pub fn runtime() -> Option<PathBuf> {
720 None
721 }
722 pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
723 known_folder(match dir {
724 UserDir::Desktop => &FOLDERID_Desktop,
725 UserDir::Documents => &FOLDERID_Documents,
726 UserDir::Download => &FOLDERID_Downloads,
727 UserDir::Music => &FOLDERID_Music,
728 UserDir::Pictures => &FOLDERID_Pictures,
729 UserDir::Videos => &FOLDERID_Videos,
730 UserDir::Templates => &FOLDERID_Templates,
731 UserDir::PublicShare => &FOLDERID_Public,
732 })
733 }
734 pub fn font_dirs() -> Vec<PathBuf> {
735 super::env_dir("WINDIR")
736 .map(|windows| windows.join("Fonts"))
737 .into_iter()
738 .collect()
739 }
740}
741
742#[cfg(not(any(unix, windows)))]
743mod platform {
744 use std::path::PathBuf;
745
746 use super::{UserDir, env_dir, home};
747
748 pub fn data() -> Option<PathBuf> {
749 env_dir("APPDATA")
750 }
751 pub fn data_local() -> Option<PathBuf> {
752 env_dir("LOCALAPPDATA")
753 }
754 pub fn config() -> Option<PathBuf> {
755 data()
756 }
757 pub fn state() -> Option<PathBuf> {
758 None
759 }
760 pub fn cache() -> Option<PathBuf> {
761 env_dir("LOCALAPPDATA")
762 }
763 pub fn runtime() -> Option<PathBuf> {
764 None
765 }
766 pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
767 Some(home()?.join(dir.conventional_name()))
768 }
769 pub fn font_dirs() -> Vec<PathBuf> {
770 Vec::new()
771 }
772}
773
774#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
784pub enum UserDir {
785 Desktop,
786 Documents,
787 Download,
788 Music,
789 Pictures,
790 Videos,
791 Templates,
792 PublicShare,
793}
794
795impl UserDir {
796 #[must_use]
797 pub const fn env_var(self) -> &'static str {
798 match self {
799 Self::Desktop => "XDG_DESKTOP_DIR",
800 Self::Documents => "XDG_DOCUMENTS_DIR",
801 Self::Download => "XDG_DOWNLOAD_DIR",
802 Self::Music => "XDG_MUSIC_DIR",
803 Self::Pictures => "XDG_PICTURES_DIR",
804 Self::Videos => "XDG_VIDEOS_DIR",
805 Self::Templates => "XDG_TEMPLATES_DIR",
806 Self::PublicShare => "XDG_PUBLICSHARE_DIR",
807 }
808 }
809
810 #[must_use]
814 pub const fn conventional_name(self) -> &'static str {
815 match self {
816 Self::Desktop => "Desktop",
817 Self::Documents => "Documents",
818 Self::Download => "Downloads",
819 Self::Music => "Music",
820 Self::Pictures => "Pictures",
821 #[cfg(target_os = "macos")]
822 Self::Videos => "Movies",
823 #[cfg(not(target_os = "macos"))]
824 Self::Videos => "Videos",
825 Self::Templates => "Templates",
826 Self::PublicShare => "Public",
827 }
828 }
829
830 #[must_use]
831 pub fn resolve(self) -> Option<PathBuf> {
832 platform::user_dir(self)
833 }
834
835 #[must_use]
839 pub fn from_environment(self) -> Option<PathBuf> {
840 absolute(var(self.env_var()))
841 }
842
843 #[must_use]
844 pub fn resolve_for_home(self, home: &std::path::Path) -> Option<PathBuf> {
845 let config_home = xdg::Base::Config
846 .resolve_from(var("XDG_CONFIG_HOME").as_deref(), Some(home.as_os_str()))?;
847 let file = std::fs::read(config_home.join("user-dirs.dirs")).ok();
848 self.resolve_from(var(self.env_var()).as_deref(), file.as_deref(), home)
849 }
850
851 #[must_use]
855 pub fn resolve_from(
856 self,
857 value: Option<&std::ffi::OsStr>,
858 user_dirs: Option<&[u8]>,
859 home: &std::path::Path,
860 ) -> Option<PathBuf> {
861 absolute(value.map(std::ffi::OsStr::to_os_string))
862 .or_else(|| user_dirs_entry(user_dirs?, self.env_var(), home))
863 }
864}
865
866fn user_dirs_entry(contents: &[u8], key: &str, home: &std::path::Path) -> Option<PathBuf> {
873 let mut found = None;
874 for line in contents.split(|&byte| byte == b'\n') {
875 let Some(separator) = line.iter().position(|&byte| byte == b'=') else {
876 continue;
877 };
878 let (name, value) = line.split_at(separator);
879 if trim_blank(name) != key.as_bytes() {
880 continue;
881 }
882 let value = trim_blank(value.get(1..).unwrap_or_default());
883 let Some(value) = value
884 .strip_prefix(b"\"")
885 .and_then(|value| value.strip_suffix(b"\""))
886 else {
887 continue;
888 };
889 found = if value == b"$HOME/" || value == b"$HOME" {
890 None
891 } else if let Some(relative) = value.strip_prefix(b"$HOME/") {
892 Some(home.join(path_from_bytes(shell_unescape(relative))))
893 } else if value.starts_with(b"/") {
894 Some(path_from_bytes(shell_unescape(value)))
895 } else {
896 continue;
897 };
898 }
899 found
900}
901
902fn trim_blank(bytes: &[u8]) -> &[u8] {
903 let blank = |byte: &u8| *byte == b' ' || *byte == b'\t' || *byte == b'\r';
904 let start = bytes
905 .iter()
906 .position(|byte| !blank(byte))
907 .unwrap_or(bytes.len());
908 let end = bytes
909 .iter()
910 .rposition(|byte| !blank(byte))
911 .map_or(start, |last| last.saturating_add(1));
912 bytes.get(start..end).unwrap_or_default()
913}
914
915fn shell_unescape(escaped: &[u8]) -> Vec<u8> {
918 let mut unescaped = Vec::with_capacity(escaped.len());
919 let mut bytes = escaped.iter().copied().peekable();
920 while let Some(byte) = bytes.next() {
921 if byte == b'\\'
922 && let Some(&next) = bytes.peek()
923 && matches!(next, b'$' | b'`' | b'"' | b'\\' | b'\n')
924 {
925 unescaped.push(next);
926 bytes.next();
927 } else {
928 unescaped.push(byte);
929 }
930 }
931 unescaped
932}
933
934#[cfg(unix)]
935fn path_from_bytes(bytes: Vec<u8>) -> PathBuf {
936 use std::os::unix::ffi::OsStringExt;
937 PathBuf::from(OsString::from_vec(bytes))
938}
939
940#[cfg(not(unix))]
941fn path_from_bytes(bytes: Vec<u8>) -> PathBuf {
942 match String::from_utf8(bytes) {
943 Ok(text) => PathBuf::from(text),
944 Err(error) => PathBuf::from(String::from_utf8_lossy(error.as_bytes()).into_owned()),
945 }
946}
947
948#[must_use]
949pub fn desktop_dir() -> Option<PathBuf> {
950 UserDir::Desktop.resolve()
951}
952
953#[must_use]
954pub fn document_dir() -> Option<PathBuf> {
955 UserDir::Documents.resolve()
956}
957
958#[must_use]
959pub fn download_dir() -> Option<PathBuf> {
960 UserDir::Download.resolve()
961}
962
963#[must_use]
964pub fn audio_dir() -> Option<PathBuf> {
965 UserDir::Music.resolve()
966}
967
968#[must_use]
969pub fn picture_dir() -> Option<PathBuf> {
970 UserDir::Pictures.resolve()
971}
972
973#[must_use]
974pub fn video_dir() -> Option<PathBuf> {
975 UserDir::Videos.resolve()
976}
977
978#[derive(Clone, Copy, Debug, PartialEq, Eq)]
981pub struct AppDirs<'a> {
982 name: &'a str,
983}
984
985impl<'a> AppDirs<'a> {
986 #[must_use]
987 pub const fn new(name: &'a str) -> Self {
988 Self { name }
989 }
990
991 #[must_use]
992 pub fn data(&self) -> Option<PathBuf> {
993 Some(data_dir()?.join(self.name))
994 }
995
996 #[must_use]
997 pub fn config(&self) -> Option<PathBuf> {
998 Some(config_dir()?.join(self.name))
999 }
1000
1001 #[must_use]
1002 pub fn state(&self) -> Option<PathBuf> {
1003 Some(state_dir()?.join(self.name))
1004 }
1005
1006 #[must_use]
1007 pub fn cache(&self) -> Option<PathBuf> {
1008 Some(cache_dir()?.join(self.name))
1009 }
1010
1011 #[must_use]
1012 pub fn runtime(&self) -> Option<PathBuf> {
1013 Some(runtime_dir()?.join(self.name))
1014 }
1015}
1016
1017#[cfg(test)]
1018mod tests {
1019 use super::xdg::Base;
1020 #[cfg(unix)]
1021 use super::xdg::search_path;
1022 use super::*;
1023 #[cfg(unix)]
1024 use std::ffi::OsStr;
1025
1026 fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
1027 move |name| {
1028 pairs
1029 .iter()
1030 .find(|(key, _)| *key == name)
1031 .map(|(_, value)| OsString::from(value))
1032 }
1033 }
1034
1035 #[cfg(unix)]
1036 fn home_is(path: &str) -> impl FnOnce() -> Option<PathBuf> + '_ {
1037 move || Some(PathBuf::from(path))
1038 }
1039
1040 #[test]
1041 fn a_locale_names_one_language_however_it_is_spelled() {
1042 for (locale, language, tag, named) in [
1043 ("de", "de", "de", true),
1044 ("de-DE", "de", "de-DE", true),
1045 ("de_DE", "de", "de-DE", true),
1046 ("de_DE.UTF-8", "de", "de-DE", true),
1047 ("de_DE.UTF-8@euro", "de", "de-DE", true),
1048 ("de.UTF-8", "de", "de", true),
1049 (" de-DE ", "de", "de-DE", true),
1050 ("DE-de", "de", "DE-de", true),
1051 ("de_AT:en_US", "de", "de-AT", true),
1052 ("en-US", "en", "en-US", true),
1053 ("es-419", "es", "es-419", true),
1054 ("zh-Hant-TW", "zh", "zh-Hant-TW", true),
1055 ("C", "c", "C", false),
1056 ("C.UTF-8", "c", "C", false),
1057 ("POSIX", "posix", "POSIX", false),
1058 ("", "", "", false),
1059 ] {
1060 assert_eq!(language_of(locale), language, "{locale:?}");
1061 assert_eq!(locale_tag(locale), tag, "{locale:?}");
1062 assert_eq!(names_language(locale), named, "{locale:?}");
1063 }
1064 }
1065
1066 #[test]
1067 fn a_reader_is_served_by_its_own_tag_or_another_region_of_its_language() {
1068 for (locale, candidates, want) in [
1069 ("de-DE", &["en-US", "de-DE"][..], Some(1)),
1070 ("de_DE.UTF-8", &["en-US", "de-DE"], Some(1)),
1071 ("de-AT", &["en-US", "de-DE"], Some(1)),
1072 ("de", &["de-DE", "de"], Some(1)),
1073 ("en-US", &["de-DE", "en-US"], Some(1)),
1074 ("fr-FR", &["de-DE", "en-US"], None),
1075 ("fr-FR", &[], None),
1076 ("C", &["de-DE"], None),
1077 ("", &["de-DE"], None),
1078 ] {
1079 assert_eq!(
1080 matching(locale, candidates.iter().copied()),
1081 want,
1082 "{locale:?}"
1083 );
1084 }
1085 }
1086
1087 #[cfg(unix)]
1088 #[test]
1089 #[allow(
1090 clippy::too_many_lines,
1091 reason = "each phase keeps one former test's body verbatim"
1092 )]
1093 fn base_directories_follow_absolute_variables_or_home_defaults() {
1094 {
1095 let vars = [
1096 ("XDG_DATA_HOME", "/data"),
1097 ("XDG_CONFIG_HOME", "/config"),
1098 ("XDG_STATE_HOME", "/state"),
1099 ("XDG_CACHE_HOME", "/cache"),
1100 ("XDG_RUNTIME_DIR", "/run/user/1000"),
1101 ];
1102 let var = env(&vars);
1103 for (base, expected) in [
1104 (Base::Data, "/data"),
1105 (Base::Config, "/config"),
1106 (Base::State, "/state"),
1107 (Base::Cache, "/cache"),
1108 (Base::Runtime, "/run/user/1000"),
1109 ] {
1110 assert_eq!(
1111 base.resolve(&var, home_is("/home/u")),
1112 Some(PathBuf::from(expected))
1113 );
1114 }
1115 }
1116 {
1117 let var = env(&[]);
1118 for (base, expected) in [
1119 (Base::Data, Some("/home/u/.local/share")),
1120 (Base::Config, Some("/home/u/.config")),
1121 (Base::State, Some("/home/u/.local/state")),
1122 (Base::Cache, Some("/home/u/.cache")),
1123 (Base::Runtime, None),
1124 ] {
1125 assert_eq!(
1126 base.resolve(&var, home_is("/home/u")),
1127 expected.map(PathBuf::from),
1128 "{base:?}"
1129 );
1130 }
1131 }
1132 {
1133 for value in ["relative/data", "", "./data", "~/data"] {
1134 let vars = [("XDG_DATA_HOME", value), ("XDG_RUNTIME_DIR", value)];
1135 let var = env(&vars);
1136 assert_eq!(
1137 Base::Data.resolve(&var, home_is("/home/u")),
1138 Some(PathBuf::from("/home/u/.local/share")),
1139 "{value:?}"
1140 );
1141 assert_eq!(
1142 Base::Runtime.resolve(&var, home_is("/home/u")),
1143 None,
1144 "{value:?}"
1145 );
1146 }
1147 }
1148 {
1149 let home = Some(OsStr::new("/home/u"));
1150 assert_eq!(
1151 Base::State.resolve_from(Some(OsStr::new("/state")), home),
1152 Some(PathBuf::from("/state"))
1153 );
1154 for invalid in [None, Some(OsStr::new("")), Some(OsStr::new("rel"))] {
1155 assert_eq!(
1156 Base::State.resolve_from(invalid, home),
1157 Some(PathBuf::from("/home/u/.local/state"))
1158 );
1159 }
1160 assert_eq!(Base::State.resolve_from(None, Some(OsStr::new(""))), None);
1161 assert_eq!(Base::Runtime.resolve_from(None, home), None);
1162 assert_eq!(Base::Config.env_var(), "XDG_CONFIG_HOME");
1163 }
1164 {
1165 let account = || Some(PathBuf::from("/var/home/account"));
1166 assert_eq!(
1167 home_from(&env(&[("HOME", "/home/u")]), account),
1168 Some(PathBuf::from("/home/u"))
1169 );
1170 assert_eq!(home_from(&env(&[("HOME", "")]), account), None);
1171 assert_eq!(
1172 home_from(&env(&[]), account),
1173 Some(PathBuf::from("/var/home/account"))
1174 );
1175 assert_eq!(home_from(&env(&[]), || Some(PathBuf::new())), None);
1176 }
1177 {
1178 let defaults = ["/usr/local/share", "/usr/share"];
1179 let expected_defaults: Vec<PathBuf> = defaults.iter().map(PathBuf::from).collect();
1180 assert_eq!(search_path(None, &defaults), expected_defaults);
1181 assert_eq!(
1182 search_path(Some(OsStr::new("")), &defaults),
1183 expected_defaults
1184 );
1185 assert_eq!(
1186 search_path(Some(OsStr::new("relative:also/relative")), &defaults),
1187 expected_defaults
1188 );
1189 assert_eq!(
1190 search_path(
1191 Some(OsStr::new("/opt/share::relative:/usr/share")),
1192 &defaults
1193 ),
1194 vec![PathBuf::from("/opt/share"), PathBuf::from("/usr/share")]
1195 );
1196 }
1197 }
1198
1199 #[test]
1200 fn app_and_user_dir_names_follow_the_spec_without_a_home() {
1201 {
1202 assert_eq!(Base::Config.resolve(&env(&[]), || None), None);
1203 #[cfg(unix)]
1204 assert_eq!(
1205 Base::Config.resolve(&env(&[("XDG_CONFIG_HOME", "/cfg")]), || None),
1206 Some(PathBuf::from("/cfg"))
1207 );
1208 }
1209 {
1210 assert_eq!(UserDir::Download.env_var(), "XDG_DOWNLOAD_DIR");
1211 assert_eq!(UserDir::PublicShare.env_var(), "XDG_PUBLICSHARE_DIR");
1212 assert_eq!(UserDir::Download.conventional_name(), "Downloads");
1213 }
1214 {
1215 let app = AppDirs::new("tilo-example");
1216 for (joined, base) in [
1217 (app.data(), data_dir()),
1218 (app.config(), config_dir()),
1219 (app.state(), state_dir()),
1220 (app.cache(), cache_dir()),
1221 (app.runtime(), runtime_dir()),
1222 ] {
1223 assert_eq!(joined, base.map(|base| base.join("tilo-example")));
1224 }
1225 }
1226 }
1227
1228 #[cfg(unix)]
1229 const USER_DIRS: &[u8] = b"# This file is written by xdg-user-dirs-update\n\
1230XDG_DESKTOP_DIR=\"$HOME/Schreibtisch\"\n\
1231XDG_DOWNLOAD_DIR=\"$HOME/Downloads\"\n\
1232 XDG_DOCUMENTS_DIR = \"$HOME/Dokumente\" \n\
1233XDG_MUSIC_DIR=\"/srv/music\"\n\
1234XDG_PICTURES_DIR=\"$HOME/\"\n\
1235XDG_VIDEOS_DIR=$HOME/Videos\n\
1236XDG_TEMPLATES_DIR=\"relative/templates\"\n\
1237XDG_PUBLICSHARE_DIR=\"$HOME/My \\\"Public\\\" \\$hare\"\n";
1238
1239 #[cfg(unix)]
1240 #[test]
1241 fn user_dirs_files_resolve_below_home_and_yield_to_variables() {
1242 {
1243 let home = std::path::Path::new("/home/u");
1244 let resolve = |dir: UserDir| dir.resolve_from(None, Some(USER_DIRS), home);
1245 assert_eq!(
1246 resolve(UserDir::Desktop),
1247 Some(PathBuf::from("/home/u/Schreibtisch"))
1248 );
1249 assert_eq!(
1250 resolve(UserDir::Download),
1251 Some(PathBuf::from("/home/u/Downloads"))
1252 );
1253 assert_eq!(
1254 resolve(UserDir::Documents),
1255 Some(PathBuf::from("/home/u/Dokumente")),
1256 "blanks around the key and value are not part of either"
1257 );
1258 assert_eq!(resolve(UserDir::Music), Some(PathBuf::from("/srv/music")));
1259 assert_eq!(
1260 resolve(UserDir::PublicShare),
1261 Some(PathBuf::from("/home/u/My \"Public\" $hare")),
1262 "double-quote escapes are undone"
1263 );
1264 }
1265 {
1266 let home = std::path::Path::new("/home/u");
1267 for dir in [UserDir::Pictures, UserDir::Videos, UserDir::Templates] {
1268 assert_eq!(
1269 dir.resolve_from(None, Some(USER_DIRS), home),
1270 None,
1271 "{dir:?}"
1272 );
1273 }
1274 assert_eq!(UserDir::Desktop.resolve_from(None, None, home), None);
1275 assert_eq!(UserDir::Desktop.resolve_from(None, Some(b""), home), None);
1276 }
1277 {
1278 let home = std::path::Path::new("/home/u");
1279 assert_eq!(
1280 UserDir::Download.resolve_from(Some(OsStr::new("/data/dl")), Some(USER_DIRS), home),
1281 Some(PathBuf::from("/data/dl"))
1282 );
1283 for ignored in ["", "relative/dl"] {
1284 assert_eq!(
1285 UserDir::Download.resolve_from(
1286 Some(OsStr::new(ignored)),
1287 Some(USER_DIRS),
1288 home
1289 ),
1290 Some(PathBuf::from("/home/u/Downloads")),
1291 "{ignored:?}"
1292 );
1293 }
1294 }
1295 }
1296
1297 #[cfg(unix)]
1298 #[test]
1299 fn the_last_matching_line_wins() {
1300 let home = std::path::Path::new("/home/u");
1301 let file = b"XDG_DESKTOP_DIR=\"$HOME/One\"\nXDG_DESKTOP_DIR=\"$HOME/Two\"\n";
1302 assert_eq!(
1303 UserDir::Desktop.resolve_from(None, Some(file), home),
1304 Some(PathBuf::from("/home/u/Two"))
1305 );
1306 }
1307
1308 #[cfg(unix)]
1309 #[test]
1310 fn macos_keeps_data_config_and_state_in_application_support() {
1311 let tmpdir = [("TMPDIR", "/var/folders/ab/xyz/T/")];
1312 let var = env(&tmpdir);
1313 for (base, expected) in [
1314 (Base::Data, "/Users/u/Library/Application Support"),
1315 (Base::Config, "/Users/u/Library/Application Support"),
1316 (Base::State, "/Users/u/Library/Application Support"),
1317 (Base::Cache, "/Users/u/Library/Caches"),
1318 (Base::Runtime, "/var/folders/ab/xyz/T/"),
1319 ] {
1320 assert_eq!(
1321 macos::base(base, &var, home_is("/Users/u")),
1322 Some(PathBuf::from(expected)),
1323 "{base:?}"
1324 );
1325 }
1326 }
1327
1328 #[cfg(unix)]
1329 #[test]
1330 fn macos_runtime_needs_an_absolute_tmpdir_and_ignores_xdg() {
1331 for value in ["", "tmp", "./T"] {
1332 let vars = [("TMPDIR", value), ("XDG_RUNTIME_DIR", "/run/user/501")];
1333 assert_eq!(
1334 macos::base(Base::Runtime, &env(&vars), home_is("/Users/u")),
1335 None,
1336 "{value:?}"
1337 );
1338 }
1339 assert_eq!(
1340 macos::base(Base::Data, &env(&[("XDG_DATA_HOME", "/data")]), || None),
1341 None,
1342 "without a home only the runtime directory can resolve"
1343 );
1344 }
1345
1346 #[test]
1347 fn a_workspace_tree_is_one_component_under_the_files_root() {
1348 let files = std::path::Path::new("/var/workspace");
1349 let id = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
1350 assert_eq!(
1351 workspace_tree(files, id),
1352 Some(files.join(".workspaces").join(id))
1353 );
1354 for bad in [
1355 "",
1356 ".",
1357 "..",
1358 "a/b",
1359 "../x",
1360 "a.b",
1361 "a\0b",
1362 &"x".repeat(129),
1363 ] {
1364 assert_eq!(workspace_tree(files, bad), None, "{bad:?}");
1365 }
1366 }
1367}