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        #[cfg(not(target_arch = "wasm32"))]
455        let hostname = hostname::get()
456            .ok()
457            .and_then(|value| value.into_string().ok())
458            .and_then(|value| bounded_text(&value));
459        #[cfg(target_arch = "wasm32")]
460        let hostname = None;
461        let (preferred_languages, languages_truncated) = preferred_languages();
462        let locale = preferred_languages.first().cloned();
463        Self {
464            operating_system: OperatingSystem::current(),
465            family: OperatingSystemFamily::current(),
466            name,
467            version,
468            edition: info.edition().and_then(bounded_text),
469            codename: info.codename().and_then(bounded_text),
470            architecture,
471            bitness,
472            hostname,
473            locale,
474            preferred_languages: preferred_languages.into(),
475            languages_truncated,
476        }
477    }
478
479    pub const fn operating_system(&self) -> OperatingSystem {
480        self.operating_system
481    }
482
483    pub const fn family(&self) -> OperatingSystemFamily {
484        self.family
485    }
486
487    /// Platform or distribution name reported by the operating system.
488    pub fn name(&self) -> &str {
489        &self.name
490    }
491
492    pub fn version(&self) -> Option<&str> {
493        self.version.as_deref()
494    }
495
496    pub fn edition(&self) -> Option<&str> {
497        self.edition.as_deref()
498    }
499
500    pub fn codename(&self) -> Option<&str> {
501        self.codename.as_deref()
502    }
503
504    pub fn architecture(&self) -> &str {
505        &self.architecture
506    }
507
508    pub const fn bitness(&self) -> SystemBitness {
509        self.bitness
510    }
511
512    pub fn hostname(&self) -> Option<&str> {
513        self.hostname.as_deref()
514    }
515
516    /// Most preferred BCP-47 locale, when the platform reports one.
517    pub fn locale(&self) -> Option<&str> {
518        self.locale.as_deref()
519    }
520
521    /// Preferred BCP-47 languages in platform priority order.
522    pub fn preferred_languages(&self) -> &[Arc<str>] {
523        &self.preferred_languages
524    }
525
526    pub const fn languages_truncated(&self) -> bool {
527        self.languages_truncated
528    }
529}
530
531impl Default for SystemInfo {
532    fn default() -> Self {
533        Self::current()
534    }
535}
536
537fn preferred_languages() -> (Vec<Arc<str>>, bool) {
538    let mut languages = Vec::with_capacity(4);
539    let mut seen = HashSet::with_capacity(4);
540    let mut total_bytes = 0;
541    let mut truncated = false;
542    for language in sys_locale::get_locales() {
543        let language = language.replace('_', "-");
544        let Some(language) = bounded_locale(&language) else {
545            truncated = true;
546            continue;
547        };
548        if !seen.insert(language.clone()) {
549            continue;
550        }
551        if languages.len() == MAX_PREFERRED_LANGUAGES
552            || total_bytes + language.len() > MAX_SYSTEM_LOCALES_TOTAL_BYTES
553        {
554            truncated = true;
555            break;
556        }
557        total_bytes += language.len();
558        languages.push(Arc::from(language));
559    }
560    (languages, truncated)
561}
562
563fn bounded_locale(value: &str) -> Option<String> {
564    let value = value.trim();
565    if value.is_empty()
566        || value.len() > MAX_SYSTEM_LOCALE_BYTES
567        || value.contains(['\0', '\n', '\r'])
568    {
569        return None;
570    }
571    Some(value.to_owned())
572}
573
574fn bounded_text(value: &str) -> Option<Arc<str>> {
575    let value = value.trim();
576    if value.is_empty() || value.len() > MAX_SYSTEM_TEXT_BYTES || value.contains(['\0', '\n', '\r'])
577    {
578        return None;
579    }
580    Some(Arc::from(value))
581}
582
583#[cfg(test)]
584mod tests {
585    use super::*;
586
587    #[test]
588    fn validates_package_identity() {
589        let info = AppInfo::new("QuickGUI", "1.2.3", "dev.quickgui.example").unwrap();
590        assert_eq!(info.name(), "QuickGUI");
591        assert_eq!(info.version(), "1.2.3");
592        assert_eq!(info.identifier(), "dev.quickgui.example");
593        assert!(AppInfo::new("QuickGUI", "1", "../escape").is_err());
594        assert!(AppInfo::new(" padded ", "1", "dev.quickgui.example").is_err());
595        assert!(AppInfo::new("QuickGUI", "1\n2", "dev.quickgui.example").is_err());
596    }
597
598    #[test]
599    fn scopes_application_directories_without_creating_them() {
600        let paths = AppPaths::from_executable(
601            "dev.quickgui.example",
602            PathBuf::from("/opt/QuickGUI/bin/example"),
603        )
604        .unwrap();
605        assert_eq!(paths.executable_dir(), Path::new("/opt/QuickGUI/bin"));
606        assert_eq!(paths.resource_dir(), Path::new("/opt/QuickGUI/bin"));
607        for path in [
608            paths.config_dir(),
609            paths.data_dir(),
610            paths.local_data_dir(),
611            paths.cache_dir(),
612            paths.runtime_dir(),
613        ]
614        .into_iter()
615        .flatten()
616        {
617            assert_eq!(path.file_name().unwrap(), "dev.quickgui.example");
618        }
619    }
620
621    #[test]
622    fn path_overrides_are_explicit_and_immutable() {
623        let original = AppPaths::from_executable(
624            "dev.quickgui.example",
625            PathBuf::from("/opt/QuickGUI/example"),
626        )
627        .unwrap();
628        let shared = original.clone();
629        assert!(Arc::ptr_eq(&original.0, &shared.0));
630        let paths = shared
631            .with_config_dir(Some("/tmp/config"))
632            .with_resource_dir("/tmp/resources")
633            .with_temp_dir("/tmp/custom");
634        assert!(!Arc::ptr_eq(&original.0, &paths.0));
635        assert_eq!(original.resource_dir(), Path::new("/opt/QuickGUI"));
636        assert_eq!(paths.config_dir(), Some(Path::new("/tmp/config")));
637        assert_eq!(paths.resource_dir(), Path::new("/tmp/resources"));
638        assert_eq!(paths.temp_dir(), Path::new("/tmp/custom"));
639    }
640
641    #[test]
642    fn current_system_snapshot_is_bounded_and_consistent() {
643        let info = SystemInfo::current();
644        assert!(!info.name().is_empty());
645        assert!(!info.architecture().is_empty());
646        assert_eq!(info.operating_system(), OperatingSystem::current());
647        assert_eq!(info.family(), OperatingSystemFamily::current());
648        assert_eq!(
649            info.locale(),
650            info.preferred_languages().first().map(AsRef::as_ref)
651        );
652        assert!(
653            info.preferred_languages()
654                .iter()
655                .all(|language| language.len() <= MAX_SYSTEM_LOCALE_BYTES)
656        );
657    }
658
659    #[cfg(target_os = "macos")]
660    #[test]
661    fn resolves_macos_bundle_resources() {
662        let executable = Path::new("/Applications/Example.app/Contents/MacOS/example");
663        assert_eq!(
664            resource_dir_for_executable(executable),
665            Path::new("/Applications/Example.app/Contents/Resources")
666        );
667    }
668}