native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
//! Bounded-run budgets for unattended capture and smoke harnesses.
//!
//! A capture or CI runner has to photograph an app's window and then have the
//! process go away *by itself*: a `TERM` from the script always looks like a
//! hang, and it skips the app's own teardown. The convention — first
//! established by `gui_paint`'s `NATIVE_GUI_PAINT_AUTOCLOSE_MS` and generalized by
//!  is one environment variable carrying a millisecond budget:
//!
//! - `NATIVE_GUI_<APP>_AUTOCLOSE_MS` — this app's own budget, where `<APP>` is the
//!   executable's file stem with a `gui_`/`mock_` prefix removed and the rest
//!   uppercased (`gui_todo_board` → `NATIVE_GUI_TODO_BOARD_AUTOCLOSE_MS`). That is
//!   the spelling `scripts/capture_macos_screenshots.sh` and
//!   `scripts/run_widget_examples_headless.sh` export.
//! - [`FALLBACK_VAR`] (`NATIVE_GUI_EXAMPLE_AUTOCLOSE_MS`) — a shared fallback, so a
//!   runner can bound a whole batch without knowing every app name.
//!
//! The app-specific variable wins over the fallback, and a variable that is
//! set but not a valid integer is ignored with a warning rather than parsed as
//! zero, so a typo can never silently shorten a capture. No variable at all
//! means "no autoclose": the app behaves exactly as it does for a human and
//! runs until its window closes.
//!
//! [`from_env`] resolves the budget this process was launched with;
//! [`crate::Ui::run_bounded`] and [`crate::Ui::run_bounded_with`] are the
//! runners that honour it. The resolution is split from the environment read
//! ([`resolve`] takes the lookup as a parameter) so the precedence rules are
//! unit-testable without mutating process state.

use std::path::{Path, PathBuf};
use std::time::Duration;

/// The shared fallback autoclose variable (`NATIVE_GUI_EXAMPLE_AUTOCLOSE_MS`).
pub const FALLBACK_VAR: &str = "NATIVE_GUI_EXAMPLE_AUTOCLOSE_MS";

/// Prefix and suffix of the app-specific autoclose variable.
const APP_PREFIX: &str = "NATIVE_GUI_";
const APP_SUFFIX: &str = "_AUTOCLOSE_MS";

/// How often a bounded run polls for events between budget checks.
///
/// Matches the `AUTOCLOSE_POLL_INTERVAL` the hand-rolled example loops use, so
/// a bounded run behaves like the app's normal loop instead of a new one.
pub const BOUNDED_POLL_INTERVAL: Duration = Duration::from_millis(8);

/// A resolved autoclose budget and the variable that supplied it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Autoclose {
    budget: Duration,
    source: String,
}

impl Autoclose {
    /// The resolved wall-clock budget.
    pub fn budget(&self) -> Duration {
        self.budget
    }

    /// Name of the environment variable the budget came from.
    pub fn source(&self) -> &str {
        &self.source
    }

    /// The evidence line capture and smoke logs use to tell a self-terminated
    /// run apart from one the runner had to kill.
    pub fn report(&self) -> String {
        format!(
            "autoclose after {} ms (via {})",
            self.budget.as_millis(),
            self.source
        )
    }
}

/// The file stem of `path` (`gui_todo_board` for `…/examples/gui_todo_board`).
///
/// Returns `None` for a path with no file name (or one that is not valid
/// UTF-8), which leaves the caller with the shared fallback variable only.
pub fn app_name_from_path(path: &Path) -> Option<&str> {
    path.file_stem().and_then(|stem| stem.to_str())
}

/// The `NATIVE_GUI_<APP>_AUTOCLOSE_MS` spelling an app name maps to.
///
/// Mirrors the runners' shell (`${example#gui_}`, then `${…#mock_}`, then
/// uppercase), so a name that is also an example binary resolves to the same
/// variable the capture scripts export.
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}")
}

/// Every candidate variable name for `app_name`, most specific first.
///
/// The first entry is always [`autoclose_var`]. When the derived name cannot
/// be written as a shell variable (a binary called `my-app`, say, which is
/// exported as `NATIVE_GUI_MY_APP_AUTOCLOSE_MS`), the normalized spelling is offered
/// as a second candidate; [`FALLBACK_VAR`] is appended last.
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
}

/// Resolves the budget from `lookup`, trying the app-specific names before
/// [`FALLBACK_VAR`].
///
/// `app_name` is the executable's file stem (`None` — an unreadable
/// `current_exe`, say — leaves only the fallback). A candidate that is unset
/// is skipped silently; a candidate that is set but not an integer is skipped
/// with a warning, so a typo falls through to the next candidate instead of
/// being read as "no budget" or as zero.
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
}

/// Resolves the autoclose budget this process was launched with.
///
/// The app name comes from the running executable, so an app-bootstrap binary
/// answers the same `NATIVE_GUI_<APP>_AUTOCLOSE_MS` the capture runner exports
/// without any per-app plumbing.
pub fn from_env() -> Option<Autoclose> {
    // Miri isolates `current_exe`/`readlink`; fall back to argv[0] there so
    // App bootstrap unit tests can run under `cargo miri test`.
    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]
        );
        // A dashed name cannot be exported by a POSIX shell, so the
        // normalized spelling is offered as a second candidate.
        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() {
        // A typo in the specific variable must not read as zero (which would
        // end a capture instantly) nor disable the batch fallback.
        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() {
        // Zero is a deliberate "stop as soon as the loop is entered" (used by
        // tests), and it is spelled with an explicit `0`, not a typo.
        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);
    }
}