Skip to main content

quickgui_system/
app_environment.rs

1use std::{
2    collections::HashSet,
3    env,
4    path::{Path, PathBuf},
5    sync::Arc,
6};
7
8use crate::{Result, invalid, platform};
9
10pub const MAX_APP_NAME_BYTES: usize = 256;
11pub const MAX_APP_VERSION_BYTES: usize = 128;
12pub const MAX_APP_IDENTIFIER_BYTES: usize = 1_024;
13pub const MAX_SYSTEM_TEXT_BYTES: usize = 1_024;
14pub const MAX_SYSTEM_LOCALE_BYTES: usize = 256;
15pub const MAX_SYSTEM_LOCALES_TOTAL_BYTES: usize = 16 * 1_024;
16pub const MAX_PREFERRED_LANGUAGES: usize = 64;
17
18/// Immutable package identity supplied by the application at startup.
19#[derive(Clone, Debug, Eq, Hash, PartialEq)]
20pub struct AppInfo {
21    name: Arc<str>,
22    version: Arc<str>,
23    identifier: Arc<str>,
24}
25
26impl AppInfo {
27    pub fn new(
28        name: impl Into<Arc<str>>,
29        version: impl Into<Arc<str>>,
30        identifier: impl Into<Arc<str>>,
31    ) -> Result<Self> {
32        let name = name.into();
33        let version = version.into();
34        let identifier = identifier.into();
35        validate_single_line(&name, "application name", MAX_APP_NAME_BYTES)?;
36        validate_single_line(&version, "application version", MAX_APP_VERSION_BYTES)?;
37        validate_app_identifier(&identifier)?;
38        Ok(Self {
39            name,
40            version,
41            identifier,
42        })
43    }
44
45    pub fn name(&self) -> &str {
46        &self.name
47    }
48
49    pub fn version(&self) -> &str {
50        &self.version
51    }
52
53    /// Stable reverse-domain or similarly portable identifier used to scope application paths.
54    pub fn identifier(&self) -> &str {
55        &self.identifier
56    }
57
58    /// Resolve the current process's standard application paths using this identity.
59    pub fn paths(&self) -> Result<AppPaths> {
60        AppPaths::resolve(self.identifier())
61    }
62}
63
64/// Immutable snapshot of standard process, application, and user directories.
65///
66/// Application-owned directories are scoped by the package identifier. User directories and the
67/// operating-system temporary directory are not created or otherwise mutated during resolution.
68#[derive(Clone, Debug, Eq, PartialEq)]
69pub struct AppPaths(Arc<AppPathSnapshot>);
70
71#[derive(Clone, Debug, Eq, PartialEq)]
72struct AppPathSnapshot {
73    executable: PathBuf,
74    executable_dir: PathBuf,
75    resource_dir: PathBuf,
76    home_dir: Option<PathBuf>,
77    config_dir: Option<PathBuf>,
78    data_dir: Option<PathBuf>,
79    local_data_dir: Option<PathBuf>,
80    cache_dir: Option<PathBuf>,
81    log_dir: Option<PathBuf>,
82    runtime_dir: Option<PathBuf>,
83    temp_dir: PathBuf,
84    audio_dir: Option<PathBuf>,
85    desktop_dir: Option<PathBuf>,
86    document_dir: Option<PathBuf>,
87    download_dir: Option<PathBuf>,
88    picture_dir: Option<PathBuf>,
89    video_dir: Option<PathBuf>,
90}
91
92impl AppPaths {
93    /// Resolve paths once for the current process without creating any directories.
94    pub fn resolve(identifier: &str) -> Result<Self> {
95        validate_app_identifier(identifier)?;
96        let executable = env::current_exe().map_err(platform)?;
97        Self::from_executable(identifier, executable)
98    }
99
100    fn from_executable(identifier: &str, executable: PathBuf) -> Result<Self> {
101        let executable_dir = executable
102            .parent()
103            .filter(|path| !path.as_os_str().is_empty())
104            .ok_or_else(|| invalid("the current executable does not have a parent directory"))?
105            .to_path_buf();
106        let resource_dir = resource_dir_for_executable(&executable);
107        let home_dir = dirs::home_dir();
108        let config_dir = scoped(dirs::config_dir(), identifier);
109        let data_dir = scoped(dirs::data_dir(), identifier);
110        let local_data_dir = scoped(dirs::data_local_dir(), identifier);
111        let cache_dir = scoped(dirs::cache_dir(), identifier);
112        let runtime_dir = scoped(dirs::runtime_dir(), identifier);
113        let log_dir = log_dir(identifier, home_dir.as_deref(), local_data_dir.as_deref());
114        Ok(Self(Arc::new(AppPathSnapshot {
115            executable,
116            executable_dir,
117            resource_dir,
118            home_dir,
119            config_dir,
120            data_dir,
121            local_data_dir,
122            cache_dir,
123            log_dir,
124            runtime_dir,
125            temp_dir: env::temp_dir(),
126            audio_dir: dirs::audio_dir(),
127            desktop_dir: dirs::desktop_dir(),
128            document_dir: dirs::document_dir(),
129            download_dir: dirs::download_dir(),
130            picture_dir: dirs::picture_dir(),
131            video_dir: dirs::video_dir(),
132        })))
133    }
134
135    pub fn executable(&self) -> &Path {
136        &self.0.executable
137    }
138
139    pub fn executable_dir(&self) -> &Path {
140        &self.0.executable_dir
141    }
142
143    pub fn resource_dir(&self) -> &Path {
144        &self.0.resource_dir
145    }
146
147    pub fn home_dir(&self) -> Option<&Path> {
148        self.0.home_dir.as_deref()
149    }
150
151    pub fn config_dir(&self) -> Option<&Path> {
152        self.0.config_dir.as_deref()
153    }
154
155    pub fn data_dir(&self) -> Option<&Path> {
156        self.0.data_dir.as_deref()
157    }
158
159    pub fn local_data_dir(&self) -> Option<&Path> {
160        self.0.local_data_dir.as_deref()
161    }
162
163    pub fn cache_dir(&self) -> Option<&Path> {
164        self.0.cache_dir.as_deref()
165    }
166
167    pub fn log_dir(&self) -> Option<&Path> {
168        self.0.log_dir.as_deref()
169    }
170
171    pub fn runtime_dir(&self) -> Option<&Path> {
172        self.0.runtime_dir.as_deref()
173    }
174
175    pub fn temp_dir(&self) -> &Path {
176        &self.0.temp_dir
177    }
178
179    pub fn audio_dir(&self) -> Option<&Path> {
180        self.0.audio_dir.as_deref()
181    }
182
183    pub fn desktop_dir(&self) -> Option<&Path> {
184        self.0.desktop_dir.as_deref()
185    }
186
187    pub fn document_dir(&self) -> Option<&Path> {
188        self.0.document_dir.as_deref()
189    }
190
191    pub fn download_dir(&self) -> Option<&Path> {
192        self.0.download_dir.as_deref()
193    }
194
195    pub fn picture_dir(&self) -> Option<&Path> {
196        self.0.picture_dir.as_deref()
197    }
198
199    pub fn video_dir(&self) -> Option<&Path> {
200        self.0.video_dir.as_deref()
201    }
202
203    pub fn with_resource_dir(mut self, path: impl Into<PathBuf>) -> Self {
204        Arc::make_mut(&mut self.0).resource_dir = path.into();
205        self
206    }
207
208    pub fn with_config_dir(mut self, path: Option<impl Into<PathBuf>>) -> Self {
209        Arc::make_mut(&mut self.0).config_dir = path.map(Into::into);
210        self
211    }
212
213    pub fn with_data_dir(mut self, path: Option<impl Into<PathBuf>>) -> Self {
214        Arc::make_mut(&mut self.0).data_dir = path.map(Into::into);
215        self
216    }
217
218    pub fn with_local_data_dir(mut self, path: Option<impl Into<PathBuf>>) -> Self {
219        Arc::make_mut(&mut self.0).local_data_dir = path.map(Into::into);
220        self
221    }
222
223    pub fn with_cache_dir(mut self, path: Option<impl Into<PathBuf>>) -> Self {
224        Arc::make_mut(&mut self.0).cache_dir = path.map(Into::into);
225        self
226    }
227
228    pub fn with_log_dir(mut self, path: Option<impl Into<PathBuf>>) -> Self {
229        Arc::make_mut(&mut self.0).log_dir = path.map(Into::into);
230        self
231    }
232
233    pub fn with_runtime_dir(mut self, path: Option<impl Into<PathBuf>>) -> Self {
234        Arc::make_mut(&mut self.0).runtime_dir = path.map(Into::into);
235        self
236    }
237
238    pub fn with_temp_dir(mut self, path: impl Into<PathBuf>) -> Self {
239        Arc::make_mut(&mut self.0).temp_dir = path.into();
240        self
241    }
242}
243
244fn scoped(base: Option<PathBuf>, identifier: &str) -> Option<PathBuf> {
245    base.map(|base| base.join(identifier))
246}
247
248#[cfg(target_os = "macos")]
249fn log_dir(identifier: &str, home: Option<&Path>, _local_data: Option<&Path>) -> Option<PathBuf> {
250    home.map(|home| home.join("Library").join("Logs").join(identifier))
251}
252
253#[cfg(not(target_os = "macos"))]
254fn log_dir(identifier: &str, _home: Option<&Path>, local_data: Option<&Path>) -> Option<PathBuf> {
255    local_data.map(|path| {
256        debug_assert_eq!(path.file_name(), Some(identifier.as_ref()));
257        path.join("logs")
258    })
259}
260
261fn resource_dir_for_executable(executable: &Path) -> PathBuf {
262    let executable_dir = executable.parent().unwrap_or_else(|| Path::new("."));
263    #[cfg(target_os = "macos")]
264    if executable_dir
265        .file_name()
266        .is_some_and(|name| name == "MacOS")
267        && let Some(contents) = executable_dir.parent()
268        && contents.file_name().is_some_and(|name| name == "Contents")
269    {
270        return contents.join("Resources");
271    }
272    executable_dir.to_path_buf()
273}
274
275fn validate_single_line(value: &str, name: &str, maximum: usize) -> Result<()> {
276    if value.is_empty()
277        || value.contains(['\0', '\n', '\r'])
278        || value.len() > maximum
279        || value.trim() != value
280    {
281        return Err(invalid(format!(
282            "{name} must be nonempty, single-line, NUL-free, unpadded, and at most {maximum} UTF-8 bytes"
283        )));
284    }
285    Ok(())
286}
287
288fn validate_app_identifier(identifier: &str) -> Result<()> {
289    validate_single_line(
290        identifier,
291        "application identifier",
292        MAX_APP_IDENTIFIER_BYTES,
293    )?;
294    if matches!(identifier, "." | "..")
295        || !identifier
296            .as_bytes()
297            .first()
298            .is_some_and(u8::is_ascii_alphanumeric)
299        || !identifier
300            .bytes()
301            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
302    {
303        return Err(invalid(
304            "application identifier must start with an ASCII letter or digit and contain only ASCII letters, digits, '.', '_', or '-'",
305        ));
306    }
307    Ok(())
308}
309
310/// Compile-time operating-system family used by the running process.
311#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
312pub enum OperatingSystemFamily {
313    Unix,
314    Windows,
315    Wasm,
316    Other,
317}
318
319impl OperatingSystemFamily {
320    pub const fn current() -> Self {
321        #[cfg(target_arch = "wasm32")]
322        return Self::Wasm;
323        #[cfg(all(not(target_arch = "wasm32"), windows))]
324        return Self::Windows;
325        #[cfg(all(not(target_arch = "wasm32"), unix))]
326        return Self::Unix;
327        #[cfg(not(any(target_arch = "wasm32", windows, unix)))]
328        return Self::Other;
329    }
330
331    pub const fn as_str(self) -> &'static str {
332        match self {
333            Self::Unix => "unix",
334            Self::Windows => "windows",
335            Self::Wasm => "wasm",
336            Self::Other => "other",
337        }
338    }
339}
340
341/// Compile-time operating system used by the running process.
342#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
343pub enum OperatingSystem {
344    Macos,
345    Windows,
346    Linux,
347    FreeBsd,
348    DragonFly,
349    NetBsd,
350    OpenBsd,
351    Android,
352    Ios,
353    Wasm,
354    Other,
355}
356
357impl OperatingSystem {
358    pub const fn current() -> Self {
359        #[cfg(target_os = "macos")]
360        return Self::Macos;
361        #[cfg(target_os = "windows")]
362        return Self::Windows;
363        #[cfg(target_os = "linux")]
364        return Self::Linux;
365        #[cfg(target_os = "freebsd")]
366        return Self::FreeBsd;
367        #[cfg(target_os = "dragonfly")]
368        return Self::DragonFly;
369        #[cfg(target_os = "netbsd")]
370        return Self::NetBsd;
371        #[cfg(target_os = "openbsd")]
372        return Self::OpenBsd;
373        #[cfg(target_os = "android")]
374        return Self::Android;
375        #[cfg(target_os = "ios")]
376        return Self::Ios;
377        #[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))]
378        return Self::Wasm;
379        #[cfg(not(any(
380            target_os = "macos",
381            target_os = "windows",
382            target_os = "linux",
383            target_os = "freebsd",
384            target_os = "dragonfly",
385            target_os = "netbsd",
386            target_os = "openbsd",
387            target_os = "android",
388            target_os = "ios",
389            all(target_arch = "wasm32", not(target_os = "emscripten"))
390        )))]
391        return Self::Other;
392    }
393
394    pub const fn as_str(self) -> &'static str {
395        match self {
396            Self::Macos => "macos",
397            Self::Windows => "windows",
398            Self::Linux => "linux",
399            Self::FreeBsd => "freebsd",
400            Self::DragonFly => "dragonfly",
401            Self::NetBsd => "netbsd",
402            Self::OpenBsd => "openbsd",
403            Self::Android => "android",
404            Self::Ios => "ios",
405            Self::Wasm => "wasm",
406            Self::Other => "other",
407        }
408    }
409}
410
411#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
412pub enum SystemBitness {
413    X32,
414    X64,
415    Unknown,
416}
417
418/// Bounded immutable operating-system and language snapshot.
419#[derive(Clone, Debug, Eq, PartialEq)]
420pub struct SystemInfo {
421    operating_system: OperatingSystem,
422    family: OperatingSystemFamily,
423    name: Arc<str>,
424    version: Option<Arc<str>>,
425    edition: Option<Arc<str>>,
426    codename: Option<Arc<str>>,
427    architecture: Arc<str>,
428    bitness: SystemBitness,
429    hostname: Option<Arc<str>>,
430    locale: Option<Arc<str>>,
431    preferred_languages: Arc<[Arc<str>]>,
432    languages_truncated: bool,
433}
434
435impl SystemInfo {
436    /// Query the operating system once and return a stable snapshot.
437    pub fn current() -> Self {
438        let info = os_info::get();
439        let name =
440            bounded_text(&info.os_type().to_string()).unwrap_or_else(|| Arc::from(env::consts::OS));
441        let version_text = info.version().to_string();
442        let version = (version_text != "unknown")
443            .then(|| bounded_text(&version_text))
444            .flatten();
445        let architecture = info
446            .architecture()
447            .and_then(bounded_text)
448            .unwrap_or_else(|| Arc::from(env::consts::ARCH));
449        let bitness = match info.bitness() {
450            os_info::Bitness::X32 => SystemBitness::X32,
451            os_info::Bitness::X64 => SystemBitness::X64,
452            _ => SystemBitness::Unknown,
453        };
454        let hostname = hostname::get()
455            .ok()
456            .and_then(|value| value.into_string().ok())
457            .and_then(|value| bounded_text(&value));
458        let (preferred_languages, languages_truncated) = preferred_languages();
459        let locale = preferred_languages.first().cloned();
460        Self {
461            operating_system: OperatingSystem::current(),
462            family: OperatingSystemFamily::current(),
463            name,
464            version,
465            edition: info.edition().and_then(bounded_text),
466            codename: info.codename().and_then(bounded_text),
467            architecture,
468            bitness,
469            hostname,
470            locale,
471            preferred_languages: preferred_languages.into(),
472            languages_truncated,
473        }
474    }
475
476    pub const fn operating_system(&self) -> OperatingSystem {
477        self.operating_system
478    }
479
480    pub const fn family(&self) -> OperatingSystemFamily {
481        self.family
482    }
483
484    /// Platform or distribution name reported by the operating system.
485    pub fn name(&self) -> &str {
486        &self.name
487    }
488
489    pub fn version(&self) -> Option<&str> {
490        self.version.as_deref()
491    }
492
493    pub fn edition(&self) -> Option<&str> {
494        self.edition.as_deref()
495    }
496
497    pub fn codename(&self) -> Option<&str> {
498        self.codename.as_deref()
499    }
500
501    pub fn architecture(&self) -> &str {
502        &self.architecture
503    }
504
505    pub const fn bitness(&self) -> SystemBitness {
506        self.bitness
507    }
508
509    pub fn hostname(&self) -> Option<&str> {
510        self.hostname.as_deref()
511    }
512
513    /// Most preferred BCP-47 locale, when the platform reports one.
514    pub fn locale(&self) -> Option<&str> {
515        self.locale.as_deref()
516    }
517
518    /// Preferred BCP-47 languages in platform priority order.
519    pub fn preferred_languages(&self) -> &[Arc<str>] {
520        &self.preferred_languages
521    }
522
523    pub const fn languages_truncated(&self) -> bool {
524        self.languages_truncated
525    }
526}
527
528impl Default for SystemInfo {
529    fn default() -> Self {
530        Self::current()
531    }
532}
533
534fn preferred_languages() -> (Vec<Arc<str>>, bool) {
535    let mut languages = Vec::with_capacity(4);
536    let mut seen = HashSet::with_capacity(4);
537    let mut total_bytes = 0;
538    let mut truncated = false;
539    for language in sys_locale::get_locales() {
540        let language = language.replace('_', "-");
541        let Some(language) = bounded_locale(&language) else {
542            truncated = true;
543            continue;
544        };
545        if !seen.insert(language.clone()) {
546            continue;
547        }
548        if languages.len() == MAX_PREFERRED_LANGUAGES
549            || total_bytes + language.len() > MAX_SYSTEM_LOCALES_TOTAL_BYTES
550        {
551            truncated = true;
552            break;
553        }
554        total_bytes += language.len();
555        languages.push(Arc::from(language));
556    }
557    (languages, truncated)
558}
559
560fn bounded_locale(value: &str) -> Option<String> {
561    let value = value.trim();
562    if value.is_empty()
563        || value.len() > MAX_SYSTEM_LOCALE_BYTES
564        || value.contains(['\0', '\n', '\r'])
565    {
566        return None;
567    }
568    Some(value.to_owned())
569}
570
571fn bounded_text(value: &str) -> Option<Arc<str>> {
572    let value = value.trim();
573    if value.is_empty() || value.len() > MAX_SYSTEM_TEXT_BYTES || value.contains(['\0', '\n', '\r'])
574    {
575        return None;
576    }
577    Some(Arc::from(value))
578}
579
580#[cfg(test)]
581mod tests {
582    use super::*;
583
584    #[test]
585    fn validates_package_identity() {
586        let info = AppInfo::new("QuickGUI", "1.2.3", "dev.quickgui.example").unwrap();
587        assert_eq!(info.name(), "QuickGUI");
588        assert_eq!(info.version(), "1.2.3");
589        assert_eq!(info.identifier(), "dev.quickgui.example");
590        assert!(AppInfo::new("QuickGUI", "1", "../escape").is_err());
591        assert!(AppInfo::new(" padded ", "1", "dev.quickgui.example").is_err());
592        assert!(AppInfo::new("QuickGUI", "1\n2", "dev.quickgui.example").is_err());
593    }
594
595    #[test]
596    fn scopes_application_directories_without_creating_them() {
597        let paths = AppPaths::from_executable(
598            "dev.quickgui.example",
599            PathBuf::from("/opt/QuickGUI/bin/example"),
600        )
601        .unwrap();
602        assert_eq!(paths.executable_dir(), Path::new("/opt/QuickGUI/bin"));
603        assert_eq!(paths.resource_dir(), Path::new("/opt/QuickGUI/bin"));
604        for path in [
605            paths.config_dir(),
606            paths.data_dir(),
607            paths.local_data_dir(),
608            paths.cache_dir(),
609            paths.runtime_dir(),
610        ]
611        .into_iter()
612        .flatten()
613        {
614            assert_eq!(path.file_name().unwrap(), "dev.quickgui.example");
615        }
616    }
617
618    #[test]
619    fn path_overrides_are_explicit_and_immutable() {
620        let original = AppPaths::from_executable(
621            "dev.quickgui.example",
622            PathBuf::from("/opt/QuickGUI/example"),
623        )
624        .unwrap();
625        let shared = original.clone();
626        assert!(Arc::ptr_eq(&original.0, &shared.0));
627        let paths = shared
628            .with_config_dir(Some("/tmp/config"))
629            .with_resource_dir("/tmp/resources")
630            .with_temp_dir("/tmp/custom");
631        assert!(!Arc::ptr_eq(&original.0, &paths.0));
632        assert_eq!(original.resource_dir(), Path::new("/opt/QuickGUI"));
633        assert_eq!(paths.config_dir(), Some(Path::new("/tmp/config")));
634        assert_eq!(paths.resource_dir(), Path::new("/tmp/resources"));
635        assert_eq!(paths.temp_dir(), Path::new("/tmp/custom"));
636    }
637
638    #[test]
639    fn current_system_snapshot_is_bounded_and_consistent() {
640        let info = SystemInfo::current();
641        assert!(!info.name().is_empty());
642        assert!(!info.architecture().is_empty());
643        assert_eq!(info.operating_system(), OperatingSystem::current());
644        assert_eq!(info.family(), OperatingSystemFamily::current());
645        assert_eq!(
646            info.locale(),
647            info.preferred_languages().first().map(AsRef::as_ref)
648        );
649        assert!(
650            info.preferred_languages()
651                .iter()
652                .all(|language| language.len() <= MAX_SYSTEM_LOCALE_BYTES)
653        );
654    }
655
656    #[cfg(target_os = "macos")]
657    #[test]
658    fn resolves_macos_bundle_resources() {
659        let executable = Path::new("/Applications/Example.app/Contents/MacOS/example");
660        assert_eq!(
661            resource_dir_for_executable(executable),
662            Path::new("/Applications/Example.app/Contents/Resources")
663        );
664    }
665}