//! `HEXWORK_*` environment overrides (docs/05 §5.3, README env table). //! //! Pure layer: no crossterm, no terminal I/O. It reads the five override //! variables the README documents, parses them leniently, and applies them //! to a minimal capability mirror. //! //! Design trace: //! - docs/05 §5.3: detect-and-adapt automatically; every adaptation is logged //! once, and an override silences the corresponding notice. //! - `read_env` is the only impure function here (process env reads); all //! parsing (`parse_flag`, `parse_scale`) and `apply` are pure and unit-tested. //! - [`CapabilitiesView`] is a *minimal mirror* of //! `hexwork_term::Capabilities` (parent-owned, lives in //! `crates/hexwork-term/src/lib.rs`). The parent maps //! `Capabilities -> CapabilitiesView` at wiring, calls [`apply`], then maps //! back: //! //! | `Capabilities` field | `CapabilitiesView` field | touched by | //! |----------------------|--------------------------|--------------| //! | `truecolor` | `truecolor` | `FORCE_TC` / `FORCE_256` / `NO_COLOR` | //! | `unicode` | `unicode` | `FORCE_ASCII` | //! | `mouse` | — (not mirrored) | never here; opt-in parent-side | //! | `size` | — (not mirrored) | never here; probed by the backend | //! //! `HEXWORK_SCALE` never touches capabilities; the parent feeds //! [`EnvOverride::scale`] to the render adaptive-scale instead. //! `HEXWORK_FORCE_256` clears `truecolor` in the mirror (256-color is "not //! truecolor"); the parent distinguishes the 256 path from the no-color //! path via the raw [`EnvOverride`] flags, not via the view. /// Leniently parsed `HEXWORK_*` overrides (README env table, matched exactly). #[derive(Clone, Debug, Default, PartialEq)] pub struct EnvOverride { /// `HEXWORK_FORCE_TC=1`: force the truecolor path even if the probe disagrees. pub force_tc: bool, /// `HEXWORK_FORCE_256=1`: force the 256-color LUT path. pub force_256: bool, /// `HEXWORK_NO_COLOR=1`: force the no-color density + bold path. pub no_color: bool, /// `HEXWORK_FORCE_ASCII=1`: force ASCII-only glyphs (no box-drawing / half-blocks). pub force_ascii: bool, /// `HEXWORK_SCALE=0.5`: fixed render scale (disables adaptive scaling). /// `None` when unset or unparsable. pub scale: Option, } /// Minimal mirror of `hexwork_term::Capabilities` (see module docs for mapping). #[derive(Clone, Debug, PartialEq, Eq)] pub struct CapabilitiesView { /// True when the 24-bit truecolor path is active. pub truecolor: bool, /// True when box-drawing + half-block + special glyphs may be used. pub unicode: bool, } /// Lenient flag parse: `"1"` / `"true"` / `"yes"` (any case, padded) are true; /// anything else (including unset, `"0"`, `"false"`, `""`) is false. pub fn parse_flag(raw: &str) -> bool { matches!( raw.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" ) } /// Lenient scale parse: a finite, strictly positive `f32`, else `None`. /// /// Rejects `NaN` / infinities (they parse as `f32` but are unusable scales) /// and zero/negatives (a zero scale would collapse the frame; a negative one /// is meaningless). Whitespace-padded values are accepted. pub fn parse_scale(raw: &str) -> Option { match raw.trim().parse::() { Ok(f) if f.is_finite() && f > 0.0 => Some(f), _ => None, } } fn flag(name: &str) -> bool { std::env::var(name).map(|v| parse_flag(&v)).unwrap_or(false) } /// Read the five `HEXWORK_*` overrides from the process environment. /// /// | Variable | Field | Effect | /// |---|---|---| /// | `HEXWORK_FORCE_TC` | `force_tc` | Force truecolor path even if the probe disagrees | /// | `HEXWORK_FORCE_256` | `force_256` | Force 256-color LUT path | /// | `HEXWORK_NO_COLOR` | `no_color` | Force no-color density + bold path | /// | `HEXWORK_FORCE_ASCII` | `force_ascii` | Force ASCII-only glyphs | /// | `HEXWORK_SCALE` | `scale` | Fixed render scale (disables adaptive scaling) | pub fn read_env() -> EnvOverride { EnvOverride { force_tc: flag("HEXWORK_FORCE_TC"), force_256: flag("HEXWORK_FORCE_256"), no_color: flag("HEXWORK_NO_COLOR"), force_ascii: flag("HEXWORK_FORCE_ASCII"), scale: std::env::var("HEXWORK_SCALE") .ok() .and_then(|v| parse_scale(&v)), } } /// Apply overrides to a capability view. /// /// Precedence order (strongest first), chosen so the safest floor always wins: /// 1. `no_color` clears `truecolor` — an explicit opt-out of color beats any /// opt-in, including `force_tc`. /// 2. `force_tc` sets `truecolor` — the big hammer beats `force_256`. /// 3. `force_256` clears `truecolor` in the mirror (the parent still tells the /// 256 path apart from the no-color path via the raw override flags). /// 4. `force_ascii` clears `unicode` — orthogonal to the color bits. /// 5. `scale` never touches capabilities (parent-side render concern). pub fn apply(caps: &mut CapabilitiesView, o: &EnvOverride) { if o.no_color { caps.truecolor = false; } else if o.force_tc { caps.truecolor = true; } else if o.force_256 { caps.truecolor = false; } if o.force_ascii { caps.unicode = false; } } #[cfg(test)] mod tests { use super::*; use std::sync::Mutex; /// Env vars are process-global; serialize every test that touches them. /// (Pure `parse_flag` / `parse_scale` tests need no lock.) static ENV_LOCK: Mutex<()> = Mutex::new(()); /// Set vars, run `f`, restore prior values. Caller must hold `ENV_LOCK`. fn with_vars(vars: &[(&str, Option<&str>)], f: impl FnOnce()) { let saved: Vec<(&str, Option)> = vars .iter() .map(|(k, _)| (*k, std::env::var(k).ok())) .collect(); for (k, v) in vars { match v { Some(s) => std::env::set_var(k, s), None => std::env::remove_var(k), } } f(); for (k, v) in saved { match v { Some(s) => std::env::set_var(k, s), None => std::env::remove_var(k), } } } const ALL: [&str; 5] = [ "HEXWORK_FORCE_TC", "HEXWORK_FORCE_256", "HEXWORK_NO_COLOR", "HEXWORK_FORCE_ASCII", "HEXWORK_SCALE", ]; fn clear_all() -> Vec<(&'static str, Option<&'static str>)> { ALL.iter().map(|k| (*k, None)).collect() } #[test] fn flag_truthy_spellings() { for s in ["1", "true", "yes", "TRUE", "Yes", " 1 "] { assert!(parse_flag(s), "{s:?} should be truthy"); } } #[test] fn flag_falsy_spellings() { for s in ["", "0", "false", "no", "2", "banana", " "] { assert!(!parse_flag(s), "{s:?} should be falsy"); } } #[test] fn scale_accepts_positive_finite() { assert_eq!(parse_scale("0.5"), Some(0.5)); assert_eq!(parse_scale(" 1 "), Some(1.0)); assert_eq!(parse_scale("2.0"), Some(2.0)); } #[test] fn scale_rejects_garbage() { for s in ["", "banana", "NaN", "inf", "-inf", "0", "-1", "0.0"] { assert_eq!(parse_scale(s), None, "{s:?} should be None"); } } #[test] fn read_env_defaults_when_unset() { let _g = ENV_LOCK.lock().unwrap(); with_vars(&clear_all(), || { assert_eq!(read_env(), EnvOverride::default()); }); } #[test] fn read_env_picks_up_each_var() { let _g = ENV_LOCK.lock().unwrap(); with_vars( &[ ("HEXWORK_FORCE_TC", Some("1")), ("HEXWORK_FORCE_256", Some("yes")), ("HEXWORK_NO_COLOR", Some("true")), ("HEXWORK_FORCE_ASCII", Some("1")), ("HEXWORK_SCALE", Some("0.5")), ], || { let o = read_env(); assert!(o.force_tc); assert!(o.force_256); assert!(o.no_color); assert!(o.force_ascii); assert_eq!(o.scale, Some(0.5)); }, ); } #[test] fn read_env_bad_scale_is_none() { let _g = ENV_LOCK.lock().unwrap(); with_vars(&[("HEXWORK_SCALE", Some("banana"))], || { assert_eq!(read_env().scale, None); }); } #[test] fn apply_no_color_beats_force_tc() { let mut caps = CapabilitiesView { truecolor: true, unicode: true, }; let o = EnvOverride { force_tc: true, no_color: true, ..EnvOverride::default() }; apply(&mut caps, &o); assert!(!caps.truecolor); } #[test] fn apply_force_tc_beats_force_256_and_probe_false() { let mut caps = CapabilitiesView { truecolor: false, unicode: true, }; let o = EnvOverride { force_tc: true, force_256: true, ..EnvOverride::default() }; apply(&mut caps, &o); assert!(caps.truecolor); } #[test] fn apply_force_256_clears_truecolor() { let mut caps = CapabilitiesView { truecolor: true, unicode: true, }; let o = EnvOverride { force_256: true, ..EnvOverride::default() }; apply(&mut caps, &o); assert!(!caps.truecolor); } #[test] fn apply_force_ascii_clears_unicode_only() { let mut caps = CapabilitiesView { truecolor: true, unicode: true, }; let o = EnvOverride { force_ascii: true, ..EnvOverride::default() }; apply(&mut caps, &o); assert!(!caps.unicode); assert!(caps.truecolor); } #[test] fn apply_noop_without_overrides() { let mut caps = CapabilitiesView { truecolor: true, unicode: true, }; apply(&mut caps, &EnvOverride::default()); assert!(caps.truecolor); assert!(caps.unicode); } }