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