Skip to main content

tilo_paths/
session.rs

1//! Who the app runs as and on what: the login's account and host names, and whether a
2//! desktop session is there to show capture and call UI.
3//!
4//! Apps use these only as hints (a display name to start from, a seed for a fallback
5//! id).
6
7/// The login name of the account running this process: `$USER`, else
8/// `$USERNAME` (Windows), when non-empty. `None` in a page.
9#[must_use]
10pub fn user_name() -> Option<String> {
11    imp::user_name()
12}
13
14/// This machine's host name: `$HOSTNAME`, else the first line of
15/// `/etc/hostname`, when non-empty. `None` in a page.
16#[must_use]
17pub fn host_name() -> Option<String> {
18    imp::host_name()
19}
20
21#[must_use]
22pub fn has_desktop_session() -> bool {
23    imp::has_desktop_session()
24}
25
26#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
27mod imp {
28    pub fn non_empty(value: Option<String>) -> Option<String> {
29        value
30            .map(|value| value.trim().to_owned())
31            .filter(|value| !value.is_empty())
32    }
33
34    fn var(name: &str) -> Option<String> {
35        crate::var(name).and_then(|value| value.into_string().ok())
36    }
37
38    pub fn user_name() -> Option<String> {
39        non_empty(var("USER")).or_else(|| non_empty(var("USERNAME")))
40    }
41
42    pub fn host_name() -> Option<String> {
43        non_empty(var("HOSTNAME")).or_else(|| {
44            let text = std::fs::read_to_string("/etc/hostname").ok()?;
45            non_empty(text.lines().next().map(str::to_owned))
46        })
47    }
48
49    pub fn has_desktop_session() -> bool {
50        session_bus_present() || var("WAYLAND_DISPLAY").is_some()
51    }
52
53    /// A session bus address that names a socket which exists. The test
54    /// environment points the address at one that never does.
55    fn session_bus_present() -> bool {
56        let Some(address) = var("DBUS_SESSION_BUS_ADDRESS") else {
57            return false;
58        };
59        address
60            .split(';')
61            .any(|entry| match entry.strip_prefix("unix:path=") {
62                Some(rest) => {
63                    let path = rest.split(',').next().unwrap_or_default();
64                    std::path::Path::new(path).exists()
65                }
66                None => !entry.is_empty(),
67            })
68    }
69}
70
71#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
72mod imp {
73    pub const fn user_name() -> Option<String> {
74        None
75    }
76
77    pub const fn host_name() -> Option<String> {
78        None
79    }
80
81    pub const fn has_desktop_session() -> bool {
82        false
83    }
84}
85
86#[cfg(test)]
87#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
88mod tests {
89    use super::imp::non_empty;
90    use super::*;
91
92    #[test]
93    fn blank_values_name_nothing() {
94        assert_eq!(non_empty(Some("  ".into())), None);
95        assert_eq!(non_empty(None), None);
96        assert_eq!(non_empty(Some(" ada \n".into())), Some("ada".into()));
97    }
98
99    #[test]
100    fn a_scoped_profile_keeps_the_session_answers_consistent() {
101        // The names come from the process environment either way; they only
102        // have to be non-blank when present.
103        let _scope = crate::scope_profile(std::env::temp_dir());
104        assert!(user_name().is_none_or(|name| !name.is_empty()));
105        assert!(host_name().is_none_or(|name| !name.is_empty()));
106    }
107}