Skip to main content

crcbl_shell/
headless.rs

1//! [`HeadlessShell`] — a complete [`Shell`] with a virtual monitor, scripted
2//! event injection, and no OS calls anywhere.
3//!
4//! It is the windowing counterpart of `crcbl-hal`'s `NullBackend`, and it has
5//! the same three jobs, in increasing order of usefulness:
6//!
7//! 1. **Prove the seam is implementable without platform types.** If a trait
8//!    method could not be written without naming a compositor, this module
9//!    would not compile.
10//! 2. **Be the substrate CI runs the engine through.**
11//!    The windowing rules in `docs/notes/backends.md` are explicit that this is
12//!    not a stub: "CI and
13//!    `crcbl screenshot`/`sim` run the identical engine loop through it". A
14//!    render test pairs it with [`SurfaceTarget::Offscreen`] — which
15//!    [`surface_target`](Shell::surface_target) returns — so the golden-image
16//!    path exercises the same acquire/present code a real window does.
17//! 3. **Make window behaviour testable.** Resize storms, scale-factor changes
18//!    mid-session, aspect-lock clamping, focus loss: all scriptable, all
19//!    deterministic, none needing a nested compositor.
20//!
21//! # Deterministic by construction
22//!
23//! Nothing here reads a clock, a socket or an environment variable. Time comes
24//! from an internal [`ManualTime`], so a test that drives both the shell and a
25//! [`FrameClock`](crcbl_core::FrameClock) from the same schedule gets a session
26//! that is byte-identical on every machine — the property
27//! `docs/notes/process.md` demands of every nondeterminism source.
28//! [`HeadlessShell::set_time`] exists so the shell's clock can be slaved to a
29//! test's own `ManualTime` rather than drifting alongside it.
30//!
31//! # It is *stricter* than a compositor, on purpose
32//!
33//! The temptation with a test double is to make every call succeed
34//! immediately. That is the shape that proves nothing: a consumer written
35//! against it grows an assumption the real backend then breaks, all at once,
36//! long after the code was written. So where headless can be the harsher of the
37//! two, it is.
38//!
39//! * **A new window has no size.** [`create_window`](Shell::create_window)
40//!   returns a [`WindowId`] and queues *nothing*. The first
41//!   [`Resized`](ShellEvent::Resized) is delivered by a later
42//!   [`pump`](Shell::pump) — by default the second one, and
43//!   [`set_configure_delay`](HeadlessShell::set_configure_delay) makes it
44//!   later still. This models Wayland exactly: an `xdg_surface` is unsized and
45//!   may not be given a buffer until the compositor answers with a `configure`,
46//!   a round trip away. Consumers must loop on
47//!   [`WindowState::size`] before creating a swapchain, and here they are made
48//!   to. (The same trick as `crcbl-hal`'s injected readback latency, for the
49//!   same reason.)
50//! * **`set_mode` and `set_constraints` are requests, not commands.** They
51//!   record the request in [`WindowState::requested_mode`] /
52//!   [`requested_constraints`](WindowState::requested_constraints) and schedule
53//!   a configure; the *effective* mode only appears in
54//!   [`WindowConfiguration::mode`] once that configure is delivered. A consumer
55//!   that reads back its own request as fact fails here.
56//! * **Constraints are enforced on delivered configures.**
57//!   [`SizeConstraints::apply`] runs, so aspect-locked and min/max behaviour is
58//!   exercised. A tiling window manager enforces none of it — which is why
59//!   in-renderer letterboxing is the universal fallback, and why
60//!   [`inject`](HeadlessShell::inject) exists to feed sizes that violate the
61//!   constraints outright.
62//!
63//! Where it is still *easier* than a compositor, and knowingly so: the injection
64//! helpers ([`resize`](HeadlessShell::resize),
65//! [`change_scale_factor`](HeadlessShell::change_scale_factor)) apply at once,
66//! because they *are* the compositor speaking rather than the client asking.
67//! They are also the escape hatch for a test that wants a configured window in
68//! one line.
69//!
70//! # Where the model is now known to be wrong (P0.5a)
71//!
72//! The Wayland backend's end-to-end suite is the first thing that could check
73//! any of this against a real compositor. Three differences came back, and they
74//! are recorded here rather than only in the backend, because this is the file
75//! consumers are written against:
76//!
77//! 1. **A first configure usually dictates no size at all.** Headless always
78//!    delivers one. `xdg-shell` defines `0 × 0` as "you choose", and it is what
79//!    sway sends for a freshly created toplevel — so a real backend supplies
80//!    the fallback and the requested size stands. A consumer is unaffected
81//!    (both shapes are "a size arrived"), but a *backend* author reading only
82//!    this file would not expect it.
83//! 2. **Size arrives before scale.** A window's scale factor comes from
84//!    `wl_surface.enter`, which only fires once the surface is mapped — which
85//!    needs a buffer, which needs the size. So the first configure is at scale
86//!    1.0 and the true scale follows as a separate
87//!    [`ScaleFactorChanged`](ShellEvent::ScaleFactorChanged).
88//!    [`WindowConfiguration`] groups the two because they arrive in *one
89//!    message*; it does not promise the first message is right about both.
90//!    [`change_scale_factor`](HeadlessShell::change_scale_factor) is how a test
91//!    reproduces the sequence.
92//! 3. **Configured is not the same as managed.** A Wayland window that has
93//!    never been given a buffer is answered once and then ignored: no
94//!    compositor-chosen geometry, no fullscreen configure, not even present in
95//!    the window manager's tree. Headless has no such state, and nothing in the
96//!    seam expresses it. It is not a defect in the seam — the sequence a
97//!    consumer must write (configure → swapchain → present → *then* expect real
98//!    geometry) is the same either way — but a test that resizes a headless
99//!    window before its first present is exercising something a compositor
100//!    would not have done.
101//!
102//! # The clipboard's hard cases are settable (P0.5c)
103//!
104//! P0.5c found the same "test double only knows the easy path" problem in the
105//! clipboard that P0.4 had fixed for window sizes: a real compositor's
106//! clipboard is *not* always readable and *not* always claimable, and a shell
107//! that always answered instantly would let a consumer grow exactly the
108//! assumption Wayland then breaks. All three cases are now scriptable, and none
109//! of them needs a compositor:
110//!
111//! | Real behaviour | Modelled by | What a consumer learns |
112//! | --- | --- | --- |
113//! | Wayland delivers `wl_data_device.selection` only to the focused client, asynchronously | [`set_clipboard_readable`](HeadlessShell::set_clipboard_readable) | a read is **held** until it can be answered, and is never answered [`Empty`](ClipboardContent::Empty) for "I have not looked yet" |
114//! | A peer takes the transfer descriptor and never writes | [`set_clipboard_stalled`](HeadlessShell::set_clipboard_stalled) | the read ends as [`Unavailable`](ClipboardContent::Unavailable) — a failure, not an empty clipboard |
115//! | `set_selection` needs a serial from real user input | [`require_user_interaction`](HeadlessShell::require_user_interaction) | [`clipboard_offer`](Shell::clipboard_offer) can fail with [`ShellError::NeedsUserInteraction`], and that is a policy rather than a bug |
116//!
117//! The deadline a held read gives up after is
118//! [`clipboard_deadline`](HeadlessShell::clipboard_deadline), counted in
119//! **pumps** rather than milliseconds so a test asserting the timeout is not a
120//! flake. Defaults are the permissive ones — readable, not stalled, no
121//! interaction required — because most platforms have no such rules and a test
122//! that does not care about them should not have to say so.
123//!
124//! # Capabilities are settable, which is the point
125//!
126//! [`HeadlessShell::new`] reports [`ShellCaps::DESKTOP`] — everything. But
127//! [`with_caps`](HeadlessShell::with_caps) lets a test report a *degraded* set:
128//! a Wayland-shaped shell with no [`POINTER_WARP`](ShellCaps::POINTER_WARP) and
129//! no [`ASPECT_HINT_HONORED`](ShellCaps::ASPECT_HINT_HONORED), say. That is how
130//! the caps system gets tested before a second backend exists — a consumer that
131//! branches on the platform instead of on caps fails against a headless shell
132//! configured to look like the platform it forgot.
133
134use std::collections::VecDeque;
135use std::path::PathBuf;
136use std::sync::{Arc, Condvar, Mutex, PoisonError};
137
138use core::time::Duration;
139
140use crcbl_core::input::{
141    ButtonState, ContactId, DeviceId, Keysym, Modifiers, PointerButton, Scancode, ScrollDelta,
142    TouchPhase,
143};
144use crcbl_core::time::{ManualTime, TimeSource};
145use crcbl_core::{EventTime, Pool, SurfaceTarget};
146
147use crate::frame::FrameRequests;
148use crate::waker::WakeSignal;
149use crate::{
150    ClipboardContent, ClipboardOffer, ClipboardRequestId, CloseReply, CursorIcon, DisplayMode,
151    KeyCode, LogicalRect, LogicalSize, MimeType, MonitorId, MonitorInfo, PhysicalPoint,
152    PhysicalRect, PhysicalSize, PointerMode, ReceivedMime, Shell, ShellBackend, ShellCaps,
153    ShellError, ShellEvent, ShellWaker, SizeConstraints, TextPurpose, WebUrl, WindowConfiguration,
154    WindowDesc, WindowId, WindowState,
155};
156
157/// Resolution of the virtual monitor [`HeadlessShell::new`] creates.
158///
159/// 1920×1080 at scale 1.0: the size golden images are most often blessed at,
160/// and small enough that a readback in a test is cheap.
161pub const DEFAULT_MONITOR_SIZE: PhysicalSize = PhysicalSize::new(1920, 1080);
162
163/// Refresh rate of the virtual monitor, in millihertz — exactly 60 Hz.
164pub const DEFAULT_REFRESH_MILLIHERTZ: u32 = 60_000;
165
166/// Pumps that must complete before a newly requested configure is delivered.
167///
168/// One, not zero: a consumer that creates a window and immediately reads its
169/// size must fail, because that is what it will do on Wayland. See the [module
170/// docs](self).
171pub const DEFAULT_CONFIGURE_DELAY: u32 = 1;
172
173/// The device id every injected input event carries unless a helper says
174/// otherwise.
175///
176/// A real id rather than [`DeviceId::UNKNOWN`], so a consumer that routes by
177/// device is exercised rather than short-circuited.
178pub const VIRTUAL_DEVICE: DeviceId = DeviceId(1);
179
180/// Pumps a held clipboard read waits before giving up.
181///
182/// The modelled form of the deadline every real backend needs: a read that
183/// cannot be answered has to *end* rather than stay outstanding, and
184/// [`ClipboardContent::Unavailable`] is how it ends. Counted in pumps rather
185/// than in milliseconds, because a headless shell has no wall clock and a test
186/// that waited on one would be a flake.
187pub const DEFAULT_CLIPBOARD_DEADLINE: u32 = 4;
188
189/// A clipboard read that has been accepted and not yet answered.
190///
191/// The seam's obligation 5 — "a read that cannot be answered yet is held, never
192/// answered empty" — made into state. `HeadlessShell` models the case because
193/// it is the one a consumer written only against the easy path gets wrong.
194#[derive(Clone, Debug)]
195struct PendingRead {
196    window: WindowId,
197    request: ClipboardRequestId,
198    mime: MimeType,
199    /// Pumps still to go before this is reported unavailable.
200    countdown: u32,
201}
202
203/// A configure the window system has decided on but not yet delivered.
204///
205/// The whole point of the delay; see the [module docs](self).
206#[derive(Clone, Copy, Debug)]
207struct PendingConfigure {
208    size: PhysicalSize,
209    scale_factor: f64,
210    mode: DisplayMode,
211    /// Pumps still to go before this is delivered.
212    countdown: u32,
213}
214
215/// A script [`HeadlessShell::schedule`] holds until its pump comes.
216struct ScheduledScript {
217    /// Pumps still to go before this runs.
218    countdown: u32,
219    script: Box<dyn FnOnce(&mut HeadlessShell) + Send>,
220}
221
222impl core::fmt::Debug for ScheduledScript {
223    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
224        f.debug_struct("ScheduledScript")
225            .field("countdown", &self.countdown)
226            .finish_non_exhaustive()
227    }
228}
229
230/// A window inside the headless shell.
231#[derive(Clone, Debug)]
232struct HeadlessWindow {
233    title: String,
234    /// What has actually been reported. `None` until the first configure.
235    configuration: Option<WindowConfiguration>,
236    /// What is on its way, if anything.
237    pending: Option<PendingConfigure>,
238    requested_mode: DisplayMode,
239    requested_constraints: SizeConstraints,
240    focused: bool,
241    visible: bool,
242    pointer_mode: PointerMode,
243    cursor: Option<CursorIcon>,
244    close_pending: bool,
245    accept_drops: bool,
246    /// The window a popup belongs to, which takes it along when destroyed.
247    parent: Option<WindowId>,
248    /// What input a popup takes, which decides whether `Escape` dismisses it.
249    popup_input: Option<crate::PopupInput>,
250    /// What a panel was created with, or last given by [`Shell::set_panel`];
251    /// its monitor's unplugging asks it to close. `None` for every other
252    /// window.
253    panel: Option<crate::role::KeptPanel>,
254    /// [`Shell::set_text_input`]'s last word.
255    text_input: Option<TextPurpose>,
256    /// [`Shell::set_text_input_area`]'s last word.
257    text_input_area: Option<PhysicalRect>,
258    /// [`Shell::set_input_region`]'s last word: `None` for the whole window.
259    input_region: Option<Vec<PhysicalRect>>,
260    /// [`Shell::set_idle_inhibit`]'s last word.
261    idle_inhibit: bool,
262    /// Whether a pretend assistive technology is reading the window, and what
263    /// it has been sent since it started.
264    #[cfg(feature = "accesskit")]
265    accessibility: Option<Vec<accesskit::TreeUpdate>>,
266}
267
268impl HeadlessWindow {
269    /// The client area, or `None` while unconfigured.
270    fn size(&self) -> Option<PhysicalSize> {
271        self.configuration.map(|config| config.size)
272    }
273
274    /// The scale factor to apply to a logical size right now.
275    ///
276    /// Falls back to the pending configure's, then to 1.0 — which is exactly
277    /// what a Wayland client does before its first configure: render at scale 1
278    /// and correct itself when told.
279    fn scale_factor(&self) -> f64 {
280        self.configuration
281            .map(|config| config.scale_factor)
282            .or_else(|| self.pending.map(|pending| pending.scale_factor))
283            .unwrap_or(1.0)
284    }
285
286    /// The mode that is in effect, or — before the first configure — the one
287    /// that is on its way.
288    ///
289    /// Deliberately *not* the pending configure's when the window is already
290    /// configured: a compositor answering a `set_mode` with something else is a
291    /// case the seam exists to express, so an injected
292    /// [`resize`](HeadlessShell::resize) must report the mode currently in
293    /// effect rather than adopting the one that was merely asked for.
294    fn settled_mode(&self) -> DisplayMode {
295        self.configuration
296            .map(|config| config.mode)
297            .or_else(|| self.pending.map(|pending| pending.mode))
298            .unwrap_or(self.requested_mode)
299    }
300
301    /// The size a fresh configure should start from.
302    fn base_size(&self) -> PhysicalSize {
303        self.size()
304            .or_else(|| self.pending.map(|pending| pending.size))
305            .unwrap_or(PhysicalSize::new(1, 1))
306    }
307
308    /// Takes `size` as the configure on its way, or as a new one due in
309    /// `countdown` pumps once the first has been delivered: a window system
310    /// answering a request for a new size.
311    fn configure_at(&mut self, size: LogicalSize, countdown: u32) {
312        if let Some(pending) = self.pending.as_mut() {
313            pending.size = size.to_physical(pending.scale_factor);
314        } else if let Some(config) = self.configuration {
315            self.pending = Some(PendingConfigure {
316                size: size.to_physical(config.scale_factor),
317                scale_factor: config.scale_factor,
318                mode: config.mode,
319                countdown,
320            });
321        }
322    }
323}
324
325/// A [`Shell`] with no window system behind it.
326///
327/// See the [module docs](self) for what it models and where it deliberately
328/// differs from a real compositor.
329#[derive(Debug)]
330pub struct HeadlessShell {
331    caps: ShellCaps,
332    monitors: Vec<MonitorInfo>,
333    next_monitor_id: u32,
334    windows: Pool<HeadlessWindow>,
335    queue: VecDeque<ShellEvent>,
336    /// Scripts waiting for their pump, in the order they were scheduled; see
337    /// [`schedule`](HeadlessShell::schedule).
338    scripts: Vec<ScheduledScript>,
339    clock: ManualTime,
340    modifiers: Modifiers,
341    clipboard: Vec<(ReceivedMime, Vec<u8>)>,
342    next_request_id: u32,
343    /// Reads that have been accepted and not yet answered; see
344    /// [`PendingRead`].
345    reads: Vec<PendingRead>,
346    /// Whether the clipboard can be read at all right now — the modelled form
347    /// of Wayland's focus gate. See
348    /// [`set_clipboard_readable`](HeadlessShell::set_clipboard_readable).
349    clipboard_readable: bool,
350    /// Whether a peer holds the clipboard and never delivers.
351    clipboard_stalled: bool,
352    /// Whether claiming the clipboard requires a recent input event.
353    clipboard_needs_interaction: bool,
354    /// Whether any input has been injected since the last
355    /// [`clear_user_interaction`](HeadlessShell::clear_user_interaction).
356    saw_interaction: bool,
357    /// Pumps a held read waits before it reports
358    /// [`ClipboardContent::Unavailable`].
359    clipboard_deadline: u32,
360    waits: u32,
361    configure_delay: u32,
362    /// The doorbell [`waker`](Shell::waker) hands out, made on the first ask.
363    wake: Option<Arc<HeadlessWake>>,
364    /// [`Shell::request_frame`]s the next pump answers.
365    frames: FrameRequests,
366    /// Whether the outputs are on, so frame requests are answered. See
367    /// [`set_outputs_powered`](HeadlessShell::set_outputs_powered).
368    outputs_powered: bool,
369    /// Every [`Shell::open_url`] accepted, in order, with the window that
370    /// asked; see [`opened_urls`](HeadlessShell::opened_urls).
371    opened_urls: Vec<(WindowId, WebUrl)>,
372}
373
374/// The headless shell's doorbell: a flag and the condition variable a wait
375/// sleeps on.
376#[derive(Debug, Default)]
377struct HeadlessWake {
378    rung: Mutex<bool>,
379    bell: Condvar,
380}
381
382impl HeadlessWake {
383    /// Sleeps until rung or until `timeout` passes, then clears the bell. A
384    /// ring that came before the wait ends it at once.
385    fn wait(&self, timeout: Option<Duration>) {
386        let rung = self.rung.lock().unwrap_or_else(PoisonError::into_inner);
387        let mut rung = match timeout {
388            Some(timeout) => {
389                self.bell
390                    .wait_timeout_while(rung, timeout, |rung| !*rung)
391                    .unwrap_or_else(PoisonError::into_inner)
392                    .0
393            }
394            None => self
395                .bell
396                .wait_while(rung, |rung| !*rung)
397                .unwrap_or_else(PoisonError::into_inner),
398        };
399        *rung = false;
400    }
401}
402
403impl WakeSignal for HeadlessWake {
404    fn wake(&self) {
405        *self.rung.lock().unwrap_or_else(PoisonError::into_inner) = true;
406        self.bell.notify_all();
407    }
408}
409
410impl Default for HeadlessShell {
411    fn default() -> Self {
412        Self::new()
413    }
414}
415
416impl HeadlessShell {
417    /// A shell with one 1920×1080 monitor at scale 1.0 and every capability.
418    #[must_use]
419    pub fn new() -> Self {
420        Self {
421            caps: ShellCaps::DESKTOP,
422            monitors: vec![MonitorInfo {
423                id: MonitorId(1),
424                name: "HEADLESS-1".to_string(),
425                connector: None,
426                bounds: PhysicalRect::new(
427                    0,
428                    0,
429                    DEFAULT_MONITOR_SIZE.width,
430                    DEFAULT_MONITOR_SIZE.height,
431                ),
432                work_area: PhysicalRect::new(
433                    0,
434                    0,
435                    DEFAULT_MONITOR_SIZE.width,
436                    DEFAULT_MONITOR_SIZE.height,
437                ),
438                scale_factor: 1.0,
439                refresh_millihertz: DEFAULT_REFRESH_MILLIHERTZ,
440                is_primary: true,
441            }],
442            next_monitor_id: 2,
443            windows: Pool::new(),
444            queue: VecDeque::new(),
445            scripts: Vec::new(),
446            clock: ManualTime::new(),
447            modifiers: Modifiers::empty(),
448            clipboard: Vec::new(),
449            next_request_id: 1,
450            reads: Vec::new(),
451            clipboard_readable: true,
452            clipboard_stalled: false,
453            clipboard_needs_interaction: false,
454            saw_interaction: false,
455            clipboard_deadline: DEFAULT_CLIPBOARD_DEADLINE,
456            waits: 0,
457            configure_delay: DEFAULT_CONFIGURE_DELAY,
458            wake: None,
459            frames: FrameRequests::default(),
460            outputs_powered: true,
461            opened_urls: Vec::new(),
462        }
463    }
464
465    /// This shell, reporting only `caps`.
466    ///
467    /// The lever that makes the capability system testable; see the [module
468    /// docs](self).
469    #[must_use]
470    pub fn with_caps(mut self, caps: ShellCaps) -> Self {
471        self.caps = caps;
472        self
473    }
474
475    /// This shell, with `monitors` instead of the default one.
476    ///
477    /// # Panics
478    ///
479    /// If `monitors` is empty. A shell with no monitor cannot answer where a
480    /// borderless window goes, and every backend that could report zero
481    /// monitors (a headless X server, a disconnected session) is a case the
482    /// engine treats as "no display".
483    ///
484    /// If two monitors share a [`MonitorId`], or if one uses `u32::MAX`. Ids
485    /// are the key [`Shell::monitor`] looks up and the ones
486    /// [`plug_monitor`](Self::plug_monitor) hands out afterwards, so a
487    /// duplicate makes the lookup ambiguous and `u32::MAX` leaves no id for the
488    /// next hotplug.
489    #[must_use]
490    pub fn with_monitors(mut self, monitors: Vec<MonitorInfo>) -> Self {
491        assert!(!monitors.is_empty(), "a shell needs at least one monitor");
492        for (index, monitor) in monitors.iter().enumerate() {
493            assert!(
494                monitor.id.0 != u32::MAX,
495                "monitor id {} leaves no id for the next hotplug",
496                monitor.id.0
497            );
498            assert!(
499                !monitors[..index].iter().any(|seen| seen.id == monitor.id),
500                "monitor id {} appears twice",
501                monitor.id.0
502            );
503        }
504        self.next_monitor_id = monitors
505            .iter()
506            .map(|monitor| monitor.id.0 + 1)
507            .max()
508            .unwrap_or(1);
509        self.monitors = monitors;
510        self
511    }
512
513    /// This shell, with the primary monitor at `scale_factor`.
514    ///
515    /// Convenience for the common DPI test, which otherwise has to build a
516    /// whole [`MonitorInfo`].
517    #[must_use]
518    pub fn with_scale_factor(mut self, scale_factor: f64) -> Self {
519        assert!(scale_factor > 0.0, "scale factor must be positive");
520        self.monitors[0].scale_factor = scale_factor;
521        self
522    }
523
524    /// This shell, delivering the first configure after `pumps` calls to
525    /// [`pump`](Shell::pump).
526    ///
527    /// See [`set_configure_delay`](Self::set_configure_delay).
528    #[must_use]
529    pub const fn with_configure_delay(mut self, pumps: u32) -> Self {
530        self.configure_delay = pumps;
531        self
532    }
533
534    /// How many pumps a configure waits before it is delivered.
535    ///
536    /// Defaults to [`DEFAULT_CONFIGURE_DELAY`]. Raise it to prove that a
537    /// consumer's create-then-wait loop is a real loop rather than an
538    /// off-by-one that happens to work; drop it to `0` when a test is about
539    /// something else entirely and wants a window configured on the first
540    /// pump.
541    ///
542    /// Applies to configures scheduled *after* this call.
543    pub const fn set_configure_delay(&mut self, pumps: u32) {
544        self.configure_delay = pumps;
545    }
546
547    /// Replaces the reported capabilities mid-session.
548    ///
549    /// Real backends must not do this — [`Shell::caps`] is latched — but a test
550    /// building one shell per capability set is noise. Setting it before the
551    /// first [`create_window`](Shell::create_window) is the intended use.
552    pub fn set_caps(&mut self, caps: ShellCaps) {
553        self.caps = caps;
554    }
555
556    /// The shell's current time, which every injected event is stamped with.
557    #[must_use]
558    pub fn now(&self) -> EventTime {
559        EventTime::from_duration(self.clock.elapsed())
560    }
561
562    /// Moves the shell's clock forward.
563    ///
564    /// Injected events are stamped with the time *after* the advance, so
565    /// `advance(200ms)` between a press and a release produces a 200 ms hold —
566    /// which is how the P2 pattern evaluator's tap/hold table gets tested.
567    pub fn advance(&mut self, delta: Duration) {
568        self.clock.advance(delta);
569    }
570
571    /// Slaves the shell's clock to an absolute timestamp.
572    ///
573    /// Pass `time.elapsed()` from the test's own
574    /// [`ManualTime`] each frame and the shell's
575    /// event timestamps land on the same timeline as the
576    /// [`FrameClock`](crcbl_core::FrameClock)'s, which is what
577    /// [`EventTime`]'s epoch contract requires of a real backend.
578    pub fn set_time(&mut self, now: Duration) {
579        self.clock.set(now);
580    }
581
582    /// The modifier state stamped onto subsequent injected events.
583    ///
584    /// Sticky, like a real backend's tracked state — see [`event`](crate::event)
585    /// for why modifiers ride on each event rather than arriving separately.
586    pub fn set_modifiers(&mut self, modifiers: Modifiers) {
587        self.modifiers = modifiers;
588    }
589
590    /// How many events are queued and not yet pumped.
591    #[must_use]
592    pub fn pending_events(&self) -> usize {
593        self.queue.len()
594    }
595
596    /// How many times [`Shell::wait_events`] has been called.
597    ///
598    /// A test for an editor-style idle loop asserts that it actually waits
599    /// instead of spinning, and there is nothing else observable about a
600    /// headless wait.
601    #[must_use]
602    pub const fn wait_count(&self) -> u32 {
603        self.waits
604    }
605
606    /// Queues an event verbatim, with no state update and no validation.
607    ///
608    /// The escape hatch: use it to inject sequences a well-behaved compositor
609    /// would not produce — a resize that violates the constraints, events for a
610    /// destroyed window, a scale change with no resize — because those are
611    /// exactly the cases a consumer is most likely to get wrong. The typed
612    /// helpers below keep the shell's state consistent; this one does not.
613    pub fn inject(&mut self, event: ShellEvent) {
614        self.queue.push_back(event);
615    }
616
617    /// Runs `script` on this shell at the top of the pump `pumps` pumps from
618    /// now, so what it injects is delivered by that pump; `0` is the next one.
619    ///
620    /// Everything injected directly arrives in the next pump, so a consumer
621    /// that runs its own loop over this shell would see a whole scripted run
622    /// at once, before it has drawn a frame. A schedule spreads the run over
623    /// frames: layout, present and an out-of-date retry happen between keys.
624    /// The script runs then, not now, so the typed helpers it calls stamp the
625    /// clock as it stands at that pump and see the windows as they are then.
626    ///
627    /// Every turn of the window system counts, as for
628    /// [`set_configure_delay`](Self::set_configure_delay): a script that comes
629    /// due in [`keep_alive`](Shell::keep_alive) runs there, and what it injects
630    /// waits for the next pump. Scripts due at the same pump run in the order
631    /// they were scheduled; one scheduled by a script is counted from the pump
632    /// after the one it was scheduled in. While a script waits,
633    /// [`wait_events`](Shell::wait_events) returns at once, since only pumping
634    /// brings it closer.
635    pub fn schedule(&mut self, pumps: u32, script: impl FnOnce(&mut Self) + Send + 'static) {
636        self.scripts.push(ScheduledScript {
637            countdown: pumps,
638            script: Box::new(script),
639        });
640    }
641
642    /// Delivers a configure at `size` immediately, as a compositor answering a
643    /// resize would.
644    ///
645    /// This is the *compositor* speaking, not the client asking, so it takes
646    /// effect at once and supersedes any pending configure. It is therefore
647    /// also the one-line way to get a configured window in a test that is about
648    /// something other than the configure handshake.
649    ///
650    /// The window's constraints are applied, because a compositor that honours
651    /// hints would have applied them. Use [`inject`](Self::inject) to feed a
652    /// size that violates them, which is what a tiling window manager does.
653    ///
654    /// # Errors
655    ///
656    /// [`ShellError::InvalidWindow`] if the handle is stale.
657    pub fn resize(&mut self, window: WindowId, size: PhysicalSize) -> Result<(), ShellError> {
658        let state = self.window_mut(window)?;
659        let scale_factor = state.scale_factor();
660        let mode = state.settled_mode();
661        let constrained = state.requested_constraints.apply(size, scale_factor);
662        state.pending = None;
663        state.configuration = Some(WindowConfiguration {
664            size: constrained,
665            scale_factor,
666            mode,
667        });
668        self.queue.push_back(ShellEvent::Resized {
669            window,
670            size: constrained,
671            scale_factor,
672        });
673        Ok(())
674    }
675
676    /// Changes a window's scale factor, as dragging it to another monitor
677    /// would.
678    ///
679    /// The window's *logical* size is preserved and the physical size
680    /// recomputed, which is what both Wayland (`wl_surface.set_buffer_scale`
681    /// against an unchanged window geometry) and Win32 (`WM_DPICHANGED`'s
682    /// suggested rectangle) do. Queues a
683    /// [`ScaleFactorChanged`](ShellEvent::ScaleFactorChanged) carrying both
684    /// facts, so a consumer cannot hold a mismatched size/scale pair, followed
685    /// by the [`Resized`](ShellEvent::Resized) it implies — which is the pair
686    /// both Linux backends emit for a scale change, and the pair
687    /// `deliver_due_configures` emits for a
688    /// scale change that arrives with a configure.
689    ///
690    /// # Errors
691    ///
692    /// [`ShellError::InvalidWindow`] if the handle is stale.
693    ///
694    /// # Panics
695    ///
696    /// If `scale_factor` is not positive.
697    pub fn change_scale_factor(
698        &mut self,
699        window: WindowId,
700        scale_factor: f64,
701    ) -> Result<(), ShellError> {
702        assert!(scale_factor > 0.0, "scale factor must be positive");
703        let state = self.window_mut(window)?;
704        let logical = state.base_size().to_logical(state.scale_factor());
705        let mode = state.settled_mode();
706        let size = state
707            .requested_constraints
708            .apply(logical.to_physical(scale_factor), scale_factor);
709        state.pending = None;
710        state.configuration = Some(WindowConfiguration {
711            size,
712            scale_factor,
713            mode,
714        });
715        self.queue.push_back(ShellEvent::ScaleFactorChanged {
716            window,
717            scale_factor,
718            size,
719        });
720        self.queue.push_back(ShellEvent::Resized {
721            window,
722            size,
723            scale_factor,
724        });
725        Ok(())
726    }
727
728    /// Gives or takes keyboard focus.
729    ///
730    /// # Errors
731    ///
732    /// [`ShellError::InvalidWindow`] if the handle is stale.
733    pub fn set_focus(&mut self, window: WindowId, focused: bool) -> Result<(), ShellError> {
734        self.window_mut(window)?.focused = focused;
735        self.queue.push_back(ShellEvent::Focus { window, focused });
736        Ok(())
737    }
738
739    /// Asks the application to close the window, as a title-bar button would.
740    ///
741    /// The window stays open until
742    /// [`reply_close_request`](Shell::reply_close_request).
743    ///
744    /// # Errors
745    ///
746    /// [`ShellError::InvalidWindow`] if the handle is stale.
747    pub fn request_close(&mut self, window: WindowId) -> Result<(), ShellError> {
748        self.window_mut(window)?.close_pending = true;
749        self.queue.push_back(ShellEvent::CloseRequested { window });
750        Ok(())
751    }
752
753    /// Injects a key press or release.
754    ///
755    /// The scancode and keysym are synthesized deterministically from `key`:
756    /// the scancode is the key's index in [`KeyCode::ALL`] offset by 8 (evdev's
757    /// convention, so the numbers look plausible in a log), and the keysym is
758    /// the US-layout symbol where there is one. Neither is a claim about any
759    /// real keyboard; they exist so a consumer reading those fields is
760    /// exercised rather than reading zero.
761    ///
762    /// # Errors
763    ///
764    /// [`ShellError::InvalidWindow`] if the handle is stale.
765    pub fn key(
766        &mut self,
767        window: WindowId,
768        key: KeyCode,
769        state: ButtonState,
770    ) -> Result<(), ShellError> {
771        self.key_with(window, key, state, false)
772    }
773
774    /// Injects a key press.
775    ///
776    /// # Errors
777    ///
778    /// [`ShellError::InvalidWindow`] if the handle is stale.
779    pub fn key_press(&mut self, window: WindowId, key: KeyCode) -> Result<(), ShellError> {
780        self.key(window, key, ButtonState::Pressed)
781    }
782
783    /// Injects a key release.
784    ///
785    /// # Errors
786    ///
787    /// [`ShellError::InvalidWindow`] if the handle is stale.
788    pub fn key_release(&mut self, window: WindowId, key: KeyCode) -> Result<(), ShellError> {
789        self.key(window, key, ButtonState::Released)
790    }
791
792    /// Injects an auto-repeat press, the kind a text field wants and a jump
793    /// button must ignore.
794    ///
795    /// # Errors
796    ///
797    /// [`ShellError::InvalidWindow`] if the handle is stale.
798    pub fn key_repeat(&mut self, window: WindowId, key: KeyCode) -> Result<(), ShellError> {
799        self.key_with(window, key, ButtonState::Pressed, true)
800    }
801
802    fn key_with(
803        &mut self,
804        window: WindowId,
805        key: KeyCode,
806        state: ButtonState,
807        repeat: bool,
808    ) -> Result<(), ShellError> {
809        let popup_input = self.window(window)?.popup_input;
810        self.saw_interaction = true;
811        let event = ShellEvent::Key {
812            window,
813            device: VIRTUAL_DEVICE,
814            time: self.now(),
815            scancode: synthetic_scancode(key),
816            key_code: Some(key),
817            keysym: synthetic_keysym(key),
818            // The synthetic keyboard has no Caps Lock to apply.
819            shortcut_keysym: synthetic_keysym(key),
820            state,
821            repeat,
822            modifiers: self.modifiers,
823        };
824        let dismissed = crate::role::escape_dismisses(popup_input, &event);
825        self.queue.push_back(event);
826        // As the real backends do: one request until it is answered.
827        if dismissed && !self.window(window)?.close_pending {
828            self.request_close(window)?;
829        }
830        Ok(())
831    }
832
833    /// Moves the pointer to an absolute position, reporting the implied
834    /// relative delta as well.
835    ///
836    /// Under [`PointerMode::Locked`] the absolute position is dropped, matching
837    /// what the mode documents — which is what makes a camera that wrongly
838    /// reads `abs` fail here rather than in a playtest.
839    ///
840    /// # Errors
841    ///
842    /// [`ShellError::InvalidWindow`] if the handle is stale.
843    pub fn move_pointer(
844        &mut self,
845        window: WindowId,
846        position: PhysicalPoint,
847        raw_delta: (f64, f64),
848    ) -> Result<(), ShellError> {
849        let locked = self.window(window)?.pointer_mode == PointerMode::Locked;
850        let raw = if self.caps.contains(ShellCaps::RAW_POINTER_MOTION) {
851            Some(raw_delta)
852        } else {
853            None
854        };
855        self.saw_interaction = true;
856        let event = ShellEvent::PointerMotion {
857            window,
858            device: VIRTUAL_DEVICE,
859            time: self.now(),
860            abs: if locked { None } else { Some(position) },
861            raw_delta: raw,
862        };
863        self.queue.push_back(event);
864        Ok(())
865    }
866
867    /// Moves the pointer into or out of the window.
868    ///
869    /// # Errors
870    ///
871    /// [`ShellError::InvalidWindow`] if the handle is stale.
872    pub fn set_pointer_focus(
873        &mut self,
874        window: WindowId,
875        entered: bool,
876        position: Option<PhysicalPoint>,
877    ) -> Result<(), ShellError> {
878        self.check_window(window)?;
879        let event = ShellEvent::PointerFocus {
880            window,
881            device: VIRTUAL_DEVICE,
882            time: self.now(),
883            entered,
884            position: if entered { position } else { None },
885        };
886        self.queue.push_back(event);
887        Ok(())
888    }
889
890    /// Injects a pointer button press or release.
891    ///
892    /// # Errors
893    ///
894    /// [`ShellError::InvalidWindow`] if the handle is stale.
895    pub fn button(
896        &mut self,
897        window: WindowId,
898        button: PointerButton,
899        state: ButtonState,
900        position: Option<PhysicalPoint>,
901    ) -> Result<(), ShellError> {
902        self.check_window(window)?;
903        self.saw_interaction = true;
904        let event = ShellEvent::Button {
905            window,
906            device: VIRTUAL_DEVICE,
907            time: self.now(),
908            button,
909            state,
910            position,
911            modifiers: self.modifiers,
912        };
913        self.queue.push_back(event);
914        Ok(())
915    }
916
917    /// Injects a scroll.
918    ///
919    /// # Errors
920    ///
921    /// [`ShellError::InvalidWindow`] if the handle is stale.
922    pub fn scroll(
923        &mut self,
924        window: WindowId,
925        delta: ScrollDelta,
926        position: Option<PhysicalPoint>,
927    ) -> Result<(), ShellError> {
928        self.check_window(window)?;
929        self.saw_interaction = true;
930        let event = ShellEvent::Wheel {
931            window,
932            device: VIRTUAL_DEVICE,
933            time: self.now(),
934            delta,
935            position,
936            modifiers: self.modifiers,
937        };
938        self.queue.push_back(event);
939        Ok(())
940    }
941
942    /// Injects one contact's landing, move, lift or cancellation.
943    ///
944    /// **One call is one contact**, so a scripted two-finger gesture is two
945    /// interleaved sequences of these — which is the point, and is why there is
946    /// no "set the whole contact list" call that would let a script express a
947    /// state a real touchscreen never reports.
948    ///
949    /// Nothing here checks that a [`Moved`](TouchPhase::Moved) follows a
950    /// [`Began`](TouchPhase::Began), or that an id is not reused while it is
951    /// still down: a test double that refused to produce a malformed stream
952    /// could not be used to check what a consumer does with one.
953    ///
954    /// The emulated pointer events a real touch backend owes for its primary
955    /// contact are **not** synthesized here either — [`move_pointer`] and
956    /// [`button`] are how a script states those, and a test that wants the two
957    /// halves together says so rather than getting a second event it did not
958    /// ask for.
959    ///
960    /// [`move_pointer`]: Self::move_pointer
961    /// [`button`]: Self::button
962    ///
963    /// # Errors
964    ///
965    /// [`ShellError::InvalidWindow`] if the handle is stale, or
966    /// [`ShellError::Unsupported`] without [`ShellCaps::TOUCH`] — a shell
967    /// configured as a touchless backend must not be able to script a finger,
968    /// or a test would prove something about a platform that cannot happen.
969    pub fn touch(
970        &mut self,
971        window: WindowId,
972        contact: ContactId,
973        phase: TouchPhase,
974        position: PhysicalPoint,
975    ) -> Result<(), ShellError> {
976        self.check_window(window)?;
977        if !self.caps.contains(ShellCaps::TOUCH) {
978            return Err(self.unsupported("touch"));
979        }
980        self.saw_interaction = true;
981        let event = ShellEvent::Touch {
982            window,
983            device: VIRTUAL_DEVICE,
984            time: self.now(),
985            contact,
986            phase,
987            position,
988        };
989        self.queue.push_back(event);
990        Ok(())
991    }
992
993    /// Injects committed text, as an input method would.
994    ///
995    /// # Errors
996    ///
997    /// [`ShellError::InvalidWindow`] if the handle is stale.
998    ///
999    /// # Panics
1000    ///
1001    /// If `text` is empty — [`ShellEvent::TextCommit`] documents that it never
1002    /// is, and a shell that could produce one would make that a lie.
1003    pub fn commit_text(&mut self, window: WindowId, text: &str) -> Result<(), ShellError> {
1004        assert!(!text.is_empty(), "a text commit is never empty");
1005        self.check_window(window)?;
1006        let event = ShellEvent::TextCommit {
1007            window,
1008            time: self.now(),
1009            text: text.to_string(),
1010        };
1011        self.queue.push_back(event);
1012        Ok(())
1013    }
1014
1015    /// Injects a composition in progress, as an input method would: `text`
1016    /// so far, its cursor at the byte offset `cursor`, and an empty `text` for
1017    /// a composition that ended.
1018    ///
1019    /// # Errors
1020    ///
1021    /// [`ShellError::InvalidWindow`] if the handle is stale.
1022    ///
1023    /// # Panics
1024    ///
1025    /// If `cursor` is not on a `char` boundary of `text`, or is given for an
1026    /// empty `text` — [`ShellEvent::TextPreedit`] documents both.
1027    pub fn preedit_text(
1028        &mut self,
1029        window: WindowId,
1030        text: &str,
1031        cursor: Option<usize>,
1032    ) -> Result<(), ShellError> {
1033        assert!(
1034            cursor.is_none_or(|cursor| !text.is_empty() && text.is_char_boundary(cursor)),
1035            "a pre-edit's cursor is a char boundary of a non-empty text"
1036        );
1037        self.check_window(window)?;
1038        let event = ShellEvent::TextPreedit {
1039            window,
1040            time: self.now(),
1041            text: text.to_string(),
1042            cursor,
1043        };
1044        self.queue.push_back(event);
1045        Ok(())
1046    }
1047
1048    /// Drops a file on the window.
1049    ///
1050    /// # Errors
1051    ///
1052    /// [`ShellError::InvalidWindow`] if the handle is stale, or
1053    /// [`ShellError::Unsupported`] if the window did not opt into drops or the
1054    /// shell lacks [`ShellCaps::DRAG_DROP`].
1055    pub fn drop_file(
1056        &mut self,
1057        window: WindowId,
1058        path: impl Into<PathBuf>,
1059        position: Option<PhysicalPoint>,
1060    ) -> Result<(), ShellError> {
1061        if !self.caps.contains(ShellCaps::DRAG_DROP) {
1062            return Err(self.unsupported("drag and drop"));
1063        }
1064        if !self.window(window)?.accept_drops {
1065            return Err(ShellError::Unsupported {
1066                backend: ShellBackend::Headless,
1067                what: "drops on a window created without accept_drops",
1068            });
1069        }
1070        let event = ShellEvent::DroppedFile {
1071            window,
1072            time: self.now(),
1073            path: path.into(),
1074            position,
1075        };
1076        self.queue.push_back(event);
1077        Ok(())
1078    }
1079
1080    /// Adds a monitor and queues a
1081    /// [`MonitorsChanged`](ShellEvent::MonitorsChanged).
1082    ///
1083    /// The id is assigned by the shell and never reuses one that has been
1084    /// handed out, which is the obligation
1085    /// [`monitor`](crate::monitor) places on every backend.
1086    pub fn plug_monitor(&mut self, mut info: MonitorInfo) -> MonitorId {
1087        let id = MonitorId(self.next_monitor_id);
1088        self.next_monitor_id += 1;
1089        info.id = id;
1090        self.monitors.push(info);
1091        self.queue.push_back(ShellEvent::MonitorsChanged);
1092        id
1093    }
1094
1095    /// Removes a monitor: queues a
1096    /// [`MonitorRemoved`](ShellEvent::MonitorRemoved), a
1097    /// [`CloseRequested`](ShellEvent::CloseRequested) for every panel created
1098    /// for it that has none outstanding, and a
1099    /// [`MonitorsChanged`](ShellEvent::MonitorsChanged).
1100    ///
1101    /// # Errors
1102    ///
1103    /// [`ShellError::NoSuchMonitor`] if it is not connected.
1104    ///
1105    /// # Panics
1106    ///
1107    /// If it is the last monitor; see [`with_monitors`](Self::with_monitors).
1108    pub fn unplug_monitor(&mut self, id: MonitorId) -> Result<(), ShellError> {
1109        let index = self
1110            .monitors
1111            .iter()
1112            .position(|monitor| monitor.id == id)
1113            .ok_or(ShellError::NoSuchMonitor(id.0))?;
1114        assert!(
1115            self.monitors.len() > 1,
1116            "a shell needs at least one monitor"
1117        );
1118        let previous = self.monitors.clone();
1119        self.monitors.remove(index);
1120        crate::monitor::queue_removed(&previous, &self.monitors, &mut self.queue);
1121        let panels: Vec<WindowId> = self
1122            .windows
1123            .iter()
1124            .filter(|(_, state)| {
1125                state.panel.as_ref().and_then(|panel| panel.desc().monitor) == Some(id)
1126                    && !state.close_pending
1127            })
1128            .map(|(window, _)| window.cast())
1129            .collect();
1130        for panel in panels {
1131            self.request_close(panel)?;
1132        }
1133        self.queue.push_back(ShellEvent::MonitorsChanged);
1134        Ok(())
1135    }
1136
1137    /// The window's title, which no [`Shell`] method exposes.
1138    ///
1139    /// Titles are write-only across the seam — no backend can read one back
1140    /// reliably, since a window manager may decorate or truncate it — so this
1141    /// is a headless-only accessor for tests that assert
1142    /// [`set_title`](Shell::set_title) did something.
1143    ///
1144    /// # Errors
1145    ///
1146    /// [`ShellError::InvalidWindow`] if the handle is stale.
1147    pub fn title(&self, window: WindowId) -> Result<&str, ShellError> {
1148        Ok(self.window(window)?.title.as_str())
1149    }
1150
1151    /// The window's current cursor, or `None` if it is hidden.
1152    ///
1153    /// Headless-only, for the same reason as [`title`](Self::title).
1154    ///
1155    /// # Errors
1156    ///
1157    /// [`ShellError::InvalidWindow`] if the handle is stale.
1158    pub fn cursor(&self, window: WindowId) -> Result<Option<CursorIcon>, ShellError> {
1159        Ok(self.window(window)?.cursor)
1160    }
1161
1162    /// The text field the window last said is taking typing, with
1163    /// [`Shell::set_text_input`]; `None` while none is.
1164    ///
1165    /// Headless-only, for the same reason as [`title`](Self::title).
1166    ///
1167    /// # Errors
1168    ///
1169    /// [`ShellError::InvalidWindow`] if the handle is stale.
1170    pub fn text_input(&self, window: WindowId) -> Result<Option<TextPurpose>, ShellError> {
1171        Ok(self.window(window)?.text_input)
1172    }
1173
1174    /// Where the window last said text is being entered, with
1175    /// [`Shell::set_text_input_area`]; `None` until it said, or once it
1176    /// handed placement back.
1177    ///
1178    /// Headless-only, for the same reason as [`title`](Self::title).
1179    ///
1180    /// # Errors
1181    ///
1182    /// [`ShellError::InvalidWindow`] if the handle is stale.
1183    pub fn text_input_area(&self, window: WindowId) -> Result<Option<PhysicalRect>, ShellError> {
1184        Ok(self.window(window)?.text_input_area)
1185    }
1186
1187    /// What the panel was created with, or last given by
1188    /// [`Shell::set_panel`]; `None` for a window that is not a panel.
1189    ///
1190    /// Headless-only, for the same reason as [`title`](Self::title).
1191    ///
1192    /// # Errors
1193    ///
1194    /// [`ShellError::InvalidWindow`] if the handle is stale.
1195    pub fn panel(&self, window: WindowId) -> Result<Option<crate::PanelDesc<'_>>, ShellError> {
1196        Ok(self
1197            .window(window)?
1198            .panel
1199            .as_ref()
1200            .map(crate::role::KeptPanel::desc))
1201    }
1202
1203    /// The rectangles the window last limited its pointer input to, with
1204    /// [`Shell::set_input_region`]; `None` while it takes the pointer
1205    /// everywhere.
1206    ///
1207    /// Headless-only, for the same reason as [`title`](Self::title). Kept as
1208    /// given, empty rectangles included, so a test reads back what it sent.
1209    ///
1210    /// # Errors
1211    ///
1212    /// [`ShellError::InvalidWindow`] if the handle is stale.
1213    pub fn input_region(&self, window: WindowId) -> Result<Option<&[PhysicalRect]>, ShellError> {
1214        Ok(self.window(window)?.input_region.as_deref())
1215    }
1216
1217    /// Whether the window has asked for a frame, with
1218    /// [`Shell::request_frame`], that the next pump has yet to answer.
1219    ///
1220    /// Headless-only, for the same reason as [`title`](Self::title): a test
1221    /// of a loop that paces itself reads whether the loop asked.
1222    ///
1223    /// # Errors
1224    ///
1225    /// [`ShellError::InvalidWindow`] if the handle is stale.
1226    pub fn frame_requested(&self, window: WindowId) -> Result<bool, ShellError> {
1227        self.window(window)?;
1228        Ok(self.frames.contains(window))
1229    }
1230
1231    /// Whether the window is asking, with [`Shell::set_idle_inhibit`], for
1232    /// the display to be kept on.
1233    ///
1234    /// Headless-only, for the same reason as [`title`](Self::title): there
1235    /// is no display to keep on, so a test of a game that should keep it on
1236    /// during play reads whether it asked.
1237    ///
1238    /// # Errors
1239    ///
1240    /// [`ShellError::InvalidWindow`] if the handle is stale.
1241    pub fn idle_inhibited(&self, window: WindowId) -> Result<bool, ShellError> {
1242        Ok(self.window(window)?.idle_inhibit)
1243    }
1244
1245    /// Every URL [`Shell::open_url`] accepted, oldest first, with the window
1246    /// that asked.
1247    ///
1248    /// Headless-only, for the same reason as [`title`](Self::title): there is
1249    /// no browser to open, so a test of a menu's "Wishlist" button reads that
1250    /// it asked for the store page. Kept when the window is destroyed, since
1251    /// the browser it would have opened stays open too.
1252    #[must_use]
1253    pub fn opened_urls(&self) -> &[(WindowId, WebUrl)] {
1254        &self.opened_urls
1255    }
1256
1257    /// Turns every output off or back on, as far as frame requests go.
1258    ///
1259    /// **A compositor's frame pacing, modelled.** Where
1260    /// [`ShellCaps::FRAME_CALLBACK`] is set, a window on an output that is off
1261    /// is never asked for a frame: Wayland withholds `wl_surface.frame`'s
1262    /// `done` until something of the surface is shown again, which is what
1263    /// `swaymsg output HEADLESS-1 power off` does to a real one. With this
1264    /// `false`, a [`Shell::request_frame`] is held rather than answered at the
1265    /// next pump, and a held request does not cut a
1266    /// [`wait_events`](Shell::wait_events) short; it is answered at the first
1267    /// pump after this is `true` again, unless its window was destroyed
1268    /// first. Every other event is delivered as before.
1269    ///
1270    /// On by default: a request is answered at the next pump, as on every
1271    /// backend without the capability.
1272    pub fn set_outputs_powered(&mut self, powered: bool) {
1273        self.outputs_powered = powered;
1274    }
1275
1276    /// Starts a pretend assistive technology reading `window`, raising
1277    /// [`ShellEvent::AccessibilityActivated`]. Does nothing if one already is.
1278    ///
1279    /// Headless-only.
1280    ///
1281    /// # Errors
1282    ///
1283    /// [`ShellError::InvalidWindow`] if the handle is stale.
1284    #[cfg(feature = "accesskit")]
1285    pub fn activate_accessibility(&mut self, window: WindowId) -> Result<(), ShellError> {
1286        let state = &mut self.window_mut(window)?.accessibility;
1287        if state.is_none() {
1288            *state = Some(Vec::new());
1289            self.queue
1290                .push_back(ShellEvent::AccessibilityActivated { window });
1291        }
1292        Ok(())
1293    }
1294
1295    /// Stops the pretend assistive technology, raising
1296    /// [`ShellEvent::AccessibilityDeactivated`] and forgetting what it was
1297    /// sent. Does nothing if none was reading.
1298    ///
1299    /// Headless-only.
1300    ///
1301    /// # Errors
1302    ///
1303    /// [`ShellError::InvalidWindow`] if the handle is stale.
1304    #[cfg(feature = "accesskit")]
1305    pub fn deactivate_accessibility(&mut self, window: WindowId) -> Result<(), ShellError> {
1306        if self.window_mut(window)?.accessibility.take().is_some() {
1307            self.queue
1308                .push_back(ShellEvent::AccessibilityDeactivated { window });
1309        }
1310        Ok(())
1311    }
1312
1313    /// Has the pretend assistive technology ask for `request`, raising
1314    /// [`ShellEvent::AccessibilityAction`].
1315    ///
1316    /// Headless-only.
1317    ///
1318    /// # Errors
1319    ///
1320    /// [`ShellError::InvalidWindow`] if the handle is stale.
1321    ///
1322    /// # Panics
1323    ///
1324    /// If nothing is reading `window`: an assistive technology that never
1325    /// started has no tree to act on.
1326    #[cfg(feature = "accesskit")]
1327    pub fn request_accessibility_action(
1328        &mut self,
1329        window: WindowId,
1330        request: accesskit::ActionRequest,
1331    ) -> Result<(), ShellError> {
1332        assert!(
1333            self.window(window)?.accessibility.is_some(),
1334            "no assistive technology is reading the window"
1335        );
1336        self.queue
1337            .push_back(ShellEvent::AccessibilityAction { window, request });
1338        Ok(())
1339    }
1340
1341    /// The tree updates the pretend assistive technology has been sent since
1342    /// it started, oldest first; `None` while none is reading.
1343    ///
1344    /// Headless-only.
1345    ///
1346    /// # Errors
1347    ///
1348    /// [`ShellError::InvalidWindow`] if the handle is stale.
1349    #[cfg(feature = "accesskit")]
1350    pub fn accessibility_updates(
1351        &self,
1352        window: WindowId,
1353    ) -> Result<Option<&[accesskit::TreeUpdate]>, ShellError> {
1354        Ok(self.window(window)?.accessibility.as_deref())
1355    }
1356
1357    /// The bytes currently offered on the in-process clipboard for `mime`.
1358    ///
1359    /// Headless-only.
1360    #[must_use]
1361    pub fn clipboard_bytes(&self, mime: MimeType) -> Option<&[u8]> {
1362        self.clipboard
1363            .iter()
1364            .find(|(offered, _)| offered.matches(mime))
1365            .map(|(_, bytes)| bytes.as_slice())
1366    }
1367
1368    /// Whether the clipboard can be read at all right now.
1369    ///
1370    /// **The focus gate, modelled.** On Wayland a client learns what is on the
1371    /// clipboard from `wl_data_device.selection`, which arrives only while one
1372    /// of its windows has keyboard focus — so a background window cannot read
1373    /// the clipboard, and a read issued a moment before focus arrives has
1374    /// nothing to answer from. `HeadlessShell` is readable by default, because
1375    /// most platforms have no such gate; set this to `false` to make a test
1376    /// walk the path a Wayland consumer will walk.
1377    ///
1378    /// A read issued while this is `false` is **held**, not answered: it is
1379    /// answered as soon as this becomes `true` again, or reported
1380    /// [`ClipboardContent::Unavailable`] once
1381    /// [`clipboard_deadline`](Self::clipboard_deadline) pumps have gone by.
1382    /// That is the seam's obligation 5, and this is how a consumer is tested
1383    /// against it.
1384    pub fn set_clipboard_readable(&mut self, readable: bool) {
1385        self.clipboard_readable = readable;
1386    }
1387
1388    /// Whether a peer holds the clipboard and never hands the data over.
1389    ///
1390    /// The other way a read can fail to complete, and the one that has no
1391    /// protocol event behind it: on Wayland the transfer is a pipe another
1392    /// application writes, and an application that accepts the descriptor and
1393    /// then hangs produces exactly this. The read is held and then reported
1394    /// [`ClipboardContent::Unavailable`] — never `Empty`, because there really
1395    /// is something on the clipboard.
1396    pub fn set_clipboard_stalled(&mut self, stalled: bool) {
1397        self.clipboard_stalled = stalled;
1398    }
1399
1400    /// Whether claiming the clipboard requires a recent user interaction.
1401    ///
1402    /// **The serial requirement, modelled.** Off by default, because X11 and
1403    /// Win32 have no such rule; on, [`clipboard_offer`](Shell::clipboard_offer)
1404    /// fails with [`ShellError::NeedsUserInteraction`] until an input event has
1405    /// been injected — a key, a pointer button, a scroll or a motion. That is
1406    /// what Wayland's `set_selection` serial and the browser's user-gesture gate
1407    /// both amount to, and it is a *feature*: it is what stops a background
1408    /// process taking the clipboard.
1409    ///
1410    /// ```
1411    /// use crcbl_shell::{ClipboardOffer, HeadlessShell, KeyCode, Shell, ShellError, WindowDesc};
1412    ///
1413    /// let mut shell = HeadlessShell::new();
1414    /// let window = shell.create_window(&WindowDesc::default())?;
1415    /// shell.require_user_interaction(true);
1416    ///
1417    /// // Nobody has touched anything, so the clipboard is not ours to take.
1418    /// let refused = shell.clipboard_offer(window, &[ClipboardOffer::text("x")]);
1419    /// assert!(matches!(refused, Err(ShellError::NeedsUserInteraction { .. })));
1420    ///
1421    /// // The copy the user actually asked for goes through.
1422    /// shell.key_press(window, KeyCode::KeyC)?;
1423    /// shell.clipboard_offer(window, &[ClipboardOffer::text("x")])?;
1424    /// # Ok::<(), ShellError>(())
1425    /// ```
1426    pub fn require_user_interaction(&mut self, required: bool) {
1427        self.clipboard_needs_interaction = required;
1428    }
1429
1430    /// Forgets that any input has been injected.
1431    ///
1432    /// For a test that wants a *second* refusal after a successful copy — a
1433    /// real serial goes stale the same way.
1434    pub fn clear_user_interaction(&mut self) {
1435        self.saw_interaction = false;
1436    }
1437
1438    /// How many pumps a held read waits before it reports
1439    /// [`ClipboardContent::Unavailable`].
1440    ///
1441    /// Defaults to [`DEFAULT_CLIPBOARD_DEADLINE`]. Zero means the very next
1442    /// pump gives up, which is the shortest way to write the timeout case.
1443    pub fn clipboard_deadline(&mut self, pumps: u32) {
1444        self.clipboard_deadline = pumps;
1445    }
1446
1447    /// How many reads have been accepted and not yet answered.
1448    ///
1449    /// Headless-only, so a test can assert that a request really is being
1450    /// *held* rather than having been answered and missed.
1451    #[must_use]
1452    pub fn held_clipboard_reads(&self) -> usize {
1453        self.reads.len()
1454    }
1455
1456    /// Replaces the clipboard with content spelled the way *another*
1457    /// application would spell it.
1458    ///
1459    /// [`clipboard_offer`](Shell::clipboard_offer) can only publish the mimes
1460    /// this engine names, so it cannot produce the case that matters: a paste
1461    /// from a foreign application whose mime string is neither `'static` nor
1462    /// one of ours. This can.
1463    pub fn set_foreign_clipboard(&mut self, offers: Vec<(ReceivedMime, Vec<u8>)>) {
1464        self.clipboard = offers;
1465    }
1466
1467    /// Whether a read issued now could be answered from what this shell knows.
1468    ///
1469    /// Two ways to say no, and they model different real things: the clipboard
1470    /// is not readable at all (Wayland's focus gate), or a peer owns it and
1471    /// never delivers (a hung application on the other end of the pipe).
1472    fn answerable(&self) -> bool {
1473        self.clipboard_readable && !self.clipboard_stalled
1474    }
1475
1476    /// The answer to one read, from the current clipboard.
1477    fn answer(&self, window: WindowId, request: ClipboardRequestId, mime: MimeType) -> ShellEvent {
1478        // Match on format, not on spelling: a peer offering `text/plain`
1479        // satisfies a request for `text/plain;charset=utf-8`. The answer
1480        // reports the peer's spelling, because that is what a real backend has
1481        // in hand and what an editor may need to echo back.
1482        let found = self
1483            .clipboard
1484            .iter()
1485            .find(|(offered, _)| offered.matches(mime));
1486        let (mime, content) = match found {
1487            Some((offered, bytes)) => (offered.clone(), ClipboardContent::Bytes(bytes.clone())),
1488            // Nothing on the clipboard, or nothing in this format — one case,
1489            // and emphatically not the same as "could not read it".
1490            None => (ReceivedMime::from(mime), ClipboardContent::Empty),
1491        };
1492        ShellEvent::ClipboardData {
1493            window,
1494            request,
1495            mime,
1496            content,
1497        }
1498    }
1499
1500    /// Answers every held read that has become answerable, and gives up on the
1501    /// ones that have run out of pumps.
1502    ///
1503    /// Runs at the top of [`pump`](Shell::pump), beside the configure delivery,
1504    /// because a read is the same kind of thing: something the window system
1505    /// will get to, not something that has already happened.
1506    fn resolve_reads(&mut self) {
1507        if self.reads.is_empty() {
1508            return;
1509        }
1510        let answerable = self.answerable();
1511        let mut held = Vec::with_capacity(self.reads.len());
1512        for mut read in core::mem::take(&mut self.reads) {
1513            // A window destroyed while its read was outstanding: the answer
1514            // would name a stale handle, which the seam forbids. Obligation 4
1515            // is about *accepted* requests, and this one's window is gone.
1516            if self.window(read.window).is_err() {
1517                continue;
1518            }
1519            if answerable {
1520                let answer = self.answer(read.window, read.request, read.mime);
1521                self.queue.push_back(answer);
1522                continue;
1523            }
1524            if read.countdown > 0 {
1525                read.countdown -= 1;
1526                held.push(read);
1527                continue;
1528            }
1529            // Out of time. Ending the request is the obligation; ending it with
1530            // `Empty` would be the lie this whole shape exists to prevent.
1531            self.queue.push_back(ShellEvent::ClipboardData {
1532                window: read.window,
1533                request: read.request,
1534                mime: ReceivedMime::from(read.mime),
1535                content: ClipboardContent::Unavailable,
1536            });
1537        }
1538        self.reads = held;
1539    }
1540
1541    /// Delivers every configure whose countdown has run out, and ticks the
1542    /// rest.
1543    ///
1544    /// Runs at the top of [`pump`](Shell::pump), so a configure scheduled
1545    /// during frame *n* is visible to the consumer no earlier than frame
1546    /// *n + 1 + delay*.
1547    fn deliver_due_configures(&mut self) {
1548        // Two phases: the window pool is borrowed mutably while deciding, and
1549        // the event queue is a separate field that cannot be touched until that
1550        // borrow ends.
1551        let mut due: Vec<(WindowId, PendingConfigure, Option<f64>)> = Vec::new();
1552        for (handle, state) in self.windows.iter_mut() {
1553            let Some(pending) = state.pending.as_mut() else {
1554                continue;
1555            };
1556            if pending.countdown > 0 {
1557                pending.countdown -= 1;
1558                continue;
1559            }
1560            let pending = state.pending.take().expect("checked just above");
1561            let previous_scale = state.configuration.map(|config| config.scale_factor);
1562            state.configuration = Some(WindowConfiguration {
1563                size: pending.size,
1564                scale_factor: pending.scale_factor,
1565                mode: pending.mode,
1566            });
1567            due.push((handle.cast(), pending, previous_scale));
1568        }
1569
1570        for (window, pending, previous_scale) in due {
1571            // A *change* of scale needs its own event; the first configure does
1572            // not, because `Resized` already carries the scale and there was
1573            // nothing to change from.
1574            if previous_scale.is_some_and(|previous| previous != pending.scale_factor) {
1575                self.queue.push_back(ShellEvent::ScaleFactorChanged {
1576                    window,
1577                    scale_factor: pending.scale_factor,
1578                    size: pending.size,
1579                });
1580            }
1581            self.queue.push_back(ShellEvent::Resized {
1582                window,
1583                size: pending.size,
1584                scale_factor: pending.scale_factor,
1585            });
1586        }
1587    }
1588
1589    /// Runs every script whose countdown has run out, and ticks the rest.
1590    fn run_due_scripts(&mut self) {
1591        if self.scripts.is_empty() {
1592            return;
1593        }
1594        let mut due = Vec::new();
1595        for mut scheduled in core::mem::take(&mut self.scripts) {
1596            if scheduled.countdown > 0 {
1597                scheduled.countdown -= 1;
1598                self.scripts.push(scheduled);
1599            } else {
1600                due.push(scheduled.script);
1601            }
1602        }
1603        for script in due {
1604            script(self);
1605        }
1606    }
1607
1608    fn window(&self, window: WindowId) -> Result<&HeadlessWindow, ShellError> {
1609        self.windows
1610            .get(window.cast())
1611            .ok_or_else(|| ShellError::invalid_window(window))
1612    }
1613
1614    fn window_mut(&mut self, window: WindowId) -> Result<&mut HeadlessWindow, ShellError> {
1615        self.windows
1616            .get_mut(window.cast())
1617            .ok_or_else(|| ShellError::invalid_window(window))
1618    }
1619
1620    fn check_window(&self, window: WindowId) -> Result<(), ShellError> {
1621        self.window(window).map(|_| ())
1622    }
1623
1624    fn unsupported(&self, what: &'static str) -> ShellError {
1625        ShellError::Unsupported {
1626            backend: ShellBackend::Headless,
1627            what,
1628        }
1629    }
1630}
1631
1632/// A stable, plausible-looking scancode for a key.
1633///
1634/// Not a claim about any real keyboard; see [`HeadlessShell::key`].
1635fn synthetic_scancode(key: KeyCode) -> Scancode {
1636    let index = KeyCode::ALL
1637        .iter()
1638        .position(|candidate| *candidate == key)
1639        .unwrap_or(0);
1640    // evdev codes reach the client offset by 8 on both Wayland and X11, so
1641    // starting there keeps the numbers in a range that looks right in a log.
1642    Scancode(index as u32 + 8)
1643}
1644
1645/// The US-layout symbol a key produces, where it produces one.
1646fn synthetic_keysym(key: KeyCode) -> Keysym {
1647    let name = key.as_str();
1648    if let Some(letter) = name.strip_prefix("Key") {
1649        // Unshifted, as XKB reports for a key with no modifiers.
1650        return Keysym::from_char(letter.to_ascii_lowercase().chars().next().unwrap_or('?'));
1651    }
1652    if let Some(digit) = name.strip_prefix("Digit") {
1653        return Keysym::from_char(digit.chars().next().unwrap_or('?'));
1654    }
1655    match key {
1656        KeyCode::Space => Keysym::from_char(' '),
1657        KeyCode::Minus => Keysym::from_char('-'),
1658        KeyCode::Equal => Keysym::from_char('='),
1659        KeyCode::Comma => Keysym::from_char(','),
1660        KeyCode::Period => Keysym::from_char('.'),
1661        KeyCode::Slash => Keysym::from_char('/'),
1662        KeyCode::Semicolon => Keysym::from_char(';'),
1663        KeyCode::Quote => Keysym::from_char('\''),
1664        KeyCode::Backslash => Keysym::from_char('\\'),
1665        KeyCode::BracketLeft => Keysym::from_char('['),
1666        KeyCode::BracketRight => Keysym::from_char(']'),
1667        KeyCode::Backquote => Keysym::from_char('`'),
1668        // Function keys, modifiers and navigation produce no character, and
1669        // report the named keysym every real backend reports for them, so a
1670        // consumer that reads Enter or an arrow from the keysym can be driven.
1671        _ => crate::keysym::named_keysym(key).unwrap_or(Keysym::NONE),
1672    }
1673}
1674
1675impl Shell for HeadlessShell {
1676    fn backend(&self) -> ShellBackend {
1677        ShellBackend::Headless
1678    }
1679
1680    fn caps(&self) -> ShellCaps {
1681        self.caps
1682    }
1683
1684    fn create_window(&mut self, desc: &WindowDesc<'_>) -> Result<WindowId, ShellError> {
1685        crate::role::check(desc, self.caps(), self.backend(), |monitor| {
1686            self.monitor(monitor).is_some()
1687        })?;
1688        if !self.windows.is_empty() && !self.caps.contains(ShellCaps::MULTI_WINDOW) {
1689            return Err(self.unsupported("a second window"));
1690        }
1691        if let DisplayMode::Borderless {
1692            monitor: Some(monitor),
1693        } = desc.mode
1694            && self.monitor(monitor).is_none()
1695        {
1696            return Err(ShellError::NoSuchMonitor(monitor.0));
1697        }
1698
1699        // `desc.accept_drops` without `ShellCaps::DRAG_DROP` is deliberately not
1700        // an error: it is a hint, and on a backend with no drag-and-drop it is
1701        // simply a hint nobody reads — which is what X11 does with it too. The
1702        // request is inert rather than ignored, because
1703        // [`drop_file`](Self::drop_file) refuses without the capability.
1704        //
1705        // The scale factor comes from the monitor the window lands on, not from
1706        // the primary one: a borderless window on a HiDPI secondary monitor is
1707        // exactly the case the windowing rules' DPI matrix is looking
1708        // for, and reporting the primary's scale there produces a swapchain at
1709        // the wrong size. `set_mode` takes the same pair from the same place.
1710        let (size, scale_factor) = match desc.mode {
1711            DisplayMode::Windowed => {
1712                let scale_factor = self.monitors[0].scale_factor;
1713                (
1714                    desc.constraints
1715                        .apply(desc.size.to_physical(scale_factor), scale_factor),
1716                    scale_factor,
1717                )
1718            }
1719            DisplayMode::Borderless { monitor } => {
1720                let monitor = monitor
1721                    .and_then(|id| self.monitor(id))
1722                    .unwrap_or(&self.monitors[0]);
1723                (monitor.size(), monitor.scale_factor)
1724            }
1725        };
1726
1727        let (parent, popup_input, panel) = match desc.role {
1728            crate::WindowRole::Popup(popup) => {
1729                self.window(popup.parent)?;
1730                (Some(popup.parent), Some(popup.input), None)
1731            }
1732            crate::WindowRole::Panel(panel) => {
1733                (None, None, Some(crate::role::KeptPanel::new(&panel)))
1734            }
1735            crate::WindowRole::Toplevel => (None, None, None),
1736        };
1737        let countdown = self.configure_delay;
1738        let window: WindowId = self
1739            .windows
1740            .insert(HeadlessWindow {
1741                title: desc.title.to_string(),
1742                // Unsized until the compositor says otherwise. This is the
1743                // whole point; see the module docs.
1744                configuration: None,
1745                pending: Some(PendingConfigure {
1746                    size,
1747                    scale_factor,
1748                    mode: desc.mode,
1749                    countdown,
1750                }),
1751                requested_mode: desc.mode,
1752                requested_constraints: desc.constraints,
1753                focused: false,
1754                visible: desc.visible,
1755                pointer_mode: PointerMode::Free,
1756                cursor: Some(CursorIcon::Default),
1757                close_pending: false,
1758                accept_drops: desc.accept_drops,
1759                parent,
1760                popup_input,
1761                panel,
1762                text_input: None,
1763                text_input_area: None,
1764                input_region: None,
1765                idle_inhibit: false,
1766                #[cfg(feature = "accesskit")]
1767                accessibility: None,
1768            })
1769            .cast();
1770        Ok(window)
1771    }
1772
1773    /// Destroys the window and, first, every popup that belongs to it — each
1774    /// with its own [`ShellEvent::WindowDestroyed`] — as every window system
1775    /// destroys a popup with its parent.
1776    fn destroy_window(&mut self, window: WindowId) -> Result<(), ShellError> {
1777        self.window(window)?;
1778        let popups: Vec<WindowId> = self
1779            .windows
1780            .iter()
1781            .filter(|(_, state)| state.parent == Some(window))
1782            .map(|(id, _)| id.cast())
1783            .collect();
1784        for popup in popups {
1785            self.destroy_window(popup)?;
1786        }
1787        self.windows
1788            .remove(window.cast())
1789            .ok_or_else(|| ShellError::invalid_window(window))?;
1790        self.queue.push_back(ShellEvent::WindowDestroyed { window });
1791        Ok(())
1792    }
1793
1794    fn window_state(&self, window: WindowId) -> Result<WindowState, ShellError> {
1795        let state = self.window(window)?;
1796        Ok(WindowState {
1797            configuration: state.configuration,
1798            requested_mode: state.requested_mode,
1799            requested_constraints: state.requested_constraints,
1800            focused: state.focused,
1801            visible: state.visible,
1802            pointer_mode: state.pointer_mode,
1803            close_pending: state.close_pending,
1804        })
1805    }
1806
1807    fn set_title(&mut self, window: WindowId, title: &str) -> Result<(), ShellError> {
1808        self.window_mut(window)?.title = title.to_string();
1809        Ok(())
1810    }
1811
1812    fn set_visible(&mut self, window: WindowId, visible: bool) -> Result<(), ShellError> {
1813        self.window_mut(window)?.visible = visible;
1814        Ok(())
1815    }
1816
1817    fn set_mode(&mut self, window: WindowId, mode: DisplayMode) -> Result<(), ShellError> {
1818        let target = match mode {
1819            DisplayMode::Windowed => None,
1820            DisplayMode::Borderless { monitor } => {
1821                let monitor = match monitor {
1822                    Some(id) => self
1823                        .monitor(id)
1824                        .ok_or(ShellError::NoSuchMonitor(id.0))?
1825                        .clone(),
1826                    None => self.monitors[0].clone(),
1827                };
1828                Some(monitor)
1829            }
1830        };
1831        let countdown = self.configure_delay;
1832
1833        let state = self.window_mut(window)?;
1834        // The request is recorded immediately — we said it, so it is a fact —
1835        // and the *effect* is scheduled. Nothing about the window's reported
1836        // configuration changes until the configure is delivered, so a consumer
1837        // that reads back its own request as fact is wrong here exactly as it
1838        // would be on Wayland.
1839        state.requested_mode = mode;
1840        let (size, scale_factor) = match &target {
1841            Some(monitor) => (monitor.size(), monitor.scale_factor),
1842            // Leaving borderless restores nothing in particular — a real
1843            // compositor restores the pre-fullscreen geometry, and a test that
1844            // cares injects the resize it expects.
1845            None => (state.base_size(), state.scale_factor()),
1846        };
1847        state.pending = Some(PendingConfigure {
1848            size,
1849            scale_factor,
1850            mode,
1851            countdown,
1852        });
1853        Ok(())
1854    }
1855
1856    fn set_constraints(
1857        &mut self,
1858        window: WindowId,
1859        constraints: SizeConstraints,
1860    ) -> Result<(), ShellError> {
1861        let countdown = self.configure_delay;
1862        let state = self.window_mut(window)?;
1863        state.requested_constraints = constraints;
1864
1865        // A configure already on its way is the authoritative statement of what
1866        // is coming, whether or not the window has been configured before, so
1867        // the hints fold into it rather than scheduling a second one. Rebuilding
1868        // it from the *effective* configuration instead would silently discard
1869        // whatever `set_mode` had put there — leaving `requested_mode` set,
1870        // `effective_mode` unchanged and `mode_request_honoured` false forever.
1871        if let Some(pending) = state.pending.as_mut() {
1872            pending.size = constraints.apply(pending.size, pending.scale_factor);
1873            return Ok(());
1874        }
1875
1876        // Nothing in flight: the window system already told us a size, and if
1877        // the new hints disagree with it, a compositor that honours them answers
1878        // with a fresh configure — later, not now.
1879        if let Some(config) = state.configuration {
1880            let constrained = constraints.apply(config.size, config.scale_factor);
1881            if constrained != config.size {
1882                state.pending = Some(PendingConfigure {
1883                    size: constrained,
1884                    scale_factor: config.scale_factor,
1885                    mode: config.mode,
1886                    countdown,
1887                });
1888            }
1889        }
1890        Ok(())
1891    }
1892
1893    /// Takes the new size as a pending configure, like a window system that
1894    /// answers a move with a resize. The anchor places nothing: there is no
1895    /// screen to place against.
1896    fn reposition_popup(
1897        &mut self,
1898        popup: WindowId,
1899        anchor: LogicalRect,
1900        size: LogicalSize,
1901    ) -> Result<(), ShellError> {
1902        let _ = anchor;
1903        let countdown = self.configure_delay;
1904        let state = self.window_mut(popup)?;
1905        if state.parent.is_none() {
1906            return Err(crate::role::not_a_popup(popup));
1907        }
1908        state.configure_at(size, countdown);
1909        Ok(())
1910    }
1911
1912    /// Records the new descriptor, which [`panel`](Self::panel) reads back,
1913    /// and takes the new size as a pending configure, as
1914    /// [`create_window`](Shell::create_window) takes a panel's first.
1915    fn set_panel(
1916        &mut self,
1917        window: WindowId,
1918        size: LogicalSize,
1919        panel: &crate::PanelDesc<'_>,
1920    ) -> Result<(), ShellError> {
1921        let was = self.window(window)?.panel.as_ref().map(|kept| kept.desc());
1922        crate::role::check_set_panel(window, was, panel, self.caps, self.backend(), |monitor| {
1923            self.monitor(monitor).is_some()
1924        })?;
1925        let countdown = self.configure_delay;
1926        let state = self.window_mut(window)?;
1927        state.panel = Some(crate::role::KeptPanel::new(panel));
1928        state.configure_at(size, countdown);
1929        Ok(())
1930    }
1931
1932    fn monitors(&self) -> &[MonitorInfo] {
1933        &self.monitors
1934    }
1935
1936    fn pump(&mut self, sink: &mut dyn FnMut(ShellEvent)) {
1937        self.keep_alive();
1938        if self.outputs_powered {
1939            let windows = &self.windows;
1940            self.queue.extend(
1941                self.frames
1942                    .take_due(|window| windows.contains(window.cast())),
1943            );
1944        }
1945        // Drain by count rather than `while let`: a sink that injects further
1946        // events (a UI that opens a window on a click) must not be able to spin
1947        // this loop forever, and the events it queued belong to the next frame
1948        // anyway — which is exactly what a real backend's socket read does.
1949        for _ in 0..self.queue.len() {
1950            let Some(event) = self.queue.pop_front() else {
1951                break;
1952            };
1953            sink(event);
1954        }
1955    }
1956
1957    /// Lets the configures, the held reads and the scheduled scripts come due,
1958    /// and keeps what they produce.
1959    ///
1960    /// **This counts as a pump** for each of this shell's pump-counted delays,
1961    /// [`set_configure_delay`](Self::set_configure_delay),
1962    /// [`clipboard_deadline`](Self::clipboard_deadline) and
1963    /// [`schedule`](Self::schedule): each counts the window system's turns, and
1964    /// delivery is the only part of a turn this leaves out.
1965    fn keep_alive(&mut self) {
1966        self.deliver_due_configures();
1967        self.resolve_reads();
1968        self.run_due_scripts();
1969    }
1970
1971    /// Sleeps as far as a shell with no window system behind it can.
1972    ///
1973    /// This shell reports [`ShellCaps::EVENT_WAIT`] by default, and that bit
1974    /// says `wait_events` *genuinely blocks* — so it does: with the capability
1975    /// set, nothing already queued, no frame due and no script
1976    /// [scheduled](Self::schedule), this really sleeps for
1977    /// `timeout`, and an editor-style idle loop tested here idles rather than
1978    /// spinning. Without
1979    /// the capability it returns immediately, like every backend that cannot
1980    /// block.
1981    ///
1982    /// A [`waker`](Shell::waker) ends the sleep early, from any thread, and so
1983    /// does a wake rung before the wait began.
1984    ///
1985    /// `None` — "until something happens" — returns immediately while no waker
1986    /// has been handed out, because then the only thing that can make
1987    /// something happen in a headless shell is the caller, on this thread, and
1988    /// blocking forever would be a deadlock by construction rather than a
1989    /// wait. Once a waker exists, another thread can, so `None` sleeps until it
1990    /// rings.
1991    fn wait_events(&mut self, timeout: Option<Duration>) {
1992        self.waits += 1;
1993        if !self.caps.contains(ShellCaps::EVENT_WAIT)
1994            || !self.queue.is_empty()
1995            || !self.scripts.is_empty()
1996            || (self.outputs_powered && self.frames.is_pending())
1997        {
1998            return;
1999        }
2000        match (&self.wake, timeout) {
2001            (Some(wake), timeout) => wake.wait(timeout),
2002            (None, Some(timeout)) => std::thread::sleep(timeout),
2003            (None, None) => {}
2004        }
2005    }
2006
2007    /// The headless doorbell: a condition variable [`wait_events`](Shell::wait_events)
2008    /// sleeps on, rung from any thread.
2009    fn waker(&mut self) -> Option<ShellWaker> {
2010        let wake = self.wake.get_or_insert_with(Arc::default);
2011        Some(ShellWaker::new(Arc::clone(wake) as Arc<dyn WakeSignal>))
2012    }
2013
2014    /// The seam-level spelling of [`set_time`](Self::set_time).
2015    ///
2016    /// Both exist because a test drives this shell through the concrete type
2017    /// and calls `set_time` every frame, while a consumer written against
2018    /// `dyn Shell` can only reach the trait — and the trait method is the one
2019    /// a real backend has to implement, so it must be exercised here too.
2020    fn align_event_clock(&mut self, elapsed: Duration) {
2021        self.set_time(elapsed);
2022    }
2023
2024    fn surface_target(&self, window: WindowId) -> Result<SurfaceTarget, ShellError> {
2025        // Available from creation — the *handle* exists as soon as the window
2026        // does — and constant thereafter. It deliberately carries no size: the
2027        // extent travels through `WindowState::size` and the swapchain
2028        // descriptor, so nothing here goes stale on a resize. The only thing
2029        // this call can fail on is a dead handle.
2030        self.window(window)?;
2031        Ok(SurfaceTarget::Offscreen)
2032    }
2033
2034    fn set_pointer_mode(&mut self, window: WindowId, mode: PointerMode) -> Result<(), ShellError> {
2035        if !self.caps.contains(mode.required_cap()) {
2036            return Err(self.unsupported(mode.as_str()));
2037        }
2038        self.window_mut(window)?.pointer_mode = mode;
2039        Ok(())
2040    }
2041
2042    /// Records the request, which
2043    /// [`text_input`](HeadlessShell::text_input) reads back; there is no
2044    /// input method to tell.
2045    fn set_text_input(
2046        &mut self,
2047        window: WindowId,
2048        field: Option<TextPurpose>,
2049    ) -> Result<(), ShellError> {
2050        self.window_mut(window)?.text_input = field;
2051        Ok(())
2052    }
2053
2054    /// Records the area, which
2055    /// [`text_input_area`](HeadlessShell::text_input_area) reads back; there
2056    /// is no input method to place.
2057    fn set_text_input_area(
2058        &mut self,
2059        window: WindowId,
2060        area: Option<PhysicalRect>,
2061    ) -> Result<(), ShellError> {
2062        self.window_mut(window)?.text_input_area = area;
2063        Ok(())
2064    }
2065
2066    /// Records the region, which
2067    /// [`input_region`](HeadlessShell::input_region) reads back; there is no
2068    /// pointer to route. A passthrough popup records it too, though no
2069    /// backend acts on it there.
2070    fn set_input_region(
2071        &mut self,
2072        window: WindowId,
2073        region: Option<&[PhysicalRect]>,
2074    ) -> Result<(), ShellError> {
2075        self.window_mut(window)?.input_region = region.map(<[PhysicalRect]>::to_vec);
2076        Ok(())
2077    }
2078
2079    /// Records the request, which
2080    /// [`idle_inhibited`](HeadlessShell::idle_inhibited) reads back; there is
2081    /// no display to keep on. Refused without [`ShellCaps::IDLE_INHIBIT`], as
2082    /// a backend that cannot act on it refuses.
2083    fn set_idle_inhibit(&mut self, window: WindowId, inhibit: bool) -> Result<(), ShellError> {
2084        if !self.caps.contains(ShellCaps::IDLE_INHIBIT) {
2085            return Err(self.unsupported("idle inhibit"));
2086        }
2087        self.window_mut(window)?.idle_inhibit = inhibit;
2088        Ok(())
2089    }
2090
2091    /// Records the request, which
2092    /// [`opened_urls`](HeadlessShell::opened_urls) reads back; there is no
2093    /// browser to open. Refused without [`ShellCaps::OPEN_URL`], as a backend
2094    /// that cannot act on it refuses.
2095    fn open_url(&mut self, window: WindowId, url: &WebUrl) -> Result<(), ShellError> {
2096        if !self.caps.contains(ShellCaps::OPEN_URL) {
2097            return Err(self.unsupported("opening a URL"));
2098        }
2099        self.check_window(window)?;
2100        self.opened_urls.push((window, url.clone()));
2101        Ok(())
2102    }
2103
2104    /// Answered at the next pump, as every backend without
2105    /// [`ShellCaps::FRAME_CALLBACK`] answers; there is no compositor to hold
2106    /// it back. [`frame_requested`](HeadlessShell::frame_requested) reads
2107    /// whether one is outstanding.
2108    fn request_frame(&mut self, window: WindowId) -> Result<(), ShellError> {
2109        self.window(window)?;
2110        self.frames.request(window);
2111        Ok(())
2112    }
2113
2114    #[cfg(feature = "accesskit")]
2115    fn update_accessibility(
2116        &mut self,
2117        window: WindowId,
2118        update: accesskit::TreeUpdate,
2119    ) -> Result<(), ShellError> {
2120        if let Some(updates) = &mut self.window_mut(window)?.accessibility {
2121            updates.push(update);
2122        }
2123        Ok(())
2124    }
2125
2126    fn set_cursor(
2127        &mut self,
2128        window: WindowId,
2129        cursor: Option<CursorIcon>,
2130    ) -> Result<(), ShellError> {
2131        self.window_mut(window)?.cursor = cursor;
2132        Ok(())
2133    }
2134
2135    fn warp_pointer(
2136        &mut self,
2137        window: WindowId,
2138        position: PhysicalPoint,
2139    ) -> Result<(), ShellError> {
2140        if !self.caps.contains(ShellCaps::POINTER_WARP) {
2141            return Err(self.unsupported("pointer warp"));
2142        }
2143        self.check_window(window)?;
2144        // A warp produces motion, as it does on every platform that has one —
2145        // which is why code that warps in response to motion oscillates.
2146        let event = ShellEvent::PointerMotion {
2147            window,
2148            device: VIRTUAL_DEVICE,
2149            time: self.now(),
2150            abs: Some(position),
2151            raw_delta: None,
2152        };
2153        self.queue.push_back(event);
2154        Ok(())
2155    }
2156
2157    fn reply_close_request(
2158        &mut self,
2159        window: WindowId,
2160        reply: CloseReply,
2161    ) -> Result<(), ShellError> {
2162        let state = self.window_mut(window)?;
2163        if !state.close_pending {
2164            return Err(ShellError::NoPendingCloseRequest { window });
2165        }
2166        state.close_pending = false;
2167        match reply {
2168            CloseReply::Close => self.destroy_window(window),
2169            CloseReply::Keep => Ok(()),
2170        }
2171    }
2172
2173    /// Claims the in-process clipboard.
2174    ///
2175    /// # Errors
2176    ///
2177    /// [`ShellError::Unsupported`] without [`ShellCaps::CLIPBOARD`],
2178    /// [`ShellError::InvalidWindow`] for a stale handle, or
2179    /// [`ShellError::NeedsUserInteraction`] when
2180    /// [`require_user_interaction`](Self::require_user_interaction) is on and
2181    /// no input has been injected since — the modelled form of Wayland's serial
2182    /// requirement and the browser's user-gesture gate.
2183    fn clipboard_offer(
2184        &mut self,
2185        window: WindowId,
2186        offers: &[ClipboardOffer<'_>],
2187    ) -> Result<(), ShellError> {
2188        if !self.caps.contains(ShellCaps::CLIPBOARD) {
2189            return Err(self.unsupported("clipboard"));
2190        }
2191        self.check_window(window)?;
2192        if self.clipboard_needs_interaction && !self.saw_interaction {
2193            return Err(ShellError::NeedsUserInteraction {
2194                backend: ShellBackend::Headless,
2195                what: "claiming the clipboard",
2196            });
2197        }
2198        self.clipboard = offers
2199            .iter()
2200            .map(|offer| (ReceivedMime::from(offer.mime), offer.bytes.to_vec()))
2201            .collect();
2202        Ok(())
2203    }
2204
2205    /// Accepts a read, answering it now if the clipboard is readable and
2206    /// **holding** it if it is not.
2207    ///
2208    /// The held path is the seam's obligation 5, modelled: with
2209    /// [`set_clipboard_readable(false)`](Self::set_clipboard_readable) the
2210    /// answer waits, exactly as it does on Wayland while another client has
2211    /// focus, and a consumer that assumed an immediate empty answer sees the
2212    /// difference here rather than on someone's desktop.
2213    ///
2214    /// # Errors
2215    ///
2216    /// [`ShellError::Unsupported`] without [`ShellCaps::CLIPBOARD`], or
2217    /// [`ShellError::InvalidWindow`] for a stale handle.
2218    fn clipboard_request(
2219        &mut self,
2220        window: WindowId,
2221        mime: MimeType,
2222    ) -> Result<ClipboardRequestId, ShellError> {
2223        if !self.caps.contains(ShellCaps::CLIPBOARD) {
2224            return Err(self.unsupported("clipboard"));
2225        }
2226        self.check_window(window)?;
2227        let request = ClipboardRequestId(self.next_request_id);
2228        self.next_request_id += 1;
2229        if self.answerable() {
2230            let answer = self.answer(window, request, mime);
2231            // Queued rather than returned: the whole point of the asynchronous
2232            // shape is that a consumer written against it also works on X11,
2233            // where the answer is several round trips away.
2234            self.queue.push_back(answer);
2235        } else {
2236            self.reads.push(PendingRead {
2237                window,
2238                request,
2239                mime,
2240                countdown: self.clipboard_deadline,
2241            });
2242        }
2243        Ok(request)
2244    }
2245
2246    /// Whether a read would be answered without waiting.
2247    ///
2248    /// The default would be "yes, always"; this one can be told otherwise, so
2249    /// that a consumer can be tested against a backend that has a focus gate
2250    /// without there being a compositor in the room.
2251    fn clipboard_readable(&self, window: WindowId) -> bool {
2252        self.caps.contains(ShellCaps::CLIPBOARD) && self.window(window).is_ok() && self.answerable()
2253    }
2254}
2255
2256#[cfg(test)]
2257mod tests {
2258    use super::*;
2259    use crate::{AspectRatio, LogicalSize};
2260
2261    /// A shell plus an *unconfigured* window — the state every window starts in.
2262    fn shell_with_window() -> (HeadlessShell, WindowId) {
2263        let mut shell = HeadlessShell::new();
2264        let window = shell
2265            .create_window(&WindowDesc::default())
2266            .expect("headless window creation never fails");
2267        (shell, window)
2268    }
2269
2270    /// A shell plus a window that has been through the configure handshake.
2271    fn shell_with_configured_window() -> (HeadlessShell, WindowId) {
2272        let (mut shell, window) = shell_with_window();
2273        settle(&mut shell);
2274        assert!(shell.window_state(window).expect("state").is_configured());
2275        (shell, window)
2276    }
2277
2278    /// Pumps until nothing new arrives, discarding events.
2279    fn settle(shell: &mut HeadlessShell) {
2280        for _ in 0..8 {
2281            let mut seen = 0;
2282            shell.pump(&mut |_| seen += 1);
2283            if seen == 0 && shell.windows.iter().all(|(_, w)| w.pending.is_none()) {
2284                return;
2285            }
2286        }
2287        panic!("the shell never settled");
2288    }
2289
2290    fn drain(shell: &mut HeadlessShell) -> Vec<ShellEvent> {
2291        let mut events = Vec::new();
2292        shell.pump(&mut |event| events.push(event));
2293        events
2294    }
2295
2296    fn names(events: &[ShellEvent]) -> Vec<&'static str> {
2297        events.iter().map(ShellEvent::name).collect()
2298    }
2299
2300    /// The shape a P1 swapchain-creating consumer has: it needs an extent, and
2301    /// there is no extent before the first configure.
2302    fn create_swapchain(state: &WindowState) -> Result<PhysicalSize, &'static str> {
2303        let size = state.size().ok_or("window is not configured yet")?;
2304        if size.is_empty() {
2305            return Err("zero-extent swapchain");
2306        }
2307        Ok(size)
2308    }
2309
2310    // ------------------------------------------------------------- activation
2311
2312    /// A backend with no activation tokens answers `None` for a live window
2313    /// and refuses a stale one, which is the trait's default.
2314    #[test]
2315    fn a_backend_without_activation_answers_none() {
2316        let (mut shell, window) = shell_with_window();
2317        assert_eq!(shell.activation_token(window).expect("a live window"), None);
2318        shell.destroy_window(window).expect("destroy");
2319        assert!(matches!(
2320            shell.activation_token(window),
2321            Err(ShellError::InvalidWindow { .. })
2322        ));
2323    }
2324
2325    // ------------------------------------------------------------ accessibility
2326
2327    /// A tree reaches the pretend reader only while it reads, and each start
2328    /// and stop is one event: what a program that sends every frame relies on.
2329    #[cfg(feature = "accesskit")]
2330    #[test]
2331    fn a_tree_reaches_the_reader_only_while_it_reads() {
2332        use accesskit::{Action, ActionRequest, Node, NodeId, Role, TreeId, TreeInfo, TreeUpdate};
2333
2334        let (mut shell, window) = shell_with_configured_window();
2335        let update = |label: &str| TreeUpdate {
2336            nodes: vec![(NodeId(1), {
2337                let mut node = Node::new(Role::Window);
2338                node.set_label(label);
2339                node
2340            })],
2341            tree: Some(TreeInfo::new(NodeId(1))),
2342            tree_id: TreeId::ROOT,
2343            focus: NodeId(1),
2344        };
2345
2346        shell
2347            .update_accessibility(window, update("unread"))
2348            .expect("update");
2349        assert_eq!(shell.accessibility_updates(window).expect("updates"), None);
2350
2351        shell.activate_accessibility(window).expect("activate");
2352        shell
2353            .activate_accessibility(window)
2354            .expect("activate twice");
2355        shell
2356            .update_accessibility(window, update("read"))
2357            .expect("update");
2358        let click = ActionRequest {
2359            action: Action::Click,
2360            target_tree: TreeId::ROOT,
2361            target_node: NodeId(1),
2362            data: None,
2363        };
2364        shell
2365            .request_accessibility_action(window, click.clone())
2366            .expect("action");
2367        assert_eq!(
2368            shell.accessibility_updates(window).expect("updates"),
2369            Some(&[update("read")][..])
2370        );
2371        let events = drain(&mut shell);
2372        assert_eq!(
2373            names(&events),
2374            ["AccessibilityActivated", "AccessibilityAction"]
2375        );
2376        assert_eq!(
2377            events[1],
2378            ShellEvent::AccessibilityAction {
2379                window,
2380                request: click
2381            }
2382        );
2383
2384        shell.deactivate_accessibility(window).expect("deactivate");
2385        shell
2386            .deactivate_accessibility(window)
2387            .expect("deactivate twice");
2388        shell
2389            .update_accessibility(window, update("gone"))
2390            .expect("update");
2391        assert_eq!(shell.accessibility_updates(window).expect("updates"), None);
2392        assert_eq!(names(&drain(&mut shell)), ["AccessibilityDeactivated"]);
2393    }
2394
2395    // ---------------------------------------------------------------- configure
2396
2397    #[test]
2398    fn a_new_window_has_no_size_until_a_later_pump() {
2399        let (mut shell, window) = shell_with_window();
2400
2401        // Nothing has been reported. Not "0x0", not "the requested size" —
2402        // nothing.
2403        let state = shell.window_state(window).expect("state");
2404        assert!(!state.is_configured());
2405        assert_eq!(state.size(), None);
2406        assert_eq!(state.scale_factor(), None);
2407        assert_eq!(state.effective_mode(), None);
2408        assert_eq!(state.requested_mode, DisplayMode::Windowed);
2409
2410        // The default delay is one pump: the first delivers nothing.
2411        assert_eq!(drain(&mut shell), Vec::new());
2412        assert!(!shell.window_state(window).expect("state").is_configured());
2413
2414        // The second delivers the configure.
2415        let events = drain(&mut shell);
2416        assert_eq!(
2417            events,
2418            vec![ShellEvent::Resized {
2419                window,
2420                size: PhysicalSize::new(1280, 720),
2421                scale_factor: 1.0,
2422            }]
2423        );
2424        let state = shell.window_state(window).expect("state");
2425        assert_eq!(state.size(), Some(PhysicalSize::new(1280, 720)));
2426        assert_eq!(state.scale_factor(), Some(1.0));
2427        assert_eq!(state.effective_mode(), Some(DisplayMode::Windowed));
2428        assert!(state.mode_request_honoured());
2429    }
2430
2431    /// A loader's `keep_alive` is a turn of the window system that keeps what
2432    /// the turn produced: the configure comes due, and it and an event that was
2433    /// already waiting are delivered by the next pump, in order, once each.
2434    #[test]
2435    fn keep_alive_takes_a_turn_and_keeps_everything_for_the_next_pump() {
2436        let (mut shell, window) = shell_with_window();
2437        shell.inject(ShellEvent::CloseRequested { window });
2438
2439        // The configure waits this many turns and comes due on the next one.
2440        for _ in 0..=DEFAULT_CONFIGURE_DELAY {
2441            shell.keep_alive();
2442        }
2443        assert!(
2444            shell.window_state(window).expect("state").is_configured(),
2445            "every turn the configure waits for was taken by keep_alive"
2446        );
2447
2448        assert_eq!(
2449            drain(&mut shell),
2450            vec![
2451                ShellEvent::CloseRequested { window },
2452                ShellEvent::Resized {
2453                    window,
2454                    size: PhysicalSize::new(1280, 720),
2455                    scale_factor: 1.0,
2456                },
2457            ],
2458            "nothing keep_alive saw was delivered or dropped"
2459        );
2460        assert_eq!(drain(&mut shell), Vec::new(), "and each arrived once");
2461    }
2462
2463    #[test]
2464    fn a_consumer_that_skips_the_wait_gets_a_clean_error_not_a_wrong_extent() {
2465        let (mut shell, window) = shell_with_window();
2466
2467        // The failure mode this whole design exists to force.
2468        assert_eq!(
2469            create_swapchain(&shell.window_state(window).expect("state")),
2470            Err("window is not configured yet")
2471        );
2472
2473        // And the surface handle *is* available meanwhile — only the extent is
2474        // pending. The target carries no size at all, which is the stronger
2475        // version of the same guarantee: there is no plausible-looking number
2476        // in it for a consumer to mistake for the size the window is about to
2477        // have.
2478        let target = shell.surface_target(window).expect("the handle exists");
2479        assert_eq!(target, SurfaceTarget::Offscreen);
2480
2481        // The loop a consumer must write.
2482        let size = loop {
2483            shell.pump(&mut |_| {});
2484            if let Ok(size) = create_swapchain(&shell.window_state(window).expect("state")) {
2485                break size;
2486            }
2487        };
2488        assert_eq!(size, PhysicalSize::new(1280, 720));
2489        // Configuring the window did not change the target: a HAL surface made
2490        // from the pre-configure value is still describing the right object.
2491        assert_eq!(
2492            shell.surface_target(window).expect("target"),
2493            target,
2494            "the target is invariant under a configure"
2495        );
2496    }
2497
2498    #[test]
2499    fn the_configure_delay_is_a_knob() {
2500        let mut shell = HeadlessShell::new().with_configure_delay(3);
2501        let window = shell.create_window(&WindowDesc::default()).expect("window");
2502        for pump in 0..3 {
2503            assert_eq!(drain(&mut shell), Vec::new(), "pump {pump}");
2504            assert!(!shell.window_state(window).expect("state").is_configured());
2505        }
2506        assert_eq!(names(&drain(&mut shell)), ["Resized"]);
2507        assert!(shell.window_state(window).expect("state").is_configured());
2508
2509        // Zero means "configured on the first pump", for tests about something
2510        // else.
2511        let mut shell = HeadlessShell::new().with_configure_delay(0);
2512        let window = shell.create_window(&WindowDesc::default()).expect("window");
2513        assert_eq!(names(&drain(&mut shell)), ["Resized"]);
2514        assert!(shell.window_state(window).expect("state").is_configured());
2515
2516        shell.set_configure_delay(2);
2517        shell
2518            .set_mode(window, DisplayMode::Borderless { monitor: None })
2519            .expect("request");
2520        assert_eq!(drain(&mut shell), Vec::new());
2521        assert_eq!(drain(&mut shell), Vec::new());
2522        assert_eq!(names(&drain(&mut shell)), ["Resized"]);
2523    }
2524
2525    #[test]
2526    fn set_mode_is_a_request_whose_effect_arrives_later() {
2527        let (mut shell, window) = shell_with_configured_window();
2528        shell
2529            .set_mode(window, DisplayMode::Borderless { monitor: None })
2530            .expect("request");
2531
2532        // The request is a fact; the effect is not.
2533        let state = shell.window_state(window).expect("state");
2534        assert_eq!(
2535            state.requested_mode,
2536            DisplayMode::Borderless { monitor: None }
2537        );
2538        assert_eq!(
2539            state.effective_mode(),
2540            Some(DisplayMode::Windowed),
2541            "still windowed until the window system says otherwise"
2542        );
2543        assert!(
2544            !state.mode_request_honoured(),
2545            "a UI toggle reading the request instead of the effect would lie here"
2546        );
2547        assert_eq!(state.size(), Some(PhysicalSize::new(1280, 720)));
2548
2549        settle(&mut shell);
2550        let state = shell.window_state(window).expect("state");
2551        assert_eq!(
2552            state.effective_mode(),
2553            Some(DisplayMode::Borderless { monitor: None })
2554        );
2555        assert!(state.mode_request_honoured());
2556        assert_eq!(state.size(), Some(PhysicalSize::new(1920, 1080)));
2557    }
2558
2559    #[test]
2560    fn a_refused_mode_is_expressible_through_injection() {
2561        // What a compositor that says no looks like: the request stands, and
2562        // the configure that arrives says something else.
2563        let (mut shell, window) = shell_with_configured_window();
2564        shell
2565            .set_mode(window, DisplayMode::Borderless { monitor: None })
2566            .expect("request");
2567        // The compositor answers with a windowed configure instead.
2568        shell
2569            .resize(window, PhysicalSize::new(1280, 720))
2570            .expect("answer");
2571        let state = shell.window_state(window).expect("state");
2572        assert_eq!(state.effective_mode(), Some(DisplayMode::Windowed));
2573        assert!(!state.mode_request_honoured());
2574    }
2575
2576    /// A reconfigured panel keeps its new descriptor and is configured at its
2577    /// new size, reported by a `Resized` as its first size was; a change of
2578    /// namespace or monitor, a window that is no panel, a descriptor a new
2579    /// panel could not have and a stale handle are each refused, and a
2580    /// refusal changes nothing.
2581    #[test]
2582    fn a_reconfigured_panel_is_configured_at_its_new_size() {
2583        let mut shell = HeadlessShell::new();
2584        let monitor = shell.monitors()[0].id;
2585        let bar = crate::PanelDesc {
2586            namespace: "bar",
2587            monitor: Some(monitor),
2588            anchor: crate::PanelAnchor::TOP | crate::PanelAnchor::LEFT | crate::PanelAnchor::RIGHT,
2589            reserve: crate::Reserve::OwnExtent,
2590            ..crate::PanelDesc::default()
2591        };
2592        let window = shell
2593            .create_window(&WindowDesc {
2594                size: LogicalSize::new(400.0, 30.0),
2595                role: crate::WindowRole::Panel(bar),
2596                ..WindowDesc::default()
2597            })
2598            .expect("a panel");
2599        settle(&mut shell);
2600        let scale = shell
2601            .window_state(window)
2602            .expect("live")
2603            .scale_factor()
2604            .expect("configured");
2605
2606        let taller = crate::PanelDesc {
2607            layer: crate::PanelLayer::Overlay,
2608            margins: crate::Margins {
2609                top: 4.0,
2610                ..crate::Margins::default()
2611            },
2612            keyboard: crate::PanelKeyboard::OnDemand,
2613            ..bar
2614        };
2615        let size = LogicalSize::new(400.0, 50.0);
2616        shell.set_panel(window, size, &taller).expect("set_panel");
2617        assert_eq!(shell.panel(window).expect("live"), Some(taller));
2618        assert_eq!(
2619            shell.window_state(window).expect("live").size(),
2620            Some(LogicalSize::new(400.0, 30.0).to_physical(scale)),
2621            "a request: nothing changes before the window system answers"
2622        );
2623        let mut resized = Vec::new();
2624        for _ in 0..8 {
2625            resized.extend(
2626                drain(&mut shell)
2627                    .into_iter()
2628                    .filter_map(|event| match event {
2629                        ShellEvent::Resized {
2630                            window: of, size, ..
2631                        } if of == window => Some(size),
2632                        _ => None,
2633                    }),
2634            );
2635        }
2636        assert_eq!(resized, [size.to_physical(scale)]);
2637
2638        let refused = |shell: &mut HeadlessShell, panel: &crate::PanelDesc<'_>| match shell
2639            .set_panel(window, LogicalSize::new(1.0, 1.0), panel)
2640        {
2641            Err(ShellError::InvalidDescriptor(message)) => message,
2642            other => panic!("expected InvalidDescriptor, got {other:?}"),
2643        };
2644        let renamed = crate::PanelDesc {
2645            namespace: "dock",
2646            ..taller
2647        };
2648        assert!(refused(&mut shell, &renamed).contains("namespace"));
2649        let anywhere = crate::PanelDesc {
2650            monitor: None,
2651            ..taller
2652        };
2653        assert!(refused(&mut shell, &anywhere).contains("monitor"));
2654        let toplevel = shell
2655            .create_window(&WindowDesc::default())
2656            .expect("a toplevel");
2657        assert!(matches!(
2658            shell.set_panel(toplevel, size, &taller),
2659            Err(ShellError::InvalidDescriptor(message)) if message.contains("not a panel")
2660        ));
2661        let cornered = crate::PanelDesc {
2662            anchor: crate::PanelAnchor::TOP | crate::PanelAnchor::LEFT,
2663            ..taller
2664        };
2665        assert!(matches!(
2666            shell.set_panel(window, size, &cornered),
2667            Err(ShellError::Unsupported { .. })
2668        ));
2669        assert_eq!(
2670            shell.panel(window).expect("live"),
2671            Some(taller),
2672            "a refused descriptor is not recorded"
2673        );
2674        assert_eq!(shell.panel(toplevel).expect("live"), None);
2675
2676        shell.destroy_window(window).expect("destroy");
2677        assert!(matches!(
2678            shell.set_panel(window, size, &taller),
2679            Err(ShellError::InvalidWindow { .. })
2680        ));
2681    }
2682
2683    /// A repositioned popup is configured at its new size, as a window system
2684    /// answers a move; a window that is not a popup is refused.
2685    #[test]
2686    fn a_repositioned_popup_is_configured_at_its_new_size() {
2687        let (mut shell, window) = shell_with_configured_window();
2688        let anchor = crate::LogicalRect::new(
2689            crate::LogicalPoint::new(10.0, 10.0),
2690            LogicalSize::new(100.0, 20.0),
2691        );
2692        let popup = shell
2693            .create_window(&WindowDesc {
2694                size: LogicalSize::new(200.0, 150.0),
2695                role: crate::WindowRole::Popup(crate::PopupDesc {
2696                    parent: window,
2697                    anchor,
2698                    placement: crate::PopupPlacement::Below,
2699                    input: crate::PopupInput::Pointer,
2700                }),
2701                ..WindowDesc::default()
2702            })
2703            .expect("a popup");
2704        settle(&mut shell);
2705        let scale = shell
2706            .window_state(popup)
2707            .expect("live")
2708            .scale_factor()
2709            .expect("configured");
2710
2711        let moved = LogicalSize::new(240.0, 90.0);
2712        shell
2713            .reposition_popup(popup, anchor, moved)
2714            .expect("reposition");
2715        settle(&mut shell);
2716        assert_eq!(
2717            shell.window_state(popup).expect("live").size(),
2718            Some(moved.to_physical(scale))
2719        );
2720        assert!(matches!(
2721            shell.reposition_popup(window, anchor, moved),
2722            Err(ShellError::InvalidDescriptor(_))
2723        ));
2724    }
2725
2726    /// Escape on a grabbing popup is delivered and then asks the popup to
2727    /// close, once until answered; a popup that does not hold the keyboard
2728    /// only hears the key.
2729    #[test]
2730    fn escape_on_a_grabbing_popup_is_delivered_then_asks_it_to_close() {
2731        let (mut shell, window) = shell_with_configured_window();
2732        let popup_of = |shell: &mut HeadlessShell, input| {
2733            shell
2734                .create_window(&WindowDesc {
2735                    role: crate::WindowRole::Popup(crate::PopupDesc {
2736                        parent: window,
2737                        anchor: crate::LogicalRect::default(),
2738                        placement: crate::PopupPlacement::Below,
2739                        input,
2740                    }),
2741                    ..WindowDesc::default()
2742                })
2743                .expect("a popup")
2744        };
2745        let menu = popup_of(&mut shell, crate::PopupInput::Grab);
2746        let tooltip = popup_of(&mut shell, crate::PopupInput::Pointer);
2747        settle(&mut shell);
2748        let is_close = |event: &ShellEvent| matches!(event, ShellEvent::CloseRequested { .. });
2749
2750        shell.key_press(menu, KeyCode::Escape).expect("press");
2751        let events = drain(&mut shell);
2752        assert!(
2753            matches!(
2754                events.as_slice(),
2755                [
2756                    ShellEvent::Key {
2757                        key_code: Some(KeyCode::Escape),
2758                        ..
2759                    },
2760                    ShellEvent::CloseRequested { window: closed },
2761                ] if *closed == menu
2762            ),
2763            "the key, then the request: {events:?}"
2764        );
2765        // Unanswered, a second press and a repeat ask nothing more.
2766        shell.key_press(menu, KeyCode::Escape).expect("press");
2767        shell.key_repeat(menu, KeyCode::Escape).expect("repeat");
2768        assert!(!drain(&mut shell).iter().any(is_close));
2769
2770        // Kept open — backing out of a submenu — the next press asks again.
2771        shell
2772            .reply_close_request(menu, CloseReply::Keep)
2773            .expect("keep");
2774        shell.key_release(menu, KeyCode::Escape).expect("release");
2775        shell.key_press(menu, KeyCode::Enter).expect("press");
2776        assert!(!drain(&mut shell).iter().any(is_close), "not these");
2777        shell.key_press(menu, KeyCode::Escape).expect("press");
2778        assert!(drain(&mut shell).iter().any(is_close));
2779
2780        shell.key_press(tooltip, KeyCode::Escape).expect("press");
2781        shell.key_press(window, KeyCode::Escape).expect("press");
2782        assert!(!drain(&mut shell).iter().any(is_close));
2783    }
2784
2785    #[test]
2786    fn set_constraints_is_a_request_too() {
2787        let (mut shell, window) = shell_with_configured_window();
2788        let constraints = SizeConstraints::min(LogicalSize::new(1600.0, 900.0));
2789        shell.set_constraints(window, constraints).expect("request");
2790
2791        let state = shell.window_state(window).expect("state");
2792        assert_eq!(state.requested_constraints, constraints);
2793        assert_eq!(
2794            state.size(),
2795            Some(PhysicalSize::new(1280, 720)),
2796            "the size only changes when the window system says so"
2797        );
2798
2799        settle(&mut shell);
2800        assert_eq!(
2801            shell.window_state(window).expect("state").size(),
2802            Some(PhysicalSize::new(1600, 900))
2803        );
2804    }
2805
2806    #[test]
2807    fn constraints_do_not_cancel_a_mode_request_that_has_not_landed() {
2808        // Both are requests, and they are independent. Rebuilding the pending
2809        // configure from the *effective* configuration threw the mode away:
2810        // `requested_mode` stayed `Borderless`, `effective_mode` stayed
2811        // `Windowed`, and `mode_request_honoured` was false forever.
2812        let (mut shell, window) = shell_with_configured_window();
2813        shell
2814            .set_mode(window, DisplayMode::Borderless { monitor: None })
2815            .expect("mode request");
2816        shell
2817            .set_constraints(window, SizeConstraints::min(LogicalSize::new(320.0, 180.0)))
2818            .expect("constraint request");
2819        settle(&mut shell);
2820
2821        let state = shell.window_state(window).expect("state");
2822        assert_eq!(
2823            state.effective_mode(),
2824            Some(DisplayMode::Borderless { monitor: None })
2825        );
2826        assert!(state.mode_request_honoured());
2827    }
2828
2829    #[test]
2830    fn a_borderless_window_reports_its_own_monitors_scale() {
2831        // The scale used to be hoisted from `monitors[0]` above the match, so a
2832        // borderless window on a HiDPI secondary monitor took that monitor's
2833        // *size* and the primary's *scale* — a swapchain sized for one and a UI
2834        // laid out for the other.
2835        let mut shell = HeadlessShell::new();
2836        let hidpi = shell.plug_monitor(MonitorInfo {
2837            id: MonitorId(0),
2838            name: "HEADLESS-2".to_string(),
2839            connector: None,
2840            bounds: PhysicalRect::new(1920, 0, 2560, 1440),
2841            work_area: PhysicalRect::new(1920, 0, 2560, 1440),
2842            scale_factor: 2.0,
2843            refresh_millihertz: 143_998,
2844            is_primary: false,
2845        });
2846        let window = shell
2847            .create_window(&WindowDesc {
2848                mode: DisplayMode::Borderless {
2849                    monitor: Some(hidpi),
2850                },
2851                ..WindowDesc::default()
2852            })
2853            .expect("window");
2854        settle(&mut shell);
2855
2856        let state = shell.window_state(window).expect("state");
2857        assert_eq!(state.size(), Some(PhysicalSize::new(2560, 1440)));
2858        assert_eq!(
2859            state.scale_factor(),
2860            Some(2.0),
2861            "the scale is the borderless monitor's, not the primary's"
2862        );
2863        // And `set_mode` onto the same monitor agrees, which is the pair that
2864        // used to disagree.
2865        let other = shell
2866            .create_window(&WindowDesc::default())
2867            .expect("second window");
2868        settle(&mut shell);
2869        shell
2870            .set_mode(
2871                other,
2872                DisplayMode::Borderless {
2873                    monitor: Some(hidpi),
2874                },
2875            )
2876            .expect("request");
2877        settle(&mut shell);
2878        assert_eq!(
2879            shell.window_state(other).expect("state").scale_factor(),
2880            shell.window_state(window).expect("state").scale_factor()
2881        );
2882    }
2883
2884    #[test]
2885    fn constraints_set_before_the_first_configure_fold_into_it() {
2886        let mut shell = HeadlessShell::new();
2887        let window = shell.create_window(&WindowDesc::default()).expect("window");
2888        shell
2889            .set_constraints(
2890                window,
2891                SizeConstraints::NONE.with_aspect(AspectRatio::SQUARE),
2892            )
2893            .expect("request");
2894        settle(&mut shell);
2895        // One configure, already square — not a 1280x720 configure followed by
2896        // a correction.
2897        assert_eq!(
2898            shell.window_state(window).expect("state").size(),
2899            Some(PhysicalSize::new(720, 720))
2900        );
2901    }
2902
2903    #[test]
2904    fn creation_uses_the_requested_size_and_the_monitors_scale() {
2905        let mut shell = HeadlessShell::new();
2906        let window = shell
2907            .create_window(&WindowDesc {
2908                size: LogicalSize::new(800.0, 600.0),
2909                ..WindowDesc::default()
2910            })
2911            .expect("window");
2912        settle(&mut shell);
2913        assert_eq!(
2914            shell.window_state(window).expect("state").size(),
2915            Some(PhysicalSize::new(800, 600))
2916        );
2917
2918        let mut shell = HeadlessShell::new().with_scale_factor(2.0);
2919        let window = shell
2920            .create_window(&WindowDesc {
2921                size: LogicalSize::new(640.0, 360.0),
2922                ..WindowDesc::default()
2923            })
2924            .expect("window");
2925        settle(&mut shell);
2926        let state = shell.window_state(window).expect("state");
2927        assert_eq!(state.size(), Some(PhysicalSize::new(1280, 720)));
2928        assert_eq!(state.scale_factor(), Some(2.0));
2929    }
2930
2931    // ------------------------------------------------------------ compositor side
2932
2933    #[test]
2934    fn scale_changes_preserve_logical_size_and_report_both_facts() {
2935        let (mut shell, window) = shell_with_configured_window();
2936        shell
2937            .change_scale_factor(window, 1.5)
2938            .expect("scale change");
2939        let events = drain(&mut shell);
2940        assert_eq!(
2941            events,
2942            vec![
2943                ShellEvent::ScaleFactorChanged {
2944                    window,
2945                    scale_factor: 1.5,
2946                    size: PhysicalSize::new(1920, 1080),
2947                },
2948                // The resize the scale change implies, in the same order both
2949                // Linux backends report it.
2950                ShellEvent::Resized {
2951                    window,
2952                    size: PhysicalSize::new(1920, 1080),
2953                    scale_factor: 1.5,
2954                },
2955            ]
2956        );
2957        // 1280x720 logical at 1.5 is 1920x1080 physical — the swapchain must be
2958        // recreated at the new size, which is the leak the DPI matrix test in
2959        // the windowing rules (`docs/notes/backends.md`) is looking for.
2960        assert_eq!(
2961            shell.window_state(window).expect("state").size(),
2962            Some(PhysicalSize::new(1920, 1080))
2963        );
2964    }
2965
2966    #[test]
2967    fn a_scale_change_scheduled_by_a_mode_switch_arrives_before_the_resize() {
2968        let mut shell = HeadlessShell::new();
2969        let hidpi = shell.plug_monitor(MonitorInfo {
2970            id: MonitorId(0),
2971            name: "HEADLESS-2".to_string(),
2972            connector: None,
2973            bounds: PhysicalRect::new(1920, 0, 2560, 1440),
2974            work_area: PhysicalRect::new(1920, 0, 2560, 1440),
2975            scale_factor: 2.0,
2976            refresh_millihertz: 143_998,
2977            is_primary: false,
2978        });
2979        assert_eq!(hidpi, MonitorId(2), "ids are never reused");
2980        let window = shell.create_window(&WindowDesc::default()).expect("window");
2981        settle(&mut shell);
2982
2983        shell
2984            .set_mode(
2985                window,
2986                DisplayMode::Borderless {
2987                    monitor: Some(hidpi),
2988                },
2989            )
2990            .expect("request");
2991        assert_eq!(drain(&mut shell), Vec::new(), "still only a request");
2992        let events = drain(&mut shell);
2993        assert_eq!(names(&events), ["ScaleFactorChanged", "Resized"]);
2994
2995        let state = shell.window_state(window).expect("state");
2996        assert_eq!(state.size(), Some(PhysicalSize::new(2560, 1440)));
2997        assert_eq!(state.scale_factor(), Some(2.0));
2998        assert!(state.effective_mode().expect("configured").is_borderless());
2999        // A mode change is the one event the seam says can invalidate a target.
3000        // Here it does not, because this backend's target names nothing that a
3001        // mode switch recreates — and, crucially, it does not encode the new
3002        // size either.
3003        assert_eq!(
3004            shell.surface_target(window).expect("target"),
3005            SurfaceTarget::Offscreen
3006        );
3007
3008        assert!(matches!(
3009            shell.set_mode(
3010                window,
3011                DisplayMode::Borderless {
3012                    monitor: Some(MonitorId(99)),
3013                },
3014            ),
3015            Err(ShellError::NoSuchMonitor(99))
3016        ));
3017    }
3018
3019    #[test]
3020    fn resizes_honour_constraints_and_inject_bypasses_them() {
3021        let (mut shell, window) = shell_with_configured_window();
3022        shell
3023            .set_constraints(
3024                window,
3025                SizeConstraints::min(LogicalSize::new(640.0, 360.0))
3026                    .with_aspect(AspectRatio::WIDESCREEN),
3027            )
3028            .expect("request");
3029        settle(&mut shell);
3030
3031        shell
3032            .resize(window, PhysicalSize::new(1000, 1000))
3033            .expect("resize");
3034        assert_eq!(
3035            drain(&mut shell),
3036            vec![ShellEvent::Resized {
3037                window,
3038                size: PhysicalSize::new(1000, 562),
3039                scale_factor: 1.0,
3040            }]
3041        );
3042
3043        // A tiling window manager ignores every hint, and `inject` is how that
3044        // gets tested.
3045        shell.inject(ShellEvent::Resized {
3046            window,
3047            size: PhysicalSize::new(300, 900),
3048            scale_factor: 1.0,
3049        });
3050        assert_eq!(
3051            drain(&mut shell)[0],
3052            ShellEvent::Resized {
3053                window,
3054                size: PhysicalSize::new(300, 900),
3055                scale_factor: 1.0,
3056            }
3057        );
3058    }
3059
3060    #[test]
3061    fn a_compositor_configure_supersedes_a_pending_one() {
3062        let (mut shell, window) = shell_with_configured_window();
3063        shell
3064            .set_mode(window, DisplayMode::Borderless { monitor: None })
3065            .expect("request");
3066        // The compositor answers before the scheduled configure lands.
3067        shell
3068            .resize(window, PhysicalSize::new(640, 480))
3069            .expect("answer");
3070        assert_eq!(names(&drain(&mut shell)), ["Resized"]);
3071        assert_eq!(
3072            shell.window_state(window).expect("state").size(),
3073            Some(PhysicalSize::new(640, 480))
3074        );
3075        // And nothing else arrives later.
3076        assert_eq!(drain(&mut shell), Vec::new());
3077    }
3078
3079    // ------------------------------------------------------------------- input
3080
3081    #[test]
3082    fn timestamps_come_from_the_shells_clock_not_from_the_pump() {
3083        let (mut shell, window) = shell_with_configured_window();
3084        shell.set_time(Duration::from_secs(2));
3085        shell.key_press(window, KeyCode::Space).expect("press");
3086        shell.advance(Duration::from_millis(180));
3087        shell.key_release(window, KeyCode::Space).expect("release");
3088
3089        let events = drain(&mut shell);
3090        let held = events[1]
3091            .time()
3092            .expect("input")
3093            .saturating_since(events[0].time().expect("input"));
3094        assert_eq!(held, Duration::from_millis(180));
3095        assert_eq!(events[0].time(), Some(EventTime::from_millis(2_000)));
3096    }
3097
3098    /// A scheduled script runs at its pump, not before, and what it injects
3099    /// is stamped with the clock as it stands then.
3100    #[test]
3101    fn a_scheduled_script_injects_at_its_pump_with_that_pumps_time() {
3102        let (mut shell, window) = shell_with_configured_window();
3103        shell.schedule(2, move |shell| {
3104            shell.key_press(window, KeyCode::Space).expect("press");
3105        });
3106
3107        for pump in 0..2 {
3108            shell.advance(Duration::from_millis(16));
3109            assert_eq!(drain(&mut shell), Vec::new(), "pump {pump} came early");
3110        }
3111        shell.set_time(Duration::from_secs(3));
3112        let events = drain(&mut shell);
3113        assert_eq!(names(&events), ["Key"]);
3114        assert_eq!(events[0].time(), Some(EventTime::from_millis(3_000)));
3115        assert_eq!(drain(&mut shell), Vec::new(), "and it ran once");
3116    }
3117
3118    /// Scripts due together run in the order scheduled; one a script
3119    /// schedules at zero waits for the pump after.
3120    #[test]
3121    fn scheduled_scripts_run_in_order_and_a_nested_one_waits_a_pump() {
3122        let (mut shell, window) = shell_with_configured_window();
3123        shell.schedule(0, move |shell| {
3124            shell.key_press(window, KeyCode::KeyA).expect("press");
3125            shell.schedule(0, move |shell| {
3126                shell.key_press(window, KeyCode::KeyC).expect("press");
3127            });
3128        });
3129        shell.schedule(0, move |shell| {
3130            shell.key_press(window, KeyCode::KeyB).expect("press");
3131        });
3132
3133        let keys = |events: Vec<ShellEvent>| -> Vec<Option<KeyCode>> {
3134            events
3135                .into_iter()
3136                .map(|event| match event {
3137                    ShellEvent::Key { key_code, .. } => key_code,
3138                    other => panic!("not a key: {other:?}"),
3139                })
3140                .collect()
3141        };
3142        assert_eq!(
3143            keys(drain(&mut shell)),
3144            [Some(KeyCode::KeyA), Some(KeyCode::KeyB)]
3145        );
3146        assert_eq!(keys(drain(&mut shell)), [Some(KeyCode::KeyC)]);
3147    }
3148
3149    /// `keep_alive` is a turn for a script as for a configure: it runs
3150    /// there, and the next pump delivers what it injected.
3151    #[test]
3152    fn keep_alive_runs_a_due_script_and_keeps_its_events() {
3153        let (mut shell, window) = shell_with_configured_window();
3154        shell.schedule(1, move |shell| {
3155            shell.key_press(window, KeyCode::Enter).expect("press");
3156        });
3157        shell.keep_alive();
3158        shell.keep_alive();
3159        assert_eq!(shell.pending_events(), 1, "the script ran in keep_alive");
3160        assert_eq!(names(&drain(&mut shell)), ["Key"]);
3161    }
3162
3163    /// A wait while a script is scheduled returns at once: only a pump brings
3164    /// the script closer, so sleeping would only delay it, and an untimed
3165    /// wait with a waker out would never end.
3166    #[test]
3167    fn a_wait_does_not_sleep_while_a_script_is_scheduled() {
3168        let (mut shell, window) = shell_with_configured_window();
3169        shell.schedule(1, move |shell| {
3170            shell.key_press(window, KeyCode::Space).expect("press");
3171        });
3172        let start = std::time::Instant::now();
3173        shell.wait_events(Some(LONG_WAIT));
3174        assert!(
3175            start.elapsed() < LONG_WAIT / 2,
3176            "the wait slept {:?}",
3177            start.elapsed()
3178        );
3179    }
3180
3181    #[test]
3182    fn synthesized_key_fields_are_stable_and_plausible() {
3183        let (mut shell, window) = shell_with_configured_window();
3184        shell.set_modifiers(Modifiers::CTRL);
3185        shell.key_press(window, KeyCode::KeyS).expect("press");
3186        let events = drain(&mut shell);
3187        let ShellEvent::Key {
3188            scancode,
3189            key_code,
3190            keysym,
3191            modifiers,
3192            repeat,
3193            device,
3194            ..
3195        } = events[0].clone()
3196        else {
3197            panic!("wrong variant");
3198        };
3199        assert_eq!(key_code, Some(KeyCode::KeyS));
3200        assert_eq!(keysym, Keysym::from_char('s'));
3201        assert_eq!(modifiers, Modifiers::CTRL);
3202        assert!(!repeat);
3203        assert_eq!(device, VIRTUAL_DEVICE);
3204        assert!(scancode.0 >= 8, "evdev-shaped scancodes start at 8");
3205        assert_eq!(synthetic_keysym(KeyCode::Digit7), Keysym::from_char('7'));
3206        assert_eq!(synthetic_keysym(KeyCode::F5), Keysym(0xFFC2));
3207        assert_eq!(synthetic_keysym(KeyCode::Enter), Keysym(0xFF0D));
3208        assert_eq!(synthetic_keysym(KeyCode::Escape), Keysym(0xFF1B));
3209        assert_eq!(synthetic_keysym(KeyCode::ArrowLeft), Keysym(0xFF51));
3210        assert_eq!(synthetic_keysym(KeyCode::Slash), Keysym::from_char('/'));
3211
3212        shell.key_repeat(window, KeyCode::KeyS).expect("repeat");
3213        let events = drain(&mut shell);
3214        let ShellEvent::Key { repeat, .. } = events[0] else {
3215            panic!("wrong variant");
3216        };
3217        assert!(repeat);
3218    }
3219
3220    #[test]
3221    fn a_locked_pointer_reports_no_absolute_position() {
3222        let (mut shell, window) = shell_with_configured_window();
3223        shell
3224            .set_pointer_mode(window, PointerMode::Locked)
3225            .expect("lock");
3226        shell
3227            .move_pointer(window, PhysicalPoint::new(10.0, 10.0), (3.0, -4.0))
3228            .expect("motion");
3229        let events = drain(&mut shell);
3230        let ShellEvent::PointerMotion { abs, raw_delta, .. } = events[0] else {
3231            panic!("wrong variant");
3232        };
3233        assert_eq!(abs, None);
3234        assert_eq!(raw_delta, Some((3.0, -4.0)));
3235    }
3236
3237    #[test]
3238    fn a_backend_without_raw_motion_reports_none() {
3239        let mut shell = HeadlessShell::new()
3240            .with_caps(ShellCaps::DESKTOP - ShellCaps::RAW_POINTER_MOTION)
3241            .with_configure_delay(0);
3242        let window = shell.create_window(&WindowDesc::default()).expect("window");
3243        drain(&mut shell);
3244        shell
3245            .move_pointer(window, PhysicalPoint::new(1.0, 2.0), (5.0, 5.0))
3246            .expect("motion");
3247        let events = drain(&mut shell);
3248        let ShellEvent::PointerMotion { abs, raw_delta, .. } = events[0] else {
3249            panic!("wrong variant");
3250        };
3251        assert_eq!(abs, Some(PhysicalPoint::new(1.0, 2.0)));
3252        assert_eq!(raw_delta, None, "no relative-motion source");
3253        assert!(!shell.caps().has_mouselook());
3254    }
3255
3256    #[test]
3257    fn pointer_focus_and_scroll_and_text_are_injectable() {
3258        let (mut shell, window) = shell_with_configured_window();
3259        shell
3260            .set_pointer_focus(window, true, Some(PhysicalPoint::new(1.0, 1.0)))
3261            .expect("enter");
3262        shell
3263            .scroll(window, ScrollDelta::Lines { x: 0.0, y: -1.0 }, None)
3264            .expect("scroll");
3265        shell
3266            .button(
3267                window,
3268                PointerButton::Left,
3269                ButtonState::Pressed,
3270                Some(PhysicalPoint::new(1.0, 1.0)),
3271            )
3272            .expect("click");
3273        shell.commit_text(window, "ありがとう").expect("text");
3274        shell
3275            .set_pointer_focus(window, false, Some(PhysicalPoint::new(1.0, 1.0)))
3276            .expect("leave");
3277
3278        let events = drain(&mut shell);
3279        assert_eq!(
3280            names(&events),
3281            [
3282                "PointerFocus",
3283                "Wheel",
3284                "Button",
3285                "TextCommit",
3286                "PointerFocus"
3287            ]
3288        );
3289        let ShellEvent::PointerFocus {
3290            entered, position, ..
3291        } = &events[4]
3292        else {
3293            panic!("wrong variant");
3294        };
3295        assert!(!entered);
3296        assert_eq!(*position, None, "a leave has no position");
3297        assert!(events.iter().all(ShellEvent::is_input));
3298    }
3299
3300    /// Two fingers script as two contacts, and a touchless shell has none.
3301    ///
3302    /// The second half is the one worth having: a backend with the capability
3303    /// clear is a platform where a finger *cannot arrive*, and a script that
3304    /// could inject one anyway would let a test assert a game works on a
3305    /// touchscreen the shell does not have.
3306    #[test]
3307    fn contacts_are_injectable_and_a_touchless_shell_refuses_them() {
3308        let (mut shell, window) = shell_with_configured_window();
3309        assert!(shell.caps().contains(ShellCaps::TOUCH));
3310        for (contact, phase, x) in [
3311            (1, TouchPhase::Began, 10.0),
3312            (2, TouchPhase::Began, 200.0),
3313            (2, TouchPhase::Moved, 220.0),
3314            (1, TouchPhase::Ended, 10.0),
3315            (2, TouchPhase::Cancelled, 220.0),
3316        ] {
3317            shell
3318                .touch(
3319                    window,
3320                    ContactId(contact),
3321                    phase,
3322                    PhysicalPoint::new(x, 5.0),
3323                )
3324                .expect("a contact");
3325        }
3326        let events = drain(&mut shell);
3327        assert_eq!(names(&events), ["Touch"; 5]);
3328        let seen: Vec<(ContactId, TouchPhase, f64)> = events
3329            .iter()
3330            .map(|event| {
3331                let ShellEvent::Touch {
3332                    contact,
3333                    phase,
3334                    position,
3335                    ..
3336                } = event
3337                else {
3338                    panic!("wrong variant");
3339                };
3340                (*contact, *phase, position.x)
3341            })
3342            .collect();
3343        assert_eq!(
3344            seen,
3345            vec![
3346                (ContactId(1), TouchPhase::Began, 10.0),
3347                (ContactId(2), TouchPhase::Began, 200.0),
3348                (ContactId(2), TouchPhase::Moved, 220.0),
3349                (ContactId(1), TouchPhase::Ended, 10.0),
3350                (ContactId(2), TouchPhase::Cancelled, 220.0),
3351            ]
3352        );
3353        assert!(events.iter().all(ShellEvent::is_input));
3354
3355        let mut touchless = HeadlessShell::new()
3356            .with_caps(ShellCaps::DESKTOP - ShellCaps::TOUCH)
3357            .with_configure_delay(0);
3358        let window = touchless
3359            .create_window(&WindowDesc::default())
3360            .expect("window");
3361        drain(&mut touchless);
3362        assert!(matches!(
3363            touchless.touch(
3364                window,
3365                ContactId(1),
3366                TouchPhase::Began,
3367                PhysicalPoint::ORIGIN
3368            ),
3369            Err(ShellError::Unsupported { .. })
3370        ));
3371        assert!(drain(&mut touchless).is_empty(), "and queued nothing");
3372    }
3373
3374    #[test]
3375    fn warping_produces_motion_like_every_platform_that_has_it() {
3376        let (mut shell, window) = shell_with_configured_window();
3377        shell
3378            .warp_pointer(window, PhysicalPoint::new(320.0, 180.0))
3379            .expect("warp");
3380        let events = drain(&mut shell);
3381        let ShellEvent::PointerMotion { abs, raw_delta, .. } = events[0] else {
3382            panic!("wrong variant");
3383        };
3384        assert_eq!(abs, Some(PhysicalPoint::new(320.0, 180.0)));
3385        assert_eq!(raw_delta, None, "a warp is not physical motion");
3386    }
3387
3388    // ------------------------------------------------------------- lifecycle
3389
3390    #[test]
3391    fn capabilities_gate_the_operations_that_need_them() {
3392        let mut shell = HeadlessShell::new().with_caps(ShellCaps::empty());
3393        let window = shell.create_window(&WindowDesc::default()).expect("window");
3394
3395        assert!(matches!(
3396            shell.warp_pointer(window, PhysicalPoint::ORIGIN),
3397            Err(ShellError::Unsupported { .. })
3398        ));
3399        assert!(matches!(
3400            shell.set_pointer_mode(window, PointerMode::Locked),
3401            Err(ShellError::Unsupported { .. })
3402        ));
3403        assert!(matches!(
3404            shell.clipboard_request(window, MimeType::TextUtf8),
3405            Err(ShellError::Unsupported { .. })
3406        ));
3407        // Free needs no capability, so it always works.
3408        shell
3409            .set_pointer_mode(window, PointerMode::Free)
3410            .expect("Free is always available");
3411        // And a second window is refused without MULTI_WINDOW.
3412        assert!(matches!(
3413            shell.create_window(&WindowDesc::default()),
3414            Err(ShellError::Unsupported { .. })
3415        ));
3416    }
3417
3418    #[test]
3419    fn stale_handles_fail_cleanly_on_every_accessor() {
3420        let (mut shell, window) = shell_with_configured_window();
3421        shell.destroy_window(window).expect("destroy");
3422        assert_eq!(
3423            drain(&mut shell),
3424            vec![ShellEvent::WindowDestroyed { window }]
3425        );
3426
3427        assert!(matches!(
3428            shell.window_state(window),
3429            Err(ShellError::InvalidWindow { .. })
3430        ));
3431        assert!(matches!(
3432            shell.surface_target(window),
3433            Err(ShellError::InvalidWindow { .. })
3434        ));
3435        assert!(matches!(
3436            shell.resize(window, PhysicalSize::new(1, 1)),
3437            Err(ShellError::InvalidWindow { .. })
3438        ));
3439        assert!(matches!(
3440            shell.set_title(window, "gone"),
3441            Err(ShellError::InvalidWindow { .. })
3442        ));
3443        assert!(matches!(
3444            shell.destroy_window(window),
3445            Err(ShellError::InvalidWindow { .. })
3446        ));
3447        assert!(matches!(
3448            shell.key_press(window, KeyCode::KeyA),
3449            Err(ShellError::InvalidWindow { .. })
3450        ));
3451    }
3452
3453    #[test]
3454    fn destroying_a_window_cancels_its_pending_configure() {
3455        // The bug a naive delayed-configure implementation has: an event for a
3456        // window that no longer exists.
3457        let (mut shell, window) = shell_with_window();
3458        shell.destroy_window(window).expect("destroy");
3459        assert_eq!(names(&drain(&mut shell)), ["WindowDestroyed"]);
3460        assert_eq!(drain(&mut shell), Vec::new());
3461        assert_eq!(drain(&mut shell), Vec::new());
3462    }
3463
3464    #[test]
3465    fn close_requests_are_questions() {
3466        let (mut shell, window) = shell_with_configured_window();
3467        assert!(matches!(
3468            shell.reply_close_request(window, CloseReply::Close),
3469            Err(ShellError::NoPendingCloseRequest { .. })
3470        ));
3471
3472        shell.request_close(window).expect("request");
3473        assert!(shell.window_state(window).expect("state").close_pending);
3474        shell
3475            .reply_close_request(window, CloseReply::Keep)
3476            .expect("keep");
3477        assert!(!shell.window_state(window).expect("state").close_pending);
3478        assert!(shell.window_state(window).is_ok(), "still open");
3479
3480        shell.request_close(window).expect("request again");
3481        shell
3482            .reply_close_request(window, CloseReply::Close)
3483            .expect("close");
3484        assert!(matches!(
3485            shell.window_state(window),
3486            Err(ShellError::InvalidWindow { .. })
3487        ));
3488    }
3489
3490    #[test]
3491    fn monitor_hotplug_reports_a_change_and_keeps_ids_unique() {
3492        let mut shell = HeadlessShell::new();
3493        let extra = shell.plug_monitor(MonitorInfo {
3494            id: MonitorId(0),
3495            name: "HEADLESS-2".to_string(),
3496            connector: None,
3497            bounds: PhysicalRect::new(1920, 0, 1920, 1080),
3498            work_area: PhysicalRect::new(1920, 0, 1920, 1080),
3499            scale_factor: 1.0,
3500            refresh_millihertz: 60_000,
3501            is_primary: false,
3502        });
3503        assert_eq!(shell.monitors().len(), 2);
3504        assert_eq!(drain(&mut shell), vec![ShellEvent::MonitorsChanged]);
3505
3506        shell.unplug_monitor(extra).expect("unplug");
3507        assert_eq!(shell.monitors().len(), 1);
3508        assert_eq!(
3509            drain(&mut shell),
3510            vec![
3511                ShellEvent::MonitorRemoved { monitor: extra },
3512                ShellEvent::MonitorsChanged
3513            ]
3514        );
3515        assert!(matches!(
3516            shell.unplug_monitor(extra),
3517            Err(ShellError::NoSuchMonitor(_))
3518        ));
3519        assert_eq!(
3520            shell.monitor(MonitorId(1)).map(|m| m.name.as_str()),
3521            Some("HEADLESS-1")
3522        );
3523        assert!(shell.monitor(extra).is_none());
3524    }
3525
3526    #[test]
3527    fn unplugging_a_monitor_asks_its_panels_and_only_its_panels_to_close() {
3528        let mut shell = HeadlessShell::new();
3529        let second = shell.plug_monitor(MonitorInfo {
3530            id: MonitorId(0),
3531            name: "HEADLESS-2".to_string(),
3532            connector: None,
3533            bounds: PhysicalRect::new(1920, 0, 1920, 1080),
3534            work_area: PhysicalRect::new(1920, 0, 1920, 1080),
3535            scale_factor: 1.0,
3536            refresh_millihertz: 60_000,
3537            is_primary: false,
3538        });
3539        let first = shell.monitors()[0].id;
3540        let panel_on = |shell: &mut HeadlessShell, monitor| {
3541            shell
3542                .create_window(&WindowDesc {
3543                    role: crate::WindowRole::Panel(crate::PanelDesc {
3544                        monitor,
3545                        ..crate::PanelDesc::default()
3546                    }),
3547                    ..WindowDesc::default()
3548                })
3549                .expect("panel")
3550        };
3551        let doomed = panel_on(&mut shell, Some(second));
3552        let already_asked = panel_on(&mut shell, Some(second));
3553        let elsewhere = panel_on(&mut shell, Some(first));
3554        let anywhere = panel_on(&mut shell, None);
3555        let toplevel = shell.create_window(&WindowDesc::default()).expect("window");
3556        shell.request_close(already_asked).expect("close");
3557        settle(&mut shell);
3558        drain(&mut shell);
3559
3560        shell.unplug_monitor(second).expect("unplug");
3561        assert_eq!(
3562            drain(&mut shell),
3563            vec![
3564                ShellEvent::MonitorRemoved { monitor: second },
3565                ShellEvent::CloseRequested { window: doomed },
3566                ShellEvent::MonitorsChanged,
3567            ]
3568        );
3569        for window in [elsewhere, anywhere, toplevel] {
3570            assert!(!shell.window_state(window).expect("open").close_pending);
3571        }
3572    }
3573
3574    #[test]
3575    fn drops_require_both_the_capability_and_the_opt_in() {
3576        let mut shell = HeadlessShell::new();
3577        let plain = shell.create_window(&WindowDesc::default()).expect("window");
3578        assert!(matches!(
3579            shell.drop_file(plain, "/tmp/a.gltf", None),
3580            Err(ShellError::Unsupported { .. })
3581        ));
3582
3583        let dropper = shell
3584            .create_window(&WindowDesc {
3585                accept_drops: true,
3586                ..WindowDesc::default()
3587            })
3588            .expect("window");
3589        settle(&mut shell);
3590        shell
3591            .drop_file(dropper, "/tmp/a.gltf", Some(PhysicalPoint::new(4.0, 5.0)))
3592            .expect("drop");
3593        assert_eq!(names(&drain(&mut shell))[0], "DroppedFile");
3594    }
3595
3596    #[test]
3597    fn a_sink_that_queues_more_events_does_not_spin_the_pump() {
3598        let (mut shell, window) = shell_with_configured_window();
3599        shell.inject(ShellEvent::MonitorsChanged);
3600        let mut extra = Vec::new();
3601        shell.pump(&mut |event| extra.push(event));
3602        assert_eq!(extra.len(), 1);
3603        shell.inject(ShellEvent::CloseRequested { window });
3604        assert_eq!(shell.pending_events(), 1);
3605    }
3606
3607    #[test]
3608    fn accessors_that_no_real_backend_can_provide_are_headless_only() {
3609        let (mut shell, window) = shell_with_configured_window();
3610        shell.set_title(window, "renamed").expect("title");
3611        assert_eq!(shell.title(window).expect("title"), "renamed");
3612        shell.set_cursor(window, None).expect("hide");
3613        assert_eq!(shell.cursor(window).expect("cursor"), None);
3614        shell
3615            .set_cursor(window, Some(CursorIcon::Crosshair))
3616            .expect("shape");
3617        assert_eq!(
3618            shell.cursor(window).expect("cursor"),
3619            Some(CursorIcon::Crosshair)
3620        );
3621        shell.set_visible(window, false).expect("hide window");
3622        assert!(!shell.window_state(window).expect("state").visible);
3623    }
3624
3625    #[test]
3626    fn an_input_region_is_recorded_replaced_and_given_back() {
3627        let (mut shell, window) = shell_with_configured_window();
3628        assert_eq!(shell.input_region(window).expect("region"), None);
3629        let panel = PhysicalRect::new(0, 0, 400, 300).rounded(12);
3630        shell
3631            .set_input_region(window, Some(&panel))
3632            .expect("a region");
3633        assert_eq!(
3634            shell.input_region(window).expect("region"),
3635            Some(panel.as_slice())
3636        );
3637        shell.set_input_region(window, Some(&[])).expect("nothing");
3638        assert_eq!(shell.input_region(window).expect("region"), Some(&[][..]));
3639        shell.set_input_region(window, None).expect("whole window");
3640        assert_eq!(shell.input_region(window).expect("region"), None);
3641        shell.destroy_window(window).expect("destroy");
3642        assert!(matches!(
3643            shell.set_input_region(window, None),
3644            Err(ShellError::InvalidWindow { .. })
3645        ));
3646        assert!(shell.input_region(window).is_err());
3647    }
3648
3649    #[test]
3650    fn an_idle_inhibit_is_recorded_and_ends_with_its_window() {
3651        let (mut shell, window) = shell_with_configured_window();
3652        assert!(!shell.idle_inhibited(window).expect("live"));
3653        shell.set_idle_inhibit(window, true).expect("inhibit");
3654        shell.set_idle_inhibit(window, true).expect("asking twice");
3655        assert!(shell.idle_inhibited(window).expect("live"));
3656        shell.set_idle_inhibit(window, false).expect("stop");
3657        assert!(!shell.idle_inhibited(window).expect("live"));
3658        shell.set_idle_inhibit(window, true).expect("inhibit again");
3659        shell.destroy_window(window).expect("destroy");
3660        assert!(matches!(
3661            shell.set_idle_inhibit(window, false),
3662            Err(ShellError::InvalidWindow { .. })
3663        ));
3664        assert!(shell.idle_inhibited(window).is_err());
3665    }
3666
3667    #[test]
3668    fn an_idle_inhibit_is_refused_without_the_capability() {
3669        let mut shell =
3670            HeadlessShell::new().with_caps(ShellCaps::DESKTOP - ShellCaps::IDLE_INHIBIT);
3671        let window = shell.create_window(&WindowDesc::default()).expect("window");
3672        assert!(matches!(
3673            shell.set_idle_inhibit(window, true),
3674            Err(ShellError::Unsupported {
3675                backend: ShellBackend::Headless,
3676                ..
3677            })
3678        ));
3679        assert!(!shell.idle_inhibited(window).expect("live"));
3680    }
3681
3682    fn url(text: &str) -> WebUrl {
3683        WebUrl::parse(text).expect("a web URL")
3684    }
3685
3686    #[test]
3687    fn an_opened_url_is_recorded_in_order() {
3688        let (mut shell, window) = shell_with_configured_window();
3689        let other = shell.create_window(&WindowDesc::default()).expect("window");
3690        assert!(shell.opened_urls().is_empty());
3691        let store = url("https://store.example/app/1");
3692        let privacy = url("HTTPS://EXAMPLE.COM/privacy");
3693        shell.open_url(window, &store).expect("store page");
3694        shell.open_url(other, &privacy).expect("privacy policy");
3695        shell
3696            .open_url(window, &store)
3697            .expect("asking twice opens twice");
3698        assert_eq!(
3699            shell.opened_urls(),
3700            [
3701                (window, store.clone()),
3702                (other, privacy),
3703                (window, store.clone())
3704            ]
3705        );
3706        shell.destroy_window(window).expect("destroy");
3707        assert!(matches!(
3708            shell.open_url(window, &store),
3709            Err(ShellError::InvalidWindow { .. })
3710        ));
3711        assert_eq!(
3712            shell.opened_urls().len(),
3713            3,
3714            "the history outlives the window"
3715        );
3716    }
3717
3718    #[test]
3719    fn opening_a_url_is_refused_without_the_capability() {
3720        let mut shell = HeadlessShell::new().with_caps(ShellCaps::DESKTOP - ShellCaps::OPEN_URL);
3721        let window = shell.create_window(&WindowDesc::default()).expect("window");
3722        assert!(matches!(
3723            shell.open_url(window, &url("https://example.com/")),
3724            Err(ShellError::Unsupported {
3725                backend: ShellBackend::Headless,
3726                ..
3727            })
3728        ));
3729        assert!(shell.opened_urls().is_empty());
3730    }
3731
3732    fn frames_for(events: &[ShellEvent], window: WindowId) -> usize {
3733        events
3734            .iter()
3735            .filter(|event| matches!(event, ShellEvent::FrameReady { window: w } if *w == window))
3736            .count()
3737    }
3738
3739    #[test]
3740    fn requests_for_a_frame_share_one_answer_at_the_next_pump() {
3741        let (mut shell, window) = shell_with_configured_window();
3742        assert!(!shell.frame_requested(window).expect("live"));
3743        shell.request_frame(window).expect("a frame");
3744        shell.request_frame(window).expect("the same frame");
3745        assert!(shell.frame_requested(window).expect("live"));
3746        let events = drain(&mut shell);
3747        assert_eq!(frames_for(&events, window), 1, "{:?}", names(&events));
3748        assert!(!shell.frame_requested(window).expect("live"));
3749        assert_eq!(
3750            frames_for(&drain(&mut shell), window),
3751            0,
3752            "nothing asked again"
3753        );
3754        shell.request_frame(window).expect("the next frame");
3755        assert_eq!(frames_for(&drain(&mut shell), window), 1);
3756    }
3757
3758    #[test]
3759    fn a_window_destroyed_with_a_frame_requested_is_not_answered() {
3760        let (mut shell, doomed) = shell_with_configured_window();
3761        let kept = shell
3762            .create_window(&WindowDesc::default())
3763            .expect("a second window");
3764        settle(&mut shell);
3765        shell.request_frame(doomed).expect("a frame");
3766        shell.request_frame(kept).expect("a frame");
3767        shell.destroy_window(doomed).expect("destroy");
3768        let events = drain(&mut shell);
3769        assert_eq!(frames_for(&events, doomed), 0, "{:?}", names(&events));
3770        assert_eq!(frames_for(&events, kept), 1, "the other window still asked");
3771        assert!(matches!(
3772            shell.request_frame(doomed),
3773            Err(ShellError::InvalidWindow { .. })
3774        ));
3775        assert!(shell.frame_requested(doomed).is_err());
3776    }
3777
3778    #[test]
3779    fn a_wait_does_not_sleep_through_a_frame_that_is_due() {
3780        let (mut shell, window) = shell_with_configured_window();
3781        shell.request_frame(window).expect("a frame");
3782        let start = std::time::Instant::now();
3783        shell.wait_events(Some(LONG_WAIT));
3784        assert!(
3785            start.elapsed() < LONG_WAIT / 2,
3786            "slept {:?} with a frame due",
3787            start.elapsed()
3788        );
3789        assert_eq!(frames_for(&drain(&mut shell), window), 1);
3790    }
3791
3792    #[test]
3793    fn an_output_that_is_off_holds_frame_requests_until_it_is_on() {
3794        let (mut shell, window) = shell_with_configured_window();
3795        shell.set_outputs_powered(false);
3796        shell.request_frame(window).expect("a frame");
3797        assert_eq!(frames_for(&drain(&mut shell), window), 0, "held");
3798        assert!(shell.frame_requested(window).expect("live"), "still owed");
3799
3800        let wait = Duration::from_millis(20);
3801        let start = std::time::Instant::now();
3802        shell.wait_events(Some(wait));
3803        assert!(
3804            start.elapsed() >= wait,
3805            "a held request cut the wait short after {:?}",
3806            start.elapsed()
3807        );
3808
3809        shell.set_outputs_powered(true);
3810        assert_eq!(
3811            frames_for(&drain(&mut shell), window),
3812            1,
3813            "answered once on"
3814        );
3815        assert!(!shell.frame_requested(window).expect("live"));
3816    }
3817
3818    #[test]
3819    fn waiting_is_observable_and_focus_transitions_are_events() {
3820        let (mut shell, window) = shell_with_configured_window();
3821        assert_eq!(shell.wait_count(), 0);
3822        shell.wait_events(Some(Duration::from_millis(5)));
3823        shell.wait_events(None);
3824        assert_eq!(shell.wait_count(), 2);
3825
3826        shell.set_focus(window, true).expect("focus");
3827        assert!(shell.window_state(window).expect("state").focused);
3828        shell.set_focus(window, false).expect("unfocus");
3829        assert_eq!(names(&drain(&mut shell)), ["Focus", "Focus"]);
3830    }
3831
3832    // ----------------------------------------------------------------- waker
3833
3834    /// Longer than any of these tests should take: a wait that runs this long
3835    /// was not woken.
3836    const LONG_WAIT: Duration = Duration::from_secs(60);
3837    /// How long the waking thread lets the wait settle before it rings.
3838    const RING_AFTER: Duration = Duration::from_millis(50);
3839
3840    /// Rings `waker` from another thread after [`RING_AFTER`].
3841    fn ring_later(waker: ShellWaker) -> std::thread::JoinHandle<()> {
3842        std::thread::spawn(move || {
3843            std::thread::sleep(RING_AFTER);
3844            waker.wake();
3845        })
3846    }
3847
3848    #[test]
3849    fn a_wake_from_another_thread_ends_a_long_wait() {
3850        let mut shell = HeadlessShell::new();
3851        let ringer = ring_later(shell.waker().expect("headless has a waker"));
3852        let start = std::time::Instant::now();
3853        shell.wait_events(Some(LONG_WAIT));
3854        let slept = start.elapsed();
3855        ringer.join().expect("the ringer");
3856        assert!(slept < LONG_WAIT / 2, "the wait ran {slept:?}");
3857    }
3858
3859    #[test]
3860    fn a_wake_before_the_wait_ends_it_at_once_and_wakes_coalesce() {
3861        let mut shell = HeadlessShell::new();
3862        let waker = shell.waker().expect("headless has a waker");
3863        for _ in 0..3 {
3864            waker.wake();
3865        }
3866        let start = std::time::Instant::now();
3867        shell.wait_events(Some(LONG_WAIT));
3868        assert!(
3869            start.elapsed() < LONG_WAIT / 2,
3870            "a rung bell must end the wait"
3871        );
3872
3873        // Three rings were one: the next wait sleeps out its timeout.
3874        let timeout = Duration::from_millis(100);
3875        let start = std::time::Instant::now();
3876        shell.wait_events(Some(timeout));
3877        assert!(
3878            start.elapsed() >= timeout / 2,
3879            "the bell was cleared, so this wait must sleep, but it took {:?}",
3880            start.elapsed()
3881        );
3882    }
3883
3884    #[test]
3885    fn with_a_waker_out_an_untimed_wait_sleeps_until_it_rings() {
3886        let mut shell = HeadlessShell::new();
3887        let ringer = ring_later(shell.waker().expect("headless has a waker"));
3888        let start = std::time::Instant::now();
3889        shell.wait_events(None);
3890        let slept = start.elapsed();
3891        ringer.join().expect("the ringer");
3892        assert!(
3893            slept >= RING_AFTER / 2,
3894            "an untimed wait returned after {slept:?}, before anything rang"
3895        );
3896    }
3897
3898    // ------------------------------------------------------------- clipboard
3899
3900    #[test]
3901    fn the_clipboard_round_trips_through_an_event() {
3902        let (mut shell, window) = shell_with_configured_window();
3903        shell
3904            .clipboard_offer(
3905                window,
3906                &[
3907                    ClipboardOffer::text("node"),
3908                    ClipboardOffer::ron("(kind:\"node\")"),
3909                ],
3910            )
3911            .expect("offer");
3912        assert_eq!(
3913            shell.clipboard_bytes(MimeType::TextUtf8),
3914            Some(&b"node"[..])
3915        );
3916
3917        let request = shell
3918            .clipboard_request(window, MimeType::CrcblRon)
3919            .expect("request");
3920        assert_eq!(
3921            drain(&mut shell)[0],
3922            ShellEvent::ClipboardData {
3923                window,
3924                request,
3925                mime: ReceivedMime::from(MimeType::CrcblRon),
3926                content: ClipboardContent::Bytes(b"(kind:\"node\")".to_vec()),
3927            }
3928        );
3929
3930        // A format nobody offered comes back `Empty` — an answer, and a
3931        // different one from "the read failed".
3932        let request = shell
3933            .clipboard_request(window, MimeType::UriList)
3934            .expect("request");
3935        assert_eq!(
3936            drain(&mut shell)[0],
3937            ShellEvent::ClipboardData {
3938                window,
3939                request,
3940                mime: ReceivedMime::from(MimeType::UriList),
3941                content: ClipboardContent::Empty,
3942            }
3943        );
3944
3945        // A published payload of zero bytes is a *successful* read of nothing,
3946        // which the old `Option<Vec<u8>>` shape could not say.
3947        shell
3948            .clipboard_offer(window, &[ClipboardOffer::text("")])
3949            .expect("offer");
3950        let request = shell
3951            .clipboard_request(window, MimeType::TextUtf8)
3952            .expect("request");
3953        assert_eq!(
3954            drain(&mut shell)[0],
3955            ShellEvent::ClipboardData {
3956                window,
3957                request,
3958                mime: ReceivedMime::from(MimeType::TextUtf8),
3959                content: ClipboardContent::Bytes(Vec::new()),
3960            }
3961        );
3962    }
3963
3964    #[test]
3965    fn a_read_taken_while_the_clipboard_is_unreadable_is_held_not_answered_empty() {
3966        // The Wayland focus gate, modelled. A consumer written only against a
3967        // clipboard that answers instantly cannot tell "empty" from "I have
3968        // not looked yet" — which is exactly what the seam's obligation 5
3969        // exists to stop backends doing, and what this shell can now reproduce
3970        // with no compositor in the room.
3971        let (mut shell, window) = shell_with_configured_window();
3972        shell
3973            .clipboard_offer(window, &[ClipboardOffer::text("published")])
3974            .expect("offer");
3975        shell.set_clipboard_readable(false);
3976        assert!(!shell.clipboard_readable(window));
3977
3978        let request = shell
3979            .clipboard_request(window, MimeType::TextUtf8)
3980            .expect("a read is accepted even when it cannot be answered yet");
3981        assert_eq!(shell.held_clipboard_reads(), 1);
3982        assert!(
3983            drain(&mut shell).is_empty(),
3984            "a held read produces no event at all — least of all an empty one"
3985        );
3986
3987        // Focus arrives. The *same* request answers; the caller asked once.
3988        shell.set_clipboard_readable(true);
3989        let events = drain(&mut shell);
3990        assert_eq!(events.len(), 1);
3991        assert_eq!(
3992            events[0],
3993            ShellEvent::ClipboardData {
3994                window,
3995                request,
3996                mime: ReceivedMime::from(MimeType::TextUtf8),
3997                content: ClipboardContent::Bytes(b"published".to_vec()),
3998            }
3999        );
4000        assert_eq!(shell.held_clipboard_reads(), 0);
4001    }
4002
4003    #[test]
4004    fn a_read_that_never_becomes_answerable_ends_as_unavailable() {
4005        // Obligation 4: every accepted request is answered, within a bounded
4006        // time. A request that stayed outstanding forever is a UI stuck on
4007        // "pasting…" that no consumer can detect.
4008        let (mut shell, window) = shell_with_configured_window();
4009        shell
4010            .clipboard_offer(window, &[ClipboardOffer::text("unreachable")])
4011            .expect("offer");
4012        shell.set_clipboard_readable(false);
4013        shell.clipboard_deadline(2);
4014
4015        let request = shell
4016            .clipboard_request(window, MimeType::TextUtf8)
4017            .expect("request");
4018        assert!(drain(&mut shell).is_empty(), "pump 1: still held");
4019        assert!(drain(&mut shell).is_empty(), "pump 2: still held");
4020        let events = drain(&mut shell);
4021        assert_eq!(
4022            events[0],
4023            ShellEvent::ClipboardData {
4024                window,
4025                request,
4026                mime: ReceivedMime::from(MimeType::TextUtf8),
4027                // Not `Empty`: there is something on the clipboard, and this
4028                // shell simply could not get at it.
4029                content: ClipboardContent::Unavailable,
4030            }
4031        );
4032        assert_eq!(shell.held_clipboard_reads(), 0);
4033    }
4034
4035    #[test]
4036    fn a_peer_that_holds_the_clipboard_and_never_delivers_is_unavailable() {
4037        // The other failure with no protocol event behind it: on Wayland the
4038        // transfer is a pipe another application writes, and an application
4039        // that takes the descriptor and hangs produces exactly this.
4040        let (mut shell, window) = shell_with_configured_window();
4041        shell.set_foreign_clipboard(vec![(
4042            ReceivedMime::new("text/plain"),
4043            b"never sent".to_vec(),
4044        )]);
4045        shell.set_clipboard_stalled(true);
4046        shell.clipboard_deadline(1);
4047        assert!(
4048            !shell.clipboard_readable(window),
4049            "a clipboard whose owner will not answer is not readable"
4050        );
4051
4052        let request = shell
4053            .clipboard_request(window, MimeType::TextUtf8)
4054            .expect("request");
4055        assert!(drain(&mut shell).is_empty());
4056        let events = drain(&mut shell);
4057        let ShellEvent::ClipboardData {
4058            request: answered,
4059            content,
4060            ..
4061        } = &events[0]
4062        else {
4063            panic!("wrong variant");
4064        };
4065        assert_eq!(*answered, request);
4066        assert_eq!(*content, ClipboardContent::Unavailable);
4067
4068        // The peer wakes up; a fresh read now succeeds.
4069        shell.set_clipboard_stalled(false);
4070        let request = shell
4071            .clipboard_request(window, MimeType::TextUtf8)
4072            .expect("request");
4073        assert_eq!(
4074            drain(&mut shell)[0],
4075            ShellEvent::ClipboardData {
4076                window,
4077                request,
4078                mime: ReceivedMime::new("text/plain"),
4079                content: ClipboardContent::Bytes(b"never sent".to_vec()),
4080            }
4081        );
4082    }
4083
4084    #[test]
4085    fn claiming_the_clipboard_can_require_a_user_interaction() {
4086        // Wayland's `set_selection` serial and the browser's user-gesture gate,
4087        // modelled as one thing — because they are one thing: a background
4088        // process must not be able to take the clipboard.
4089        let (mut shell, window) = shell_with_configured_window();
4090        shell.require_user_interaction(true);
4091
4092        let refused = shell.clipboard_offer(window, &[ClipboardOffer::text("stolen")]);
4093        assert!(
4094            matches!(
4095                refused,
4096                Err(ShellError::NeedsUserInteraction {
4097                    backend: ShellBackend::Headless,
4098                    ..
4099                })
4100            ),
4101            "{refused:?}"
4102        );
4103        assert!(
4104            shell.clipboard_bytes(MimeType::TextUtf8).is_none(),
4105            "a refused claim must not have taken the clipboard anyway"
4106        );
4107
4108        // The copy the user actually asked for. Any injected input counts, as
4109        // any real input serial would.
4110        shell.key_press(window, KeyCode::KeyC).expect("key");
4111        shell
4112            .clipboard_offer(window, &[ClipboardOffer::text("copied")])
4113            .expect("with a serial in hand, the claim goes through");
4114        assert_eq!(
4115            shell.clipboard_bytes(MimeType::TextUtf8),
4116            Some(&b"copied"[..])
4117        );
4118
4119        // And the permission goes stale, exactly as a serial does.
4120        shell.clear_user_interaction();
4121        assert!(matches!(
4122            shell.clipboard_offer(window, &[ClipboardOffer::text("later")]),
4123            Err(ShellError::NeedsUserInteraction { .. })
4124        ));
4125    }
4126
4127    #[test]
4128    fn a_held_read_for_a_destroyed_window_is_dropped_rather_than_answered() {
4129        // Obligation 1 outranks obligation 4: an answer naming a window that no
4130        // longer exists is a stale handle in a consumer's hands.
4131        let (mut shell, window) = shell_with_configured_window();
4132        shell.set_clipboard_readable(false);
4133        let _request = shell
4134            .clipboard_request(window, MimeType::TextUtf8)
4135            .expect("request");
4136        assert_eq!(shell.held_clipboard_reads(), 1);
4137
4138        shell.destroy_window(window).expect("destroy");
4139        let events = drain(&mut shell);
4140        assert_eq!(shell.held_clipboard_reads(), 0);
4141        assert!(
4142            !events
4143                .iter()
4144                .any(|event| matches!(event, ShellEvent::ClipboardData { .. })),
4145            "no clipboard answer may name a destroyed window: {events:?}"
4146        );
4147    }
4148
4149    #[test]
4150    fn a_paste_from_a_foreign_application_keeps_the_foreign_spelling() {
4151        let (mut shell, window) = shell_with_configured_window();
4152        shell.set_foreign_clipboard(vec![
4153            // Exactly what a GTK application offers, and a string no
4154            // `&'static str` in this crate could have held.
4155            (ReceivedMime::new("text/plain"), b"from gedit".to_vec()),
4156            (
4157                ReceivedMime::new("application/vnd.some-editor.scene+json"),
4158                b"{}".to_vec(),
4159            ),
4160        ]);
4161
4162        // Asking for our canonical spelling still finds it …
4163        let request = shell
4164            .clipboard_request(window, MimeType::TextUtf8)
4165            .expect("request");
4166        let events = drain(&mut shell);
4167        let ShellEvent::ClipboardData {
4168            request: answered,
4169            mime,
4170            content,
4171            ..
4172        } = &events[0]
4173        else {
4174            panic!("wrong variant");
4175        };
4176        assert_eq!(*answered, request);
4177        assert_eq!(content.bytes(), Some(&b"from gedit"[..]));
4178        // … and the answer reports what the peer actually called it.
4179        assert_eq!(mime.as_str(), "text/plain");
4180        assert!(mime.matches(MimeType::TextUtf8));
4181        assert_ne!(*mime, ReceivedMime::from(MimeType::TextUtf8));
4182
4183        // A format the engine has no name for is still reachable and still
4184        // reported verbatim.
4185        assert_eq!(
4186            shell.clipboard_bytes(MimeType::Other("application/vnd.some-editor.scene+json")),
4187            Some(&b"{}"[..])
4188        );
4189    }
4190
4191    // ------------------------------------------------------------------ panics
4192
4193    #[test]
4194    #[should_panic(expected = "a shell needs at least one monitor")]
4195    fn a_shell_with_no_monitors_is_rejected() {
4196        let _ = HeadlessShell::new().with_monitors(Vec::new());
4197    }
4198
4199    #[test]
4200    #[should_panic(expected = "a text commit is never empty")]
4201    fn an_empty_text_commit_is_rejected() {
4202        let (mut shell, window) = shell_with_configured_window();
4203        let _ = shell.commit_text(window, "");
4204    }
4205}