use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use unic_langid::LanguageIdentifier;
#[cfg(feature = "native")]
mod native;
#[cfg(feature = "native")]
pub use native::process_environment;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContinuationMetadata {
pub schema_version: u16,
pub bytes: Vec<u8>,
}
#[cfg(feature = "native")]
pub(crate) fn decode_continuation(hex: &str, schema: &str) -> Option<ContinuationMetadata> {
let bytes = hex::decode(hex).ok()?;
let schema_version = schema.parse().ok()?;
(!bytes.is_empty() && bytes.len() <= 32 * 1024).then_some(ContinuationMetadata {
schema_version,
bytes,
})
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ProcessIdentity {
pub app_id: Option<String>,
pub development_app_id: Option<String>,
pub app_name: Option<String>,
pub workspace_id: Option<String>,
pub account_name: Option<String>,
pub continuity_resume: Option<ContinuationMetadata>,
pub continuity_instance: Option<String>,
pub participation: Option<String>,
pub collab_service_configured: bool,
pub managed_agent_context: bool,
}
#[must_use]
pub fn media_player_bus_name(app_id: &str) -> String {
format!("org.mpris.MediaPlayer2.{app_id}")
}
impl ProcessIdentity {
#[must_use]
pub fn media_player_bus_name(&self, fallback_app_id: &str) -> String {
media_player_bus_name(self.app_id.as_deref().unwrap_or(fallback_app_id))
}
}
pub const FONT_INDEX_ENV: &str = "TILO_FONT_INDEX";
pub const FONTS_REQUIRED_ENV: &str = "TILO_REQUIRE_FONTS";
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ProcessPaths {
pub user_home: Option<PathBuf>,
pub home: Option<PathBuf>,
pub config_home: Option<PathBuf>,
pub cache_home: Option<PathBuf>,
pub pipeline_seed: Option<PathBuf>,
pub font_index: Option<PathBuf>,
pub font_catalog: Option<PathBuf>,
pub font_artifact_cache: Option<PathBuf>,
}
impl ProcessPaths {
pub fn config_dir(&self) -> Option<PathBuf> {
self.config_home
.clone()
.or_else(|| self.home.as_ref().map(|home| home.join(".config")))
}
pub fn cache_dir(&self) -> Option<PathBuf> {
self.cache_home
.clone()
.or_else(|| self.home.as_ref().map(|home| home.join(".cache")))
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct AccessibilityInputs {
pub screen_reader: bool,
pub high_contrast: bool,
pub reduce_motion: bool,
pub text_scale: Option<f32>,
pub ui_scale: Option<f32>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[allow(
clippy::struct_excessive_bools,
reason = "each flag is an independent opt-in switch a developer sets"
)]
pub struct RunnerDiagnostics {
pub debug_overlay: bool,
pub perf_log: bool,
pub disable_scroll_fast_path: bool,
pub gpu_timestamps: bool,
pub gpu_dispatch_timestamps: bool,
pub profile_hud: bool,
pub profile_out: Option<PathBuf>,
pub presentation_profile: bool,
pub presentation_timing: bool,
pub window_no_activate: bool,
pub host_perf_baseline: bool,
pub hosted_pump_timing: bool,
pub fonts_required: bool,
}
pub const REVEAL_ENV: &str = "TILO_WINDOW_REVEAL";
pub const NO_WINDOW_ENV: &str = "TILO_NO_WINDOW";
pub const NO_WINDOW_IDLE_ENV: &str = "TILO_NO_WINDOW_IDLE";
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ProcessEnvironment {
pub identity: ProcessIdentity,
pub paths: ProcessPaths,
pub accessibility: AccessibilityInputs,
pub locale: Option<String>,
pub desktop: Option<String>,
pub diagnostics: RunnerDiagnostics,
pub dev_session: Option<PathBuf>,
pub ui_graph_dir: Option<PathBuf>,
pub reveal: Option<String>,
pub windowless: bool,
pub no_window_idle: Option<std::time::Duration>,
}
impl ProcessEnvironment {
#[must_use]
pub fn no_window(&self) -> bool {
self.windowless && self.no_window_idle.is_some()
}
}
static INSTALLED: RwLock<Option<Arc<ProcessEnvironment>>> = RwLock::new(None);
pub fn parse_posix_locale(locale: &str) -> Option<LanguageIdentifier> {
let first = locale.split(':').next().unwrap_or(locale);
if !tilo_paths::names_language(first) {
return None;
}
tilo_paths::locale_tag(first).parse().ok()
}
#[cfg(any(feature = "native", test))]
pub(crate) fn locale_from_vars(var: impl Fn(&str) -> Option<String>) -> Option<String> {
for name in ["LC_ALL", "LC_MESSAGES", "LANGUAGE", "LANG"] {
let Some(value) = var(name) else {
continue;
};
if value.trim().is_empty() {
continue;
}
if !tilo_paths::names_language(&value) {
return None;
}
if parse_posix_locale(&value).is_some() {
return Some(value);
}
}
None
}
pub fn install_environment(environment: ProcessEnvironment) {
if let Ok(mut slot) = INSTALLED.write() {
*slot = Some(Arc::new(environment));
}
}
pub fn environment() -> Arc<ProcessEnvironment> {
if let Some(installed) = INSTALLED.read().ok().and_then(|slot| slot.clone()) {
return installed;
}
#[cfg(feature = "native")]
return Arc::new(process_environment());
#[cfg(not(feature = "native"))]
Arc::new(ProcessEnvironment::default())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn config_dir_falls_back_to_home() {
let paths = ProcessPaths {
home: Some("/home/ada".into()),
..ProcessPaths::default()
};
assert_eq!(paths.config_dir(), Some(PathBuf::from("/home/ada/.config")));
let paths = ProcessPaths {
home: Some("/home/ada".into()),
config_home: Some("/cfg".into()),
..ProcessPaths::default()
};
assert_eq!(paths.config_dir(), Some(PathBuf::from("/cfg")));
}
#[test]
fn cache_dir_falls_back_to_home() {
let paths = ProcessPaths {
home: Some("/home/ada".into()),
..ProcessPaths::default()
};
assert_eq!(paths.cache_dir(), Some(PathBuf::from("/home/ada/.cache")));
let paths = ProcessPaths {
home: Some("/home/ada".into()),
cache_home: Some("/run/tilo/app/.cache".into()),
..ProcessPaths::default()
};
assert_eq!(
paths.cache_dir(),
Some(PathBuf::from("/run/tilo/app/.cache"))
);
assert_eq!(ProcessPaths::default().cache_dir(), None);
}
#[test]
fn an_explicit_c_locale_ends_the_environment_search() {
let env = |vars: &'static [(&'static str, &'static str)]| {
move |name: &str| {
vars.iter()
.find(|(key, _)| *key == name)
.map(|(_, value)| (*value).to_owned())
}
};
let found = |vars| {
locale_from_vars(env(vars))
.and_then(|value| parse_posix_locale(&value))
.map(|l| l.to_string())
};
assert_eq!(
found(&[("LC_ALL", "C.UTF-8"), ("LANG", "de_DE.UTF-8")]),
None
);
assert_eq!(
found(&[("LC_ALL", ""), ("LANG", "de_DE.UTF-8")]).as_deref(),
Some("de-DE")
);
assert_eq!(
found(&[("LC_MESSAGES", "not a locale!"), ("LANG", "fr_FR")]).as_deref(),
Some("fr-FR"),
"a malformed value is skipped"
);
assert_eq!(found(&[]), None);
}
}