use std::collections::BTreeMap;
use std::fmt;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant, SystemTime};
use iced_core::theme;
use icedwright_trace::{TraceConfig, TraceError, TraceMode};
use icedwright_types::units::{Logical, ScaleFactor};
use icedwright_types::{Size, VirtualDuration};
use crate::effects::{ExternalSource, TaskRules};
use crate::error::ConfigError;
use crate::fakes::FakeClipboard;
use crate::harness::{Harness, TestProgram};
use crate::headed::{Headed, HeadedLink};
use crate::observer::StepObserver;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HangAfter {
After(Duration),
Off,
}
impl Default for HangAfter {
fn default() -> Self {
Self::After(Duration::from_secs(120))
}
}
#[cfg_attr(test, mockall::automock)]
pub trait RealClock: Send + Sync {
fn now(&self) -> Instant;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemClock;
impl RealClock for SystemClock {
#[expect(
clippy::disallowed_methods,
reason = "the hang detector is the one place that measures real time"
)]
fn now(&self) -> Instant {
Instant::now()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum Platform {
#[default]
X11,
Wayland,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum Draw {
#[default]
OnDemand,
EveryFrame,
}
#[must_use]
pub struct HarnessConfig<P: TestProgram> {
pub size: Option<Logical<Size>>,
pub scale_factor: ScaleFactor,
pub max_widget_scale: ScaleFactor,
pub system_theme: theme::Mode,
pub monitor_size: Logical<Size>,
pub wall_clock_start: SystemTime,
pub frame_interval: VirtualDuration,
pub default_timeout: VirtualDuration,
pub hang_after: HangAfter,
pub real_clock: Arc<dyn RealClock>,
pub platform: Platform,
pub preset: Option<&'static str>,
pub draw: Draw,
pub tasks: TaskRules<P>,
pub external_sources: Vec<ExternalSource>,
pub clipboard: FakeClipboard,
pub trace: TraceConfig,
pub out_dir: Option<PathBuf>,
pub variant: crate::snapshot::Variant,
pub system_fonts: bool,
pub observers: Vec<Box<dyn StepObserver<P>>>,
pub headed: Headed,
pub slow_mo: Option<Duration>,
pub headed_socket: Option<PathBuf>,
pub headed_link: Option<Box<dyn HeadedLink>>,
}
const WALL_CLOCK_START: Duration = Duration::from_secs(1_767_225_600);
impl<P: TestProgram> Default for HarnessConfig<P> {
fn default() -> Self {
Self {
size: None,
scale_factor: ScaleFactor::ONE,
max_widget_scale: ScaleFactor::ONE,
system_theme: theme::Mode::Light,
monitor_size: Logical(Size::new(1920.0, 1080.0)),
wall_clock_start: SystemTime::UNIX_EPOCH + WALL_CLOCK_START,
frame_interval: VirtualDuration::from_micros(16_667),
default_timeout: VirtualDuration::from_secs(5),
hang_after: HangAfter::default(),
real_clock: Arc::new(SystemClock),
platform: Platform::default(),
preset: None,
draw: Draw::default(),
tasks: TaskRules::default(),
external_sources: Vec::new(),
clipboard: FakeClipboard::default(),
trace: TraceConfig::default(),
out_dir: None,
variant: crate::snapshot::Variant::new(),
system_fonts: false,
observers: Vec::new(),
headed: Headed::Off,
slow_mo: None,
headed_socket: None,
headed_link: None,
}
}
}
impl<P: TestProgram> fmt::Debug for HarnessConfig<P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HarnessConfig")
.field("size", &self.size)
.field("scale_factor", &self.scale_factor)
.field("system_theme", &self.system_theme)
.field("frame_interval", &self.frame_interval)
.field("default_timeout", &self.default_timeout)
.field("hang_after", &self.hang_after)
.field("platform", &self.platform)
.field("preset", &self.preset)
.field("draw", &self.draw)
.field("tasks", &self.tasks)
.field("external_sources", &self.external_sources)
.field("clipboard", &self.clipboard)
.field("trace", &self.trace)
.field("out_dir", &self.out_dir)
.field("variant", &self.variant)
.field("observers", &self.observers.len())
.field("headed", &self.headed)
.field("slow_mo", &self.slow_mo)
.field("headed_socket", &self.headed_socket)
.finish_non_exhaustive()
}
}
macro_rules! setters {
($target:ident . $($path:ident).*) => {
pub fn size(mut self, size: impl Into<Logical<Size>>) -> Self {
self.$($path.)*size = Some(size.into());
self
}
pub fn scale_factor(mut self, factor: ScaleFactor) -> Self {
self.$($path.)*scale_factor = factor;
self
}
pub fn max_widget_scale(mut self, factor: ScaleFactor) -> Self {
self.$($path.)*max_widget_scale = factor;
self
}
pub fn system_theme(mut self, mode: theme::Mode) -> Self {
self.$($path.)*system_theme = mode;
self
}
pub fn monitor_size(mut self, size: impl Into<Logical<Size>>) -> Self {
self.$($path.)*monitor_size = size.into();
self
}
pub fn wall_clock_start(mut self, start: SystemTime) -> Self {
self.$($path.)*wall_clock_start = start;
self
}
pub fn frame_interval(mut self, interval: impl Into<VirtualDuration>) -> Self {
self.$($path.)*frame_interval = interval.into();
self
}
pub fn default_timeout(mut self, timeout: impl Into<VirtualDuration>) -> Self {
self.$($path.)*default_timeout = timeout.into();
self
}
pub fn hang_after(mut self, after: HangAfter) -> Self {
self.$($path.)*hang_after = after;
self
}
pub fn real_clock(mut self, clock: Arc<dyn RealClock>) -> Self {
self.$($path.)*real_clock = clock;
self
}
pub fn platform(mut self, platform: Platform) -> Self {
self.$($path.)*platform = platform;
self
}
pub fn preset(mut self, name: &'static str) -> Self {
self.$($path.)*preset = Some(name);
self
}
pub fn draw(mut self, draw: Draw) -> Self {
self.$($path.)*draw = draw;
self
}
pub fn tasks(mut self, rules: impl FnOnce(&mut TaskRules<P>)) -> Self {
rules(&mut self.$($path.)*tasks);
self
}
pub fn external_source(mut self, source: ExternalSource) -> Self {
self.$($path.)*external_sources.push(source);
self
}
pub fn clipboard(mut self, clipboard: FakeClipboard) -> Self {
self.$($path.)*clipboard = clipboard;
self
}
pub fn trace(mut self, trace: TraceConfig) -> Self {
self.$($path.)*trace = trace;
self
}
pub fn out_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.$($path.)*out_dir = Some(dir.into());
self
}
pub fn system_fonts(mut self, on: bool) -> Self {
self.$($path.)*system_fonts = on;
self
}
pub fn observer(mut self, observer: impl StepObserver<P> + 'static) -> Self {
self.$($path.)*observers.push(Box::new(observer));
self
}
pub fn headed(mut self, headed: Headed) -> Self {
self.$($path.)*headed = headed;
self
}
pub fn slow_mo(mut self, each: Duration) -> Self {
self.$($path.)*slow_mo = Some(each);
self
}
pub fn headed_socket(mut self, path: impl Into<PathBuf>) -> Self {
self.$($path.)*headed_socket = Some(path.into());
self
}
pub fn headed_link(mut self, link: impl HeadedLink + 'static) -> Self {
self.$($path.)*headed_link = Some(Box::new(link));
self
}
pub fn variant(mut self, variant: crate::snapshot::Variant) -> Self {
variant.configure(
&mut self.$($path.)*system_theme,
&mut self.$($path.)*size,
&mut self.$($path.)*scale_factor,
);
self.$($path.)*variant = variant;
self
}
};
}
impl<P: TestProgram> HarnessConfig<P> {
setters!(self.);
}
#[must_use]
pub struct HarnessBuilder<P: TestProgram> {
program: P,
config: HarnessConfig<P>,
}
impl<P: TestProgram> fmt::Debug for HarnessBuilder<P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HarnessBuilder")
.field("config", &self.config)
.finish_non_exhaustive()
}
}
impl<P: TestProgram> HarnessBuilder<P> {
pub(crate) fn new(program: P) -> Self {
Self {
program,
config: HarnessConfig::default(),
}
}
setters!(self.config);
pub fn build(self) -> crate::Result<Harness<P>> {
Harness::with_config(self.program, self.config)
}
}
const KNOWN: &[&str] = &[
OUT_DIR,
WATCHDOG,
TRACE,
TRACE_DIR,
TRACE_MAX_MB,
HEADED,
SLOW_MO,
"ICEDWRIGHT_STUDIO",
"ICEDWRIGHT_SCREENSHOTS",
"ICEDWRIGHT_UPDATE",
"ICEDWRIGHT_SEED",
"ICEDWRIGHT_COVERAGE",
"ICEDWRIGHT_REMOTE",
];
const OUT_DIR: &str = "ICEDWRIGHT_OUT_DIR";
const WATCHDOG: &str = "ICEDWRIGHT_WATCHDOG";
const TRACE: &str = "ICEDWRIGHT_TRACE";
const TRACE_DIR: &str = "ICEDWRIGHT_TRACE_DIR";
const TRACE_MAX_MB: &str = "ICEDWRIGHT_TRACE_MAX_MB";
const HEADED: &str = "ICEDWRIGHT_HEADED";
const SLOW_MO: &str = "ICEDWRIGHT_SLOW_MO";
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct EnvOverrides {
pub out_dir: Option<PathBuf>,
pub hang_after: Option<HangAfter>,
pub trace: Option<TraceMode>,
pub trace_dir: Option<PathBuf>,
pub trace_max_mb: Option<u64>,
pub headed: Option<Headed>,
pub slow_mo: Option<Duration>,
pub ci: bool,
pub runtime_dir: Option<PathBuf>,
pub unknown: Vec<String>,
}
impl EnvOverrides {
pub fn from_env() -> Result<&'static EnvOverrides, ConfigError> {
static PARSED: OnceLock<Result<EnvOverrides, ConfigError>> = OnceLock::new();
PARSED
.get_or_init(|| Self::from_vars(std::env::vars()))
.as_ref()
.map_err(Clone::clone)
}
pub fn from_vars(
vars: impl IntoIterator<Item = (String, String)>,
) -> Result<Self, ConfigError> {
let mut ci = false;
let mut runtime_dir = None;
let vars: BTreeMap<String, String> = vars
.into_iter()
.filter(|(name, value)| match name.as_str() {
"CI" => {
ci = !value.is_empty();
false
}
"XDG_RUNTIME_DIR" => {
runtime_dir = (!value.is_empty()).then(|| PathBuf::from(value));
false
}
name => name.starts_with("ICEDWRIGHT_"),
})
.collect();
let get = |name: &str| vars.get(name).cloned();
let mut overrides = EnvOverrides {
unknown: vars
.keys()
.filter(|name| !KNOWN.contains(&name.as_str()))
.cloned()
.collect(),
ci,
runtime_dir,
..EnvOverrides::default()
};
if let Some(value) = get(HEADED) {
overrides.headed = Some(Headed::parse(&value).ok_or_else(|| {
ConfigError::invalid(HEADED, value, "1 or on to watch, step to pause, or off")
})?);
}
if let Some(value) = get(SLOW_MO) {
overrides.slow_mo =
Some(parse_duration(&value).ok_or_else(|| {
ConfigError::invalid(SLOW_MO, value, "a duration such as 250ms")
})?);
}
let trace = TraceConfig::new()
.from_env(&|name: &str| get(name))
.map_err(|error| match error {
TraceError::BadEnv {
var,
value,
expected,
} => ConfigError::invalid(var, value, expected),
other => ConfigError::invalid(TRACE, other.to_string(), "a valid trace setting"),
})?;
if get(TRACE).is_some() {
overrides.trace = Some(trace.trace_mode());
}
if get(OUT_DIR).is_some() {
overrides.out_dir = Some(trace.output_dir().to_path_buf());
}
if get(TRACE_MAX_MB).is_some() {
overrides.trace_max_mb = Some(trace.size_cap().get() / (1024 * 1024));
}
if let Some(value) = get(TRACE_DIR) {
if value.is_empty() {
return Err(ConfigError::invalid(TRACE_DIR, value, "a directory path"));
}
overrides.trace_dir = Some(PathBuf::from(value));
}
if let Some(value) = get(WATCHDOG) {
overrides.hang_after = Some(parse_hang_after(&value)?);
}
Ok(overrides)
}
pub(crate) fn apply<P: TestProgram>(&self, config: &mut HarnessConfig<P>) {
if let Some(after) = self.hang_after {
config.hang_after = after;
}
if let Some(dir) = &self.out_dir {
config.out_dir = Some(dir.clone());
}
let mut trace = config.trace.clone();
if let Some(mode) = self.trace {
trace = trace.mode(mode);
}
if let Some(mb) = self.trace_max_mb {
trace = trace.max_size(icedwright_trace::ByteSize::mib(mb));
}
if let Some(dir) = &config.out_dir {
trace = trace.out_dir(dir.clone());
}
config.trace = trace;
if let Some(headed) = self.headed {
config.headed = headed;
}
if let Some(each) = self.slow_mo {
config.slow_mo = Some(each);
}
let named_peer = config.headed_socket.is_some() || config.headed_link.is_some();
if config.headed_socket.is_none() {
config.headed_socket = self.runtime_dir.as_deref().map(crate::headed::socket_in);
}
if self.ci && config.headed != Headed::Off && !named_peer {
static WARNED: std::sync::Once = std::sync::Once::new();
WARNED.call_once(|| {
eprintln!("icedwright: CI is set, so headed mode is off; nobody is watching");
});
config.headed = Headed::Off;
}
}
}
fn parse_hang_after(value: &str) -> Result<HangAfter, ConfigError> {
const EXPECTED: &str = "a duration such as 120s or 500ms, or off";
if value == "off" {
return Ok(HangAfter::Off);
}
parse_duration(value)
.filter(|duration| !duration.is_zero())
.map(HangAfter::After)
.ok_or_else(|| ConfigError::invalid(WATCHDOG, value, EXPECTED))
}
pub(crate) fn parse_duration(value: &str) -> Option<Duration> {
let value = value.trim();
let split = value.find(|c: char| !c.is_ascii_digit())?;
let (number, unit) = value.split_at(split);
let number: u64 = number.parse().ok()?;
match unit {
"ms" => Some(Duration::from_millis(number)),
"s" => Some(Duration::from_secs(number)),
"m" => Some(Duration::from_secs(number.checked_mul(60)?)),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn vars(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
pairs
.iter()
.map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
.collect()
}
#[test]
fn every_documented_variable_parses_into_its_type() {
let parsed = EnvOverrides::from_vars(vars(&[
("ICEDWRIGHT_OUT_DIR", "/tmp/out"),
("ICEDWRIGHT_WATCHDOG", "1s"),
("ICEDWRIGHT_TRACE", "always"),
("ICEDWRIGHT_TRACE_DIR", "/tmp/traces"),
("ICEDWRIGHT_TRACE_MAX_MB", "8"),
("PATH", "/usr/bin"),
]))
.unwrap();
assert_eq!(parsed.out_dir, Some(PathBuf::from("/tmp/out")));
assert_eq!(
parsed.hang_after,
Some(HangAfter::After(Duration::from_secs(1)))
);
assert_eq!(parsed.trace, Some(TraceMode::Always));
assert_eq!(parsed.trace_dir, Some(PathBuf::from("/tmp/traces")));
assert_eq!(parsed.trace_max_mb, Some(8));
assert!(parsed.unknown.is_empty());
}
#[test]
fn headed_mode_comes_from_the_environment_and_ci_turns_it_off() {
let parsed = EnvOverrides::from_vars(vars(&[
("ICEDWRIGHT_HEADED", "step"),
("ICEDWRIGHT_SLOW_MO", "250ms"),
("XDG_RUNTIME_DIR", "/run/user/1000"),
]))
.unwrap();
assert_eq!(parsed.headed, Some(Headed::Step));
assert_eq!(parsed.slow_mo, Some(Duration::from_millis(250)));
assert!(parsed.unknown.is_empty());
let config = applied(&probe(), &parsed);
assert_eq!(config.headed, Headed::Step);
assert_eq!(config.slow_mo, Some(Duration::from_millis(250)));
assert_eq!(
config.headed_socket,
Some(PathBuf::from("/run/user/1000/icedwright/studio.sock"))
);
let on_ci =
EnvOverrides::from_vars(vars(&[("ICEDWRIGHT_HEADED", "1"), ("CI", "true")])).unwrap();
assert!(on_ci.ci);
assert_eq!(applied(&probe(), &on_ci).headed, Headed::Off);
let on_ci_with_runtime_dir = EnvOverrides::from_vars(vars(&[
("ICEDWRIGHT_HEADED", "1"),
("CI", "true"),
("XDG_RUNTIME_DIR", "/run/user/1000"),
]))
.unwrap();
assert_eq!(
applied(&probe(), &on_ci_with_runtime_dir).headed,
Headed::Off,
"CI turns off headed mode that would reach for studio's default socket"
);
let mut named = applied(&probe(), &EnvOverrides::default());
named.headed = Headed::Step;
named.headed_socket = Some(PathBuf::from("/tmp/stand-in.sock"));
on_ci.apply(&mut named);
assert_eq!(
named.headed,
Headed::Watch,
"a socket the test names is its own peer, so CI keeps it"
);
for (var, value) in [
("ICEDWRIGHT_HEADED", "maybe"),
("ICEDWRIGHT_SLOW_MO", "slow"),
] {
let error = EnvOverrides::from_vars(vars(&[(var, value)])).unwrap_err();
assert!(error.to_string().contains(var), "{error}");
}
}
fn view(_: &u8) -> iced::Element<'_, ()> {
iced::widget::text("probe").into()
}
fn probe() -> impl TestProgram {
iced::application(u8::default, |_: &mut u8, (): ()| {}, view)
}
fn applied<P: TestProgram>(_: &P, env: &EnvOverrides) -> HarnessConfig<P> {
let mut config = HarnessConfig::default();
env.apply(&mut config);
config
}
#[test]
fn nothing_set_overrides_nothing() {
assert_eq!(
EnvOverrides::from_vars(Vec::new()).unwrap(),
EnvOverrides::default()
);
}
#[test]
fn the_watchdog_takes_off_and_durations() {
assert_eq!(parse_hang_after("off").unwrap(), HangAfter::Off);
assert_eq!(
parse_hang_after("250ms").unwrap(),
HangAfter::After(Duration::from_millis(250))
);
assert_eq!(
parse_hang_after("2m").unwrap(),
HangAfter::After(Duration::from_secs(120))
);
}
#[test]
fn an_unparseable_value_names_the_variable_and_the_forms() {
for (var, value) in [
("ICEDWRIGHT_WATCHDOG", "soon"),
("ICEDWRIGHT_WATCHDOG", "0s"),
("ICEDWRIGHT_TRACE", "sometimes"),
("ICEDWRIGHT_TRACE_MAX_MB", "lots"),
("ICEDWRIGHT_TRACE_DIR", ""),
] {
let error = EnvOverrides::from_vars(vars(&[(var, value)])).unwrap_err();
let ConfigError::Invalid {
var: named,
value: held,
..
} = &error;
assert_eq!(*named, var);
assert_eq!(held, value);
assert!(error.to_string().contains("expected"), "{error}");
}
}
#[test]
fn an_undocumented_variable_is_listed_not_applied() {
let parsed = EnvOverrides::from_vars(vars(&[("ICEDWRIGHT_TRACES", "always")])).unwrap();
assert_eq!(parsed.unknown, vec!["ICEDWRIGHT_TRACES".to_owned()]);
assert_eq!(parsed.trace, None);
}
#[test]
fn durations_read_three_units() {
assert_eq!(parse_duration("15ms"), Some(Duration::from_millis(15)));
assert_eq!(parse_duration("3s"), Some(Duration::from_secs(3)));
assert_eq!(parse_duration("3"), None);
assert_eq!(parse_duration("s"), None);
assert_eq!(parse_duration("3h"), None);
}
}