Something went wrong. Try again.
HEXWORK - A Lantern in the Deep: 3D ASCII terminal roguelike RPG in Rust.
Entirely designed and built by Muse Spark 1.3 to evaluate if I like the model.
Something went wrong. Try again.
10 kB · 302 lines
Rust
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303//! `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<f32>,}
/// 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<f32> { match raw.trim().parse::<f32>() { 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<String>)> = 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); }}