use std::path::{Path, PathBuf};
use std::time::Duration;
pub const FALLBACK_VAR: &str = "NATIVE_GUI_EXAMPLE_AUTOCLOSE_MS";
const APP_PREFIX: &str = "NATIVE_GUI_";
const APP_SUFFIX: &str = "_AUTOCLOSE_MS";
pub const BOUNDED_POLL_INTERVAL: Duration = Duration::from_millis(8);
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Autoclose {
budget: Duration,
source: String,
}
impl Autoclose {
pub fn budget(&self) -> Duration {
self.budget
}
pub fn source(&self) -> &str {
&self.source
}
pub fn report(&self) -> String {
format!(
"autoclose after {} ms (via {})",
self.budget.as_millis(),
self.source
)
}
}
pub fn app_name_from_path(path: &Path) -> Option<&str> {
path.file_stem().and_then(|stem| stem.to_str())
}
pub fn autoclose_var(app_name: &str) -> String {
let without_gui = app_name.strip_prefix("gui_").unwrap_or(app_name);
let slug = without_gui
.strip_prefix("mock_")
.unwrap_or(without_gui)
.to_ascii_uppercase();
format!("{APP_PREFIX}{slug}{APP_SUFFIX}")
}
pub fn var_names(app_name: &str) -> Vec<String> {
let primary = autoclose_var(app_name);
let mut names = vec![primary.clone()];
let normalized: String = primary
.chars()
.map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
.collect();
if normalized != primary {
names.push(normalized);
}
names.push(FALLBACK_VAR.to_owned());
names
}
pub fn resolve<F>(app_name: Option<&str>, lookup: F) -> Option<Autoclose>
where
F: Fn(&str) -> Option<String>,
{
let candidates = match app_name {
Some(name) => var_names(name),
None => vec![FALLBACK_VAR.to_owned()],
};
for name in candidates {
let Some(raw) = lookup(&name) else {
continue;
};
match raw.trim().parse::<u64>() {
Ok(ms) => {
return Some(Autoclose {
budget: Duration::from_millis(ms),
source: name,
})
}
Err(_) => {
eprintln!("[{name}] ignoring non-numeric value {raw:?} (expected milliseconds)")
}
}
}
None
}
pub fn from_env() -> Option<Autoclose> {
let exe = if cfg!(miri) {
std::env::args_os().next().map(PathBuf::from)
} else {
std::env::current_exe()
.ok()
.or_else(|| std::env::args_os().next().map(PathBuf::from))
};
let app_name = exe.as_deref().and_then(app_name_from_path);
resolve(app_name, |key| std::env::var(key).ok())
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
fn lookup(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
let map: HashMap<String, String> = pairs
.iter()
.map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))
.collect();
move |key: &str| map.get(key).cloned()
}
#[test]
fn app_var_mirrors_the_capture_runner_spelling() {
assert_eq!(
autoclose_var("gui_todo_board"),
"NATIVE_GUI_TODO_BOARD_AUTOCLOSE_MS"
);
assert_eq!(
autoclose_var("mock_todo_board"),
"NATIVE_GUI_TODO_BOARD_AUTOCLOSE_MS"
);
assert_eq!(autoclose_var("gui_paint"), "NATIVE_GUI_PAINT_AUTOCLOSE_MS");
assert_eq!(
autoclose_var("gui_widget_text_input"),
"NATIVE_GUI_WIDGET_TEXT_INPUT_AUTOCLOSE_MS"
);
assert_eq!(
autoclose_var("first_app"),
"NATIVE_GUI_FIRST_APP_AUTOCLOSE_MS"
);
assert_eq!(
autoclose_var("gui_gui_thing"),
"NATIVE_GUI_GUI_THING_AUTOCLOSE_MS"
);
}
#[test]
fn app_name_comes_from_the_executable_file_stem() {
assert_eq!(
app_name_from_path(&PathBuf::from("/repo/target/debug/examples/gui_todo_board")),
Some("gui_todo_board")
);
assert_eq!(
app_name_from_path(&PathBuf::from("C:/repo/target/debug/gui_paint.exe")),
Some("gui_paint")
);
assert_eq!(app_name_from_path(&PathBuf::from("")), None);
}
#[test]
fn var_names_prefers_the_specific_spelling_then_the_fallback() {
assert_eq!(
var_names("gui_todo_board"),
vec!["NATIVE_GUI_TODO_BOARD_AUTOCLOSE_MS", FALLBACK_VAR]
);
assert_eq!(
var_names("my-app"),
vec![
"NATIVE_GUI_MY-APP_AUTOCLOSE_MS",
"NATIVE_GUI_MY_APP_AUTOCLOSE_MS",
FALLBACK_VAR
]
);
}
#[test]
fn resolve_prefers_the_app_specific_variable_over_the_fallback() {
let budget = resolve(
Some("gui_todo_board"),
lookup(&[
("NATIVE_GUI_TODO_BOARD_AUTOCLOSE_MS", "1200"),
(FALLBACK_VAR, "45000"),
]),
)
.expect("the specific variable wins");
assert_eq!(budget.budget(), Duration::from_millis(1200));
assert_eq!(budget.source(), "NATIVE_GUI_TODO_BOARD_AUTOCLOSE_MS");
assert_eq!(
budget.report(),
"autoclose after 1200 ms (via NATIVE_GUI_TODO_BOARD_AUTOCLOSE_MS)"
);
}
#[test]
fn resolve_falls_back_to_the_shared_variable() {
let budget = resolve(Some("gui_todo_board"), lookup(&[(FALLBACK_VAR, " 45000 ")]))
.expect("the shared fallback bounds batch runs");
assert_eq!(budget.budget(), Duration::from_millis(45_000));
assert_eq!(budget.source(), FALLBACK_VAR);
}
#[test]
fn resolve_treats_an_invalid_value_as_unset_and_keeps_looking() {
let budget = resolve(
Some("gui_paint"),
lookup(&[
("NATIVE_GUI_PAINT_AUTOCLOSE_MS", "soon"),
(FALLBACK_VAR, "9000"),
]),
)
.expect("the fallback still applies");
assert_eq!(budget.budget(), Duration::from_millis(9000));
assert_eq!(budget.source(), FALLBACK_VAR);
assert_eq!(
resolve(
Some("gui_paint"),
lookup(&[("NATIVE_GUI_PAINT_AUTOCLOSE_MS", "soon")])
),
None,
"an invalid value alone means no autoclose"
);
}
#[test]
fn resolve_without_any_variable_disables_autoclose() {
assert_eq!(resolve(Some("gui_todo_board"), lookup(&[])), None);
assert_eq!(resolve(None, lookup(&[])), None);
}
#[test]
fn resolve_without_an_app_name_still_honours_the_fallback() {
let budget = resolve(None, lookup(&[(FALLBACK_VAR, "8000")]))
.expect("the shared fallback needs no app name");
assert_eq!(budget.budget(), Duration::from_millis(8000));
}
#[test]
fn resolve_accepts_a_zero_budget() {
let budget = resolve(
Some("gui_paint"),
lookup(&[("NATIVE_GUI_PAINT_AUTOCLOSE_MS", "0")]),
)
.expect("zero is a valid budget");
assert_eq!(budget.budget(), Duration::ZERO);
}
}