mod handle;
mod surface;
#[cfg(test)]
mod tests;
mod turn;
use std::cell::{RefCell, RefMut};
use std::collections::{BTreeMap, VecDeque};
use std::fmt;
use std::rc::Rc;
use std::sync::{Arc, Once};
use std::time::SystemTime;
use iced_core::input_method::InputMethod;
use iced_core::{Event, mouse, theme, window};
use iced_futures::futures::channel::mpsc;
use iced_runtime::Action;
use icedwright_probe::control::{Installed, install};
use icedwright_semantics::SemanticTree;
use icedwright_types::units::{Logical, ScaleFactor};
use icedwright_types::{Messages, Size, VirtualDuration, VirtualInstant};
use crate::config::{Draw, EnvOverrides, HarnessBuilder, HarnessConfig, Platform};
use crate::effects::{
Control, ExternalSource, HarnessController, SinkGuard, Spawn, TaskInfo, TaskRules, Tasks,
UntypedTaskId,
};
use crate::error::{HarnessError, Result};
use crate::fakes::FakeClipboard;
use crate::messages::{MessageCoverage, MessageOrigin, MessageRecord};
use crate::runtime::{self, Blocking, HarnessExecutor, SharedBook, Signal, WakeHub, lock};
use crate::time::{Clock, EPOCH_OFFSET, HangDetector, RealDeadline, VirtualClock, WakeUp};
use crate::trace::TraceRecorder;
use crate::windows::{WindowInfo, WindowRef, WindowSet};
pub use handle::{Handle, Resolved};
pub(crate) use surface::{Surface, delayed_tooltip_under, with_ui};
pub trait TestProgram:
iced_program::Program<
Renderer: iced_core::renderer::Headless + 'static,
Message: Clone + fmt::Debug + Send + 'static,
State: 'static,
Theme: 'static,
> + 'static
{
}
impl<P> TestProgram for P
where
P: iced_program::Program + 'static,
P::Renderer: iced_core::renderer::Headless + 'static,
P::Message: Clone + fmt::Debug + Send + 'static,
P::State: 'static,
P::Theme: 'static,
{
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
Note,
Warning,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum DiagnosticKind {
ForeignWake {
task: UntypedTaskId,
},
RealClockRedraw {
window: window::Id,
},
TooltipLeft {
window: window::Id,
},
Unsupported {
action: &'static str,
},
UnusedPattern {
pattern: String,
},
UnknownVariable {
name: String,
},
UncoveredGlyphs {
window: window::Id,
characters: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
pub severity: Severity,
pub kind: DiagnosticKind,
pub at: VirtualInstant,
pub step: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[must_use]
pub enum ExternalWait {
Delivered(UntypedTaskId),
Ended(UntypedTaskId),
NoneLive,
}
#[derive(Debug, Clone)]
pub struct Probed {
pub statuses: Vec<iced_core::event::Status>,
pub tree: Arc<SemanticTree>,
pub cursors: icedwright_check::actionability::LayerCursors,
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum Origin {
Task(UntypedTaskId),
Subscription,
}
pub(crate) struct Envelope<M> {
pub(crate) origin: Origin,
pub(crate) action: Action<M>,
}
impl<M> Envelope<M> {
fn subscription(message: M) -> Self {
Self {
origin: Origin::Subscription,
action: Action::Output(message),
}
}
}
pub(crate) type Subscriptions<M> =
iced_futures::Runtime<HarnessExecutor, mpsc::UnboundedSender<Envelope<M>>, Envelope<M>>;
#[derive(Debug, Clone, Copy)]
struct Wall {
start: SystemTime,
epoch: tokio::time::Instant,
}
impl Wall {
fn at(self, now: tokio::time::Instant) -> SystemTime {
self.start + now.saturating_duration_since(self.epoch)
}
}
static WALLS: std::sync::Mutex<Vec<(tokio::runtime::Id, Wall)>> = std::sync::Mutex::new(Vec::new());
thread_local! {
static BUILT: RefCell<Vec<(tokio::runtime::Handle, Wall)>> = const { RefCell::new(Vec::new()) };
}
fn virtual_now() -> std::time::Instant {
tokio::time::Instant::now().into_std()
}
#[expect(
clippy::disallowed_methods,
reason = "threads with no harness see the real wall clock, as without the hook"
)]
fn virtual_system_now() -> SystemTime {
if let Ok(handle) = tokio::runtime::Handle::try_current() {
let id = handle.id();
let wall = lock(&WALLS)
.iter()
.find(|(runtime, _)| *runtime == id)
.map(|(_, wall)| *wall);
if let Some(wall) = wall {
return wall.at(tokio::time::Instant::now());
}
}
let built = BUILT.with(|built| built.borrow().last().cloned());
match built {
Some((handle, wall)) => {
let _enter = handle.enter();
wall.at(tokio::time::Instant::now())
}
None => SystemTime::now(),
}
}
#[derive(Debug)]
struct WallGuard {
id: tokio::runtime::Id,
wall: Wall,
}
impl WallGuard {
fn install(
handle: &tokio::runtime::Handle,
start: SystemTime,
epoch: tokio::time::Instant,
) -> Self {
static HOOKS: Once = Once::new();
HOOKS.call_once(|| icedwright_probe::time::install(virtual_now, virtual_system_now));
let wall = Wall { start, epoch };
let id = handle.id();
lock(&WALLS).push((id, wall));
BUILT.with(|built| built.borrow_mut().push((handle.clone(), wall)));
Self { id, wall }
}
}
impl Drop for WallGuard {
fn drop(&mut self) {
let id = self.id;
lock(&WALLS).retain(|(runtime, _)| *runtime != id);
BUILT.with(|built| built.borrow_mut().retain(|(handle, _)| handle.id() != id));
}
}
#[must_use]
pub struct Harness<P: TestProgram> {
pub(crate) trace: Option<TraceRecorder>,
pub(crate) surfaces: BTreeMap<window::Id, Surface<P>>,
pub(crate) subscriptions: Subscriptions<P::Message>,
pub(crate) state: P::State,
pub(crate) tokio: Option<tokio::runtime::Runtime>,
pub(crate) program: P,
pub(crate) receiver: mpsc::UnboundedReceiver<Envelope<P::Message>>,
pub(crate) sender: mpsc::UnboundedSender<Envelope<P::Message>>,
pub(crate) executor: HarnessExecutor,
pub(crate) book: SharedBook,
pub(crate) control: Rc<RefCell<Control>>,
pub(crate) rules: Rc<RefCell<TaskRules<P>>>,
_controller: Installed,
_sink: SinkGuard,
wall: WallGuard,
pub(crate) watch: crate::watchdog::ContextGuard,
pub(crate) activity: Arc<tokio::sync::Notify>,
pub(crate) set: WindowSet,
pub(crate) clock: VirtualClock,
pub(crate) blocking: Blocking,
pub(crate) signal: Arc<Signal>,
pub(crate) hang: HangDetector,
pub(crate) settings: iced_core::Settings,
pub(crate) queue: VecDeque<(P::Message, MessageOrigin)>,
pub(crate) input: BTreeMap<window::Id, Vec<Event>>,
pub(crate) messages: Vec<MessageRecord<P::Message>>,
pub(crate) clipboard: FakeClipboard,
pub(crate) system_theme: theme::Mode,
pub(crate) system_scale: ScaleFactor,
pub(crate) size_override: Option<Logical<Size>>,
pub(crate) diagnostics: Vec<Diagnostic>,
pub(crate) exited: bool,
pub(crate) generation: u64,
pub(crate) steps: u64,
pub(crate) trees: Option<(u64, Option<window::Id>, Arc<SemanticTree>)>,
pub(crate) dirty: bool,
pub(crate) broadcast_at: Option<VirtualInstant>,
pub(crate) last_work_at: VirtualInstant,
pub(crate) alive: usize,
pub(crate) foreign_seen: usize,
pub(crate) foreign_polled: usize,
pub(crate) frame_interval: VirtualDuration,
pub(crate) default_timeout: VirtualDuration,
pub(crate) draw: Draw,
pub(crate) platform: Platform,
pub(crate) external_sources: Vec<ExternalSource>,
pub(crate) step_depth: u32,
pub(crate) traced_generation: Option<u64>,
pub(crate) previous_tree: Option<Arc<SemanticTree>>,
pub(crate) variant: crate::snapshot::Variant,
pub(crate) devices: crate::actions::Devices,
pub(crate) expectations: crate::expect::ExpectState,
pub(crate) observers: crate::observer::Observers<P>,
pub(crate) headed: Option<crate::trace::HeadedStream>,
}
impl<P: TestProgram> fmt::Debug for Harness<P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Harness")
.field("now", &self.now())
.field("windows", &self.set.windows.keys().collect::<Vec<_>>())
.field("messages", &self.messages.len())
.field("exited", &self.exited)
.finish_non_exhaustive()
}
}
impl<P: TestProgram> Harness<P> {
pub fn new(program: P) -> Result<Self> {
Self::with_config(program, HarnessConfig::default())
}
pub fn builder(program: P) -> HarnessBuilder<P> {
HarnessBuilder::new(program)
}
pub fn with_config(program: P, mut config: HarnessConfig<P>) -> Result<Self> {
if tokio::runtime::Handle::try_current().is_ok() {
return Err(HarnessError::InsideRuntime.into());
}
crate::snapshot::fonts::prepare(config.system_fonts)?;
if let Some(executor) = surface::non_tokio_backend(std::any::type_name::<P::Executor>()) {
return Err(HarnessError::NonTokioTimeBackend { executor }.into());
}
let env = EnvOverrides::from_env()?;
env.apply(&mut config);
let signal = Arc::new(Signal::default());
let blocking = Blocking::new(signal.clone());
let tokio = runtime::build(&blocking)?;
tokio.block_on(tokio::time::advance(EPOCH_OFFSET));
let epoch = {
let _enter = tokio.enter();
tokio::time::Instant::now()
};
let clock = VirtualClock::new(epoch);
let wall = WallGuard::install(tokio.handle(), config.wall_clock_start, epoch);
let book = SharedBook::default();
let activity = Arc::new(tokio::sync::Notify::new());
let hub = Arc::new(WakeHub::new(
std::thread::current().id(),
book.clone(),
signal.clone(),
activity.clone(),
config
.external_sources
.contains(&ExternalSource::Subscriptions),
));
let executor = HarnessExecutor::new(tokio.handle().clone(), book.clone(), hub, clock);
let (sender, receiver) = mpsc::unbounded();
let subscriptions = iced_futures::Runtime::new(executor.clone(), sender.clone());
let named_external = config
.external_sources
.iter()
.filter_map(|source| match source {
ExternalSource::Named(pattern) => Some(*pattern),
ExternalSource::Subscriptions => None,
})
.collect();
let control = Rc::new(RefCell::new(Control::new(named_external)));
let rules = Rc::new(RefCell::new(std::mem::take(&mut config.tasks)));
let controller = install(Rc::new(HarnessController::new(
control.clone(),
rules.clone(),
book.clone(),
clock,
)));
let sink = SinkGuard::install(control.clone());
let watch = crate::watchdog::ContextGuard::install(crate::watchdog::Context::new(
crate::watchdog::Watchdog::global().cloned(),
crate::watchdog::budget(env.hang_after, config.hang_after),
crate::watchdog::pending_tasks(book.clone()),
));
let settings = program.settings();
crate::snapshot::fonts::load_program_fonts(&settings.fonts)?;
let (state, task) = {
let _enter = tokio.enter();
let preset = config
.preset
.and_then(|name| program.presets().iter().find(|p| p.name() == name));
crate::watchdog::app_call("boot", || match preset {
Some(preset) => preset.boot(),
None => program.boot(),
})
};
let hang = HangDetector::new(config.hang_after, config.real_clock.clone());
let daemon = program.window().is_none();
let mut harness = Self {
trace: None,
surfaces: BTreeMap::new(),
subscriptions,
state,
tokio: Some(tokio),
program,
receiver,
sender,
executor,
book,
control,
rules,
_controller: controller,
_sink: sink,
wall,
watch,
activity,
set: WindowSet::new(daemon, config.monitor_size),
clock,
blocking,
signal,
hang,
settings,
queue: VecDeque::new(),
input: BTreeMap::new(),
messages: Vec::new(),
clipboard: config.clipboard,
system_theme: config.system_theme,
system_scale: config.scale_factor,
size_override: config.size,
diagnostics: Vec::new(),
exited: false,
generation: 0,
steps: 0,
trees: None,
dirty: true,
broadcast_at: None,
last_work_at: VirtualInstant::__from_offset(VirtualDuration::ZERO),
alive: 0,
foreign_seen: 0,
foreign_polled: 0,
frame_interval: config.frame_interval,
default_timeout: config.default_timeout,
draw: config.draw,
platform: config.platform,
external_sources: config.external_sources,
step_depth: 0,
traced_generation: None,
previous_tree: None,
variant: config.variant,
devices: crate::actions::Devices::default(),
expectations: crate::expect::ExpectState::default(),
observers: crate::observer::Observers::new(std::mem::take(&mut config.observers)),
headed: None,
};
for name in &env.unknown {
harness.diagnose(
Severity::Warning,
DiagnosticKind::UnknownVariable { name: name.clone() },
);
}
if let Some(settings) = harness.program.window() {
harness.open_window(window::Id::unique(), settings)?;
}
harness.spawn_task(task, Spawn::Boot, false);
harness.resubscribe();
harness.settle()?;
harness.trace = TraceRecorder::start(&mut harness, &config.trace);
harness.start_headed(
config.headed,
config.slow_mo,
config.headed_socket,
config.headed_link,
);
Ok(harness)
}
pub(crate) fn diagnose(&mut self, severity: Severity, kind: DiagnosticKind) {
let at = self.now();
let diagnostic = Diagnostic {
severity,
kind,
at,
step: self.steps,
};
self.observe(|observer| observer.diagnostic(&diagnostic));
self.diagnostics.push(diagnostic);
}
#[must_use]
pub fn now(&self) -> VirtualInstant {
match &self.tokio {
Some(tokio) => {
let _enter = tokio.enter();
self.clock.of(tokio::time::Instant::now())
}
None => self.last_work_at,
}
}
#[must_use]
pub fn wall_clock(&self) -> SystemTime {
self.wall.wall.start + self.now().since_boot().as_std()
}
#[must_use]
pub fn classify(&self, instant: iced_core::time::Instant) -> Clock {
self.clock.classify(instant)
}
#[must_use]
pub fn to_iced(&self, instant: VirtualInstant) -> iced_core::time::Instant {
self.clock.to_iced(instant)
}
#[must_use]
pub fn frame_interval(&self) -> VirtualDuration {
self.frame_interval
}
#[must_use]
pub fn default_timeout(&self) -> VirtualDuration {
self.default_timeout
}
#[must_use]
pub fn next_wake_up(&self) -> Option<WakeUp> {
let windows: Vec<_> = self
.surfaces
.iter()
.map(|(id, surface)| (*id, surface.redraw))
.collect();
crate::time::next_wake_up(self.now(), self.frame_interval, &windows)
}
#[must_use]
pub fn state(&self) -> &P::State {
&self.state
}
#[must_use]
pub fn messages(&self) -> &[MessageRecord<P::Message>] {
&self.messages
}
#[must_use]
pub fn coverage(&self) -> MessageCoverage<P::Message>
where
P::Message: Messages,
{
MessageCoverage::of(self.messages.iter().map(|record| &record.message))
}
#[must_use]
pub fn diagnostics(&self) -> &[Diagnostic] {
&self.diagnostics
}
#[must_use]
pub fn has_exited(&self) -> bool {
self.exited
}
#[must_use]
pub fn generation(&self) -> u64 {
self.generation
}
pub fn clipboard(&mut self) -> &mut FakeClipboard {
&mut self.clipboard
}
pub fn tasks(&mut self) -> Tasks<'_, P> {
Tasks::new(self)
}
#[must_use]
pub fn windows(&self) -> Vec<window::Id> {
self.set.windows.keys().copied().collect()
}
#[must_use]
pub fn focused(&self) -> Option<window::Id> {
self.set.focused
}
pub fn window(&mut self, id: window::Id) -> Result<WindowRef<'_, P>> {
self.set.get(id)?;
Ok(WindowRef::new(self, id))
}
pub fn main_window(&mut self) -> Result<WindowRef<'_, P>> {
let id = self
.set
.windows
.values()
.min_by_key(|state| state.ordinal)
.map(|state| state.info.id)
.ok_or(HarnessError::NoWindow)?;
Ok(WindowRef::new(self, id))
}
pub fn window_info(&self, id: window::Id) -> Result<&WindowInfo> {
Ok(&self.set.get(id)?.info)
}
pub fn mouse_interaction(&self, id: window::Id) -> Result<mouse::Interaction> {
Ok(self.surface(id)?.mouse_interaction)
}
pub fn cursor(&self, id: window::Id) -> Result<mouse::Cursor> {
Ok(self.surface(id)?.cursor)
}
pub fn variant(&self) -> &crate::snapshot::Variant {
&self.variant
}
pub fn tree_window(&self, id: window::Id) -> Result<icedwright_protocol::WindowId> {
Ok(icedwright_protocol::WindowId(self.set.get(id)?.ordinal))
}
#[must_use]
pub fn window_of(&self, tree_window: icedwright_protocol::WindowId) -> Option<window::Id> {
self.set
.windows
.iter()
.find(|(_, state)| state.ordinal == tree_window.0)
.map(|(id, _)| *id)
}
pub fn input_method(&self, id: window::Id) -> Result<&InputMethod> {
Ok(&self.surface(id)?.input_method)
}
pub fn real_clock_deadline(&self, id: window::Id) -> Result<RealDeadline> {
Ok(self.surface(id)?.deadlines)
}
pub(crate) fn surface(&self, id: window::Id) -> Result<&Surface<P>, HarnessError> {
self.surfaces.get(&id).ok_or(HarnessError::NoSuchWindow(id))
}
pub(crate) fn window_set(&self) -> &WindowSet {
&self.set
}
pub(crate) fn control(&self) -> Rc<RefCell<Control>> {
self.control.clone()
}
pub(crate) fn rules(&self) -> RefMut<'_, TaskRules<P>> {
self.rules.borrow_mut()
}
pub(crate) fn task_infos(&self) -> Vec<TaskInfo> {
let mut infos: Vec<TaskInfo> = lock(&self.book)
.tasks
.iter()
.map(|(id, record)| TaskInfo::from_record(*id, record))
.collect();
infos.extend(self.control.borrow().infos().cloned());
infos.sort_by_key(TaskInfo::id);
infos
}
pub fn finish(mut self) -> Result {
if let Some(soft) = self.expectations.take_soft() {
return Err(soft.into());
}
let unused = self.rules.borrow().unused_patterns();
for pattern in unused {
let diagnostic = Diagnostic {
severity: Severity::Warning,
kind: DiagnosticKind::UnusedPattern { pattern },
at: self.last_work_at,
step: self.steps,
};
self.observe(|observer| observer.diagnostic(&diagnostic));
self.diagnostics.push(diagnostic);
}
let held = self.control.borrow().held();
if !held.is_empty() {
return Err(HarnessError::HeldAtEnd(held).into());
}
Ok(())
}
pub(crate) fn check_file_drops(&self) -> Result {
if self.platform == Platform::Wayland {
return Err(HarnessError::UnsupportedAction(
"dropping files on Wayland, where winit does not deliver drops (\"Wayland: Not implemented\")",
)
.into());
}
Ok(())
}
pub fn block_on<T>(&mut self, future: impl Future<Output = T>) -> Result<T> {
let tokio = self.tokio.as_ref().ok_or(HarnessError::Exited)?;
Ok(tokio.block_on(future))
}
}
impl<P: TestProgram> Drop for Harness<P> {
fn drop(&mut self) {
self.finish_trace();
self.finish_headed();
self.surfaces.clear();
if let Err(error) = self.drain_blocking() {
eprintln!("icedwright: a blocking job was abandoned when the harness dropped: {error}");
}
if let Some(tokio) = self.tokio.take() {
tokio.shutdown_background();
}
self.expectations.report_unfinished();
}
}