icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
//! [`Harness`]: one iced program running headlessly on the test thread.

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};

/// The bound every harness API uses: an iced program whose messages can be logged by value
/// and printed. Implemented for every such program.
///
/// `iced_program::Program` already requires a renderer that implements `Headless`, so an
/// app's `program()` function can return `iced::Application<impl iced::Program<State = S,
/// Message = M, Theme = iced::Theme>>` and a helper can return
/// `Harness<impl TestProgram<State = S, Message = M>>`.
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,
{
}

/// How bad a diagnostic is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
    /// Worth knowing.
    Note,
    /// May make the test depend on something it does not control.
    Warning,
}

/// What a diagnostic is about.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum DiagnosticKind {
    /// A task was woken by a thread the harness does not own.
    ForeignWake {
        /// The task.
        task: UntypedTaskId,
    },
    /// A window asked for a redraw at a real-clock instant, drawn on the next frame instead.
    RealClockRedraw {
        /// The window.
        window: window::Id,
    },
    /// The pointer was moved off a delayed tooltip's trigger.
    TooltipLeft {
        /// The window.
        window: window::Id,
    },
    /// An action with no headless meaning.
    Unsupported {
        /// The action.
        action: &'static str,
    },
    /// A task pattern matched no task.
    UnusedPattern {
        /// The pattern.
        pattern: String,
    },
    /// An `ICEDWRIGHT_` environment variable icedwright does not know.
    UnknownVariable {
        /// The variable.
        name: String,
    },
    /// Text in a window holds characters no loaded font covers, which draw as the
    /// missing-glyph box.
    UncoveredGlyphs {
        /// The window.
        window: window::Id,
        /// The characters, in code point order.
        characters: String,
    },
}

/// Something the harness noticed that did not fail the step.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
    /// How bad it is.
    pub severity: Severity,
    /// What it is about.
    pub kind: DiagnosticKind,
    /// When.
    pub at: VirtualInstant,
    /// The harness's step count then.
    pub step: u64,
}

/// How [`Harness::wait_for_external`] ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[must_use]
pub enum ExternalWait {
    /// A thread the harness does not own woke a declared source's task.
    Delivered(UntypedTaskId),
    /// A declared source's task ended.
    Ended(UntypedTaskId),
    /// No declared source is live.
    NoneLive,
}

/// What [`Harness::send_probed`] saw in the interface that handled the events.
#[derive(Debug, Clone)]
pub struct Probed {
    /// Each event's status.
    pub statuses: Vec<iced_core::event::Status>,
    /// The window's tree, recorded before the interface was cached.
    pub tree: Arc<SemanticTree>,
    /// The cursor kind each layer was handed for the last mouse event.
    pub cursors: icedwright_check::actionability::LayerCursors,
}

/// Where a message on the harness channel came from.
#[derive(Debug, Clone, Copy)]
pub(crate) enum Origin {
    Task(UntypedTaskId),
    Subscription,
}

/// An action from a task or subscription, tagged with where it came from.
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>>;

/// One harness's wall clock: the wall-clock time at boot and the virtual epoch.
#[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)
    }
}

/// Every live harness's wall clock, by its runtime, so every thread a runtime owns (the
/// harness thread and its blocking thread) reads that harness's clock.
static WALLS: std::sync::Mutex<Vec<(tokio::runtime::Id, Wall)>> = std::sync::Mutex::new(Vec::new());

thread_local! {
    /// The harnesses built on this thread, oldest first, for code that reads the clock
    /// outside any runtime, such as the test itself.
    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(),
    }
}

/// Keeps the harness's wall clock installed for its runtime and its thread.
#[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));
    }
}

/// A whole iced program running headlessly: `boot`, `update`, `view`, subscriptions and every
/// task, on a current-thread tokio runtime whose paused clock starts one virtual day ahead of
/// the real one. Every method blocks until the app has settled.
#[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> {
    /// Boots `program` with the default configuration.
    pub fn new(program: P) -> Result<Self> {
        Self::with_config(program, HarnessConfig::default())
    }

    /// A builder for `program`'s configuration.
    pub fn builder(program: P) -> HarnessBuilder<P> {
        HarnessBuilder::new(program)
    }

    /// Boots `program` with `config`, in the order `iced_winit` uses: boot, open the main
    /// window, start the boot task, subscribe, settle.
    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);
    }

    /// The current virtual instant.
    #[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,
        }
    }

    /// The virtual wall clock: `wall_clock_start` plus the virtual time since boot.
    #[must_use]
    pub fn wall_clock(&self) -> SystemTime {
        self.wall.wall.start + self.now().since_boot().as_std()
    }

    /// Which clock an instant from app state came from.
    #[must_use]
    pub fn classify(&self, instant: iced_core::time::Instant) -> Clock {
        self.clock.classify(instant)
    }

    /// The `iced::time::Instant` the app sees for a virtual instant.
    #[must_use]
    pub fn to_iced(&self, instant: VirtualInstant) -> iced_core::time::Instant {
        self.clock.to_iced(instant)
    }

    /// The virtual time between frames.
    #[must_use]
    pub fn frame_interval(&self) -> VirtualDuration {
        self.frame_interval
    }

    /// How long waits wait by default.
    #[must_use]
    pub fn default_timeout(&self) -> VirtualDuration {
        self.default_timeout
    }

    /// The next thing the harness itself will do: a frame or a widget timer. tokio does not
    /// expose its timer queue, so the app's own timers are not listed.
    #[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)
    }

    /// The app's state.
    #[must_use]
    pub fn state(&self) -> &P::State {
        &self.state
    }

    /// Every message `update` received, in order.
    #[must_use]
    pub fn messages(&self) -> &[MessageRecord<P::Message>] {
        &self.messages
    }

    /// Which message variants were seen, from the list `#[derive(Messages)]` generates.
    #[must_use]
    pub fn coverage(&self) -> MessageCoverage<P::Message>
    where
        P::Message: Messages,
    {
        MessageCoverage::of(self.messages.iter().map(|record| &record.message))
    }

    /// Everything noticed that did not fail a step.
    #[must_use]
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }

    /// Whether the app asked to exit.
    #[must_use]
    pub fn has_exited(&self) -> bool {
        self.exited
    }

    /// Turns that could have changed what is on screen.
    #[must_use]
    pub fn generation(&self) -> u64 {
        self.generation
    }

    /// The fake clipboard.
    pub fn clipboard(&mut self) -> &mut FakeClipboard {
        &mut self.clipboard
    }

    /// The app's tasks.
    pub fn tasks(&mut self) -> Tasks<'_, P> {
        Tasks::new(self)
    }

    /// Open windows, in `window::Id` order.
    #[must_use]
    pub fn windows(&self) -> Vec<window::Id> {
        self.set.windows.keys().copied().collect()
    }

    /// The focused window.
    #[must_use]
    pub fn focused(&self) -> Option<window::Id> {
        self.set.focused
    }

    /// A handle on one window.
    pub fn window(&mut self, id: window::Id) -> Result<WindowRef<'_, P>> {
        self.set.get(id)?;
        Ok(WindowRef::new(self, id))
    }

    /// A handle on the oldest open window.
    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))
    }

    /// What the harness knows of a window.
    pub fn window_info(&self, id: window::Id) -> Result<&WindowInfo> {
        Ok(&self.set.get(id)?.info)
    }

    /// The pointer shape the window's widgets last asked for.
    pub fn mouse_interaction(&self, id: window::Id) -> Result<mouse::Interaction> {
        Ok(self.surface(id)?.mouse_interaction)
    }

    /// Where the pointer is in the window, as its widgets last saw it.
    pub fn cursor(&self, id: window::Id) -> Result<mouse::Cursor> {
        Ok(self.surface(id)?.cursor)
    }

    /// The theme, size and scale combination the test runs in.
    pub fn variant(&self) -> &crate::snapshot::Variant {
        &self.variant
    }

    /// The id the semantic tree gives a window.
    pub fn tree_window(&self, id: window::Id) -> Result<icedwright_protocol::WindowId> {
        Ok(icedwright_protocol::WindowId(self.set.get(id)?.ordinal))
    }

    /// The window a semantic tree's window id names, if it is still open.
    #[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)
    }

    /// The input method the window's widgets last asked for.
    pub fn input_method(&self, id: window::Id) -> Result<&InputMethod> {
        Ok(&self.surface(id)?.input_method)
    }

    /// Real-clock redraws the window asked for and tooltip leaves the harness made for it.
    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()
    }

    /// Every task, unnamed and named, in start order.
    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
    }

    /// Checks the end of a test: soft expectation failures and held tasks still pending are
    /// errors, and unused task patterns become warnings.
    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(())
    }

    /// Runs `future` on the harness runtime under virtual time.
    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();
        // A blocking job left running would go on writing files or sending on channels
        // while the next test in this process runs.
        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();
    }
}