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