Skip to main content

tilo_process/
environment.rs

1//! Host inputs: who the process is, where its files live, and how its user asked to
2//! be served.
3//!
4//! Toolkit and collab-client code take these from [`environment`] rather than reading
5//! the process environment. Only the native fallback derives them from the process
6//! ([`process_environment`], feature `native`); another host installs its own with
7//! [`install_environment`].
8
9use std::path::PathBuf;
10use std::sync::{Arc, RwLock};
11
12use unic_langid::LanguageIdentifier;
13
14#[cfg(feature = "native")]
15mod native;
16#[cfg(feature = "native")]
17pub use native::process_environment;
18
19/// Inert, app-owned resume projection sent only to the local shell: the bytes are
20/// opaque to the toolkit, so each app can version its own schema, and the shell
21/// validates size and path redaction before keeping them.
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub struct ContinuationMetadata {
24    pub schema_version: u16,
25    pub bytes: Vec<u8>,
26}
27
28/// Decode a hex resume payload and its schema version. Invalid input is
29/// ignored so an app outside Tilo or an older sender opens normally.
30#[cfg(feature = "native")]
31pub(crate) fn decode_continuation(hex: &str, schema: &str) -> Option<ContinuationMetadata> {
32    let bytes = hex::decode(hex).ok()?;
33    let schema_version = schema.parse().ok()?;
34    (!bytes.is_empty() && bytes.len() <= 32 * 1024).then_some(ContinuationMetadata {
35        schema_version,
36        bytes,
37    })
38}
39
40/// Who this process is and which workspace it serves; every field is optional, and
41/// each reader applies its own fallback.
42#[derive(Clone, Debug, Default, PartialEq, Eq)]
43pub struct ProcessIdentity {
44    pub app_id: Option<String>,
45    pub development_app_id: Option<String>,
46    pub app_name: Option<String>,
47    pub workspace_id: Option<String>,
48    pub account_name: Option<String>,
49    pub continuity_resume: Option<ContinuationMetadata>,
50    pub continuity_instance: Option<String>,
51    /// How the launcher admitted the process to its workspace: `author` or `read-only`.
52    pub participation: Option<String>,
53    /// The launcher configured a collaboration service for this process, so
54    /// its absence is a failure rather than a standalone launch.
55    pub collab_service_configured: bool,
56    /// The process runs as an admitted managed agent, which receives task work
57    /// on its own broker queue instead of the room's task-run stream.
58    pub managed_agent_context: bool,
59}
60
61/// The MPRIS bus name of the media player a launched package publishes:
62/// `org.mpris.MediaPlayer2.<package id>`.
63#[must_use]
64pub fn media_player_bus_name(app_id: &str) -> String {
65    format!("org.mpris.MediaPlayer2.{app_id}")
66}
67
68impl ProcessIdentity {
69    /// The MPRIS bus name this process's media player goes by: its app's
70    /// ([`media_player_bus_name`]), else `fallback_app_id`'s, so an app run
71    /// outside a launcher still names its player.
72    #[must_use]
73    pub fn media_player_bus_name(&self, fallback_app_id: &str) -> String {
74        media_player_bus_name(self.app_id.as_deref().unwrap_or(fallback_app_id))
75    }
76}
77
78/// Env var naming the font index directory, for a process the launcher puts
79/// in a sandbox ([`ProcessPaths::font_index`]).
80pub const FONT_INDEX_ENV: &str = "TILO_FONT_INDEX";
81
82/// `TILO_REQUIRE_FONTS=1` promises every process that sets text the product's
83/// font catalog, as `TILO_REQUIRE_GPU=1` promises a GPU: a test run sets it.
84pub const FONTS_REQUIRED_ENV: &str = "TILO_REQUIRE_FONTS";
85
86#[derive(Clone, Debug, Default, PartialEq, Eq)]
87pub struct ProcessPaths {
88    pub user_home: Option<PathBuf>,
89    pub home: Option<PathBuf>,
90    pub config_home: Option<PathBuf>,
91    pub cache_home: Option<PathBuf>,
92    /// The session's read-only pipeline cache directory (`TILO_PIPELINE_SEED_DIR`), bound
93    /// in by the launcher.
94    pub pipeline_seed: Option<PathBuf>,
95    /// The directory this process reads and records its font index in
96    /// (`TILO_FONT_INDEX`), when the host names one; else it is
97    /// `tilo/font-index` under [`Self::cache_dir`].
98    pub font_index: Option<PathBuf>,
99    /// The font catalog to read instead of the compiled-in one (`TILO_FONT_CATALOG`); a
100    /// build bakes in the pinned catalog's path, which a binary built elsewhere does not
101    /// have.
102    pub font_catalog: Option<PathBuf>,
103    pub font_artifact_cache: Option<PathBuf>,
104}
105
106impl ProcessPaths {
107    pub fn config_dir(&self) -> Option<PathBuf> {
108        self.config_home
109            .clone()
110            .or_else(|| self.home.as_ref().map(|home| home.join(".config")))
111    }
112
113    pub fn cache_dir(&self) -> Option<PathBuf> {
114        self.cache_home
115            .clone()
116            .or_else(|| self.home.as_ref().map(|home| home.join(".cache")))
117    }
118}
119
120#[derive(Clone, Copy, Debug, Default, PartialEq)]
121pub struct AccessibilityInputs {
122    pub screen_reader: bool,
123    pub high_contrast: bool,
124    pub reduce_motion: bool,
125    pub text_scale: Option<f32>,
126    pub ui_scale: Option<f32>,
127}
128
129#[derive(Clone, Debug, Default, PartialEq, Eq)]
130#[allow(
131    clippy::struct_excessive_bools,
132    reason = "each flag is an independent opt-in switch a developer sets"
133)]
134pub struct RunnerDiagnostics {
135    /// Debug overlays (only honoured in debug builds).
136    pub debug_overlay: bool,
137    pub perf_log: bool,
138    pub disable_scroll_fast_path: bool,
139    pub gpu_timestamps: bool,
140    pub gpu_dispatch_timestamps: bool,
141    pub profile_hud: bool,
142    pub profile_out: Option<PathBuf>,
143    pub presentation_profile: bool,
144    pub presentation_timing: bool,
145    /// Open windows without taking focus from the active application.
146    pub window_no_activate: bool,
147    /// Restore the always-refresh hosted pump for paired host measurements.
148    pub host_perf_baseline: bool,
149    pub hosted_pump_timing: bool,
150    /// The run was promised the product's font catalog (`TILO_REQUIRE_FONTS=1`), so a
151    /// process that finds none stops rather than setting text in the host's faces.
152    pub fonts_required: bool,
153}
154
155pub const REVEAL_ENV: &str = "TILO_WINDOW_REVEAL";
156
157/// The variable a launch sets (`1`) for a process started with no window: the app takes its
158/// actions and publishes what it offers, and makes a window only once a shell asks it for one.
159pub const NO_WINDOW_ENV: &str = "TILO_NO_WINDOW";
160
161/// The seconds a process the daemon started with no window runs on with no call for, after
162/// which it ends: the daemon starts it again on the next call. A process the session starts
163/// with no window is given none, and runs until the session ends it.
164pub const NO_WINDOW_IDLE_ENV: &str = "TILO_NO_WINDOW_IDLE";
165
166#[derive(Clone, Debug, Default, PartialEq)]
167pub struct ProcessEnvironment {
168    pub identity: ProcessIdentity,
169    pub paths: ProcessPaths,
170    pub accessibility: AccessibilityInputs,
171    /// The user's preferred locale, as a POSIX or BCP 47 tag.
172    pub locale: Option<String>,
173    pub desktop: Option<String>,
174    pub diagnostics: RunnerDiagnostics,
175    pub dev_session: Option<PathBuf>,
176    pub ui_graph_dir: Option<PathBuf>,
177    pub reveal: Option<String>,
178    pub windowless: bool,
179    /// How long a process with no window runs on with no call before it ends
180    /// ([`NO_WINDOW_IDLE_ENV`]): `None` for one that stays until it is ended.
181    pub no_window_idle: Option<std::time::Duration>,
182}
183
184impl ProcessEnvironment {
185    /// Whether this process runs on the loop that opens no display: the daemon started it with
186    /// no window, and named the period nothing calls it for. Nothing can ask such a process for
187    /// a window, so it needs no display at all.
188    #[must_use]
189    pub fn no_window(&self) -> bool {
190        self.windowless && self.no_window_idle.is_some()
191    }
192}
193
194static INSTALLED: RwLock<Option<Arc<ProcessEnvironment>>> = RwLock::new(None);
195
196/// A POSIX locale value (`de_DE.UTF-8`, or a `LANGUAGE` list such as
197/// `de:en_US`, whose first entry wins) as a language identifier. `C`, `POSIX`,
198/// empty and malformed values name none.
199pub fn parse_posix_locale(locale: &str) -> Option<LanguageIdentifier> {
200    let first = locale.split(':').next().unwrap_or(locale);
201    if !tilo_paths::names_language(first) {
202        return None;
203    }
204    tilo_paths::locale_tag(first).parse().ok()
205}
206
207/// The user's message locale from the variables `var` reads: `LC_ALL`, `LC_MESSAGES`,
208/// `LANGUAGE`, then `LANG`. The first variable with a usable value decides, and an
209/// explicit `C`/`POSIX` there means source copy.
210#[cfg(any(feature = "native", test))]
211pub(crate) fn locale_from_vars(var: impl Fn(&str) -> Option<String>) -> Option<String> {
212    for name in ["LC_ALL", "LC_MESSAGES", "LANGUAGE", "LANG"] {
213        let Some(value) = var(name) else {
214            continue;
215        };
216        if value.trim().is_empty() {
217            continue;
218        }
219        if !tilo_paths::names_language(&value) {
220            return None;
221        }
222        if parse_posix_locale(&value).is_some() {
223            return Some(value);
224        }
225    }
226    None
227}
228
229pub fn install_environment(environment: ProcessEnvironment) {
230    if let Ok(mut slot) = INSTALLED.write() {
231        *slot = Some(Arc::new(environment));
232    }
233}
234
235/// The host inputs for this process: the installed ones, else (with `native`) what the
236/// runner reads from the process environment afresh on each call, else none.
237pub fn environment() -> Arc<ProcessEnvironment> {
238    if let Some(installed) = INSTALLED.read().ok().and_then(|slot| slot.clone()) {
239        return installed;
240    }
241    #[cfg(feature = "native")]
242    return Arc::new(process_environment());
243    #[cfg(not(feature = "native"))]
244    Arc::new(ProcessEnvironment::default())
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250
251    #[test]
252    fn config_dir_falls_back_to_home() {
253        let paths = ProcessPaths {
254            home: Some("/home/ada".into()),
255            ..ProcessPaths::default()
256        };
257        assert_eq!(paths.config_dir(), Some(PathBuf::from("/home/ada/.config")));
258        let paths = ProcessPaths {
259            home: Some("/home/ada".into()),
260            config_home: Some("/cfg".into()),
261            ..ProcessPaths::default()
262        };
263        assert_eq!(paths.config_dir(), Some(PathBuf::from("/cfg")));
264    }
265
266    #[test]
267    fn cache_dir_falls_back_to_home() {
268        let paths = ProcessPaths {
269            home: Some("/home/ada".into()),
270            ..ProcessPaths::default()
271        };
272        assert_eq!(paths.cache_dir(), Some(PathBuf::from("/home/ada/.cache")));
273        let paths = ProcessPaths {
274            home: Some("/home/ada".into()),
275            cache_home: Some("/run/tilo/app/.cache".into()),
276            ..ProcessPaths::default()
277        };
278        assert_eq!(
279            paths.cache_dir(),
280            Some(PathBuf::from("/run/tilo/app/.cache"))
281        );
282        assert_eq!(ProcessPaths::default().cache_dir(), None);
283    }
284
285    #[test]
286    fn an_explicit_c_locale_ends_the_environment_search() {
287        let env = |vars: &'static [(&'static str, &'static str)]| {
288            move |name: &str| {
289                vars.iter()
290                    .find(|(key, _)| *key == name)
291                    .map(|(_, value)| (*value).to_owned())
292            }
293        };
294        let found = |vars| {
295            locale_from_vars(env(vars))
296                .and_then(|value| parse_posix_locale(&value))
297                .map(|l| l.to_string())
298        };
299        assert_eq!(
300            found(&[("LC_ALL", "C.UTF-8"), ("LANG", "de_DE.UTF-8")]),
301            None
302        );
303        assert_eq!(
304            found(&[("LC_ALL", ""), ("LANG", "de_DE.UTF-8")]).as_deref(),
305            Some("de-DE")
306        );
307        assert_eq!(
308            found(&[("LC_MESSAGES", "not a locale!"), ("LANG", "fr_FR")]).as_deref(),
309            Some("fr-FR"),
310            "a malformed value is skipped"
311        );
312        assert_eq!(found(&[]), None);
313    }
314}