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
446#[must_use]
453pub fn device_data_dir() -> Option<PathBuf> {
454 absolute(var(APPS_DATA_DIR_ENV)).or_else(|| Some(xdg::data_home()?.join("tilo-apps")))
455}
456
457#[must_use]
461pub fn config_dir() -> Option<PathBuf> {
462 platform::config()
463}
464
465#[must_use]
470pub fn state_dir() -> Option<PathBuf> {
471 platform::state()
472}
473
474#[must_use]
478pub fn profile_root() -> Option<PathBuf> {
479 Some(xdg::config_home()?.join("tilo"))
480}
481
482#[must_use]
485pub fn cache_dir() -> Option<PathBuf> {
486 platform::cache()
487}
488
489#[must_use]
493pub fn runtime_dir() -> Option<PathBuf> {
494 platform::runtime()
495}
496
497#[must_use]
502pub fn temp_dir() -> Option<PathBuf> {
503 (available(Feature::NativePaths)).then(std::env::temp_dir)
504}
505
506#[must_use]
511pub fn memory_temp_dir() -> Option<PathBuf> {
512 if !cfg!(target_os = "linux") {
513 return None;
514 }
515 Some(PathBuf::from("/dev/shm")).filter(|directory| directory.is_dir())
516}
517
518#[must_use]
525pub fn system_font_dirs() -> Vec<PathBuf> {
526 platform::font_dirs()
527}
528
529#[cfg(all(unix, not(target_os = "macos")))]
530mod platform {
531 use std::path::PathBuf;
532
533 use super::{UserDir, home, xdg};
534
535 pub fn data() -> Option<PathBuf> {
536 xdg::data_home()
537 }
538 pub fn data_local() -> Option<PathBuf> {
539 xdg::data_home()
540 }
541 pub fn config() -> Option<PathBuf> {
542 xdg::config_home()
543 }
544 pub fn state() -> Option<PathBuf> {
545 xdg::state_home()
546 }
547 pub fn cache() -> Option<PathBuf> {
548 xdg::cache_home()
549 }
550 pub fn runtime() -> Option<PathBuf> {
551 xdg::runtime_dir()
552 }
553 pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
554 dir.resolve_for_home(&home()?)
555 }
556 pub fn font_dirs() -> Vec<PathBuf> {
557 [
558 "/usr/share/fonts",
559 "/usr/local/share/fonts",
560 "/usr/share/X11/fonts/Type1",
561 "/usr/share/X11/fonts/TTF",
562 ]
563 .into_iter()
564 .map(PathBuf::from)
565 .collect()
566 }
567}
568
569#[cfg(target_os = "macos")]
570mod platform {
571 use std::path::PathBuf;
572
573 use super::xdg::Base;
574 use super::{UserDir, home, macos};
575
576 fn base(base: Base) -> Option<PathBuf> {
577 macos::base(base, &|name| crate::var(name), home)
578 }
579
580 pub fn data() -> Option<PathBuf> {
581 base(Base::Data)
582 }
583 pub fn data_local() -> Option<PathBuf> {
584 data()
585 }
586 pub fn config() -> Option<PathBuf> {
587 base(Base::Config)
588 }
589 pub fn state() -> Option<PathBuf> {
590 base(Base::State)
591 }
592 pub fn cache() -> Option<PathBuf> {
593 base(Base::Cache)
594 }
595 pub fn runtime() -> Option<PathBuf> {
596 base(Base::Runtime)
597 }
598 pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
599 Some(macos::user_dir(dir, &home()?))
600 }
601 pub fn font_dirs() -> Vec<PathBuf> {
602 let mut dirs = vec![
603 PathBuf::from("/System/Library/Fonts"),
604 PathBuf::from("/Library/Fonts"),
605 ];
606 dirs.extend(home().map(|home| home.join("Library/Fonts")));
607 dirs
608 }
609}
610
611#[cfg(any(target_os = "macos", all(test, unix)))]
614mod macos {
615 use std::ffi::OsString;
616 use std::path::PathBuf;
617
618 use super::absolute;
619 use super::xdg::Base;
620
621 pub(crate) fn base(
628 base: Base,
629 var: &dyn Fn(&str) -> Option<OsString>,
630 home: impl FnOnce() -> Option<PathBuf>,
631 ) -> Option<PathBuf> {
632 match base {
633 Base::Data | Base::Config | Base::State => {
634 Some(home()?.join("Library/Application Support"))
635 }
636 Base::Cache => Some(home()?.join("Library/Caches")),
637 Base::Runtime => absolute(var("TMPDIR")),
638 }
639 }
640
641 #[cfg(target_os = "macos")]
642 pub(crate) fn user_dir(dir: super::UserDir, home: &std::path::Path) -> PathBuf {
643 home.join(match dir {
644 super::UserDir::Videos => "Movies",
645 other => other.conventional_name(),
646 })
647 }
648}
649
650#[cfg(windows)]
651mod platform {
652 use std::ffi::OsString;
653 use std::os::windows::ffi::OsStringExt;
654 use std::path::PathBuf;
655
656 use windows_sys::Win32::System::Com::CoTaskMemFree;
657 use windows_sys::Win32::UI::Shell::{
658 FOLDERID_Desktop, FOLDERID_Documents, FOLDERID_Downloads, FOLDERID_LocalAppData,
659 FOLDERID_Music, FOLDERID_Pictures, FOLDERID_Profile, FOLDERID_Public,
660 FOLDERID_RoamingAppData, FOLDERID_Templates, FOLDERID_Videos, SHGetKnownFolderPath,
661 };
662 use windows_sys::core::{GUID, PWSTR};
663
664 use super::UserDir;
665
666 fn known_folder(id: &GUID) -> Option<PathBuf> {
667 let mut raw: PWSTR = std::ptr::null_mut();
668 let status = unsafe { SHGetKnownFolderPath(id, 0, std::ptr::null_mut(), &raw mut raw) };
672 let path = (status == 0 && !raw.is_null()).then(|| {
673 let mut len = 0_usize;
674 while unsafe { *raw.add(len) } != 0 {
677 len = len.saturating_add(1);
678 }
679 let wide = unsafe { std::slice::from_raw_parts(raw, len) };
681 PathBuf::from(OsString::from_wide(wide))
682 });
683 unsafe { CoTaskMemFree(raw.cast()) };
686 path.filter(|path| !path.as_os_str().is_empty())
687 }
688
689 pub fn home() -> Option<PathBuf> {
690 known_folder(&FOLDERID_Profile)
691 }
692 pub fn data() -> Option<PathBuf> {
693 known_folder(&FOLDERID_RoamingAppData)
694 }
695 pub fn data_local() -> Option<PathBuf> {
696 known_folder(&FOLDERID_LocalAppData)
697 }
698 pub fn config() -> Option<PathBuf> {
699 data()
700 }
701 pub fn state() -> Option<PathBuf> {
702 data_local()
703 }
704 pub fn cache() -> Option<PathBuf> {
705 data_local()
706 }
707 pub fn runtime() -> Option<PathBuf> {
708 None
709 }
710 pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
711 known_folder(match dir {
712 UserDir::Desktop => &FOLDERID_Desktop,
713 UserDir::Documents => &FOLDERID_Documents,
714 UserDir::Download => &FOLDERID_Downloads,
715 UserDir::Music => &FOLDERID_Music,
716 UserDir::Pictures => &FOLDERID_Pictures,
717 UserDir::Videos => &FOLDERID_Videos,
718 UserDir::Templates => &FOLDERID_Templates,
719 UserDir::PublicShare => &FOLDERID_Public,
720 })
721 }
722 pub fn font_dirs() -> Vec<PathBuf> {
723 super::env_dir("WINDIR")
724 .map(|windows| windows.join("Fonts"))
725 .into_iter()
726 .collect()
727 }
728}
729
730#[cfg(not(any(unix, windows)))]
731mod platform {
732 use std::path::PathBuf;
733
734 use super::{UserDir, env_dir, home};
735
736 pub fn data() -> Option<PathBuf> {
737 env_dir("APPDATA")
738 }
739 pub fn data_local() -> Option<PathBuf> {
740 env_dir("LOCALAPPDATA")
741 }
742 pub fn config() -> Option<PathBuf> {
743 data()
744 }
745 pub fn state() -> Option<PathBuf> {
746 None
747 }
748 pub fn cache() -> Option<PathBuf> {
749 env_dir("LOCALAPPDATA")
750 }
751 pub fn runtime() -> Option<PathBuf> {
752 None
753 }
754 pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
755 Some(home()?.join(dir.conventional_name()))
756 }
757 pub fn font_dirs() -> Vec<PathBuf> {
758 Vec::new()
759 }
760}
761
762#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
772pub enum UserDir {
773 Desktop,
774 Documents,
775 Download,
776 Music,
777 Pictures,
778 Videos,
779 Templates,
780 PublicShare,
781}
782
783impl UserDir {
784 #[must_use]
785 pub const fn env_var(self) -> &'static str {
786 match self {
787 Self::Desktop => "XDG_DESKTOP_DIR",
788 Self::Documents => "XDG_DOCUMENTS_DIR",
789 Self::Download => "XDG_DOWNLOAD_DIR",
790 Self::Music => "XDG_MUSIC_DIR",
791 Self::Pictures => "XDG_PICTURES_DIR",
792 Self::Videos => "XDG_VIDEOS_DIR",
793 Self::Templates => "XDG_TEMPLATES_DIR",
794 Self::PublicShare => "XDG_PUBLICSHARE_DIR",
795 }
796 }
797
798 #[must_use]
802 pub const fn conventional_name(self) -> &'static str {
803 match self {
804 Self::Desktop => "Desktop",
805 Self::Documents => "Documents",
806 Self::Download => "Downloads",
807 Self::Music => "Music",
808 Self::Pictures => "Pictures",
809 #[cfg(target_os = "macos")]
810 Self::Videos => "Movies",
811 #[cfg(not(target_os = "macos"))]
812 Self::Videos => "Videos",
813 Self::Templates => "Templates",
814 Self::PublicShare => "Public",
815 }
816 }
817
818 #[must_use]
819 pub fn resolve(self) -> Option<PathBuf> {
820 platform::user_dir(self)
821 }
822
823 #[must_use]
827 pub fn from_environment(self) -> Option<PathBuf> {
828 absolute(var(self.env_var()))
829 }
830
831 #[must_use]
832 pub fn resolve_for_home(self, home: &std::path::Path) -> Option<PathBuf> {
833 let config_home = xdg::Base::Config
834 .resolve_from(var("XDG_CONFIG_HOME").as_deref(), Some(home.as_os_str()))?;
835 let file = std::fs::read(config_home.join("user-dirs.dirs")).ok();
836 self.resolve_from(var(self.env_var()).as_deref(), file.as_deref(), home)
837 }
838
839 #[must_use]
843 pub fn resolve_from(
844 self,
845 value: Option<&std::ffi::OsStr>,
846 user_dirs: Option<&[u8]>,
847 home: &std::path::Path,
848 ) -> Option<PathBuf> {
849 absolute(value.map(std::ffi::OsStr::to_os_string))
850 .or_else(|| user_dirs_entry(user_dirs?, self.env_var(), home))
851 }
852}
853
854fn user_dirs_entry(contents: &[u8], key: &str, home: &std::path::Path) -> Option<PathBuf> {
861 let mut found = None;
862 for line in contents.split(|&byte| byte == b'\n') {
863 let Some(separator) = line.iter().position(|&byte| byte == b'=') else {
864 continue;
865 };
866 let (name, value) = line.split_at(separator);
867 if trim_blank(name) != key.as_bytes() {
868 continue;
869 }
870 let value = trim_blank(value.get(1..).unwrap_or_default());
871 let Some(value) = value
872 .strip_prefix(b"\"")
873 .and_then(|value| value.strip_suffix(b"\""))
874 else {
875 continue;
876 };
877 found = if value == b"$HOME/" || value == b"$HOME" {
878 None
879 } else if let Some(relative) = value.strip_prefix(b"$HOME/") {
880 Some(home.join(path_from_bytes(shell_unescape(relative))))
881 } else if value.starts_with(b"/") {
882 Some(path_from_bytes(shell_unescape(value)))
883 } else {
884 continue;
885 };
886 }
887 found
888}
889
890fn trim_blank(bytes: &[u8]) -> &[u8] {
891 let blank = |byte: &u8| *byte == b' ' || *byte == b'\t' || *byte == b'\r';
892 let start = bytes
893 .iter()
894 .position(|byte| !blank(byte))
895 .unwrap_or(bytes.len());
896 let end = bytes
897 .iter()
898 .rposition(|byte| !blank(byte))
899 .map_or(start, |last| last.saturating_add(1));
900 bytes.get(start..end).unwrap_or_default()
901}
902
903fn shell_unescape(escaped: &[u8]) -> Vec<u8> {
906 let mut unescaped = Vec::with_capacity(escaped.len());
907 let mut bytes = escaped.iter().copied().peekable();
908 while let Some(byte) = bytes.next() {
909 if byte == b'\\'
910 && let Some(&next) = bytes.peek()
911 && matches!(next, b'$' | b'`' | b'"' | b'\\' | b'\n')
912 {
913 unescaped.push(next);
914 bytes.next();
915 } else {
916 unescaped.push(byte);
917 }
918 }
919 unescaped
920}
921
922#[cfg(unix)]
923fn path_from_bytes(bytes: Vec<u8>) -> PathBuf {
924 use std::os::unix::ffi::OsStringExt;
925 PathBuf::from(OsString::from_vec(bytes))
926}
927
928#[cfg(not(unix))]
929fn path_from_bytes(bytes: Vec<u8>) -> PathBuf {
930 match String::from_utf8(bytes) {
931 Ok(text) => PathBuf::from(text),
932 Err(error) => PathBuf::from(String::from_utf8_lossy(error.as_bytes()).into_owned()),
933 }
934}
935
936#[must_use]
937pub fn desktop_dir() -> Option<PathBuf> {
938 UserDir::Desktop.resolve()
939}
940
941#[must_use]
942pub fn document_dir() -> Option<PathBuf> {
943 UserDir::Documents.resolve()
944}
945
946#[must_use]
947pub fn download_dir() -> Option<PathBuf> {
948 UserDir::Download.resolve()
949}
950
951#[must_use]
952pub fn audio_dir() -> Option<PathBuf> {
953 UserDir::Music.resolve()
954}
955
956#[must_use]
957pub fn picture_dir() -> Option<PathBuf> {
958 UserDir::Pictures.resolve()
959}
960
961#[must_use]
962pub fn video_dir() -> Option<PathBuf> {
963 UserDir::Videos.resolve()
964}
965
966#[derive(Clone, Copy, Debug, PartialEq, Eq)]
969pub struct AppDirs<'a> {
970 name: &'a str,
971}
972
973impl<'a> AppDirs<'a> {
974 #[must_use]
975 pub const fn new(name: &'a str) -> Self {
976 Self { name }
977 }
978
979 #[must_use]
980 pub fn data(&self) -> Option<PathBuf> {
981 Some(data_dir()?.join(self.name))
982 }
983
984 #[must_use]
985 pub fn config(&self) -> Option<PathBuf> {
986 Some(config_dir()?.join(self.name))
987 }
988
989 #[must_use]
990 pub fn state(&self) -> Option<PathBuf> {
991 Some(state_dir()?.join(self.name))
992 }
993
994 #[must_use]
995 pub fn cache(&self) -> Option<PathBuf> {
996 Some(cache_dir()?.join(self.name))
997 }
998
999 #[must_use]
1000 pub fn runtime(&self) -> Option<PathBuf> {
1001 Some(runtime_dir()?.join(self.name))
1002 }
1003}
1004
1005#[cfg(test)]
1006mod tests {
1007 use super::xdg::Base;
1008 #[cfg(unix)]
1009 use super::xdg::search_path;
1010 use super::*;
1011 #[cfg(unix)]
1012 use std::ffi::OsStr;
1013
1014 fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
1015 move |name| {
1016 pairs
1017 .iter()
1018 .find(|(key, _)| *key == name)
1019 .map(|(_, value)| OsString::from(value))
1020 }
1021 }
1022
1023 #[cfg(unix)]
1024 fn home_is(path: &str) -> impl FnOnce() -> Option<PathBuf> + '_ {
1025 move || Some(PathBuf::from(path))
1026 }
1027
1028 #[test]
1029 fn a_locale_names_one_language_however_it_is_spelled() {
1030 for (locale, language, tag, named) in [
1031 ("de", "de", "de", true),
1032 ("de-DE", "de", "de-DE", true),
1033 ("de_DE", "de", "de-DE", true),
1034 ("de_DE.UTF-8", "de", "de-DE", true),
1035 ("de_DE.UTF-8@euro", "de", "de-DE", true),
1036 ("de.UTF-8", "de", "de", true),
1037 (" de-DE ", "de", "de-DE", true),
1038 ("DE-de", "de", "DE-de", true),
1039 ("de_AT:en_US", "de", "de-AT", true),
1040 ("en-US", "en", "en-US", true),
1041 ("es-419", "es", "es-419", true),
1042 ("zh-Hant-TW", "zh", "zh-Hant-TW", true),
1043 ("C", "c", "C", false),
1044 ("C.UTF-8", "c", "C", false),
1045 ("POSIX", "posix", "POSIX", false),
1046 ("", "", "", false),
1047 ] {
1048 assert_eq!(language_of(locale), language, "{locale:?}");
1049 assert_eq!(locale_tag(locale), tag, "{locale:?}");
1050 assert_eq!(names_language(locale), named, "{locale:?}");
1051 }
1052 }
1053
1054 #[test]
1055 fn a_reader_is_served_by_its_own_tag_or_another_region_of_its_language() {
1056 for (locale, candidates, want) in [
1057 ("de-DE", &["en-US", "de-DE"][..], Some(1)),
1058 ("de_DE.UTF-8", &["en-US", "de-DE"], Some(1)),
1059 ("de-AT", &["en-US", "de-DE"], Some(1)),
1060 ("de", &["de-DE", "de"], Some(1)),
1061 ("en-US", &["de-DE", "en-US"], Some(1)),
1062 ("fr-FR", &["de-DE", "en-US"], None),
1063 ("fr-FR", &[], None),
1064 ("C", &["de-DE"], None),
1065 ("", &["de-DE"], None),
1066 ] {
1067 assert_eq!(
1068 matching(locale, candidates.iter().copied()),
1069 want,
1070 "{locale:?}"
1071 );
1072 }
1073 }
1074
1075 #[cfg(unix)]
1076 #[test]
1077 #[allow(
1078 clippy::too_many_lines,
1079 reason = "each phase keeps one former test's body verbatim"
1080 )]
1081 fn base_directories_follow_absolute_variables_or_home_defaults() {
1082 {
1083 let vars = [
1084 ("XDG_DATA_HOME", "/data"),
1085 ("XDG_CONFIG_HOME", "/config"),
1086 ("XDG_STATE_HOME", "/state"),
1087 ("XDG_CACHE_HOME", "/cache"),
1088 ("XDG_RUNTIME_DIR", "/run/user/1000"),
1089 ];
1090 let var = env(&vars);
1091 for (base, expected) in [
1092 (Base::Data, "/data"),
1093 (Base::Config, "/config"),
1094 (Base::State, "/state"),
1095 (Base::Cache, "/cache"),
1096 (Base::Runtime, "/run/user/1000"),
1097 ] {
1098 assert_eq!(
1099 base.resolve(&var, home_is("/home/u")),
1100 Some(PathBuf::from(expected))
1101 );
1102 }
1103 }
1104 {
1105 let var = env(&[]);
1106 for (base, expected) in [
1107 (Base::Data, Some("/home/u/.local/share")),
1108 (Base::Config, Some("/home/u/.config")),
1109 (Base::State, Some("/home/u/.local/state")),
1110 (Base::Cache, Some("/home/u/.cache")),
1111 (Base::Runtime, None),
1112 ] {
1113 assert_eq!(
1114 base.resolve(&var, home_is("/home/u")),
1115 expected.map(PathBuf::from),
1116 "{base:?}"
1117 );
1118 }
1119 }
1120 {
1121 for value in ["relative/data", "", "./data", "~/data"] {
1122 let vars = [("XDG_DATA_HOME", value), ("XDG_RUNTIME_DIR", value)];
1123 let var = env(&vars);
1124 assert_eq!(
1125 Base::Data.resolve(&var, home_is("/home/u")),
1126 Some(PathBuf::from("/home/u/.local/share")),
1127 "{value:?}"
1128 );
1129 assert_eq!(
1130 Base::Runtime.resolve(&var, home_is("/home/u")),
1131 None,
1132 "{value:?}"
1133 );
1134 }
1135 }
1136 {
1137 let home = Some(OsStr::new("/home/u"));
1138 assert_eq!(
1139 Base::State.resolve_from(Some(OsStr::new("/state")), home),
1140 Some(PathBuf::from("/state"))
1141 );
1142 for invalid in [None, Some(OsStr::new("")), Some(OsStr::new("rel"))] {
1143 assert_eq!(
1144 Base::State.resolve_from(invalid, home),
1145 Some(PathBuf::from("/home/u/.local/state"))
1146 );
1147 }
1148 assert_eq!(Base::State.resolve_from(None, Some(OsStr::new(""))), None);
1149 assert_eq!(Base::Runtime.resolve_from(None, home), None);
1150 assert_eq!(Base::Config.env_var(), "XDG_CONFIG_HOME");
1151 }
1152 {
1153 let account = || Some(PathBuf::from("/var/home/account"));
1154 assert_eq!(
1155 home_from(&env(&[("HOME", "/home/u")]), account),
1156 Some(PathBuf::from("/home/u"))
1157 );
1158 assert_eq!(home_from(&env(&[("HOME", "")]), account), None);
1159 assert_eq!(
1160 home_from(&env(&[]), account),
1161 Some(PathBuf::from("/var/home/account"))
1162 );
1163 assert_eq!(home_from(&env(&[]), || Some(PathBuf::new())), None);
1164 }
1165 {
1166 let defaults = ["/usr/local/share", "/usr/share"];
1167 let expected_defaults: Vec<PathBuf> = defaults.iter().map(PathBuf::from).collect();
1168 assert_eq!(search_path(None, &defaults), expected_defaults);
1169 assert_eq!(
1170 search_path(Some(OsStr::new("")), &defaults),
1171 expected_defaults
1172 );
1173 assert_eq!(
1174 search_path(Some(OsStr::new("relative:also/relative")), &defaults),
1175 expected_defaults
1176 );
1177 assert_eq!(
1178 search_path(
1179 Some(OsStr::new("/opt/share::relative:/usr/share")),
1180 &defaults
1181 ),
1182 vec![PathBuf::from("/opt/share"), PathBuf::from("/usr/share")]
1183 );
1184 }
1185 }
1186
1187 #[test]
1188 fn app_and_user_dir_names_follow_the_spec_without_a_home() {
1189 {
1190 assert_eq!(Base::Config.resolve(&env(&[]), || None), None);
1191 #[cfg(unix)]
1192 assert_eq!(
1193 Base::Config.resolve(&env(&[("XDG_CONFIG_HOME", "/cfg")]), || None),
1194 Some(PathBuf::from("/cfg"))
1195 );
1196 }
1197 {
1198 assert_eq!(UserDir::Download.env_var(), "XDG_DOWNLOAD_DIR");
1199 assert_eq!(UserDir::PublicShare.env_var(), "XDG_PUBLICSHARE_DIR");
1200 assert_eq!(UserDir::Download.conventional_name(), "Downloads");
1201 }
1202 {
1203 let app = AppDirs::new("tilo-example");
1204 for (joined, base) in [
1205 (app.data(), data_dir()),
1206 (app.config(), config_dir()),
1207 (app.state(), state_dir()),
1208 (app.cache(), cache_dir()),
1209 (app.runtime(), runtime_dir()),
1210 ] {
1211 assert_eq!(joined, base.map(|base| base.join("tilo-example")));
1212 }
1213 }
1214 }
1215
1216 #[cfg(unix)]
1217 const USER_DIRS: &[u8] = b"# This file is written by xdg-user-dirs-update\n\
1218XDG_DESKTOP_DIR=\"$HOME/Schreibtisch\"\n\
1219XDG_DOWNLOAD_DIR=\"$HOME/Downloads\"\n\
1220 XDG_DOCUMENTS_DIR = \"$HOME/Dokumente\" \n\
1221XDG_MUSIC_DIR=\"/srv/music\"\n\
1222XDG_PICTURES_DIR=\"$HOME/\"\n\
1223XDG_VIDEOS_DIR=$HOME/Videos\n\
1224XDG_TEMPLATES_DIR=\"relative/templates\"\n\
1225XDG_PUBLICSHARE_DIR=\"$HOME/My \\\"Public\\\" \\$hare\"\n";
1226
1227 #[cfg(unix)]
1228 #[test]
1229 fn user_dirs_files_resolve_below_home_and_yield_to_variables() {
1230 {
1231 let home = std::path::Path::new("/home/u");
1232 let resolve = |dir: UserDir| dir.resolve_from(None, Some(USER_DIRS), home);
1233 assert_eq!(
1234 resolve(UserDir::Desktop),
1235 Some(PathBuf::from("/home/u/Schreibtisch"))
1236 );
1237 assert_eq!(
1238 resolve(UserDir::Download),
1239 Some(PathBuf::from("/home/u/Downloads"))
1240 );
1241 assert_eq!(
1242 resolve(UserDir::Documents),
1243 Some(PathBuf::from("/home/u/Dokumente")),
1244 "blanks around the key and value are not part of either"
1245 );
1246 assert_eq!(resolve(UserDir::Music), Some(PathBuf::from("/srv/music")));
1247 assert_eq!(
1248 resolve(UserDir::PublicShare),
1249 Some(PathBuf::from("/home/u/My \"Public\" $hare")),
1250 "double-quote escapes are undone"
1251 );
1252 }
1253 {
1254 let home = std::path::Path::new("/home/u");
1255 for dir in [UserDir::Pictures, UserDir::Videos, UserDir::Templates] {
1256 assert_eq!(
1257 dir.resolve_from(None, Some(USER_DIRS), home),
1258 None,
1259 "{dir:?}"
1260 );
1261 }
1262 assert_eq!(UserDir::Desktop.resolve_from(None, None, home), None);
1263 assert_eq!(UserDir::Desktop.resolve_from(None, Some(b""), home), None);
1264 }
1265 {
1266 let home = std::path::Path::new("/home/u");
1267 assert_eq!(
1268 UserDir::Download.resolve_from(Some(OsStr::new("/data/dl")), Some(USER_DIRS), home),
1269 Some(PathBuf::from("/data/dl"))
1270 );
1271 for ignored in ["", "relative/dl"] {
1272 assert_eq!(
1273 UserDir::Download.resolve_from(
1274 Some(OsStr::new(ignored)),
1275 Some(USER_DIRS),
1276 home
1277 ),
1278 Some(PathBuf::from("/home/u/Downloads")),
1279 "{ignored:?}"
1280 );
1281 }
1282 }
1283 }
1284
1285 #[cfg(unix)]
1286 #[test]
1287 fn the_last_matching_line_wins() {
1288 let home = std::path::Path::new("/home/u");
1289 let file = b"XDG_DESKTOP_DIR=\"$HOME/One\"\nXDG_DESKTOP_DIR=\"$HOME/Two\"\n";
1290 assert_eq!(
1291 UserDir::Desktop.resolve_from(None, Some(file), home),
1292 Some(PathBuf::from("/home/u/Two"))
1293 );
1294 }
1295
1296 #[cfg(unix)]
1297 #[test]
1298 fn macos_keeps_data_config_and_state_in_application_support() {
1299 let tmpdir = [("TMPDIR", "/var/folders/ab/xyz/T/")];
1300 let var = env(&tmpdir);
1301 for (base, expected) in [
1302 (Base::Data, "/Users/u/Library/Application Support"),
1303 (Base::Config, "/Users/u/Library/Application Support"),
1304 (Base::State, "/Users/u/Library/Application Support"),
1305 (Base::Cache, "/Users/u/Library/Caches"),
1306 (Base::Runtime, "/var/folders/ab/xyz/T/"),
1307 ] {
1308 assert_eq!(
1309 macos::base(base, &var, home_is("/Users/u")),
1310 Some(PathBuf::from(expected)),
1311 "{base:?}"
1312 );
1313 }
1314 }
1315
1316 #[cfg(unix)]
1317 #[test]
1318 fn macos_runtime_needs_an_absolute_tmpdir_and_ignores_xdg() {
1319 for value in ["", "tmp", "./T"] {
1320 let vars = [("TMPDIR", value), ("XDG_RUNTIME_DIR", "/run/user/501")];
1321 assert_eq!(
1322 macos::base(Base::Runtime, &env(&vars), home_is("/Users/u")),
1323 None,
1324 "{value:?}"
1325 );
1326 }
1327 assert_eq!(
1328 macos::base(Base::Data, &env(&[("XDG_DATA_HOME", "/data")]), || None),
1329 None,
1330 "without a home only the runtime directory can resolve"
1331 );
1332 }
1333
1334 #[test]
1335 fn a_workspace_tree_is_one_component_under_the_files_root() {
1336 let files = std::path::Path::new("/var/workspace");
1337 let id = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
1338 assert_eq!(
1339 workspace_tree(files, id),
1340 Some(files.join(".workspaces").join(id))
1341 );
1342 for bad in [
1343 "",
1344 ".",
1345 "..",
1346 "a/b",
1347 "../x",
1348 "a.b",
1349 "a\0b",
1350 &"x".repeat(129),
1351 ] {
1352 assert_eq!(workspace_tree(files, bad), None, "{bad:?}");
1353 }
1354 }
1355}