Skip to main content

day_mock/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-mock: the headless toolkit (DESIGN.md §3.2, §21.2 M0–M1).
5//!
6//! Records every toolkit call into a compact op log (golden-diffable), performs deterministic
7//! measurement (8pt/char × 16pt line labels, fixed control sizes), and lets tests inject
8//! native events through the real sink. The op log is the contract for the fine-grained
9//! guarantees: "exactly one op per state change" and "bounded measure calls" are assertions
10//! over this log.
11
12use std::any::Any;
13use std::cell::RefCell;
14use std::collections::HashMap;
15use std::fmt::Write as _;
16use std::rc::Rc;
17
18use day_spec::props::*;
19use day_spec::*;
20
21// --- the opt-in native behavior: list and tree viewports, cover reports ----------------------
22//
23// A native list binds the rows it shows into cells by itself: on attach, after a reload, and
24// around a row it is asked to scroll to. Unit tests drive that by hand through
25// `MockProbe::list_bind`; the conformance harness has no test in the loop to do it, so it turns
26// this on (`MockProbe::set_list_viewport`) and the mock binds a window of rows itself.
27//
28// The binding cannot happen where the list learns of a change: that is inside a Toolkit duty,
29// with Day's tree borrowed, and day-core skips a bind it cannot reach the tree for. So a change
30// marks the viewport dirty, and the next `post_delayed` (a `sleep`, which the runner's retry
31// loop reaches with the tree free) binds it.
32
33/// An event a native toolkit raises by itself, with the sink to raise it through.
34type NativeEvent = (Rc<dyn Fn(NodeId, Event)>, NodeId, Event);
35/// A viewport's rows in display order, given the disclosed rows.
36type VisibleRows = Rc<dyn Fn(&std::collections::HashSet<u64>) -> Vec<u64>>;
37
38thread_local! {
39    /// Rows a list shows at once; 0 = off (the default: unit tests bind by hand).
40    static VIEWPORT_ROWS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
41    static VIEWPORTS: RefCell<HashMap<u64, Viewport>> = RefCell::new(HashMap::new());
42    /// Each bound viewport cell's row height, as the source reported it after the bind and
43    /// `ListPatch::RowSizeInvalidated` corrected it since: the cells stack by these heights,
44    /// which is where `read_native` finds a row's content in the window.
45    static CELL_HEIGHTS: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
46    /// Events a native toolkit would raise by itself (a cover's size and its dismissal), held
47    /// like the viewport binds until the tree is free, with the sink to raise them through.
48    static NATIVE_EVENTS: RefCell<Vec<NativeEvent>> = RefCell::new(Vec::new());
49    /// The primary window's size, which a presented cover fills.
50    static MOCK_WINDOW: std::cell::Cell<Size> = const { std::cell::Cell::new(Size::new(0.0, 0.0)) };
51}
52
53struct Viewport {
54    /// The rows in display order, given the tree's disclosed rows: a list's indices, a tree's
55    /// tokens.
56    visible: VisibleRows,
57    bind_row: Rc<dyn Fn(u64, RawHandle)>,
58    recycle: Rc<dyn Fn(RawHandle)>,
59    /// The bound row's height (`ListSource::cell_height`); a tree's rows report none.
60    cell_height: Option<Rc<dyn Fn(RawHandle) -> f64>>,
61    /// A tree's disclosed rows, as `TreePatch::Expand` set them.
62    expanded: std::collections::HashSet<u64>,
63    /// The first row shown.
64    start: usize,
65    /// Scroll to the end on the next bind.
66    to_end: bool,
67    /// Cells bound by the last bind.
68    bound: usize,
69    dirty: bool,
70}
71
72/// The physical cell `slot` of list `host`: stable per list and slot, clear of widget handles.
73fn viewport_cell(host: u64, slot: usize) -> RawHandle {
74    ((1u64 << 40) + host * 4096 + slot as u64) as RawHandle
75}
76
77/// The list and slot a viewport cell belongs to: [`viewport_cell`] inverted.
78fn viewport_slot(cell: u64) -> Option<(u64, usize)> {
79    let offset = cell.checked_sub(1u64 << 40)?;
80    Some((offset / 4096, (offset % 4096) as usize))
81}
82
83/// How far down its list viewport cell `cell` sits: the heights of the cells above it.
84fn viewport_cell_top(cell: u64) -> f64 {
85    let Some((host, slot)) = viewport_slot(cell) else {
86        return 0.0;
87    };
88    CELL_HEIGHTS.with(|h| {
89        let h = h.borrow();
90        (0..slot)
91            .map(|s| {
92                h.get(&(viewport_cell(host, s) as u64))
93                    .copied()
94                    .unwrap_or(0.0)
95            })
96            .sum()
97    })
98}
99
100/// Widget `id`'s frame in the window, as `NativeSnapshot::frame` is defined: its own frame
101/// moved by each ancestor's origin, and a list row's content by where its cell sits in the list.
102fn window_frame(s: &MockState, id: u64) -> Rect {
103    let Some(w) = s.widgets.get(&id) else {
104        return Rect::default();
105    };
106    let mut frame = w.frame;
107    let mut current = id;
108    // Bounded: a malformed test tree must not hang the probe.
109    for _ in 0..4096 {
110        let next = match s.widgets.get(&current) {
111            Some(w) if w.kind == kinds::LIST_CELL => viewport_slot(current).map(|(host, _)| {
112                frame.origin.y += viewport_cell_top(current);
113                host
114            }),
115            _ => s
116                .widgets
117                .iter()
118                .find(|(_, p)| p.children.contains(&current))
119                .map(|(k, _)| *k),
120        };
121        let Some(parent) = next else {
122            break;
123        };
124        if let Some(p) = s.widgets.get(&parent) {
125            frame.origin.x += p.frame.origin.x;
126            frame.origin.y += p.frame.origin.y;
127        }
128        current = parent;
129    }
130    frame
131}
132
133fn viewport_touch(host: u64, f: impl FnOnce(&mut Viewport)) {
134    VIEWPORTS.with(|v| {
135        if let Some(port) = v.borrow_mut().get_mut(&host) {
136            f(port);
137            port.dirty = true;
138        }
139    });
140}
141
142/// Bind every dirty viewport's rows, outside any borrow of the registry.
143fn viewport_flush() {
144    let rows = VIEWPORT_ROWS.with(std::cell::Cell::get);
145    if rows == 0 {
146        return;
147    }
148    let events = NATIVE_EVENTS.with(|q| std::mem::take(&mut *q.borrow_mut()));
149    for (sink, node, event) in events {
150        sink(node, event);
151    }
152    let dirty: Vec<u64> = VIEWPORTS.with(|v| {
153        v.borrow()
154            .iter()
155            .filter(|(_, p)| p.dirty)
156            .map(|(h, _)| *h)
157            .collect()
158    });
159    for host in dirty {
160        let Some((visible, bind_row, recycle, cell_height, expanded, start, to_end, bound)) =
161            VIEWPORTS.with(|v| {
162                let mut v = v.borrow_mut();
163                let p = v.get_mut(&host)?;
164                p.dirty = false;
165                Some((
166                    p.visible.clone(),
167                    p.bind_row.clone(),
168                    p.recycle.clone(),
169                    p.cell_height.clone(),
170                    p.expanded.clone(),
171                    p.start,
172                    p.to_end,
173                    p.bound,
174                ))
175            })
176        else {
177            continue;
178        };
179        let rows_now = visible(&expanded);
180        let total = rows_now.len();
181        let start = if to_end {
182            total.saturating_sub(rows)
183        } else {
184            start.min(total.saturating_sub(rows))
185        };
186        let count = rows.min(total - start.min(total));
187        for slot in 0..count {
188            let cell = viewport_cell(host, slot);
189            bind_row(rows_now[start + slot], cell);
190            // A native list sizes the row once it is bound, from the height Day laid it at.
191            if let Some(height) = &cell_height {
192                let laid = height(cell);
193                CELL_HEIGHTS.with(|h| h.borrow_mut().insert(cell as u64, laid));
194            }
195        }
196        // Cells past a shrunk source go back to the pool, as a native list's would.
197        for slot in count..bound {
198            recycle(viewport_cell(host, slot));
199        }
200        VIEWPORTS.with(|v| {
201            if let Some(p) = v.borrow_mut().get_mut(&host) {
202                p.start = start;
203                p.to_end = false;
204                p.bound = count;
205            }
206        });
207    }
208}
209
210#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
211pub struct MockHandle(pub u64);
212
213#[derive(Default, Debug, Clone)]
214pub struct MockWidget {
215    pub kind: &'static str,
216    pub node: u64,
217    pub text: String,
218    pub placeholder: String,
219    /// A text field's last requested selection (`TextFieldPatch::Select`), in characters,
220    /// probe-visible for tests. The mock has no focus to gate it on, so it keeps every request.
221    pub selection: Option<day_spec::props::TextSelection>,
222    pub value: f64,
223    pub flag: bool,
224    /// A cover presented as a half sheet (`CoverProps::half`): its present reports half the
225    /// window's height, as the native sheet would.
226    pub half: bool,
227    pub enabled: bool,
228    /// A button's selected state (`ButtonProps::selected`), probe-visible for tests.
229    pub selected: bool,
230    /// `text_area` attributes (probe-visible for tests): editable/read-only, selectable, spell-check.
231    pub editable: bool,
232    pub selectable: bool,
233    pub spellcheck: bool,
234    /// The last text entry traits applied to this widget (docs/textfield.md), probe-visible
235    /// for tests; `None` until a field asks for anything but the defaults.
236    pub input_traits: Option<day_spec::InputTraits>,
237    /// The last `.cursor()` applied to this widget (probe-visible for tests), `None` until set.
238    pub cursor: Option<day_spec::Cursor>,
239    pub children: Vec<u64>,
240    pub frame: Rect,
241    pub a11y: A11yProps,
242    pub scroll_content: Size,
243    /// The scroll offset after the last `scroll_to` (docs/scroll.md), computed with the same
244    /// minimal-reveal clamp every real backend applies (probe-visible for tests).
245    pub scroll_offset: Point,
246    pub ops: Vec<DrawOp>,
247    /// Surface style from a `background`/`corner_radius` decorator (probe-visible for tests).
248    pub background: Option<Color>,
249    pub corner_radius: f64,
250    pub clips: bool,
251    /// Semantic theme-adaptive surface (a form section card), probe-visible for tests.
252    pub surface_role: Option<day_spec::SurfaceRole>,
253    /// A label's resolved font spec (probe-visible so tests can assert e.g. `Font::Custom` flow).
254    pub font: Option<day_spec::FontSpec>,
255    /// A label's styled spans (docs/text-runs.md). Probe-visible so a test can assert that the
256    /// second word is bold, which no screenshot comparison can state and no `assert_text` can
257    /// see, since the plain text is identical either way.
258    pub runs: Vec<day_spec::TextRun>,
259    /// Last focus state driven through the `focus` duty (docs/focus.md), probe-visible.
260    pub focused: bool,
261    /// Last opacity applied via `set_opacity` (§8.4); `None` until touched (probe-visible).
262    pub opacity: Option<f64>,
263    /// Last transform applied via `set_transform` (§8.4), probe-visible.
264    pub transform: Option<day_spec::Transform>,
265    /// The most recent animation intent seen on any duty for this widget (`update`/`set_frame`/
266    /// `set_opacity`/`set_transform`). Lets tests assert `with_animation` threaded the intent.
267    pub last_anim: Option<AnimSpec>,
268    /// A nav host's current presentation (docs/size-classes.md), probe-visible so a test can
269    /// assert which of the four a morph landed on. `flag` carries only split-ness, which cannot
270    /// tell `Tabs` from `Rail` from `Stack`; both are kept because the older tests read `flag`.
271    pub presentation: Option<day_spec::props::NavPresentation>,
272    /// The resident detail page index a `NavPatch::Select` last chose (docs/navigation.md).
273    /// `None` until the host is asked to select one, which only happens in a presentation whose
274    /// rows are chrome; a stacked host pushes and pops instead.
275    pub selected_page: Option<usize>,
276    /// Pages a nav host holds above its root (`NavPatch::Pushed` less `Popped`), what the
277    /// mock's [`Toolkit::native_back`] pops first.
278    pub nav_depth: usize,
279    /// A nav host's back guard (`NavPatch::GuardTop`): the native back asks Day instead of
280    /// popping.
281    pub nav_guarded: bool,
282}
283
284/// A secondary window opened through the `open_window` duty (docs/windows.md),
285/// probe-visible for the `open_window` tests.
286#[derive(Clone, Debug)]
287pub struct MockWindow {
288    /// The content-container widget handle.
289    pub handle: u64,
290    /// The window root's spec-boundary id (events emit to it).
291    pub node: NodeId,
292    pub title: String,
293    pub size: Size,
294    /// `"normal"` | `"preferences"`.
295    pub kind: String,
296    /// The tabbing the window was opened with (docs/windows.md).
297    pub tabbing: day_spec::WindowTabbing,
298    pub open: bool,
299    pub focused: bool,
300    /// The content size the window was fitted to (`WindowOptions::size_to_fit`), or `None` if it
301    /// kept the size it was opened at. Probe-visible so a test can assert that a preferences
302    /// panel shrank to its rows rather than keeping the caller's ceiling.
303    pub fit_size: Option<Size>,
304}
305
306#[derive(Default)]
307pub struct MockState {
308    /// Optional synthetic palette for appearance-reactivity tests.
309    pub system_colors: Option<[day_spec::Color; 5]>,
310    /// Simulate native navigation that has not settled yet in engine tests.
311    pub ui_busy: bool,
312    next: u64,
313    pub widgets: HashMap<u64, MockWidget>,
314    pub log: Vec<String>,
315    /// Held as an `Rc` rather than the `Box` day-spec hands over, so it can be CALLED without
316    /// being taken out.
317    ///
318    /// Taking it out is what a `Box<dyn Fn>` forces, and it is a trap: the whole dispatch of one
319    /// event (pump, handler, action, any completion a Toolkit duty raises along the way)
320    /// happens inside that window, so a second event raised during the first found no sink and
321    /// vanished. An image decode completing inside a button's action is exactly that shape
322    /// (docs/images.md).
323    pub sink: Option<Rc<dyn Fn(NodeId, Event)>>,
324    /// Decoded images by id (docs/images.md): what `image_info` answers and `release_image`
325    /// forgets, so a test can assert both that a decode landed and that dropping the handle
326    /// released it.
327    pub bitmaps: HashMap<u64, day_spec::BitmapInfo>,
328    /// (kind, proposal) measure-call counter for the M1 bounded-measure tests.
329    pub measure_calls: usize,
330    /// What `scroll_bar_inset` answers (docs/scroll.md): 0, overlay bars, unless a test plays a
331    /// backend whose classic bar takes room from the viewport.
332    pub scroll_bar_inset: f64,
333    /// Recycling-list row-pull sources, keyed by list host handle (docs/list.md). A test drives
334    /// the "viewport" through [`MockProbe::list_bind`], simulating what a native list would do.
335    pub list_sources: HashMap<u64, ListSource>,
336    /// Hierarchical-tree row-pull sources, keyed by tree host handle (docs/tree.md). A test
337    /// drives the "native tree" through the `MockProbe::tree_*` probes.
338    pub tree_sources: HashMap<u64, day_spec::TreeSource>,
339    /// Exercise the shared composed tree/section implementation instead of native pulls.
340    pub emulated_trees: bool,
341    /// The app menu as last applied (docs/menus.md): item titles, probe-visible.
342    pub app_menu: Vec<String>,
343    /// The Dock menu as last applied (docs/menus.md "Dock menu"): item titles.
344    pub dock_menu: Vec<String>,
345    /// The widgets marked as window drag regions (docs/window-chrome.md), by handle.
346    pub drag_regions: std::collections::HashSet<u64>,
347    /// The status items as last applied (docs/status-item.md).
348    pub status_items: Vec<day_spec::StatusItemSpec>,
349    /// The Dock or taskbar progress as last applied.
350    pub app_progress: day_spec::AppProgress,
351    /// Whether the Dock icon is shown (`None` until the app asks).
352    pub dock_visible: Option<bool>,
353    /// Whether day-core asked the platform to keep running with no window.
354    pub keep_running: bool,
355    /// The run-time launcher shortcuts as last applied.
356    pub launcher_shortcuts: Vec<day_spec::LauncherShortcut>,
357    /// Every `apply_window` change, oldest first, keyed by content-container handle
358    /// (docs/windows.md "Window properties").
359    pub window_changes: Vec<(u64, day_spec::WindowChange)>,
360    /// Each window's display state as the mock platform holds it, keyed by handle.
361    pub window_states: HashMap<u64, day_spec::WindowState>,
362    /// Hold `WindowChange::State` requests instead of completing them, so a test can model a
363    /// platform that declines one (a browser refusing fullscreen outside a gesture).
364    pub decline_window_states: bool,
365    /// Every window-toolbar edit, in order (docs/toolbars.md). A test reads these to hold
366    /// day-core to touching only the items that changed.
367    pub toolbar_edits: Vec<Vec<day_spec::ToolbarOp>>,
368    /// The bar those edits and the patches produced, the way a backend keeps it.
369    pub toolbar: day_spec::ToolbarMirror,
370    /// `Cap::ToolbarSearch` answers `Unsupported`: a phone's bar, a row of actions with no room
371    /// for a field (docs/search.md).
372    pub no_toolbar_search: bool,
373    /// `edit_toolbar` declines every edit, as a window with no bar to edit yet does.
374    pub decline_toolbar_edits: bool,
375    /// Every targeted toolbar patch, in order.
376    pub toolbar_patches: Vec<day_spec::ToolbarPatch>,
377    /// Context menus by widget handle (docs/menus.md): item titles per handle.
378    pub context_menus: HashMap<u64, Vec<String>>,
379    /// Summon-time menus, callable after releasing the probe's state borrow.
380    pub context_menu_providers: HashMap<u64, day_spec::ContextMenuFn>,
381    /// Menu buttons' providers by button handle (`set_button_menu`, docs/menus.md "Menu
382    /// buttons"), callable after releasing the probe's state borrow, as a press would.
383    pub button_menus: HashMap<u64, day_spec::ContextMenuFn>,
384    /// Every share chooser presented, with the handle of the control it pointed at, if any
385    /// (docs/sharing.md).
386    pub shares: Vec<(day_spec::share::ShareSpec, Option<u64>)>,
387    /// Whether day-core armed the system back for the app's handlers
388    /// (`Toolkit::set_system_back`, docs/navigation.md "Handling the system Back").
389    pub system_back: bool,
390    /// Secondary windows (docs/windows.md), in open order, probe-visible.
391    pub windows: Vec<MockWindow>,
392    /// `open_window` answers `Unsupported` (the cover-fallback test harness).
393    pub no_multi_window: bool,
394    /// Delay native close confirmation until `MockProbe::close_window_natively` is called.
395    pub defer_window_close: bool,
396    /// Enable the OS window-tab contract for lifecycle tests.
397    pub native_window_tabs: bool,
398    /// Realize `kinds::LIST_ITEM` natively (`Cap::ListItem` answers `Native`), so a test sees
399    /// the item's props and patches; off, the `list_item` piece composes.
400    pub native_list_items: bool,
401    /// Native tab groups in display order; tests can simulate an OS reorder or detach.
402    pub window_tab_groups: Vec<Vec<NodeId>>,
403    /// Every `announce` in order, as `(text, urgent)` (docs/accessibility.md), probe-visible.
404    pub announcements: Vec<(String, bool)>,
405    /// What `reduce_motion` answers (docs/accessibility.md): the user's system setting as
406    /// the mock models it. A test flips it and calls `day_core::note_motion_changed`, as a
407    /// backend's observer would.
408    pub reduce_motion: bool,
409    /// Model a toolkit whose secure field is a different native class (AppKit, WinUI):
410    /// `set_input_traits` answers a secure flip with a replacement widget under a new handle
411    /// (docs/textfield.md). Off by default: most toolkits flip a property.
412    pub secure_class_swap: bool,
413    /// `Cap::NavSplit` answers `Native`: the harness for split and re-presenting nav hosts
414    /// (docs/size-classes.md). Off by default, so the mock keeps modeling a phone.
415    pub nav_split: bool,
416    /// `Cap::NavTabs` answers `Unsupported`: the harness for the degradation path, where an
417    /// `Automatic` nav host falls back to the sidebar resolver (docs/navigation.md). Inverted
418    /// like `no_multi_window` because the capability is on by default: a phone has a tab bar,
419    /// so a mock that models a phone must have one too, or the default resolution is a fiction.
420    pub no_nav_tabs: bool,
421    /// Preserve native navigation while content lists remain draggable, as on UIKit.
422    pub no_nav_reorder: bool,
423    /// `Cap::NavReorder` answers `Native`: the sidebar drags its own rows, as on AppKit, so a
424    /// reordering nav keeps its `day.nav_menu` and marks the movable rows. Off, the mock
425    /// answers `Emulated` and the nav stands a reorderable list in.
426    pub native_nav_reorder: bool,
427    /// `Cap::NavTabsAdaptive` answers `Unsupported`: the harness for a desktop idiom, where a
428    /// narrow window collapses to a stack instead of growing a tab bar. Also inverted: the mock
429    /// models a phone by default, and a phone adapts.
430    pub desktop_idiom: bool,
431    /// What `Cap::NavContentList` answers (docs/navigation.md): `Unsupported` by default (the
432    /// composed path); a test opts into `Native` (persistent pane) or `Emulated` (merges into
433    /// the stack) with [`MockProbe::set_nav_content_list`]. Read during the build.
434    pub nav_content_list: Support,
435    /// `open_window` answers `Pending` (the async-completion test harness); the test
436    /// finishes the open through [`MockProbe::complete_window`].
437    pub pending_windows: bool,
438    /// Parked `Pending` opens: (node, title, kind).
439    pub pending_opens: Vec<(NodeId, String, String)>,
440    /// Formatters for patch types the mock does not know; see [`MockProbe::describe_patch`].
441    #[allow(clippy::type_complexity)]
442    pub describers: Vec<Box<dyn Fn(&dyn Any) -> Option<String>>>,
443}
444
445impl MockState {
446    fn log(&mut self, s: String) {
447        self.log.push(s);
448    }
449}
450
451/// The mock backend. Cloneable observer half: construct with [`MockToolkit::new`] and keep the
452/// returned [`MockProbe`] to inspect state after day-core takes ownership of the toolkit.
453pub struct MockToolkit {
454    pub state: Rc<RefCell<MockState>>,
455}
456
457#[derive(Clone)]
458pub struct MockProbe {
459    pub state: Rc<RefCell<MockState>>,
460}
461
462impl MockToolkit {
463    #[must_use]
464    pub fn new() -> (Self, MockProbe) {
465        // A fresh mock starts with the viewport off and no lists from an earlier one.
466        VIEWPORT_ROWS.with(|r| r.set(0));
467        VIEWPORTS.with(|v| v.borrow_mut().clear());
468        NATIVE_EVENTS.with(|q| q.borrow_mut().clear());
469        // Posts run on the calling thread here (see `Platform::post`), so a wake from a pool
470        // thread would have no loop to land on: blocking jobs run inline, like the web's.
471        day_async::set_blocking_inline(true);
472        let state = Rc::new(RefCell::new(MockState::default()));
473        (
474            MockToolkit {
475                state: state.clone(),
476            },
477            MockProbe { state },
478        )
479    }
480}
481
482impl MockProbe {
483    #[must_use]
484    pub fn log(&self) -> Vec<String> {
485        self.state.borrow().log.clone()
486    }
487    pub fn clear_log(&self) {
488        let mut s = self.state.borrow_mut();
489        s.log.clear();
490        s.measure_calls = 0;
491    }
492    pub fn measure_calls(&self) -> usize {
493        self.state.borrow().measure_calls
494    }
495    /// Teach the op log to name a patch type the mock doesn't know.
496    ///
497    /// A standalone piece (docs/extending.md) defines its patch enum in its own crate, so the
498    /// `update` duty sees `&dyn Any` and logs `update <kind> #n ?`. Install a describer and the
499    /// log carries the variant instead, which is what makes "this write patched attributes and
500    /// did not replace the document" an assertion a test can make:
501    ///
502    /// ```ignore
503    /// probe.describe_patch::<EditorPatch>(|p| format!("{p:?}"));
504    /// ```
505    ///
506    /// Describers are tried in the order installed; the first that matches the type wins.
507    pub fn describe_patch<T: 'static>(&self, f: impl Fn(&T) -> String + 'static) {
508        self.state
509            .borrow_mut()
510            .describers
511            .push(Box::new(move |any| any.downcast_ref::<T>().map(&f)));
512    }
513    /// Ops excluding measures (mutation ops only).
514    #[must_use]
515    pub fn mutations(&self) -> Vec<String> {
516        self.state
517            .borrow()
518            .log
519            .iter()
520            .filter(|l| !l.starts_with("measure"))
521            .cloned()
522            .collect()
523    }
524    #[must_use]
525    pub fn widget(&self, h: MockHandle) -> MockWidget {
526        self.state
527            .borrow()
528            .widgets
529            .get(&h.0)
530            .cloned()
531            .unwrap_or_default()
532    }
533    #[must_use]
534    pub fn find_by_kind(&self, kind: &str) -> Vec<(MockHandle, MockWidget)> {
535        let mut v: Vec<_> = self
536            .state
537            .borrow()
538            .widgets
539            .iter()
540            .filter(|(_, w)| w.kind == kind)
541            .map(|(k, w)| (MockHandle(*k), w.clone()))
542            .collect();
543        v.sort_by_key(|(h, _)| h.0);
544        v
545    }
546    /// Report a simulated viewport without synchronously entering application code.
547    pub fn list_first_visible(&self, host: MockHandle, index: usize) {
548        let callback = self
549            .state
550            .borrow()
551            .list_sources
552            .get(&host.0)
553            .and_then(|source| source.first_visible.clone());
554        if let Some(callback) = callback {
555            callback(index);
556        }
557    }
558
559    /// Row count a `LIST` host would query from its data-source.
560    #[must_use]
561    pub fn list_len(&self, host: MockHandle) -> usize {
562        let f = self
563            .state
564            .borrow()
565            .list_sources
566            .get(&host.0)
567            .map(|s| s.len.clone());
568        f.map_or(0, |f| f())
569    }
570
571    /// Simulate the native list binding row `index` into a physical `cell`: Day builds the row
572    /// the first time a cell is used and rebinds (slot-write) when it is recycled. Drives the real
573    /// day-core driver, so tests exercise the whole recycling path. (The source Rc is cloned out
574    /// before the call so the re-entrant `with_tree`/toolkit work holds no `MockState` borrow.)
575    pub fn list_bind(&self, host: MockHandle, index: usize, cell: MockHandle) {
576        let f = self
577            .state
578            .borrow()
579            .list_sources
580            .get(&host.0)
581            .map(|s| s.bind_row.clone());
582        if let Some(f) = f {
583            f(index, cell.0 as RawHandle);
584        }
585    }
586
587    /// Simulate an emulated-pin host binding display row `index` into its pinned-header `cell`
588    /// (`ListSource::bind_pinned`, docs/list.md "Sections").
589    pub fn list_bind_pinned(&self, host: MockHandle, index: usize, cell: MockHandle) {
590        let f = self
591            .state
592            .borrow()
593            .list_sources
594            .get(&host.0)
595            .map(|s| s.bind_pinned.clone());
596        if let Some(f) = f {
597            f(index, cell.0 as RawHandle);
598        }
599    }
600
601    /// Simulate the native list pooling a physical `cell` that scrolled out of view, the
602    /// `onViewRecycled` / prepare-for-reuse moment. Day parks the cell subtree's ids so the
603    /// hidden row stops answering lookups; the next [`Self::list_bind`] of that cell restores
604    /// them (docs/list.md).
605    /// Have the mock do by itself what a native toolkit does without being asked, for harnesses
606    /// with no test in the loop to drive it (the conformance runner): lists and trees bind a
607    /// window of `viewport_rows` rows (on attach, after a reload, around a scrolled-to row), and
608    /// a presented cover reports its size and, once dismissed, that it is hidden. 0 turns it off,
609    /// the default, where unit tests drive [`Self::list_bind`] and the cover events by hand.
610    pub fn set_native_behavior(&self, viewport_rows: usize) {
611        VIEWPORT_ROWS.with(|r| r.set(viewport_rows));
612    }
613
614    pub fn list_recycle(&self, host: MockHandle, cell: MockHandle) {
615        let f = self
616            .state
617            .borrow()
618            .list_sources
619            .get(&host.0)
620            .map(|s| s.recycle.clone());
621        if let Some(f) = f {
622            f(cell.0 as RawHandle);
623        }
624    }
625
626    /// Simulate the native list discarding a physical `cell` for good, the factory-teardown /
627    /// cell-dealloc moment: Day disposes the row it built there, so its ids are gone rather
628    /// than parked and the next [`Self::list_bind`] of the same handle builds afresh
629    /// (docs/list.md).
630    pub fn list_release(&self, host: MockHandle, cell: MockHandle) {
631        let f = self
632            .state
633            .borrow()
634            .list_sources
635            .get(&host.0)
636            .map(|s| s.release.clone());
637        if let Some(f) = f {
638            f(cell.0 as RawHandle);
639        }
640    }
641
642    /// Consult the list's reorder guard the way a native validate hook would: the accepted
643    /// target index, or -1 when the guard denies. `i64::MIN` when the list is not reorderable
644    /// (no `.reorderable()`).
645    #[must_use]
646    pub fn list_can_move(&self, host: MockHandle, from: usize, to: usize) -> i64 {
647        let f = self
648            .state
649            .borrow()
650            .list_sources
651            .get(&host.0)
652            .and_then(|s| s.reorder.as_ref().map(|r| r.can_move.clone()));
653        f.map_or(i64::MIN, |f| f(from, to))
654    }
655
656    /// Consult the list's delete guard the way a native swipe would before offering its action:
657    /// `Some(true)` to offer, `Some(false)` when the guard protects the row, `None` when the
658    /// list is not deletable (no `.deletable()`).
659    #[must_use]
660    pub fn list_can_delete(&self, host: MockHandle, index: usize) -> Option<bool> {
661        let f = self
662            .state
663            .borrow()
664            .list_sources
665            .get(&host.0)
666            .and_then(|s| s.delete.as_ref().map(|d| d.can_delete.clone()));
667        f.map(|f| f(index))
668    }
669
670    /// Simulate a native swipe-to-delete: consult the guard, commit on accept (shortening Day's
671    /// snapshot and deferring the app's `on_delete`, exactly as a native backend would). Returns
672    /// whether the delete committed.
673    #[must_use]
674    pub fn list_delete(&self, host: MockHandle, index: usize) -> bool {
675        let d = self
676            .state
677            .borrow()
678            .list_sources
679            .get(&host.0)
680            .and_then(|s| s.delete.clone());
681        let Some(d) = d else {
682            self.state
683                .borrow_mut()
684                .log(format!("list delete unsupported {index}"));
685            return false;
686        };
687        if !(d.can_delete)(index) {
688            self.state
689                .borrow_mut()
690                .log(format!("list delete denied {index}"));
691            return false;
692        }
693        (d.delete_row)(index);
694        true
695    }
696
697    /// Pull a row's swipe-action offer the way a native gesture would as the row starts to
698    /// slide (docs/list.md): `Some(actions)`, possibly empty, when the list is swipeable,
699    /// `None` when it is not (no `.swipe_leading()`/`.swipe_trailing()`).
700    #[must_use]
701    pub fn list_swipe_actions(
702        &self,
703        host: MockHandle,
704        index: usize,
705        edge: SwipeEdge,
706    ) -> Option<Vec<ListSwipeAction>> {
707        let f = self
708            .state
709            .borrow()
710            .list_sources
711            .get(&host.0)
712            .and_then(|s| s.swipe.as_ref().map(|sw| sw.actions_at.clone()));
713        f.map(|f| f(index, edge))
714    }
715
716    /// Simulate a native swipe activation: pull the offer and press button `action` (an index
717    /// into it), committing through the source's `perform`, which defers the app's handler to
718    /// the event drain, exactly as a native backend would. Returns whether an action was
719    /// activated.
720    #[must_use]
721    pub fn list_swipe(
722        &self,
723        host: MockHandle,
724        index: usize,
725        edge: SwipeEdge,
726        action: usize,
727    ) -> bool {
728        let sw = self
729            .state
730            .borrow()
731            .list_sources
732            .get(&host.0)
733            .and_then(|s| s.swipe.clone());
734        let Some(sw) = sw else {
735            self.state
736                .borrow_mut()
737                .log(format!("list swipe unsupported {index}"));
738            return false;
739        };
740        if (sw.actions_at)(index, edge).len() <= action {
741            self.state
742                .borrow_mut()
743                .log(format!("list swipe no action {index}"));
744            return false;
745        }
746        (sw.perform)(index, edge, action);
747        true
748    }
749
750    /// Simulate a native drop: consult the guard, commit on accept (rotating Day's snapshot and
751    /// deferring the app's `on_reorder`, exactly as a native backend would). Returns whether the
752    /// move committed. (Reorder Rcs are cloned out before the call, like [`Self::list_bind`].)
753    #[must_use]
754    pub fn list_move(&self, host: MockHandle, from: usize, to: usize) -> bool {
755        let r = self
756            .state
757            .borrow()
758            .list_sources
759            .get(&host.0)
760            .and_then(|s| s.reorder.clone());
761        let Some(r) = r else {
762            self.state
763                .borrow_mut()
764                .log(format!("list move unsupported {from}->{to}"));
765            return false;
766        };
767        let accepted = (r.can_move)(from, to);
768        if accepted < 0 {
769            self.state
770                .borrow_mut()
771                .log(format!("list move denied {from}->{to}"));
772            return false;
773        }
774        (r.move_row)(from, accepted as usize);
775        self.state
776            .borrow_mut()
777            .log(format!("list move {from}->{accepted}"));
778        true
779    }
780
781    /// The tree's direct children of `parent` (`None` = the root level), as tokens, read
782    /// straight from the injected `TreeSource` (docs/tree.md).
783    #[must_use]
784    pub fn tree_children(&self, host: MockHandle, parent: Option<u64>) -> Vec<u64> {
785        let fns = self
786            .state
787            .borrow()
788            .tree_sources
789            .get(&host.0)
790            .map(|s| (s.children_len.clone(), s.child_token.clone()));
791        let Some((len, tok)) = fns else {
792            return Vec::new();
793        };
794        (0..len(parent)).map(|i| tok(parent, i)).collect()
795    }
796
797    /// Whether this token can hold children (draws a disclosure), per the injected source.
798    #[must_use]
799    pub fn tree_expandable(&self, host: MockHandle, token: u64) -> bool {
800        let f = self
801            .state
802            .borrow()
803            .tree_sources
804            .get(&host.0)
805            .map(|s| s.expandable.clone());
806        f.is_some_and(|f| f(token))
807    }
808
809    /// The row's type-ahead string, per the injected source.
810    #[must_use]
811    pub fn tree_type_text(&self, host: MockHandle, token: u64) -> String {
812        let f = self
813            .state
814            .borrow()
815            .tree_sources
816            .get(&host.0)
817            .map(|s| s.type_select_text.clone());
818        f.map_or_default(|f| f(token))
819    }
820
821    /// Simulate the native tree binding `token`'s row into a physical `cell`: build on first
822    /// use, rebind (slot-write) on recycle, exactly like [`Self::list_bind`]. (The source Rc
823    /// is cloned out before the call so the re-entrant work holds no `MockState` borrow.)
824    pub fn tree_bind(&self, host: MockHandle, token: u64, cell: MockHandle) {
825        let f = self
826            .state
827            .borrow()
828            .tree_sources
829            .get(&host.0)
830            .map(|s| s.bind_row.clone());
831        if let Some(f) = f {
832            f(token, cell.0 as RawHandle);
833        }
834    }
835
836    /// Consult the tree's move guard the way a native drag-validate hook would. `None` when
837    /// the tree is not movable (no `.movable()`).
838    #[must_use]
839    pub fn tree_can_move(
840        &self,
841        host: MockHandle,
842        token: u64,
843        parent: Option<u64>,
844        index: Option<usize>,
845    ) -> Option<day_spec::MoveVerdict> {
846        let f = self
847            .state
848            .borrow()
849            .tree_sources
850            .get(&host.0)
851            .and_then(|s| s.moves.as_ref().map(|m| m.can_move.clone()));
852        f.map(|f| f(token, parent, index))
853    }
854
855    /// Simulate a native tree drop: consult the guard, commit on accept (deferring the app's
856    /// `on_move`, exactly as a native backend would). Returns whether the move committed.
857    #[must_use]
858    pub fn tree_move(
859        &self,
860        host: MockHandle,
861        token: u64,
862        parent: Option<u64>,
863        index: Option<usize>,
864    ) -> bool {
865        let m = self
866            .state
867            .borrow()
868            .tree_sources
869            .get(&host.0)
870            .and_then(|s| s.moves.clone());
871        let Some(m) = m else {
872            self.state
873                .borrow_mut()
874                .log(format!("tree move unsupported {token}"));
875            return false;
876        };
877        if (m.can_move)(token, parent, index) == day_spec::MoveVerdict::Deny {
878            self.state
879                .borrow_mut()
880                .log(format!("tree move denied {token}"));
881            return false;
882        }
883        (m.move_node)(token, parent, index);
884        self.state
885            .borrow_mut()
886            .log(format!("tree move {token} -> {parent:?}@{index:?}"));
887        true
888    }
889
890    /// Inject a native event through the real sink (as the toolkit trampoline would).
891    ///
892    /// # Panics
893    ///
894    /// Panics when no event sink is installed, which means no tree was mounted on this mock.
895    pub fn emit(&self, node: NodeId, event: Event) {
896        let sink = self.state.borrow().sink.clone();
897        match sink {
898            Some(sink) => sink(node, event),
899            None => panic!("day-mock: no event sink installed"),
900        }
901    }
902
903    /// Press the menu button with handle `button` as a toolkit does (docs/menus.md "Menu
904    /// buttons"): ask its provider, then answer the items the toolkit would show, or `None`
905    /// when the menu is empty or the provider removed the button
906    /// ([`day_spec::resolve_button_menu`]). The state borrow is released while app code runs.
907    #[must_use]
908    pub fn press_menu_button(&self, button: u64) -> Option<Vec<day_spec::MenuItem>> {
909        let provider = self.state.borrow().button_menus.get(&button).cloned()?;
910        day_spec::resolve_button_menu(&provider, || {
911            self.state.borrow().button_menus.contains_key(&button)
912        })
913    }
914
915    /// The share choosers presented so far, oldest first, with the anchor's handle.
916    #[must_use]
917    pub fn shares(&self) -> Vec<(day_spec::share::ShareSpec, Option<u64>)> {
918        self.state.borrow().shares.clone()
919    }
920
921    /// Whether day-core has the system back armed for the app's handlers (docs/navigation.md
922    /// "Handling the system Back").
923    #[must_use]
924    pub fn system_back_armed(&self) -> bool {
925        self.state.borrow().system_back
926    }
927
928    /// Choose app action `index` in the last share chooser, as a person tapping it would: the
929    /// choice arrives as the action's `Event::MenuAction`. False if there is no such action.
930    #[must_use]
931    pub fn choose_share_action(&self, index: usize) -> bool {
932        let id = self
933            .state
934            .borrow()
935            .shares
936            .last()
937            .and_then(|(spec, _)| spec.actions.get(index))
938            .map(|a| a.id);
939        match id {
940            Some(id) => {
941                self.emit(day_spec::WINDOW_NODE, day_spec::Event::MenuAction(id));
942                true
943            }
944            None => false,
945        }
946    }
947
948    // --- secondary windows (docs/windows.md) -------------------------------------------
949
950    /// Make `Cap::ToolbarSearch` answer `Unsupported`, as a phone's action bar does.
951    pub fn set_no_toolbar_search(&self, v: bool) {
952        self.state.borrow_mut().no_toolbar_search = v;
953    }
954
955    /// Realize list items natively (see `MockState::native_list_items`).
956    pub fn set_native_list_items(&self, v: bool) {
957        self.state.borrow_mut().native_list_items = v;
958    }
959
960    /// Make the toolkit decline (or accept again) toolbar edits.
961    pub fn set_decline_toolbar_edits(&self, v: bool) {
962        self.state.borrow_mut().decline_toolbar_edits = v;
963    }
964
965    /// Every window-toolbar edit applied so far, oldest first.
966    #[must_use]
967    pub fn toolbar_edits(&self) -> Vec<Vec<day_spec::ToolbarOp>> {
968        self.state.borrow().toolbar_edits.clone()
969    }
970
971    /// The window toolbar as the backend holds it now: every edit and patch applied.
972    #[must_use]
973    pub fn toolbar_items(&self) -> Vec<day_spec::ToolbarItem> {
974        self.state.borrow().toolbar.items().to_vec()
975    }
976
977    /// Every targeted toolbar patch applied so far, oldest first.
978    #[must_use]
979    pub fn toolbar_patches(&self) -> Vec<day_spec::ToolbarPatch> {
980        self.state.borrow().toolbar_patches.clone()
981    }
982
983    /// The secondary windows opened so far (closed ones stay listed with `open: false`).
984    #[must_use]
985    pub fn windows(&self) -> Vec<MockWindow> {
986        self.state.borrow().windows.clone()
987    }
988
989    /// The Dock menu's item titles as last installed (docs/menus.md "Dock menu").
990    #[must_use]
991    pub fn dock_menu(&self) -> Vec<String> {
992        self.state.borrow().dock_menu.clone()
993    }
994
995    /// Every `apply_window` change so far, oldest first, keyed by content-container handle.
996    #[must_use]
997    pub fn window_changes(&self) -> Vec<(u64, day_spec::WindowChange)> {
998        self.state.borrow().window_changes.clone()
999    }
1000
1001    /// The status items as last applied.
1002    #[must_use]
1003    pub fn status_items(&self) -> Vec<day_spec::StatusItemSpec> {
1004        self.state.borrow().status_items.clone()
1005    }
1006
1007    /// Whether day-core last asked the platform to keep running with no window.
1008    #[must_use]
1009    pub fn keep_running(&self) -> bool {
1010        self.state.borrow().keep_running
1011    }
1012
1013    /// Whether the widget at `handle` is a window drag region.
1014    #[must_use]
1015    pub fn is_drag_region(&self, handle: u64) -> bool {
1016        self.state.borrow().drag_regions.contains(&handle)
1017    }
1018
1019    /// Make the mock platform record `WindowChange::State` requests without completing them.
1020    pub fn set_decline_window_states(&self, v: bool) {
1021        self.state.borrow_mut().decline_window_states = v;
1022    }
1023
1024    /// Model the user flipping the system's reduce-motion setting (docs/accessibility.md). The
1025    /// test then calls `day_core::note_motion_changed()`, which is the backend observer's job.
1026    pub fn set_reduce_motion(&self, v: bool) {
1027        self.state.borrow_mut().reduce_motion = v;
1028    }
1029
1030    /// Make a secure flip rebuild the text field under a new handle, the harness for the
1031    /// toolkits whose secure field is its own native class (docs/textfield.md).
1032    pub fn set_secure_class_swap(&self, v: bool) {
1033        self.state.borrow_mut().secure_class_swap = v;
1034    }
1035
1036    /// Make `open_window` answer `Unsupported`, the cover-fallback test harness.
1037    pub fn set_no_multi_window(&self, v: bool) {
1038        self.state.borrow_mut().no_multi_window = v;
1039    }
1040
1041    /// Make `Cap::NavSplit` answer `Native`, the harness for a nav host that presents as split
1042    /// panes and re-presents on a size-class change (docs/size-classes.md). Unlike the window
1043    /// toggles this is read during the build, so set it before launching.
1044    pub fn set_nav_split(&self, v: bool) {
1045        self.state.borrow_mut().nav_split = v;
1046    }
1047
1048    /// Retain native navigation despite a reordering declaration, independently of lists.
1049    pub fn set_no_nav_reorder(&self, v: bool) {
1050        self.state.borrow_mut().no_nav_reorder = v;
1051    }
1052
1053    /// Answer `Cap::NavReorder` as `Native`: the sidebar drags its own rows.
1054    pub fn set_native_nav_reorder(&self, v: bool) {
1055        self.state.borrow_mut().native_nav_reorder = v;
1056    }
1057
1058    /// Make `Cap::NavTabs` answer `Unsupported`, modeling a toolkit without tab chrome.
1059    pub fn set_no_nav_tabs(&self, v: bool) {
1060        self.state.borrow_mut().no_nav_tabs = v;
1061    }
1062
1063    /// Model a desktop toolkit: `Cap::NavTabs` stays on (a pinned tab bar still draws) but
1064    /// `Cap::NavTabsAdaptive` answers `Unsupported`, so an `Automatic` nav host collapses a
1065    /// narrow window to a stack rather than growing a tab bar (docs/navigation.md). Read during
1066    /// the build, so set it before launching.
1067    pub fn set_desktop_idiom(&self, v: bool) {
1068        self.state.borrow_mut().desktop_idiom = v;
1069    }
1070
1071    /// What `Cap::NavContentList` answers (docs/navigation.md): the content-list pane
1072    /// harness. `Native` = persistent pane, `Emulated` = merges into the collapsed stack,
1073    /// `Unsupported` (the default) = the nav host composes. Read during the build.
1074    pub fn set_nav_content_list(&self, v: day_spec::Support) {
1075        self.state.borrow_mut().nav_content_list = v;
1076    }
1077
1078    /// Make `open_window` answer `Pending`, the async-completion test harness. Finish an
1079    /// open with [`Self::complete_window`] + `day_core::finish_window_open`.
1080    pub fn set_pending_windows(&self, v: bool) {
1081        self.state.borrow_mut().pending_windows = v;
1082    }
1083
1084    /// Materialize the parked `Pending` open for `node`: registers the content-container
1085    /// widget + window record (as the native side finishing creation would) and returns
1086    /// the raw handle to pass to `day_core::finish_window_open`. `None` = no such pending
1087    /// open.
1088    #[must_use]
1089    pub fn complete_window(&self, node: NodeId, size: Size) -> Option<day_spec::RawHandle> {
1090        let mut s = self.state.borrow_mut();
1091        let i = s.pending_opens.iter().position(|(n, _, _)| *n == node)?;
1092        let (node, title, kind) = s.pending_opens.remove(i);
1093        s.next += 1;
1094        let h = s.next;
1095        s.widgets.insert(
1096            h,
1097            MockWidget {
1098                kind: kinds::CONTAINER,
1099                node: node.0,
1100                enabled: true,
1101                ..Default::default()
1102            },
1103        );
1104        s.windows.push(MockWindow {
1105            handle: h,
1106            node,
1107            title,
1108            size,
1109            kind,
1110            tabbing: day_spec::WindowTabbing::Automatic,
1111            open: true,
1112            focused: false,
1113            fit_size: None,
1114        });
1115        s.log(format!("window_ready #{h} {}", fmt_size(size)));
1116        Some(h as day_spec::RawHandle)
1117    }
1118
1119    /// Resize a secondary window (as a native drag would): updates the record and reports
1120    /// `WindowResized` to the window's root.
1121    pub fn resize_window(&self, node: NodeId, size: Size) {
1122        {
1123            let mut s = self.state.borrow_mut();
1124            if let Some(w) = s.windows.iter_mut().find(|w| w.node == node) {
1125                w.size = size;
1126            }
1127        }
1128        self.emit(node, Event::WindowResized(size));
1129    }
1130
1131    /// Model a native dismissal animation: retain the window until the test confirms it
1132    /// with [`Self::close_window_natively`].
1133    pub fn set_defer_window_close(&self, defer: bool) {
1134        self.state.borrow_mut().defer_window_close = defer;
1135    }
1136
1137    /// Close a secondary window from the native side (the title-bar path): marks it closed
1138    /// and reports `WindowClosed` to the window's root.
1139    pub fn close_window_natively(&self, node: NodeId) {
1140        {
1141            let mut s = self.state.borrow_mut();
1142            if let Some(w) = s.windows.iter_mut().find(|w| w.node == node) {
1143                w.open = false;
1144            }
1145        }
1146        self.emit(node, Event::WindowClosed);
1147    }
1148
1149    /// The current op-log length; pair with [`Self::log_since`] to scope assertions.
1150    #[must_use]
1151    pub fn log_len(&self) -> usize {
1152        self.state.borrow().log.len()
1153    }
1154
1155    /// The op-log entries recorded after `mark` (from [`Self::log_len`]).
1156    #[must_use]
1157    pub fn log_since(&self, mark: usize) -> Vec<String> {
1158        self.state.borrow().log[mark..].to_vec()
1159    }
1160}
1161
1162fn fmt_size(s: Size) -> String {
1163    format!("{}x{}", s.width, s.height)
1164}
1165fn fmt_rect(r: Rect) -> String {
1166    format!(
1167        "({},{} {}x{})",
1168        r.origin.x, r.origin.y, r.size.width, r.size.height
1169    )
1170}
1171
1172/// Deterministic text metrics: 8pt per char, 16pt line height, greedy wrap.
1173/// The mock's line box: one line of text is this tall, whatever it says.
1174pub const MOCK_LINE_H: f64 = 16.0;
1175
1176/// The synthetic pixel size every mock decode reports (docs/images.md): deterministic, so a
1177/// test can predict the frame an `image(bytes)` measures to, exactly like the synthetic text
1178/// metrics above.
1179pub const MOCK_IMAGE_W: f64 = 64.0;
1180pub const MOCK_IMAGE_H: f64 = 48.0;
1181/// What the mock claims it can encode: the two formats every real backend also manages, so a
1182/// test that asserts a WebP refusal exercises the same path a desktop backend takes.
1183pub const MOCK_ENCODE_FORMATS: [day_spec::ImageFormat; 2] =
1184    [day_spec::ImageFormat::Png, day_spec::ImageFormat::Jpeg];
1185
1186/// How the probe spells an image source in the log and in `WidgetProbe::text`: the name for a
1187/// staged asset, `bytes:<len>` for a buffer, `bitmap:<id>` for a shared decode.
1188fn describe_image_source(source: &day_spec::ImageSource) -> String {
1189    match source {
1190        day_spec::ImageSource::Named(name) => name.clone(),
1191        day_spec::ImageSource::Bytes(b) => format!("bytes:{}", b.len()),
1192        day_spec::ImageSource::Decoded(id) => format!("bitmap:{}", id.0),
1193    }
1194}
1195
1196pub fn text_size(text: &str, proposal: Proposal, wraps: bool, scale: f64) -> Size {
1197    let needed = 8.0 * scale * text.chars().count() as f64;
1198    let line = MOCK_LINE_H * scale;
1199    match (proposal.width, wraps) {
1200        (Some(w), true) if needed > w && w > 0.0 => {
1201            let lines = (needed / w).ceil();
1202            Size::new(w, line * lines)
1203        }
1204        _ => Size::new(needed, line),
1205    }
1206}
1207
1208/// A semantic style's size against `Body`, the mock's 8 × 16 cell: Apple's default point sizes
1209/// (Body 17), so a large-title row measures taller than a caption row the way it does natively.
1210/// `Body` and `Headline` stay exactly 1.0, the size every older mock expectation assumes.
1211#[must_use]
1212pub fn font_scale(style: Font) -> f64 {
1213    let points = match style {
1214        Font::LargeTitle => 34.0,
1215        Font::Title => 28.0,
1216        Font::Title2 => 22.0,
1217        Font::Title3 => 20.0,
1218        Font::Headline | Font::Body => 17.0,
1219        Font::Subheadline => 15.0,
1220        Font::Callout => 16.0,
1221        Font::Footnote => 13.0,
1222        Font::Caption => 12.0,
1223        Font::Caption2 => 11.0,
1224        Font::System(pt) | Font::Custom(_, pt) => pt,
1225    };
1226    points / 17.0
1227}
1228
1229impl MockToolkit {
1230    /// Raise a completion through the installed sink (docs/images.md).
1231    ///
1232    /// Clones the `Rc` rather than taking the sink, so a completion raised while another event
1233    /// is being dispatched still reaches day-core. A missing sink is logged, not swallowed: a
1234    /// dropped completion leaves a future parked forever, which reads as a hang rather than a
1235    /// failure.
1236    fn raise(&self, event: Event) {
1237        let sink = self.state.borrow().sink.clone();
1238        match sink {
1239            Some(sink) => sink(NodeId(0), event),
1240            None => self
1241                .state
1242                .borrow_mut()
1243                .log(format!("dropped {event:?}: no event sink installed")),
1244        }
1245    }
1246}
1247
1248impl Toolkit for MockToolkit {
1249    fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
1250        let colors = self.state.borrow().system_colors;
1251        colors.map_or_else(
1252            || role.fallback(self.dark_mode()),
1253            |colors| colors[role as usize],
1254        )
1255    }
1256
1257    type Handle = MockHandle;
1258
1259    #[expect(
1260        clippy::match_same_arms,
1261        reason = "each capability keeps its own arm, with a comment saying why the mock answers it"
1262    )]
1263    fn capability(&self, cap: Cap) -> Support {
1264        match cap {
1265            Cap::Snapshot => Support::Native,
1266            // With native behavior on (the conformance harness), the mock stands in for a
1267            // toolkit with a toolbar and dialogs: it records the toolbar edits and the
1268            // presentations, and answers `dismiss`. Off, unit tests keep the toolbar-less
1269            // placement they assert (an `Automatic` search stays inline).
1270            Cap::Toolbar | Cap::Dialogs if VIEWPORT_ROWS.with(std::cell::Cell::get) > 0 => {
1271                Support::Native
1272            }
1273            // Native-behavior mode binds its bounded viewport pool to new rows on scroll.
1274            Cap::ListRecycling if VIEWPORT_ROWS.with(std::cell::Cell::get) > 0 => Support::Native,
1275            // Records every toolbar edit and patch, search item included (probe-visible). The
1276            // mock still has no `Cap::Toolbar`, so an `Automatic` search stays inline.
1277            Cap::ToolbarSearch => {
1278                if self.state.borrow().no_toolbar_search {
1279                    Support::Unsupported
1280                } else {
1281                    Support::Native
1282                }
1283            }
1284            // The mock decodes by reading magic numbers and encodes a matching signature
1285            // (docs/images.md): no pixels, but the whole request → completion → release path a
1286            // test needs. `Cap::ImageProperties` stays Unsupported in the default arm: the
1287            // mock reads no metadata, and pretending otherwise would let a test pass against a
1288            // capability no backend answers this way.
1289            Cap::ImageDecode | Cap::ImageEncode => Support::Native,
1290            // A rendered bitmap is a synthetic entry in the same table a decode fills, so app
1291            // logic around export (menus, save flows) runs headless. PDF stays Unsupported, the
1292            // answer three real toolkits give, so the disabled path is the one a test sees.
1293            Cap::CanvasBitmap => Support::Native,
1294            // Records the shape per widget (probe-visible), so a test can assert it.
1295            Cap::Cursor => Support::Native,
1296            // Records every window change and Dock menu and completes state requests the way a
1297            // platform reports them (`apply_window` below), so the two-way state signal and the
1298            // menu lowering are testable headless.
1299            // OS window tabs follow the test's own switch (`MockState::native_window_tabs`),
1300            // so a case that `requires` them is skipped unless a test turned them on.
1301            Cap::ListItem => {
1302                if self.state.borrow().native_list_items {
1303                    Support::Native
1304                } else {
1305                    Support::Unsupported
1306                }
1307            }
1308            Cap::WindowTabbing => {
1309                if self.state.borrow().native_window_tabs {
1310                    Support::Native
1311                } else {
1312                    Support::Unsupported
1313                }
1314            }
1315            Cap::WindowStates
1316            | Cap::WindowFullscreen
1317            | Cap::ContentProtection
1318            | Cap::DockMenu
1319            | Cap::DragRegion
1320            | Cap::StatusItem
1321            | Cap::AppProgress
1322            | Cap::DockVisibility
1323            | Cap::Monitors
1324            | Cap::DynamicShortcuts
1325            | Cap::WindowGeometry
1326            | Cap::WindowPosition
1327            | Cap::WindowLevel
1328            | Cap::WindowAppearance
1329            | Cap::RequestAttention => Support::Native,
1330            // A fixed two-family list (`font_families` below), composed, not read.
1331            Cap::FontList => Support::Emulated,
1332            Cap::Announce => Support::Native,
1333            Cap::ReduceMotion => Support::Native,
1334            // The mock answers `first_baseline` from its synthetic metrics (see below).
1335            Cap::BaselineAlignment => Support::Native,
1336            // The mock records the text-area attributes (probe-visible), so it "supports" all three.
1337            Cap::TextEditable | Cap::TextSelectable | Cap::TextSpellCheck => Support::Native,
1338            // Styled runs land in `WidgetProbe::runs`, which is what a test asserts on
1339            // (docs/text-runs.md). Activating a link is not modeled (nothing in the mock
1340            // hit-tests text), so `Cap::TextLinks` stays Unsupported in the default arm; a test
1341            // that wants the rail emits `Event::LinkActivated` itself.
1342            Cap::TextRuns => Support::Native,
1343            // The mock "runs" backend-executed animation by recording the intent (probe-visible).
1344            Cap::Animation => Support::Native,
1345            // Covers "present" by recording the patch (probe-visible); tests emit the
1346            // FrameChanged size report themselves, as the native surface would.
1347            Cap::Cover => Support::Native,
1348            // The status bar "hides" by recording the duty call (probe-visible).
1349            Cap::StatusBarHidden => Support::Native,
1350            // The probe drives the whole reorder sequence, guard then commit (`list_can_move`/
1351            // `list_move`).
1352            Cap::ListReorder => Support::Native,
1353            Cap::NavReorder => {
1354                let s = self.state.borrow();
1355                if s.no_nav_reorder {
1356                    Support::Unsupported
1357                } else if s.native_nav_reorder {
1358                    Support::Native
1359                } else {
1360                    Support::Emulated
1361                }
1362            }
1363            // The probe drives every tree duty (`tree_children`/`tree_bind`/`tree_move`).
1364            Cap::Tree | Cap::TreeSections if self.state.borrow().emulated_trees => {
1365                Support::Emulated
1366            }
1367            Cap::Tree | Cap::TreeSections | Cap::TreeMove => Support::Native,
1368            // Off by default: the mock models a phone, so a nav host stacks unless a test opts in.
1369            // A mock that can split can also re-present: it records the patch, which is exactly
1370            // what the morph tests assert against.
1371            Cap::NavSplit | Cap::NavRepresent => {
1372                if self.state.borrow().nav_split {
1373                    Support::Native
1374                } else {
1375                    Support::Unsupported
1376                }
1377            }
1378            // Unsupported by default (the composed path); a test opts into the pane shapes
1379            // (docs/navigation.md) with [`MockProbe::set_nav_content_list`].
1380            Cap::NavContentList => self.state.borrow().nav_content_list,
1381            // On by default (docs/navigation.md): the mock models a phone, and a phone has a tab
1382            // bar. A test opts out to exercise the degradation path, where `Automatic` falls back
1383            // to the sidebar resolver.
1384            Cap::NavTabs => {
1385                if self.state.borrow().no_nav_tabs {
1386                    Support::Unsupported
1387                } else {
1388                    Support::Native
1389                }
1390            }
1391            // Separate from `NavTabs`: a desktop draws a pinned tab bar but never adapts into one.
1392            Cap::NavTabsAdaptive => {
1393                let st = self.state.borrow();
1394                if st.no_nav_tabs || st.desktop_idiom {
1395                    Support::Unsupported
1396                } else {
1397                    Support::Native
1398                }
1399            }
1400            // Real (recorded) windows unless the test opted into the cover-fallback tier.
1401            Cap::MultiWindow => {
1402                if self.state.borrow().no_multi_window {
1403                    Support::Unsupported
1404                } else {
1405                    Support::Native
1406                }
1407            }
1408            _ => Support::Unsupported,
1409        }
1410    }
1411
1412    fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> MockHandle {
1413        let mut s = self.state.borrow_mut();
1414        s.next += 1;
1415        let h = s.next;
1416        let mut w = MockWidget {
1417            kind,
1418            node: id.0,
1419            enabled: true,
1420            ..Default::default()
1421        };
1422        let mut detail = String::new();
1423        if let Some(p) = props.downcast_ref::<CoverProps>() {
1424            w.half = p.half;
1425            detail = format!(" sheet={} half={}", p.sheet, p.half);
1426        } else if let Some(p) = props.downcast_ref::<ListItemProps>() {
1427            w.text.clone_from(&p.title);
1428            w.flag = p.checked;
1429            detail = format!(
1430                " title={:?} subtitle={:?} detail={:?} icon={:?} checked={}",
1431                p.title, p.subtitle, p.detail, p.icon, p.checked
1432            );
1433        } else if let Some(p) = props.downcast_ref::<LabelProps>() {
1434            w.text.clone_from(&p.text);
1435            w.flag = p.wraps;
1436            w.font = Some(p.font);
1437            w.runs.clone_from(&p.runs);
1438            detail = format!(" text={:?}", p.text);
1439        } else if let Some(p) = props.downcast_ref::<ButtonProps>() {
1440            w.text.clone_from(&p.title);
1441            w.enabled = p.enabled;
1442            w.selected = p.selected;
1443            detail = format!(" title={:?}", p.title);
1444        } else if let Some(p) = props.downcast_ref::<ToggleProps>() {
1445            w.flag = p.on;
1446            w.enabled = p.enabled;
1447        } else if let Some(p) = props.downcast_ref::<SliderProps>() {
1448            w.value = p.value;
1449            w.enabled = p.enabled;
1450        } else if let Some(p) = props.downcast_ref::<TextFieldProps>() {
1451            w.text.clone_from(&p.text);
1452            w.placeholder.clone_from(&p.placeholder);
1453            w.enabled = p.enabled;
1454        } else if let Some(p) = props.downcast_ref::<CanvasProps>() {
1455            w.ops.clone_from(&p.ops);
1456        } else if let Some(p) = props.downcast_ref::<ContainerProps>() {
1457            w.background = p.background;
1458            w.corner_radius = p.corner_radius;
1459            w.clips = p.clips;
1460            w.surface_role = p.role;
1461            if p.background.is_some() || p.corner_radius > 0.0 || p.clips {
1462                detail = format!(
1463                    " bg={:?} radius={} clips={}",
1464                    p.background, p.corner_radius, p.clips
1465                );
1466            }
1467        } else if let Some(p) = props.downcast_ref::<ImageProps>() {
1468            // The probe records which pixels were asked for, so a test can assert that a name
1469            // resolved, that bytes arrived, or that two nodes share one decode (docs/images.md).
1470            w.text = describe_image_source(&p.source);
1471            // Image probes expose template mode for artwork/glyph regression tests.
1472            w.flag = p.template;
1473            detail = format!(" source={}", w.text);
1474        } else if let Some(p) = props.downcast_ref::<ProgressProps>() {
1475            // `flag` records indeterminate-ness; `value` the determinate fraction.
1476            w.flag = p.value.is_none();
1477            w.value = p.value.unwrap_or(0.0);
1478            detail = format!(" value={:?}", p.value);
1479        } else if let Some(p) = props.downcast_ref::<NavProps>() {
1480            w.text.clone_from(&p.title);
1481            w.flag = p.presentation.is_split();
1482            w.presentation = Some(p.presentation);
1483            // The content-list pane's realize-time state, so a test can see the shape the host
1484            // was built with; the pane's initial visibility is settled here, not by a patch.
1485            detail = match p.list_width {
1486                Some(w) => format!(
1487                    " title={:?} presentation={:?} list_width={w} list_visible={}",
1488                    p.title, p.presentation, p.list_visible
1489                ),
1490                None => format!(" title={:?} presentation={:?}", p.title, p.presentation),
1491            };
1492        } else if let Some(p) = props.downcast_ref::<NavPageProps>() {
1493            w.text.clone_from(&p.title);
1494            // The page's pane, not the presentation drawing it: a nav host's list page reads
1495            // `sidebar` whether the host is split or stacked (docs/size-classes.md).
1496            w.flag = p.pane == day_spec::props::Pane::Sidebar;
1497            detail = format!(" title={:?} pane={:?}", p.title, p.pane);
1498        } else if let Some(p) = props.downcast_ref::<NavMenuProps>() {
1499            w.text = p.items.join("|");
1500            w.value = p.selected.map_or(-1.0, |i| i as f64);
1501            detail = format!(
1502                " items={:?} selected={:?} movable={:?}",
1503                p.items, p.selected, p.movable
1504            );
1505            // Only a regrouping sidebar carries these, so other logs read as they always have.
1506            if p.regroup {
1507                let _ = write!(detail, " regroup sorted={:?}", p.sorted);
1508            }
1509        } else if let Some(p) = props.downcast_ref::<PickerProps>() {
1510            w.text = p.options.join("|");
1511            w.value = p.selected as f64;
1512            w.enabled = p.enabled;
1513            detail = format!(" options={:?} selected={}", p.options, p.selected);
1514        } else if let Some(p) = props.downcast_ref::<TextAreaProps>() {
1515            w.text.clone_from(&p.text);
1516            w.placeholder.clone_from(&p.placeholder);
1517            w.editable = p.editable;
1518            w.selectable = p.selectable;
1519            w.spellcheck = p.spellcheck;
1520            detail = format!(
1521                " lines={}..{} editable={} selectable={} spellcheck={}",
1522                p.min_lines, p.max_lines, p.editable, p.selectable, p.spellcheck
1523            );
1524        }
1525        s.log(format!("realize {kind} #{h}{detail}"));
1526        s.widgets.insert(h, w);
1527        MockHandle(h)
1528    }
1529
1530    fn update(
1531        &mut self,
1532        h: &MockHandle,
1533        kind: PieceKind,
1534        patch: &dyn Any,
1535        anim: Option<&AnimSpec>,
1536    ) {
1537        let mut s = self.state.borrow_mut();
1538        // Ask the installed describers first; the borrow has to end before `widgets` is taken
1539        // mutably below.
1540        let described = s.describers.iter().find_map(|d| d(patch));
1541        let detail;
1542        // A cover shown or hidden, for the native-behavior mode to report (see `NATIVE_EVENTS`).
1543        // (node, shown, half)
1544        let mut cover_shown: Option<(u64, bool, bool)> = None;
1545        {
1546            let w = s.widgets.get_mut(&h.0).expect("update on unknown widget");
1547            if anim.is_some() {
1548                w.last_anim = anim.copied();
1549            }
1550            detail = if let Some(p) = patch.downcast_ref::<ImagePatch>() {
1551                match p {
1552                    // The probe's `text` is which pixels the view draws, so a test can assert a
1553                    // source swap landed in the same view (docs/images.md).
1554                    ImagePatch::Source(s) => {
1555                        w.text = describe_image_source(s);
1556                        format!("source={}", w.text)
1557                    }
1558                    ImagePatch::Tint(c) => format!("tint={c:?}"),
1559                }
1560            } else if let Some(p) = patch.downcast_ref::<LabelPatch>() {
1561                match p {
1562                    LabelPatch::Text(t) => {
1563                        w.text.clone_from(t);
1564                        format!("text={t:?}")
1565                    }
1566                    LabelPatch::Color(_) => "color".into(),
1567                    LabelPatch::Font(f) => {
1568                        w.font = Some(*f);
1569                        "font".into()
1570                    }
1571                    LabelPatch::Runs(text, runs) => {
1572                        w.text.clone_from(text);
1573                        w.runs.clone_from(runs);
1574                        format!("runs={}", runs.len())
1575                    }
1576                }
1577            } else if let Some(p) = patch.downcast_ref::<ButtonPatch>() {
1578                match p {
1579                    ButtonPatch::Content(c) => {
1580                        w.text.clone_from(&c.title);
1581                        format!("content={c:?}")
1582                    }
1583                    ButtonPatch::Title(t) => {
1584                        w.text.clone_from(t);
1585                        format!("title={t:?}")
1586                    }
1587                    ButtonPatch::Enabled(e) => {
1588                        w.enabled = *e;
1589                        format!("enabled={e}")
1590                    }
1591                    ButtonPatch::Selected(on) => {
1592                        w.selected = *on;
1593                        format!("selected={on}")
1594                    }
1595                    // Recorded so a walkthrough can see a reactive tint change, but the mock
1596                    // has no pixels to apply it to.
1597                    ButtonPatch::Style(s) => format!("style={s:?}"),
1598                }
1599            } else if let Some(p) = patch.downcast_ref::<TogglePatch>() {
1600                match p {
1601                    TogglePatch::On(v) => {
1602                        w.flag = *v;
1603                        format!("on={v}")
1604                    }
1605                    TogglePatch::Enabled(e) => {
1606                        w.enabled = *e;
1607                        format!("enabled={e}")
1608                    }
1609                }
1610            } else if let Some(p) = patch.downcast_ref::<SliderPatch>() {
1611                match p {
1612                    SliderPatch::Value(v) => {
1613                        w.value = *v;
1614                        format!("value={v}")
1615                    }
1616                    SliderPatch::Enabled(e) => {
1617                        w.enabled = *e;
1618                        format!("enabled={e}")
1619                    }
1620                }
1621            } else if let Some(p) = patch.downcast_ref::<TextFieldPatch>() {
1622                match p {
1623                    TextFieldPatch::Text { text, from_native } => {
1624                        if !*from_native {
1625                            w.text.clone_from(text);
1626                        }
1627                        format!("text={text:?} from_native={from_native}")
1628                    }
1629                    TextFieldPatch::Placeholder(t) => {
1630                        w.placeholder.clone_from(t);
1631                        format!("placeholder={t:?}")
1632                    }
1633                    TextFieldPatch::Enabled(e) => {
1634                        w.enabled = *e;
1635                        format!("enabled={e}")
1636                    }
1637                    TextFieldPatch::Select(r) => {
1638                        let r = r.clamped(&w.text);
1639                        w.selection = Some(r);
1640                        format!("select={}..{}", r.start, r.end)
1641                    }
1642                }
1643            } else if let Some(p) = patch.downcast_ref::<CanvasProps>() {
1644                w.ops.clone_from(&p.ops);
1645                format!("canvas ops={}", w.ops.len())
1646            } else if let Some(ProgressPatch::Value(v)) = patch.downcast_ref::<ProgressPatch>() {
1647                w.flag = v.is_none();
1648                w.value = v.unwrap_or(0.0);
1649                format!("value={v:?}")
1650            } else if let Some(pp) = patch.downcast_ref::<PickerPatch>() {
1651                let Some(w) = s.widgets.get_mut(&h.0) else {
1652                    return;
1653                };
1654                match pp {
1655                    PickerPatch::Selected(i) => {
1656                        w.value = *i as f64;
1657                        format!("picker.selected {i}")
1658                    }
1659                    PickerPatch::Options(opts) => {
1660                        w.text = opts.join("|");
1661                        format!("picker.options {opts:?}")
1662                    }
1663                    PickerPatch::Enabled(e) => {
1664                        w.enabled = *e;
1665                        format!("picker.enabled {e}")
1666                    }
1667                }
1668            } else if let Some(tp) = patch.downcast_ref::<TextAreaPatch>() {
1669                if let Some(w) = s.widgets.get_mut(&h.0) {
1670                    match tp {
1671                        TextAreaPatch::SetText(t) => w.text.clone_from(t),
1672                        TextAreaPatch::SetEditable(v) => w.editable = *v,
1673                        TextAreaPatch::SetSelectable(v) => w.selectable = *v,
1674                        TextAreaPatch::SetSpellCheck(v) => w.spellcheck = *v,
1675                    }
1676                }
1677                format!("textarea.patch {tp:?}")
1678            } else if let Some(p) = patch.downcast_ref::<ListItemPatch>() {
1679                match p {
1680                    ListItemPatch::Title(t) => w.text.clone_from(t),
1681                    ListItemPatch::Checked(on) => w.flag = *on,
1682                    _ => {}
1683                }
1684                format!("list_item {p:?}")
1685            } else if let Some(p) = patch.downcast_ref::<NavMenuPatch>() {
1686                match p {
1687                    NavMenuPatch::IconProgress(values) => format!("menu icon_progress={values:?}"),
1688                    NavMenuPatch::Selected(sel) => {
1689                        w.value = sel.map_or(-1.0, |i| i as f64);
1690                        format!("menu selected={sel:?}")
1691                    }
1692                    // Data-driven rows: `text` mirrors the joined labels for tests to assert.
1693                    NavMenuPatch::Items {
1694                        items,
1695                        selected,
1696                        badges,
1697                        rows_changed,
1698                        movable,
1699                        sorted,
1700                        ..
1701                    } => {
1702                        w.text = items.join("|");
1703                        w.value = selected.map_or(-1.0, |i| i as f64);
1704                        let mut line = format!(
1705                            "menu items={items:?} selected={selected:?} badges={badges:?} \
1706                             rows_changed={rows_changed:?} movable={movable:?}"
1707                        );
1708                        if !sorted.is_empty() {
1709                            let _ = write!(line, " sorted={sorted:?}");
1710                        }
1711                        line
1712                    }
1713                }
1714            } else if let Some(p) = patch.downcast_ref::<NavPatch>() {
1715                match p {
1716                    NavPatch::Pushed { title, .. } => {
1717                        w.text.clone_from(title);
1718                        w.nav_depth += 1;
1719                        format!("nav pushed title={title:?}")
1720                    }
1721                    NavPatch::Popped => {
1722                        w.nav_depth = w.nav_depth.saturating_sub(1);
1723                        "nav popped".into()
1724                    }
1725                    NavPatch::Title(t) => {
1726                        w.text.clone_from(t);
1727                        format!("nav title={t:?}")
1728                    }
1729                    // Probe-visible: tests assert the armed flag round-trips.
1730                    NavPatch::GuardTop(on) => {
1731                        w.flag = *on;
1732                        w.nav_guarded = *on;
1733                        format!("nav guard={on}")
1734                    }
1735                    // The host's presentation after a size-class change. `flag` tracks it the
1736                    // same way the initial `NavProps` did, so a walkthrough asserting the morph
1737                    // reads one field either side of it; `presentation` carries which of the
1738                    // four it actually is, which `flag` cannot say.
1739                    NavPatch::Presentation(p) => {
1740                        w.flag = p.is_split();
1741                        w.presentation = Some(*p);
1742                        format!("nav presentation={p:?}")
1743                    }
1744                    // Resident-page switch (docs/navigation.md). A stacked host never receives
1745                    // this (it gets `Pushed`/`Popped` instead), so recording it unconditionally
1746                    // is also what lets a test prove the pieces layer sent the right one.
1747                    NavPatch::Select(i) => {
1748                        w.selected_page = Some(*i);
1749                        w.value = *i as f64;
1750                        format!("nav select={i}")
1751                    }
1752                    // Content-list pane visibility / stack membership (docs/navigation.md).
1753                    // Logged only: mock answers `Cap::NavContentList` Unsupported, so the pieces
1754                    // layer composes and these arrive solely in tests that force the cap.
1755                    NavPatch::ListVisible(v) => format!("nav list visible={v}"),
1756                    NavPatch::Reorder(order) => format!("nav reorder {order:?}"),
1757                    NavPatch::ListInStack(v) => format!("nav list in-stack={v}"),
1758                }
1759            } else if let Some(p) = patch.downcast_ref::<CoverPatch>() {
1760                // `flag` records presented-ness (probe-visible). Tests emit the FrameChanged
1761                // size report and the `CoverHidden` event, as the native surface would.
1762                match p {
1763                    CoverPatch::Present {
1764                        background,
1765                        dismiss_disabled,
1766                    } => {
1767                        w.flag = true;
1768                        w.background = *background;
1769                        cover_shown = Some((w.node, true, w.half));
1770                        format!(
1771                            "cover present bg={background:?} dismiss_disabled={dismiss_disabled}"
1772                        )
1773                    }
1774                    CoverPatch::DismissDisabled(d) => format!("cover dismiss_disabled={d}"),
1775                    CoverPatch::Dismiss => {
1776                        w.flag = false;
1777                        cover_shown = Some((w.node, false, w.half));
1778                        "cover dismiss".into()
1779                    }
1780                }
1781            } else if let Some(ContainerPatch::Background(c)) =
1782                patch.downcast_ref::<ContainerPatch>()
1783            {
1784                w.background = *c;
1785                format!("bg={c:?}")
1786            } else if let Some(p) = patch.downcast_ref::<ListPatch>() {
1787                match p {
1788                    ListPatch::Reload => {
1789                        viewport_touch(h.0, |_| {});
1790                        "list reload".into()
1791                    }
1792                    ListPatch::Splice(deltas) => {
1793                        viewport_touch(h.0, |_| {});
1794                        format!("list splice {deltas:?}")
1795                    }
1796                    ListPatch::RowSizeInvalidated { cell, height } => {
1797                        CELL_HEIGHTS.with(|h| h.borrow_mut().insert(*cell as u64, *height));
1798                        format!("list row-size-invalidated {height}")
1799                    }
1800                    ListPatch::ScrollToEnd => {
1801                        // Record that the host was asked to follow its last row (probe-visible).
1802                        w.flag = true;
1803                        viewport_touch(h.0, |p| p.to_end = true);
1804                        "list scroll-to-end".into()
1805                    }
1806                    ListPatch::ScrollToRow(row) => {
1807                        let rows = VIEWPORT_ROWS.with(std::cell::Cell::get);
1808                        viewport_touch(h.0, |p| p.start = row.saturating_sub(rows / 2));
1809                        format!("list scroll-to-row {row}")
1810                    }
1811                    ListPatch::Selected(rows) => format!("list selected {rows:?}"),
1812                    ListPatch::Editing(on) => format!("list editing {on}"),
1813                }
1814            } else if let Some(p) = patch.downcast_ref::<TreePatch>() {
1815                match p {
1816                    TreePatch::Reload => {
1817                        viewport_touch(h.0, |_| {});
1818                        "tree reload".into()
1819                    }
1820                    TreePatch::Expand(tok, on) => {
1821                        let (tok, on) = (*tok, *on);
1822                        viewport_touch(h.0, |p| {
1823                            if on {
1824                                p.expanded.insert(tok);
1825                            } else {
1826                                p.expanded.remove(&tok);
1827                            }
1828                        });
1829                        format!("tree expand {tok} {on}")
1830                    }
1831                    TreePatch::Selected(toks) => format!("tree selected {toks:?}"),
1832                    TreePatch::Reveal(tok) => format!("tree reveal {tok}"),
1833                }
1834            } else {
1835                described.unwrap_or_else(|| "?".into())
1836            };
1837        }
1838        s.log(format!("update {kind} #{} {detail}", h.0));
1839        // What a native cover reports by itself: the size it gave the content, and that the
1840        // hide transition finished.
1841        if let (Some((node, shown, half)), Some(sink)) = (cover_shown, s.sink.clone())
1842            && VIEWPORT_ROWS.with(std::cell::Cell::get) > 0
1843        {
1844            let event = if shown {
1845                // A half sheet is the bottom half of the window (docs/cover.md).
1846                let mut size = MOCK_WINDOW.with(std::cell::Cell::get);
1847                if half {
1848                    size.height = (size.height * 0.5).floor();
1849                }
1850                Event::FrameChanged(size)
1851            } else {
1852                Event::CoverHidden
1853            };
1854            NATIVE_EVENTS.with(|q| q.borrow_mut().push((sink, NodeId(node), event)));
1855        }
1856    }
1857
1858    fn release(&mut self, h: MockHandle) {
1859        VIEWPORTS.with(|v| v.borrow_mut().remove(&h.0));
1860        let mut s = self.state.borrow_mut();
1861        s.widgets.remove(&h.0);
1862        s.context_menu_providers.remove(&h.0);
1863        s.button_menus.remove(&h.0);
1864        s.log(format!("release #{}", h.0));
1865    }
1866
1867    fn insert(&mut self, parent: &MockHandle, child: &MockHandle, index: usize) {
1868        let mut s = self.state.borrow_mut();
1869        {
1870            let p = s
1871                .widgets
1872                .get_mut(&parent.0)
1873                .expect("insert into unknown parent");
1874            let idx = index.min(p.children.len());
1875            p.children.insert(idx, child.0);
1876        }
1877        s.log(format!(
1878            "insert #{} into #{} at {}",
1879            child.0, parent.0, index
1880        ));
1881    }
1882
1883    fn remove(&mut self, parent: &MockHandle, child: &MockHandle) {
1884        let mut s = self.state.borrow_mut();
1885        {
1886            let p = s
1887                .widgets
1888                .get_mut(&parent.0)
1889                .expect("remove from unknown parent");
1890            p.children.retain(|&c| c != child.0);
1891        }
1892        s.log(format!("remove #{} from #{}", child.0, parent.0));
1893    }
1894
1895    fn move_child(&mut self, parent: &MockHandle, child: &MockHandle, to: usize) {
1896        let mut s = self.state.borrow_mut();
1897        {
1898            let p = s
1899                .widgets
1900                .get_mut(&parent.0)
1901                .expect("move in unknown parent");
1902            p.children.retain(|&c| c != child.0);
1903            let idx = to.min(p.children.len());
1904            p.children.insert(idx, child.0);
1905        }
1906        s.log(format!("move #{} in #{} to {}", child.0, parent.0, to));
1907    }
1908
1909    fn measure(&mut self, h: &MockHandle, kind: PieceKind, p: Proposal) -> Size {
1910        let mut s = self.state.borrow_mut();
1911        s.measure_calls += 1;
1912        let w = s.widgets.get(&h.0).cloned().unwrap_or_default();
1913        let size = match kind {
1914            kinds::LABEL => {
1915                let scale = w.font.map_or(1.0, |f| font_scale(f.style));
1916                let s = text_size(&w.text, p, w.flag, scale);
1917                Size::new(s.width.min(p.width.unwrap_or(s.width)), s.height)
1918            }
1919            kinds::BUTTON => {
1920                let t = text_size(&w.text, Proposal::UNCONSTRAINED, false, 1.0);
1921                Size::new(t.width + 16.0, 24.0)
1922            }
1923            kinds::TOGGLE => Size::new(51.0, 31.0),
1924            kinds::SLIDER | kinds::TEXT_FIELD | kinds::LIST_ITEM => {
1925                Size::new(p.width.unwrap_or(200.0), 24.0)
1926            }
1927            kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 1.0),
1928            kinds::IMAGE => Size::new(32.0, 32.0),
1929            // Indeterminate spinner is a fixed square; determinate bar fills width.
1930            kinds::PROGRESS if w.flag => Size::new(20.0, 20.0),
1931            kinds::PROGRESS => Size::new(p.width.unwrap_or(200.0), 4.0),
1932            _ => Size::new(p.width.unwrap_or(10.0), p.height.unwrap_or(10.0)),
1933        };
1934        s.log(format!(
1935            "measure {kind} #{} {:?} -> {}",
1936            h.0,
1937            p.cache_key(),
1938            fmt_size(size)
1939        ));
1940        size
1941    }
1942
1943    /// A synthetic first baseline (docs/baseline.md), modeling the one fact that matters for
1944    /// the layout math: text sits at different heights inside different widgets. The mock's
1945    /// line box is 16pt with a 12pt ascent, and a widget that frames its text (a field, a
1946    /// button) insets it, so a label beside a text field must drop by exactly that inset for
1947    /// the two to share a line. Widgets with no text report `None`.
1948    fn first_baseline(&mut self, h: &MockHandle, kind: PieceKind, size: Size) -> Option<f64> {
1949        const ASCENT: f64 = 12.0;
1950        let framed_inset = |box_h: f64| (box_h - MOCK_LINE_H) / 2.0 + ASCENT;
1951        let s = self.state.borrow();
1952        let w = s.widgets.get(&h.0).cloned().unwrap_or_default();
1953        match kind {
1954            kinds::LABEL => (!w.text.is_empty() || size.height > 0.0).then_some(ASCENT),
1955            kinds::BUTTON | kinds::TEXT_FIELD | kinds::TEXT_AREA => Some(framed_inset(size.height)),
1956            // No text, so no baseline; these are the children that keep centering.
1957            _ => None,
1958        }
1959    }
1960
1961    fn set_frame(&mut self, h: &MockHandle, frame: Rect, anim: Option<&AnimSpec>) {
1962        let mut s = self.state.borrow_mut();
1963        if let Some(w) = s.widgets.get_mut(&h.0) {
1964            w.frame = frame;
1965            if anim.is_some() {
1966                w.last_anim = anim.copied();
1967            }
1968        }
1969        let a = if anim.is_some() { " animated" } else { "" };
1970        s.log(format!("set_frame #{} {}{}", h.0, fmt_rect(frame), a));
1971    }
1972
1973    fn set_opacity(&mut self, h: &MockHandle, opacity: f64, anim: Option<&AnimSpec>) {
1974        let mut s = self.state.borrow_mut();
1975        if let Some(w) = s.widgets.get_mut(&h.0) {
1976            w.opacity = Some(opacity);
1977            if anim.is_some() {
1978                w.last_anim = anim.copied();
1979            }
1980        }
1981        let a = if anim.is_some() { " animated" } else { "" };
1982        s.log(format!("set_opacity #{} {:.3}{}", h.0, opacity, a));
1983    }
1984
1985    fn set_transform(
1986        &mut self,
1987        h: &MockHandle,
1988        t: day_spec::Transform,
1989        _size: day_spec::Size,
1990        anim: Option<&AnimSpec>,
1991    ) {
1992        let mut s = self.state.borrow_mut();
1993        if let Some(w) = s.widgets.get_mut(&h.0) {
1994            w.transform = Some(t);
1995            if anim.is_some() {
1996                w.last_anim = anim.copied();
1997            }
1998        }
1999        let a = if anim.is_some() { " animated" } else { "" };
2000        s.log(format!(
2001            "set_transform #{} tx={:.1},ty={:.1},sx={:.2},sy={:.2},rot={:.1}{}",
2002            h.0, t.tx, t.ty, t.sx, t.sy, t.rotate_deg, a
2003        ));
2004    }
2005
2006    fn set_selectable(&mut self, h: &MockHandle, selectable: bool) -> Option<MockHandle> {
2007        let mut s = self.state.borrow_mut();
2008        if let Some(w) = s.widgets.get_mut(&h.0) {
2009            w.selectable = selectable;
2010        }
2011        s.log(format!("set_selectable #{} {}", h.0, selectable));
2012        None
2013    }
2014
2015    fn set_input_traits(
2016        &mut self,
2017        h: &MockHandle,
2018        traits: &day_spec::InputTraits,
2019    ) -> Option<MockHandle> {
2020        let mut s = self.state.borrow_mut();
2021        s.log(format!(
2022            "set_input_traits #{} secure={} read_only={} purpose={:?} submit={:?} max={:?}",
2023            h.0,
2024            traits.secure,
2025            traits.read_only,
2026            traits.purpose,
2027            traits.submit_label,
2028            traits.max_length
2029        ));
2030        let was_secure = s
2031            .widgets
2032            .get(&h.0)
2033            .and_then(|w| w.input_traits.as_ref())
2034            .is_some_and(|t| t.secure);
2035        if s.secure_class_swap && was_secure != traits.secure {
2036            // The class-swap toolkits: a new widget carries the old one's state and takes its
2037            // place among the parent's children; the old handle is gone.
2038            let mut w = s.widgets.remove(&h.0)?;
2039            w.input_traits = Some(traits.clone());
2040            s.next += 1;
2041            let new = s.next;
2042            for parent in s.widgets.values_mut() {
2043                for child in parent.children.iter_mut().filter(|c| **c == h.0) {
2044                    *child = new;
2045                }
2046            }
2047            s.widgets.insert(new, w);
2048            s.log(format!("swap #{} for #{}", h.0, new));
2049            return Some(MockHandle(new));
2050        }
2051        if let Some(w) = s.widgets.get_mut(&h.0) {
2052            w.input_traits = Some(traits.clone());
2053        }
2054        None
2055    }
2056
2057    fn set_cursor(&mut self, h: &MockHandle, cursor: day_spec::Cursor) {
2058        let mut s = self.state.borrow_mut();
2059        if let Some(w) = s.widgets.get_mut(&h.0) {
2060            w.cursor = Some(cursor.clone());
2061        }
2062        s.log(format!("set_cursor #{} {}", h.0, cursor.css_name()));
2063    }
2064
2065    fn scroll_bar_inset(&mut self, _h: &MockHandle, _vertical: bool) -> f64 {
2066        self.state.borrow().scroll_bar_inset
2067    }
2068
2069    fn set_scroll_content(&mut self, h: &MockHandle, content: Size) {
2070        let mut s = self.state.borrow_mut();
2071        if let Some(w) = s.widgets.get_mut(&h.0) {
2072            w.scroll_content = content;
2073        }
2074        s.log(format!("set_scroll_content #{} {}", h.0, fmt_size(content)));
2075    }
2076
2077    fn scroll_to(&mut self, h: &MockHandle, target: Rect, _animated: bool) {
2078        let mut s = self.state.borrow_mut();
2079        if let Some(w) = s.widgets.get_mut(&h.0) {
2080            // Minimal scroll that makes `target` (content space) visible, clamped to range.
2081            let (vw, vh) = (w.frame.size.width, w.frame.size.height);
2082            let (cw, ch) = (w.scroll_content.width, w.scroll_content.height);
2083            let clamp = |cur: f64, lo: f64, hi_edge: f64, view: f64, content: f64| -> f64 {
2084                let mut o = cur;
2085                if hi_edge > o + view {
2086                    o = hi_edge - view;
2087                }
2088                if lo < o {
2089                    o = lo;
2090                }
2091                o.clamp(0.0, (content - view).max(0.0))
2092            };
2093            let o = w.scroll_offset;
2094            w.scroll_offset = Point::new(
2095                clamp(
2096                    o.x,
2097                    target.origin.x,
2098                    target.origin.x + target.size.width,
2099                    vw,
2100                    cw,
2101                ),
2102                clamp(
2103                    o.y,
2104                    target.origin.y,
2105                    target.origin.y + target.size.height,
2106                    vh,
2107                    ch,
2108                ),
2109            );
2110        }
2111        s.log(format!("scroll_to #{} {}", h.0, fmt_rect(target)));
2112    }
2113
2114    fn scroll_offset(&mut self, h: &MockHandle) -> Point {
2115        self.state
2116            .borrow()
2117            .widgets
2118            .get(&h.0)
2119            .map_or(Point::ZERO, |w| w.scroll_offset)
2120    }
2121
2122    fn enable_gesture(&mut self, h: &MockHandle, _node: NodeId, kind: GestureKind) {
2123        self.state
2124            .borrow_mut()
2125            .log(format!("enable_gesture #{} {:?}", h.0, kind));
2126    }
2127
2128    fn focus(&mut self, h: &MockHandle, node: NodeId, focused: bool) {
2129        let sink = {
2130            let mut st = self.state.borrow_mut();
2131            st.log(format!("focus #{} {}", h.0, focused));
2132            if let Some(w) = st.widgets.get_mut(&h.0) {
2133                w.focused = focused;
2134            }
2135            st.sink.clone()
2136        };
2137        // A native toolkit reports the focus it was given back as an event, which is what
2138        // day-core's probe mirrors (docs/focus.md); the mock does the same, after the borrow.
2139        if let Some(sink) = sink {
2140            sink(node, Event::FocusChanged(focused));
2141        }
2142    }
2143
2144    fn set_event_sink(&mut self, sink: EventSink) {
2145        self.state.borrow_mut().sink = Some(Rc::from(sink));
2146    }
2147
2148    fn attach_tree(&mut self, host: &MockHandle, source: day_spec::TreeSource) {
2149        if VIEWPORT_ROWS.with(std::cell::Cell::get) > 0 {
2150            let (children_len, child_token) =
2151                (source.children_len.clone(), source.child_token.clone());
2152            // Depth first, into the disclosed rows only: the order a native tree shows.
2153            let visible = move |open: &std::collections::HashSet<u64>| {
2154                fn walk(
2155                    parent: Option<u64>,
2156                    open: &std::collections::HashSet<u64>,
2157                    len: &dyn Fn(Option<u64>) -> usize,
2158                    tok: &dyn Fn(Option<u64>, usize) -> u64,
2159                    out: &mut Vec<u64>,
2160                ) {
2161                    for i in 0..len(parent) {
2162                        let t = tok(parent, i);
2163                        out.push(t);
2164                        if open.contains(&t) {
2165                            walk(Some(t), open, len, tok, out);
2166                        }
2167                    }
2168                }
2169                let mut out = Vec::new();
2170                walk(None, open, &*children_len, &*child_token, &mut out);
2171                out
2172            };
2173            VIEWPORTS.with(|v| {
2174                v.borrow_mut().insert(
2175                    host.0,
2176                    Viewport {
2177                        visible: Rc::new(visible),
2178                        bind_row: source.bind_row.clone(),
2179                        recycle: source.recycle.clone(),
2180                        cell_height: None,
2181                        expanded: std::collections::HashSet::default(),
2182                        start: 0,
2183                        to_end: false,
2184                        bound: 0,
2185                        dirty: true,
2186                    },
2187                )
2188            });
2189        }
2190        let mut s = self.state.borrow_mut();
2191        s.tree_sources.insert(host.0, source);
2192        s.log(format!("attach_tree #{}", host.0));
2193    }
2194
2195    fn attach_list(&mut self, host: &MockHandle, source: ListSource) {
2196        if VIEWPORT_ROWS.with(std::cell::Cell::get) > 0 {
2197            VIEWPORTS.with(|v| {
2198                v.borrow_mut().insert(
2199                    host.0,
2200                    Viewport {
2201                        visible: {
2202                            let len = source.len.clone();
2203                            Rc::new(move |_| (0..len() as u64).collect())
2204                        },
2205                        bind_row: {
2206                            let bind = source.bind_row.clone();
2207                            Rc::new(move |row, cell| bind(row as usize, cell))
2208                        },
2209                        recycle: source.recycle.clone(),
2210                        cell_height: Some(source.cell_height.clone()),
2211                        expanded: std::collections::HashSet::default(),
2212                        start: 0,
2213                        to_end: false,
2214                        bound: 0,
2215                        dirty: true,
2216                    },
2217                )
2218            });
2219        }
2220        let mut s = self.state.borrow_mut();
2221        s.list_sources.insert(host.0, source);
2222        s.log(format!("attach_list #{}", host.0));
2223    }
2224
2225    fn adopt(&mut self, raw: RawHandle) -> MockHandle {
2226        // A recycling list's cell: register a container widget so row content can attach to it.
2227        let h = raw as u64;
2228        let mut s = self.state.borrow_mut();
2229        s.widgets.entry(h).or_insert_with(|| MockWidget {
2230            kind: kinds::LIST_CELL,
2231            node: h,
2232            enabled: true,
2233            ..Default::default()
2234        });
2235        MockHandle(h)
2236    }
2237
2238    fn reduce_motion(&mut self) -> bool {
2239        self.state.borrow().reduce_motion
2240    }
2241
2242    fn announce(&mut self, text: &str, urgent: bool) {
2243        let mut s = self.state.borrow_mut();
2244        s.announcements.push((text.to_string(), urgent));
2245        s.log(format!("announce {text:?} urgent={urgent}"));
2246    }
2247
2248    fn set_a11y(&mut self, h: &MockHandle, a11y: &A11yProps) {
2249        let mut s = self.state.borrow_mut();
2250        if let Some(w) = s.widgets.get_mut(&h.0) {
2251            w.a11y = a11y.clone();
2252        }
2253        s.log(format!("a11y #{} id={:?}", h.0, a11y.identifier));
2254    }
2255
2256    // --- raster images (docs/images.md) --------------------------------------------------
2257    //
2258    // The mock "decodes" without pixels: it reads the format from the magic numbers and invents
2259    // a size, which is what a test needs to assert against. Undecodable bytes answer
2260    // `ImageError::Decode`, so the failure path is exercised too.
2261
2262    fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
2263        let format = day_spec::ImageFormat::sniff(bytes);
2264        let mut s = self.state.borrow_mut();
2265        s.log(format!(
2266            "decode_image #{} {} bytes {:?}",
2267            id.0,
2268            bytes.len(),
2269            format
2270        ));
2271        let event = match format {
2272            Some(format) => {
2273                let info = day_spec::BitmapInfo {
2274                    // A deterministic synthetic size a test can predict, in the same spirit as
2275                    // the mock's synthetic text metrics.
2276                    pixels: Size::new(MOCK_IMAGE_W, MOCK_IMAGE_H),
2277                    scale: 1.0,
2278                    format: Some(format),
2279                    has_alpha: format == day_spec::ImageFormat::Png,
2280                };
2281                s.bitmaps.insert(id.0, info);
2282                Event::ImageDecoded {
2283                    req,
2284                    result: Ok(info),
2285                }
2286            }
2287            None => Event::ImageDecoded {
2288                req,
2289                result: Err(day_spec::ImageError::Decode),
2290            },
2291        };
2292        drop(s);
2293        self.raise(event);
2294    }
2295
2296    fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
2297        self.state.borrow().bitmaps.get(&id.0).copied()
2298    }
2299
2300    fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
2301        let mut s = self.state.borrow_mut();
2302        s.log(format!("encode_image #{} {:?}", id.0, spec.format));
2303        let known = s.bitmaps.contains_key(&id.0);
2304        let result = if !known {
2305            Err(day_spec::ImageError::Gone)
2306        } else if !MOCK_ENCODE_FORMATS.contains(&spec.format) {
2307            Err(day_spec::ImageError::Encode)
2308        } else {
2309            // A recognizable stand-in, not real pixels: the format's magic number, so a test
2310            // can assert what came back round-trips through `ImageFormat::sniff`.
2311            Ok(match spec.format {
2312                day_spec::ImageFormat::Jpeg => vec![0xff, 0xd8, 0xff, 0xe0],
2313                _ => vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a],
2314            })
2315        };
2316        drop(s);
2317        self.raise(Event::ImageEncoded { req, result });
2318    }
2319
2320    fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
2321        MOCK_ENCODE_FORMATS.to_vec()
2322    }
2323
2324    fn release_image(&mut self, id: day_spec::BitmapId) {
2325        let mut s = self.state.borrow_mut();
2326        s.bitmaps.remove(&id.0);
2327        s.log(format!("release_image #{}", id.0));
2328    }
2329
2330    /// No pixels, like a decode: the bitmap's facts are the size and scale asked for, which is
2331    /// what a test asserts against, and it joins the table `encode_image` reads.
2332    fn render_bitmap(
2333        &mut self,
2334        req: u64,
2335        id: day_spec::BitmapId,
2336        ops: &[DrawOp],
2337        size: Size,
2338        scale: f64,
2339    ) {
2340        let (w, h) = day_spec::export_pixels(size, scale);
2341        let info = day_spec::BitmapInfo {
2342            pixels: Size::new(f64::from(w), f64::from(h)),
2343            scale,
2344            format: None,
2345            has_alpha: true,
2346        };
2347        let mut s = self.state.borrow_mut();
2348        s.log(format!(
2349            "render_bitmap #{} {} ops {} @{scale}",
2350            id.0,
2351            ops.len(),
2352            fmt_size(size)
2353        ));
2354        s.bitmaps.insert(id.0, info);
2355        drop(s);
2356        self.raise(Event::BitmapRendered {
2357            req,
2358            result: Ok(info),
2359        });
2360    }
2361
2362    fn replay(&mut self, h: &MockHandle, ops: &[DrawOp], size: Size) {
2363        let mut s = self.state.borrow_mut();
2364        if let Some(w) = s.widgets.get_mut(&h.0) {
2365            w.ops = ops.to_vec();
2366        }
2367        s.log(format!(
2368            "replay #{} {} ops in {}",
2369            h.0,
2370            ops.len(),
2371            fmt_size(size)
2372        ));
2373    }
2374
2375    /// A deterministic list a test can assert on: "Day Sans" in four faces and "Day Mono" in one.
2376    fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
2377        use day_spec::FontWeight::{Bold, Regular};
2378        self.state.borrow_mut().log("font_families".to_string());
2379        let face = |name: &str, weight: day_spec::FontWeight, italic: bool| day_spec::FontFace {
2380            name: name.to_string(),
2381            weight,
2382            italic,
2383        };
2384        vec![
2385            day_spec::FontFamilyInfo {
2386                family: "Day Sans".to_string(),
2387                faces: vec![
2388                    face("Regular", Regular, false),
2389                    face("Bold", Bold, false),
2390                    face("Italic", Regular, true),
2391                    face("Bold Italic", Bold, true),
2392                ],
2393            },
2394            day_spec::FontFamilyInfo {
2395                family: "Day Mono".to_string(),
2396                faces: vec![face("Regular", Regular, false)],
2397            },
2398        ]
2399    }
2400
2401    /// The same formula as `TextMetrics::approximate`, so a test can predict a frame.
2402    fn measure_text(
2403        &mut self,
2404        text: &str,
2405        size: f64,
2406        _font: &day_spec::CanvasFont,
2407    ) -> Option<day_spec::TextMetrics> {
2408        self.state
2409            .borrow_mut()
2410            .log(format!("measure_text {text:?} {size}"));
2411        Some(day_spec::TextMetrics::approximate(text, size))
2412    }
2413
2414    fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
2415        Ok(vec![0x89, b'P', b'N', b'G'])
2416    }
2417
2418    fn fit_window(&mut self, host: &MockHandle, size: Size) {
2419        let mut st = self.state.borrow_mut();
2420        if let Some(w) = st.windows.iter_mut().find(|w| w.handle == host.0) {
2421            w.fit_size = Some(size);
2422            w.size = size;
2423        }
2424        st.log(format!("fit_window {} {size:?}", host.0));
2425    }
2426
2427    fn native_window_tabs(&self) -> bool {
2428        self.state.borrow().native_window_tabs
2429    }
2430    fn native_document_tabs(&self) -> bool {
2431        true
2432    }
2433    fn group_windows(&mut self, hosts: &[MockHandle]) {
2434        let mut state = self.state.borrow_mut();
2435        let ids: Vec<_> = hosts
2436            .iter()
2437            .filter_map(|h| {
2438                state
2439                    .windows
2440                    .iter()
2441                    .find(|w| w.handle == h.0 && w.open)
2442                    .map(|w| w.node)
2443            })
2444            .collect();
2445        for group in &mut state.window_tab_groups {
2446            group.retain(|id| !ids.contains(id));
2447        }
2448        state.window_tab_groups.retain(|group| !group.is_empty());
2449        if !ids.is_empty() {
2450            state.window_tab_groups.push(ids);
2451        }
2452        state.log(format!("group_windows {hosts:?}"));
2453    }
2454    fn window_tab_order(&self, host: &MockHandle) -> Vec<NodeId> {
2455        let state = self.state.borrow();
2456        let Some(window) = state.windows.iter().find(|w| w.handle == host.0 && w.open) else {
2457            return Vec::new();
2458        };
2459        state
2460            .window_tab_groups
2461            .iter()
2462            .find(|group| group.contains(&window.node))
2463            .map_or_default(|group| {
2464                group
2465                    .iter()
2466                    .copied()
2467                    .filter(|id| state.windows.iter().any(|w| w.node == *id && w.open))
2468                    .collect()
2469            })
2470    }
2471    fn open_window(
2472        &mut self,
2473        id: NodeId,
2474        options: &day_spec::WindowOptions,
2475        kind: day_spec::WindowKind,
2476    ) -> day_spec::WindowOpenReply<MockHandle> {
2477        let kind_s = match kind {
2478            day_spec::WindowKind::Normal => "normal",
2479            day_spec::WindowKind::Preferences => "preferences",
2480            day_spec::WindowKind::About => "about",
2481        };
2482        let mut s = self.state.borrow_mut();
2483        if s.no_multi_window {
2484            s.log(format!("open_window unsupported kind={kind_s}"));
2485            return day_spec::WindowOpenReply::Unsupported;
2486        }
2487        if s.pending_windows {
2488            s.log(format!("open_window pending {:?} kind={kind_s}", id.0));
2489            s.pending_opens
2490                .push((id, options.title.clone(), kind_s.into()));
2491            return day_spec::WindowOpenReply::Pending;
2492        }
2493        s.next += 1;
2494        let h = s.next;
2495        s.widgets.insert(
2496            h,
2497            MockWidget {
2498                kind: kinds::CONTAINER,
2499                node: id.0,
2500                enabled: true,
2501                ..Default::default()
2502            },
2503        );
2504        s.windows.push(MockWindow {
2505            handle: h,
2506            node: id,
2507            title: options.title.clone(),
2508            size: options.size,
2509            kind: kind_s.into(),
2510            tabbing: options.tabbing.clone(),
2511            open: true,
2512            focused: false,
2513            fit_size: None,
2514        });
2515        s.log(format!(
2516            "open_window #{h} {:?} {} kind={kind_s}",
2517            options.title,
2518            fmt_size(options.size)
2519        ));
2520        day_spec::WindowOpenReply::Open(MockHandle(h))
2521    }
2522
2523    fn quit_app(&mut self) {
2524        // Recorded rather than acted on: a test asserts the close policy reached the platform
2525        // exit, and the harness has no process to end (docs/windows.md).
2526        self.state.borrow_mut().log("quit_app".to_string());
2527    }
2528
2529    fn close_window(&mut self, host: &MockHandle) {
2530        // Model the native round-trip: mark closed, then confirm through the sink with
2531        // `WindowClosed`; day-core tears down when the (queued) event drains.
2532        let mut s = self.state.borrow_mut();
2533        let Some(w) = s.windows.iter_mut().find(|w| w.handle == host.0 && w.open) else {
2534            return;
2535        };
2536        let node = w.node;
2537        s.log(format!("close_window #{}", host.0));
2538        if s.defer_window_close {
2539            return;
2540        }
2541        s.windows.iter_mut().find(|w| w.node == node).unwrap().open = false;
2542        let sink = s.sink.clone();
2543        drop(s);
2544        if let Some(sink) = sink {
2545            sink(node, Event::WindowClosed);
2546        }
2547    }
2548
2549    fn focus_window(&mut self, host: &MockHandle) {
2550        let mut s = self.state.borrow_mut();
2551        let Some(node) = s
2552            .windows
2553            .iter()
2554            .find(|w| w.handle == host.0 && w.open)
2555            .map(|w| w.node)
2556        else {
2557            return;
2558        };
2559        let prev = s.windows.iter().find(|w| w.focused).map(|w| w.node);
2560        for w in &mut s.windows {
2561            w.focused = w.handle == host.0;
2562        }
2563        s.log(format!("focus_window #{}", host.0));
2564        let sink = s.sink.clone();
2565        drop(s);
2566        if let Some(sink) = sink {
2567            if let Some(p) = prev
2568                && p != node
2569            {
2570                sink(p, Event::WindowFocused(false));
2571            }
2572            sink(node, Event::WindowFocused(true));
2573        }
2574    }
2575
2576    fn set_window_title(&mut self, host: &MockHandle, title: &str) {
2577        let mut s = self.state.borrow_mut();
2578        if let Some(w) = s.windows.iter_mut().find(|w| w.handle == host.0) {
2579            w.title = title.to_string();
2580        }
2581        s.log(format!("set_window_title #{} {title:?}", host.0));
2582    }
2583
2584    fn snapshot_window_of(&mut self, host: &MockHandle) -> Result<Vec<u8>, String> {
2585        // Distinguishable from the primary snapshot so the dayscript `window:` routing is
2586        // assertable.
2587        Ok(vec![0x89, b'P', b'N', b'G', host.0 as u8])
2588    }
2589
2590    fn present(&mut self, req: u64, spec: &day_spec::present::PresentSpec) {
2591        // No native UI; day-core's `PENDING` registry holds the spec. Log for op-log asserts;
2592        // tests answer via day_core::respond_presentation / pending_presentation.
2593        self.state
2594            .borrow_mut()
2595            .log(format!("present req={req} title={:?}", spec.title()));
2596    }
2597
2598    fn dismiss(&mut self, req: u64) {
2599        self.state.borrow_mut().log(format!("dismiss req={req}"));
2600    }
2601
2602    fn share_support(&self) -> day_spec::Support {
2603        day_spec::Support::Native
2604    }
2605
2606    fn share(&mut self, spec: &day_spec::share::ShareSpec, anchor: Option<&Self::Handle>) -> bool {
2607        // No chooser to show; record it so a test can read the request and choose an action
2608        // (`MockProbe::choose_share_action`).
2609        let anchor = anchor.map(|h| h.0);
2610        self.state.borrow_mut().shares.push((spec.clone(), anchor));
2611        true
2612    }
2613
2614    fn open_url(&mut self, url: &str) {
2615        // No browser to launch; record it so op-log assertions can verify a `link` fired.
2616        self.state.borrow_mut().log(format!("open_url {url}"));
2617    }
2618
2619    fn defer_system_gestures(&mut self, edges: day_spec::Edges) {
2620        // No system gestures to defer; record the union (docs/cover.md) for op-log asserts.
2621        self.state
2622            .borrow_mut()
2623            .log(format!("defer_system_gestures edges={:#06b}", edges.0));
2624    }
2625
2626    fn set_status_bar_hidden(&mut self, hidden: bool) {
2627        // No status bar; record the union (docs/cover.md) for op-log asserts.
2628        self.state
2629            .borrow_mut()
2630            .log(format!("set_status_bar_hidden {hidden}"));
2631    }
2632
2633    // The remaining duties, implemented observably so mock stays a complete conformance probe
2634    // (a duty a piece exercises must never vanish into a trait default here).
2635
2636    fn edit_toolbar(&mut self, _h: &MockHandle, ops: &[day_spec::ToolbarOp]) -> bool {
2637        let mut s = self.state.borrow_mut();
2638        if s.decline_toolbar_edits {
2639            return false;
2640        }
2641        for op in ops {
2642            s.toolbar.apply(op);
2643        }
2644        s.toolbar_edits.push(ops.to_vec());
2645        s.log(format!("edit_toolbar [{} ops]", ops.len()));
2646        true
2647    }
2648
2649    fn update_toolbar(&mut self, _h: &MockHandle, patch: &day_spec::ToolbarPatch) {
2650        let mut s = self.state.borrow_mut();
2651        s.toolbar.patch(patch);
2652        s.toolbar_patches.push(patch.clone());
2653    }
2654
2655    fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
2656        let mut s = self.state.borrow_mut();
2657        s.app_menu = items.iter().map(menu_title).collect();
2658        s.log(format!("set_app_menu [{} items]", items.len()));
2659    }
2660
2661    fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
2662        let mut s = self.state.borrow_mut();
2663        s.status_items = items.to_vec();
2664        s.log(format!("set_status_items [{} items]", items.len()));
2665    }
2666
2667    fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
2668        let mut s = self.state.borrow_mut();
2669        s.app_progress = progress;
2670        s.log(format!("set_app_progress {progress:?}"));
2671    }
2672
2673    fn set_dock_visible(&mut self, visible: bool) {
2674        let mut s = self.state.borrow_mut();
2675        s.dock_visible = Some(visible);
2676        s.log(format!("set_dock_visible {visible}"));
2677    }
2678
2679    fn set_keep_running(&mut self, keep: bool) {
2680        let mut s = self.state.borrow_mut();
2681        s.keep_running = keep;
2682        s.log(format!("set_keep_running {keep}"));
2683    }
2684
2685    fn monitors(&self) -> Vec<day_spec::Monitor> {
2686        // One fixed display, so placement arithmetic is testable headless.
2687        let frame = day_spec::Rect::new(0.0, 0.0, 1440.0, 900.0);
2688        vec![day_spec::Monitor {
2689            id: "mock-0".into(),
2690            name: "Mock Display".into(),
2691            frame,
2692            work_area: day_spec::Rect::new(0.0, 25.0, 1440.0, 875.0),
2693            scale: 2.0,
2694            primary: true,
2695        }]
2696    }
2697
2698    fn window_frame(&self, host: &MockHandle) -> Option<day_spec::Rect> {
2699        // The last `Frame` change applied to this window, as a platform would report it back.
2700        let s = self.state.borrow();
2701        s.window_changes.iter().rev().find_map(|(h, c)| match c {
2702            day_spec::WindowChange::Frame {
2703                origin: Some(o),
2704                size: Some(z),
2705            } if *h == host.0 => Some(day_spec::Rect::new(o.x, o.y, z.width, z.height)),
2706            _ => None,
2707        })
2708    }
2709
2710    fn set_launcher_shortcuts(&mut self, shortcuts: &[day_spec::LauncherShortcut]) {
2711        let mut s = self.state.borrow_mut();
2712        s.launcher_shortcuts = shortcuts.to_vec();
2713        s.log(format!(
2714            "set_launcher_shortcuts [{} items]",
2715            shortcuts.len()
2716        ));
2717    }
2718
2719    fn set_drag_region(&mut self, h: &MockHandle, drag: bool) {
2720        let mut s = self.state.borrow_mut();
2721        if drag {
2722            s.drag_regions.insert(h.0);
2723        } else {
2724            s.drag_regions.remove(&h.0);
2725        }
2726        s.log(format!("set_drag_region #{} {drag}", h.0));
2727    }
2728
2729    fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
2730        let mut s = self.state.borrow_mut();
2731        s.dock_menu = items.iter().map(menu_title).collect();
2732        s.log(format!("set_dock_menu [{} items]", items.len()));
2733    }
2734
2735    fn apply_window(&mut self, host: &MockHandle, change: &day_spec::WindowChange) {
2736        // Model the platform: record the request, and for a state change complete it and report
2737        // the outcome the way a real window does, through `WindowStateChanged` on the window's
2738        // own node (the primary's goes to `WINDOW_NODE`, as AppKit's does).
2739        let mut s = self.state.borrow_mut();
2740        s.log(format!("apply_window #{} {change:?}", host.0));
2741        s.window_changes.push((host.0, change.clone()));
2742        let day_spec::WindowChange::State(state) = change else {
2743            return;
2744        };
2745        if s.decline_window_states {
2746            return;
2747        }
2748        s.window_states.insert(host.0, *state);
2749        let node = s
2750            .windows
2751            .iter()
2752            .find(|w| w.handle == host.0)
2753            .map_or(day_spec::WINDOW_NODE, |w| w.node);
2754        let sink = s.sink.clone();
2755        drop(s);
2756        if let Some(sink) = sink {
2757            sink(node, Event::WindowStateChanged(*state));
2758        }
2759    }
2760
2761    fn set_context_menu(&mut self, h: &MockHandle, _node: NodeId, items: &[day_spec::MenuItem]) {
2762        let mut s = self.state.borrow_mut();
2763        if items.is_empty() {
2764            s.context_menus.remove(&h.0);
2765        } else {
2766            s.context_menus
2767                .insert(h.0, items.iter().map(menu_title).collect());
2768        }
2769        s.log(format!("set_context_menu #{} [{} items]", h.0, items.len()));
2770    }
2771
2772    fn set_context_menu_fn(&mut self, h: &MockHandle, _node: NodeId, f: day_spec::ContextMenuFn) {
2773        self.state
2774            .borrow_mut()
2775            .context_menu_providers
2776            .insert(h.0, f);
2777    }
2778
2779    fn set_button_menu(&mut self, h: &MockHandle, _node: NodeId, f: day_spec::ContextMenuFn) {
2780        let mut s = self.state.borrow_mut();
2781        s.button_menus.insert(h.0, f);
2782        s.log(format!("set_button_menu #{}", h.0));
2783    }
2784
2785    fn supports_lifecycle(&self, _phase: day_spec::Lifecycle) -> bool {
2786        // Headless CI stands in for every platform: claim the full lifecycle so tests can
2787        // exercise mobile-only phases (day-core synthesizes delivery).
2788        true
2789    }
2790
2791    fn read_native(&self, h: &MockHandle) -> day_spec::NativeSnapshot {
2792        // Echo what the setters recorded, so `a11y_audit` and `assert_native` diff cleanly
2793        // against expectations: the mock's "native" state is its widget record.
2794        let s = self.state.borrow();
2795        let Some(w) = s.widgets.get(&h.0) else {
2796            return day_spec::NativeSnapshot::default();
2797        };
2798        let kind = w.kind;
2799        let texty = matches!(
2800            kind,
2801            "day.label" | "day.button" | "day.text_field" | "day.text_area"
2802        );
2803        // A picker shows its selected option; the mock keeps the options `|`-joined.
2804        let picked = (kind == "day.picker")
2805            .then(|| w.text.split('|').nth(w.value as usize).map(str::to_owned))
2806            .flatten();
2807        day_spec::NativeSnapshot {
2808            found: true,
2809            role: w.a11y.role,
2810            label: w.a11y.label.clone(),
2811            value: w.a11y.value.clone(),
2812            identifier: w.a11y.identifier.clone(),
2813            text: texty.then(|| w.text.clone()).or(picked),
2814            number: matches!(kind, "day.slider" | "day.progress").then_some(w.value),
2815            // A toggle's state, or a button's selected state.
2816            checked: match kind {
2817                "day.toggle" => Some(w.flag),
2818                "day.button" => Some(w.selected),
2819                _ => None,
2820            },
2821            enabled: Some(w.enabled),
2822            visible: None,
2823            frame: Some(window_frame(&s, h.0)),
2824        }
2825    }
2826
2827    fn set_system_back(&mut self, armed: bool) {
2828        let mut s = self.state.borrow_mut();
2829        s.system_back = armed;
2830        s.log(format!("system_back armed={armed}"));
2831    }
2832
2833    /// Android's back dispatcher, in its order: the topmost presented cover's callback, then a
2834    /// nav host with a page above its root (asking Day when guarded, else popping natively and
2835    /// reporting it), then the app's own system-back callback while day-core arms it. With
2836    /// none of them, the press would leave the app: `false`.
2837    fn native_back(&mut self) -> bool {
2838        let target = {
2839            let mut s = self.state.borrow_mut();
2840            let Some(sink) = s.sink.clone() else {
2841                return false;
2842            };
2843            let cover = s
2844                .widgets
2845                .values()
2846                .filter(|w| w.kind == kinds::COVER && w.flag)
2847                .map(|w| w.node)
2848                .max();
2849            let host = s
2850                .widgets
2851                .iter()
2852                .filter(|(_, w)| w.nav_depth > 0)
2853                .max_by_key(|(_, w)| w.node)
2854                .map(|(h, _)| *h);
2855            let target = if let Some(node) = cover {
2856                Some((
2857                    NodeId(node),
2858                    Event::NavBack {
2859                        already_popped: false,
2860                    },
2861                ))
2862            } else if let Some(h) = host {
2863                let w = s.widgets.get_mut(&h).expect("host just found");
2864                let guarded = w.nav_guarded;
2865                if !guarded {
2866                    w.nav_depth -= 1;
2867                }
2868                Some((
2869                    NodeId(w.node),
2870                    Event::NavBack {
2871                        already_popped: !guarded,
2872                    },
2873                ))
2874            } else if s.system_back {
2875                Some((
2876                    day_spec::WINDOW_NODE,
2877                    Event::NavBack {
2878                        already_popped: false,
2879                    },
2880                ))
2881            } else {
2882                None
2883            };
2884            if let Some((node, _)) = &target {
2885                s.log(format!("native_back -> {node:?}"));
2886            }
2887            target.map(|(node, ev)| (sink, node, ev))
2888        };
2889        match target {
2890            Some((sink, node, ev)) => {
2891                sink(node, ev);
2892                true
2893            }
2894            None => false,
2895        }
2896    }
2897
2898    fn ui_idle(&mut self) -> bool {
2899        // No native transitions exist; idle is immediate, but log the poll so scripted runs
2900        // can assert dayscript's settle path touched it.
2901        self.state.borrow_mut().log("ui_idle".into());
2902        !self.state.borrow().ui_busy
2903    }
2904
2905    fn on_suspend(&mut self) {
2906        self.state.borrow_mut().log("on_suspend".into());
2907    }
2908
2909    fn on_resume(&mut self) {
2910        self.state.borrow_mut().log("on_resume".into());
2911    }
2912
2913    fn on_memory_warning(&mut self) {
2914        self.state.borrow_mut().log("on_memory_warning".into());
2915    }
2916}
2917
2918/// A menu item's display title (submenus render as their title; separators as "—").
2919fn menu_title(item: &day_spec::MenuItem) -> String {
2920    match item {
2921        day_spec::MenuItem::Action { label, .. } | day_spec::MenuItem::Submenu { label, .. } => {
2922            label.clone()
2923        }
2924        day_spec::MenuItem::Separator => "—".into(),
2925    }
2926}
2927
2928impl Platform for MockToolkit {
2929    const TARGET: &'static str = "mock-mock";
2930    const TOOLKIT: &'static str = "mock";
2931    // The host owns the loop: `run` hands back at once, and DidExit is its last callback.
2932    const RUN_ENDS_APP: bool = false;
2933
2934    fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, MockHandle, Size)>) {
2935        // No native loop: create the root container, hand off, return. Tests drive via
2936        // MockProbe::emit + day_reactive::flush_sync.
2937        let root = self.realize(kinds::CONTAINER, &ContainerProps::default(), NodeId(0));
2938        MOCK_WINDOW.with(|w| w.set(options.size));
2939        ready(self, root, options.size);
2940    }
2941
2942    fn post(f: Box<dyn FnOnce() + Send>) {
2943        // No loop to defer to: run immediately (tests are synchronous).
2944        f();
2945    }
2946
2947    fn post_delayed(_ms: u32, f: Box<dyn FnOnce() + Send>) {
2948        // A sleep is where the opt-in list viewport binds (see `viewport_flush`).
2949        viewport_flush();
2950        // The default rides a helper thread home, which has no tree or task table: a sleep in
2951        // a synchronous test is over the moment it starts, on this thread.
2952        f();
2953    }
2954}