Skip to main content

native_gui_mock/
lib.rs

1#![deny(rustdoc::broken_intra_doc_links)]
2use std::collections::{HashMap, HashSet, VecDeque};
3use std::path::PathBuf;
4use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
5use std::sync::{Arc, Condvar, Mutex};
6use std::time::Duration;
7
8#[cfg(feature = "e2e")]
9pub mod e2e;
10#[cfg(feature = "webview")]
11pub mod webview;
12
13use native_gui_core::artprov::IconRole;
14use native_gui_core::error::{GuiError, GuiResult};
15use native_gui_core::events::AccessibleNotification;
16use native_gui_core::pickers::{ColorDialogData, FontDescriptor, FontDialogData, FontEffects};
17use native_gui_core::toolbar::{self, ToolId, ToolInteraction, ToolbarItem, ToolbarOrientation};
18use native_gui_core::widgets::{DataGridModel, RichTextImage};
19use native_gui_core::{
20    AlertLevel, Backend, CalendarDate, CalendarFirstDayOfWeek, CalendarSelectionMode, Color,
21    ColumnSpec, ContainerDirection, ContainerWrap, DragCapabilities, DragPayload, DragPayloadKind,
22    DragSessionId, DragSourceOptions, DragTargetOptions, DropCancelReason, FileChooserMode,
23    GpuDegradationPolicy, GpuSurfaceCapabilities, ImageData, ImageFit, ImageResourceCapabilities,
24    ImageResourceId, LabelAlignment, LabelWrap, LoopFlow, MenuId, MenuItemId, MotionCapabilities,
25    PopupDismissReason, ShowEffect, TextRun, TimerCapabilities, TimerFire, TimerId, TimerSpec,
26    TimerStopPolicy, TrayIconId, TrayIconSpec, Ui, UiEvent, WidgetId, WidgetKind, WidgetProperty,
27    WidgetSpec, WindowCapabilities, WindowOptions, WindowRole,
28};
29
30pub use native_gui_core::image_resource::{
31    AnimationData, AnimationFrame, AnimationResourceId, LoopCount,
32};
33
34/// One frame of the scripted modal-loop stack.
35///
36/// A frame is the Mock analogue of a nested OS message pump (`MessageBoxW`,
37/// drag-and-drop, `gtk_dialog_run`): while it is open, its script is what the
38/// nested loop delivers, and the outer event queue stays parked until the
39/// loop closes.
40#[derive(Debug, Default, Clone)]
41pub struct MockModalFrame {
42    /// Events the nested pump delivers, FIFO.
43    pub script: VecDeque<UiEvent>,
44    /// How many scripted events the nested pump has delivered so far.
45    pub delivered: usize,
46}
47
48/// A virtual data-grid model retained by the Mock backend.
49///
50/// `WidgetSpec` has no slot for the boxed model: `Ui::set_data_grid_model`
51/// hands it straight to the lane, so the backend owns it. The shared
52/// [`DataGridModel`] trait is object-safe without a `Debug` bound, so this
53/// newtype supplies the `Debug` impl `MockBackend`'s derive needs while the
54/// model stays reachable through [`MockBackend::data_grid_model`].
55pub struct RetainedDataGridModel(Box<dyn DataGridModel>);
56
57impl std::fmt::Debug for RetainedDataGridModel {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        f.debug_struct("RetainedDataGridModel")
60            .field("row_count", &self.0.row_count())
61            .field("col_count", &self.0.col_count())
62            .finish()
63    }
64}
65
66/// Window transition invocation recorded by Mock.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum MockWindowEffect {
69    Show {
70        widget_id: WidgetId,
71        effect: ShowEffect,
72    },
73    Hide {
74        widget_id: WidgetId,
75        effect: ShowEffect,
76    },
77}
78
79#[derive(Debug, Clone)]
80struct MockDragSession {
81    id: DragSessionId,
82    source: WidgetId,
83    kinds: Vec<DragPayloadKind>,
84    target: Option<WidgetId>,
85}
86
87#[derive(Debug, Clone, Copy)]
88struct MockTimer {
89    spec: TimerSpec,
90    started_at: Duration,
91    deadline: Duration,
92    widget_scope: Option<(WidgetId, TimerStopPolicy)>,
93}
94
95#[derive(Debug, Clone, Copy)]
96struct TimerDelivery {
97    deadline: Duration,
98    fire: TimerFire,
99    widget_scope: Option<(WidgetId, TimerStopPolicy)>,
100}
101
102fn duration_from_nanos(nanos: u128) -> Option<Duration> {
103    const NANOS_PER_SECOND: u128 = 1_000_000_000;
104    let seconds = u64::try_from(nanos / NANOS_PER_SECOND).ok()?;
105    let subsecond_nanos = u32::try_from(nanos % NANOS_PER_SECOND).ok()?;
106    Some(Duration::new(seconds, subsecond_nanos))
107}
108
109/// Mock-side harness for [`native_gui_core::widgets::WindowedDataGridModel`].
110///
111/// A windowed model never fetches synchronously: `value_at` records a
112/// request and signals a repaint, and the UI thread applies results later
113/// through a [`native_gui_core::widgets::WindowedDataGridHandle`]. These fixtures
114/// provide the producer half of that protocol in tests - no UI event loop,
115/// no threads unless the test wants one:
116///
117/// * [`windowed_fixture::MockRowProducer`] receives the queued row requests
118///   and applies scripted rows to a handle exactly when the test serves
119///   them;
120/// * [`windowed_fixture::RepaintCounter`] counts the model's repaint
121///   signals.
122///
123/// The retained-model accessors on [`MockBackend`] remain the read path
124/// (`data_grid_model`, `data_grid_model_is_row_resident`, ...).
125#[doc(hidden)]
126pub mod windowed_fixture {
127    use native_gui_core::widgets::{WindowedDataGridHandle, WindowedDelivery};
128    use std::collections::HashMap;
129    use std::sync::atomic::{AtomicUsize, Ordering};
130    use std::sync::mpsc::{self, Receiver, TryRecvError};
131    use std::sync::Arc;
132
133    /// Counts a windowed model's repaint signals from any thread.
134    ///
135    /// Hand [`RepaintCounter::hook`] to `WindowedDataGridModel::new` and
136    /// assert on [`RepaintCounter::count`]; every hook the instance hands
137    /// out shares the counter.
138    #[derive(Debug, Default, Clone)]
139    pub struct RepaintCounter {
140        count: Arc<AtomicUsize>,
141    }
142
143    impl RepaintCounter {
144        /// Creates a zeroed counter.
145        pub fn new() -> Self {
146            Self::default()
147        }
148
149        /// The hook to hand to the model constructor.
150        pub fn hook(&self) -> impl Fn() + 'static {
151            let count = Arc::clone(&self.count);
152            move || {
153                count.fetch_add(1, Ordering::SeqCst);
154            }
155        }
156
157        /// Repaint signals observed so far.
158        pub fn count(&self) -> usize {
159            self.count.load(Ordering::SeqCst)
160        }
161    }
162
163    /// Test-controlled producer for the windowed model's load protocol.
164    ///
165    /// [`Self::new`] returns the producer plus the request hook to hand to
166    /// `WindowedDataGridModel::new`; the producer owns the receiver, so
167    /// dropping or replacing the model surfaces here as a closed channel
168    /// (see [`Self::sender_dropped`]), mirroring the fail-closed production
169    /// contract.
170    ///
171    /// Rows are answered only when the test asks: script them with
172    /// [`Self::script_row`] or install a [`Self::set_default_cells`]
173    /// generator, then call [`Self::serve_next`]/[`Self::serve_pending`].
174    pub struct MockRowProducer {
175        requests: Receiver<usize>,
176        observed: Vec<usize>,
177        scripted: HashMap<usize, Vec<String>>,
178        default_cells: Option<Box<dyn Fn(usize) -> Vec<String>>>,
179    }
180
181    impl MockRowProducer {
182        /// Creates the producer and the request hook for the model
183        /// constructor.
184        pub fn new() -> (Self, impl Fn(usize) + 'static) {
185            let (sender, requests) = mpsc::channel();
186            let producer = Self {
187                requests,
188                observed: Vec::new(),
189                scripted: HashMap::new(),
190                default_cells: None,
191            };
192            let hook = move |row: usize| {
193                // A send failure means the model was dropped with the
194                // producer still queued; the producer side observes the
195                // close through `sender_dropped`.
196                let _ = sender.send(row);
197            };
198            (producer, hook)
199        }
200
201        /// Scripts the cells served for `row`.
202        pub fn script_row(&mut self, row: usize, cells: Vec<String>) {
203            self.scripted.insert(row, cells);
204        }
205
206        /// Installs the fallback generator used for rows without a scripted
207        /// answer (default: `["row {row}"]`).
208        pub fn set_default_cells(&mut self, generator: impl Fn(usize) -> Vec<String> + 'static) {
209            self.default_cells = Some(Box::new(generator));
210        }
211
212        /// Every request observed so far, in request order (served, next,
213        /// or drained by [`Self::sender_dropped`]).
214        pub fn observed_requests(&self) -> &[usize] {
215            &self.observed
216        }
217
218        /// Pops the next queued request, FIFO, recording it. `None` when no
219        /// request is queued (or the model is gone with the queue drained).
220        pub fn next_request(&mut self) -> Option<usize> {
221            match self.requests.try_recv() {
222                Ok(row) => {
223                    self.observed.push(row);
224                    Some(row)
225                }
226                Err(TryRecvError::Empty) | Err(TryRecvError::Disconnected) => None,
227            }
228        }
229
230        /// Serves one queued request to `handle`: applies the scripted row
231        /// (or the default generator's cells). Returns the row and the
232        /// delivery outcome, or `None` when no request is queued.
233        pub fn serve_next(
234            &mut self,
235            handle: &WindowedDataGridHandle,
236        ) -> Option<(usize, WindowedDelivery)> {
237            let row = self.next_request()?;
238            let cells = self.cells_for(row);
239            let delivery = handle.deliver_row(row, cells);
240            Some((row, delivery))
241        }
242
243        /// Serves every queued request, FIFO.
244        pub fn serve_pending(
245            &mut self,
246            handle: &WindowedDataGridHandle,
247        ) -> Vec<(usize, WindowedDelivery)> {
248            let mut served = Vec::new();
249            while let Some(outcome) = self.serve_next(handle) {
250                served.push(outcome);
251            }
252            served
253        }
254
255        /// Drains and records every queued request, then reports whether the
256        /// model's hook was dropped (the model was dropped or replaced). A
257        /// real worker loop reacts to the same disconnect by stopping.
258        pub fn sender_dropped(&mut self) -> bool {
259            loop {
260                match self.requests.try_recv() {
261                    Ok(row) => self.observed.push(row),
262                    Err(TryRecvError::Empty) => return false,
263                    Err(TryRecvError::Disconnected) => return true,
264                }
265            }
266        }
267
268        fn cells_for(&self, row: usize) -> Vec<String> {
269            if let Some(cells) = self.scripted.get(&row) {
270                return cells.clone();
271            }
272            if let Some(generator) = &self.default_cells {
273                return generator(row);
274            }
275            vec![format!("row {row}")]
276        }
277    }
278}
279
280/// Mock state representation of an active system tray icon.
281#[derive(Debug, Clone, PartialEq, Eq)]
282pub struct MockTrayIconState {
283    pub id: TrayIconId,
284    pub tooltip: String,
285    pub menu: Option<MenuId>,
286    pub visible: bool,
287    pub icon_bytes: Option<Vec<u8>>,
288}
289
290impl From<&TrayIconSpec> for MockTrayIconState {
291    fn from(spec: &TrayIconSpec) -> Self {
292        Self {
293            id: spec.id,
294            tooltip: spec.tooltip.clone(),
295            menu: spec.menu,
296            visible: spec.visible,
297            icon_bytes: spec.icon_bytes.clone(),
298        }
299    }
300}
301
302/// Playback state for an animated image widget in `MockBackend`.
303#[derive(Debug, Clone, PartialEq, Eq)]
304pub struct MockAnimationState {
305    /// The animation resource being played.
306    pub resource_id: AnimationResourceId,
307    /// Current 0-based frame index in `AnimationData.frames`.
308    pub current_frame: usize,
309    /// Number of completed animation loop cycles.
310    pub completed_loops: u32,
311    /// Whether the animation is currently playing (vs stopped).
312    pub playing: bool,
313    /// Whether playback is paused due to the widget being hidden.
314    pub paused: bool,
315    /// Virtual-clock deadline when the current frame ends.
316    pub next_deadline: Option<Duration>,
317    /// Remaining display time for the current frame when paused.
318    pub remaining_in_frame: Option<Duration>,
319    /// Whether a finite-loop animation has finished all loops.
320    pub finished: bool,
321}
322
323#[derive(Debug, Default)]
324pub struct MockBackend {
325    pub created: HashMap<WidgetId, WidgetSpec>,
326    /// Per-widget count of `set_size` geometry applications
327    /// (layout-bound assertions); the values themselves still land on
328    /// `created` exactly as before.
329    pub size_writes: HashMap<WidgetId, usize>,
330    /// Per-widget count of `set_position` geometry applications.
331    pub position_writes: HashMap<WidgetId, usize>,
332    /// Layout size floors recorded by `set_min_size`, so a portable
333    /// test can assert the shared API forwards the floor to the backend that
334    /// owns its automatic layout. An absent entry means "no minimum".
335    pub min_sizes: HashMap<WidgetId, (i32, i32)>,
336    /// `natural_size` probe count. Mock never measures, so the
337    /// return value stays `None` - this counter is pure instrumentation for
338    /// the layout invalidation-bound tests.
339    pub natural_size_probes: AtomicUsize,
340    /// Opt-in deterministic natural sizes (found while dogfooding): when `true`,
341    /// `natural_size` reports a fixed per-kind size (see
342    /// [`MockBackend::mock_natural_size`]) so layouts can be asserted
343    /// headlessly. Off by default, so existing Mock layouts are unchanged.
344    pub natural_sizes: bool,
345    /// Fixture anchor index per keyed row widget (`visible_anchor_index`);
346    /// an absent entry means "no observable scroll position".
347    pub scroll_anchors: HashMap<WidgetId, usize>,
348    /// Number of rows visible from the fixture anchor, for follow-tail tests.
349    pub visible_row_counts: HashMap<WidgetId, usize>,
350    /// Injected failures for keyed-row scroll restoration.
351    pub scroll_failures: HashMap<WidgetId, GuiError>,
352    /// `scroll_to_row` calls recorded in order.
353    pub scroll_requests: Vec<(WidgetId, usize)>,
354    /// Widget ids passed to `clear_selection`, in call order.
355    pub selection_clears: Vec<WidgetId>,
356    /// Per-widget count of `set_data_list_items`/`set_data_grid_rows`
357    /// applications (keyed no-op assertions).
358    pub row_writes: HashMap<WidgetId, usize>,
359    /// Row operations passed to `apply_row_delta`, in call order.
360    pub applied_row_ops: Vec<(WidgetId, Vec<native_gui_core::widgets::RowOp>)>,
361    pub shown: Vec<WidgetId>,
362    /// Widget that currently holds keyboard focus.
363    pub focused: Option<WidgetId>,
364    /// Active theme recorded by `set_theme`.
365    pub theme: Option<native_gui_core::Theme>,
366    /// Per-widget theme overrides recorded by `set_theme_override`.
367    pub theme_overrides: HashMap<WidgetId, Vec<native_gui_core::ThemeOverride>>,
368    /// Native spell-check flags recorded by `set_spell_check`.
369    pub spell_check: HashMap<WidgetId, bool>,
370    /// Inject a live mouse/caret selection in character offsets. When absent,
371    /// text_selection reports unsupported, leaving model-only tests unchanged.
372    pub user_text_selections: HashMap<WidgetId, (usize, usize)>,
373    /// Monospace font rendering flag recorded by `set_monospace`.
374    pub monospace: HashMap<WidgetId, bool>,
375    /// Colour-dialog outcomes injected by `inject_color_dialog_result`;
376    /// an absent entry means "cancelled" so activation stays
377    /// deterministic without a fixture.
378    pub color_dialog_results: HashMap<WidgetId, Option<native_gui_core::Rgba>>,
379    /// Font-dialog outcomes injected by `inject_font_dialog_result`;
380    /// an absent entry means "cancelled".
381    pub font_dialog_results: HashMap<WidgetId, Option<(FontDescriptor, FontEffects)>>,
382    /// System light/dark preference injected by `inject_system_theme_mode`;
383    /// `None` models "unknown / no detection".
384    pub system_theme: Option<native_gui_core::ThemeMode>,
385    /// Detection capability flags reported by `theme_capabilities`.
386    pub theme_capabilities: native_gui_core::ThemeCapabilities,
387    /// Display fixture reported by `displays`; empty until a
388    /// fixture calls `set_displays`.
389    pub displays: Vec<native_gui_core::DisplayInfo>,
390    /// Display capability flags reported by `display_capabilities`.
391    pub display_capabilities: native_gui_core::DisplayCapabilities,
392    /// Optional GPU capability profile; the default is the fully enabled
393    /// deterministic Mock profile.
394    pub gpu_surface_capabilities_override: Option<GpuSurfaceCapabilities>,
395    /// Degraded Vulkan canvas policies recorded by `create_gpu_fallback`.
396    pub gpu_fallbacks: HashMap<WidgetId, GpuDegradationPolicy>,
397    pub events: VecDeque<UiEvent>,
398    /// Accessibility notification requests made by `Ui`, in call order.
399    pub posted_accessible_notifications: Vec<(WidgetId, AccessibleNotification)>,
400    /// Stack of open scripted modal loops; empty outside a
401    /// modal operation, where delivery is the plain FIFO `events` queue.
402    /// While a frame is open its script takes over delivery and `events`
403    /// stays parked, modelling a nested OS message pump.
404    pub modal_loops: Vec<MockModalFrame>,
405    pub menus: HashMap<MenuId, Vec<MenuItemId>>,
406    pub menu_shortcuts: HashMap<MenuItemId, String>,
407    pub clipboard: Option<String>,
408    /// Image returned by `paste_image_from_clipboard` (tests).
409    pub clipboard_image: Option<native_gui_core::widgets::ClipboardImage>,
410    pub context_menus: HashMap<WidgetId, MenuId>,
411    /// Active system tray icons registered with this backend.
412    pub tray_icons: HashMap<TrayIconId, MockTrayIconState>,
413    /// Requests recorded by `show_confirm_dialog`: `(token, title, message)`.
414    pub confirm_requests: Vec<(u64, String, String)>,
415    /// Requests recorded by `show_file_dialog` (found while dogfooding): `(token,
416    /// request)`. Answer one with [`MockBackend::inject_file_dialog_result`].
417    pub file_dialog_requests: Vec<(u64, native_gui_core::file_dialog::FileDialog)>,
418    /// Per-window close-request interception flags; a guarded
419    /// window reports `CloseRequested` instead of `WindowClosed`.
420    pub close_guards: HashMap<WidgetId, bool>,
421    /// Window options recorded by the extended-window contract.
422    pub window_options: HashMap<WidgetId, WindowOptions>,
423    /// Explicit fixture override; `None` selects Mock's verified v0 profile.
424    pub window_capabilities_override: Option<WindowCapabilities>,
425    /// Popups with a currently open dismissal session.
426    active_popup_sessions: HashSet<WidgetId>,
427    /// Non-blocking show/hide effects requested by the last lifecycle calls.
428    pub window_effects: Vec<MockWindowEffect>,
429    /// Drag-and-drop source and target configurations, kept separate from row drags.
430    pub drag_source_options: HashMap<WidgetId, DragSourceOptions>,
431    pub drag_target_options: HashMap<WidgetId, DragTargetOptions>,
432    /// Loaded typed RGBA8 image resources.
433    pub image_resources: HashMap<ImageResourceId, ImageData>,
434    /// Capability override for typed image-resource refusal fixtures.
435    pub image_resource_capabilities_override: Option<ImageResourceCapabilities>,
436    /// Loaded animation resources.
437    pub animation_resources: HashMap<AnimationResourceId, AnimationData>,
438    next_animation_resource_id: u64,
439    /// Active animated image playback state per Image widget.
440    pub active_animations: HashMap<WidgetId, MockAnimationState>,
441    /// Currently displayed image resource per Image widget.
442    pub widget_image_resources: HashMap<WidgetId, ImageResourceId>,
443    /// Recorded finished animation events for finite loop count completions.
444    pub animation_finished_events: Vec<WidgetId>,
445    /// Capability override for typed-refusal fixtures.
446    pub drag_capabilities_override: Option<DragCapabilities>,
447    /// The sole active drag-and-drop session, if one has begun.
448    active_drag: Option<MockDragSession>,
449    next_drag_session: u64,
450    /// Mock's monotonic virtual clock and timers.
451    virtual_now: Duration,
452    timers: HashMap<TimerId, MockTimer>,
453    pending_timer_events: HashMap<TimerId, (Option<(WidgetId, TimerStopPolicy)>, usize)>,
454    /// Capability override for timer refusal fixtures.
455    pub timer_capabilities_override: Option<TimerCapabilities>,
456    /// Capability override for typed motion-refusal fixtures.
457    pub motion_capabilities_override: Option<MotionCapabilities>,
458    /// Menu-item enable state recorded by `set_menu_item_enabled`.
459    pub menu_item_enabled: HashMap<MenuItemId, bool>,
460    /// Live menu-item labels: set at creation, replaced by
461    /// `set_menu_item_text`, dropped with the item.
462    pub menu_item_text: HashMap<MenuItemId, String>,
463    /// Row slot minted for each submenu by the shared model, so submenu rows
464    /// live in the same ordered list as items without sharing their id space.
465    pub menu_submenu_slots: HashMap<MenuId, MenuItemId>,
466    /// Inline images recorded by .
467    pub rich_text_images: HashMap<WidgetId, Vec<RichTextImage>>,
468    pub last_canvas_scene: Option<native_gui_core::CanvasScene>,
469    /// Last surface recorded by `set_canvas_surface`.
470    pub last_canvas_surface: Option<native_gui_core::CanvasSurface>,
471    /// Per-row height overrides recorded by `set_data_grid_row_height`;
472    /// absent rows keep the backend default.
473    pub data_grid_row_heights: HashMap<(WidgetId, usize), i32>,
474    /// Per-column width overrides recorded by `set_data_grid_col_width`.
475    pub data_grid_col_widths: HashMap<(WidgetId, usize), i32>,
476    /// Virtual data-grid models retained per widget by `set_data_grid_model`.
477    /// The Mock keeps the boxed model itself and never expands it
478    /// into `WidgetSpec::data_grid_rows`, so a fixture can prove a virtual
479    /// grid stayed virtual.
480    pub data_grid_models: HashMap<WidgetId, RetainedDataGridModel>,
481    /// Cell selections recorded by `set_data_grid_selection`.
482    pub data_grid_selections: HashMap<WidgetId, Vec<(usize, usize)>>,
483    /// WebViews created by `create_webview`, by host.
484    #[cfg(feature = "webview")]
485    pub webviews: HashMap<WidgetId, webview::MockWebView>,
486    /// Makes `webview_engine` and `create_webview` report a missing engine.
487    #[cfg(feature = "webview")]
488    pub webview_runtime_missing: bool,
489    /// Advanced family hosts recorded by `host_advanced_control`.
490    #[cfg(feature = "property-grid")]
491    pub advanced_hosts: std::collections::HashSet<WidgetId>,
492    /// Diagnostic engine record injected by tests (`None` = engine-free Mock).
493    #[cfg(feature = "property-grid")]
494    pub advanced_engine: Option<native_gui_core::advanced::EngineInfo>,
495    /// Bound PropertyGrid models per host.
496    #[cfg(feature = "property-grid")]
497    pub property_grid_models: HashMap<WidgetId, native_gui_core::PropertyModel>,
498    /// Node ids applied through `set_property_value`, in call order.
499    #[cfg(feature = "property-grid")]
500    pub property_grid_applied: Vec<(WidgetId, native_gui_core::PropertyId)>,
501    /// Coalesced refresh counts per host.
502    #[cfg(feature = "property-grid")]
503    pub property_grid_refreshes: HashMap<WidgetId, usize>,
504    /// Per-widget natural size overrides injected by layout tests (e.g.
505    /// `Some((0, 0))` for chrome-hosted toolbars).
506    natural_size_overrides: HashMap<WidgetId, (i32, i32)>,
507    /// Optional per-instance override returned by [`Backend::data_dir`] so
508    /// concurrent tests isolate persisted state outside `std::env::temp_dir()`.
509    pub app_data_dir: Option<PathBuf>,
510    /// Set by `UiProxy` posts; `wait_event`/`poll_event` report the internal
511    /// `UiEvent::TasksPending` once per set so `Ui` can drain the queue.
512    wake_flag: Arc<AtomicBool>,
513    /// Parking signal: `UiProxy` posts and `push_event` notify it so a
514    /// blocked `wait_event` returns promptly instead of waiting for the
515    /// 5 ms poll timeout.
516    wake_signal: Arc<(Mutex<()>, Condvar)>,
517}
518
519impl MockBackend {
520    /// A Mock backend whose leaves report deterministic natural sizes, so
521    /// `Ui::compute_layout` produces realistic, assertable geometry headlessly
522    /// (rows as tall as their tallest control, text-sized buttons, ...).
523    ///
524    /// ```
525    /// use native_gui_core::ui::Ui;
526    /// use native_gui_core::widgets::{ContainerDirection, WidgetKind};
527    /// use native_gui_mock::MockBackend;
528    ///
529    /// let mut ui = Ui::new(MockBackend::with_natural_sizes());
530    /// let window = ui.create(WidgetKind::Window, Some("w")).unwrap();
531    /// let column = ui.create(WidgetKind::Container, None).unwrap();
532    /// ui.set_container_direction(column, ContainerDirection::Vertical).unwrap();
533    /// let row = ui.create(WidgetKind::Container, None).unwrap();
534    /// ui.set_container_direction(row, ContainerDirection::Horizontal).unwrap();
535    /// let ok = ui.create(WidgetKind::Button, Some("OK")).unwrap();
536    /// ui.attach(window, column).unwrap();
537    /// ui.attach(column, row).unwrap();
538    /// ui.attach(row, ok).unwrap();
539    /// ui.set_layout_root(window).unwrap();
540    /// ui.compute_layout(window, 400.0, 300.0).unwrap();
541    /// assert_eq!(ui.layout_rect(row).unwrap().height, 32.0);
542    /// ```
543    pub fn with_natural_sizes() -> Self {
544        Self {
545            natural_sizes: true,
546            ..Self::default()
547        }
548    }
549
550    /// Overrides [`Backend::data_dir`] with an isolated test directory so
551    /// concurrent tests do not share persistence files under `std::env::temp_dir()`.
552    pub fn with_data_dir(mut self, dir: impl Into<PathBuf>) -> Self {
553        self.app_data_dir = Some(dir.into());
554        self
555    }
556
557    /// The deterministic natural size Mock reports for `spec` when
558    /// [`MockBackend::natural_sizes`] is on: 8 px per character of text plus
559    /// window decorations, and fixed sizes for editors, lists and canvases. Containers
560    /// and windows report `None` (they are measured from their children).
561    pub fn mock_natural_size(spec: &WidgetSpec) -> Option<(i32, i32)> {
562        let chars = spec
563            .text
564            .as_deref()
565            .unwrap_or("")
566            .lines()
567            .map(|line| line.chars().count())
568            .max()
569            .unwrap_or(0) as i32;
570        let text_w = chars * 8;
571        Some(match spec.kind {
572            WidgetKind::Window | WidgetKind::Container => return None,
573            #[cfg(feature = "widgets-containers")]
574            WidgetKind::SplitPane => return None,
575            WidgetKind::Label => (text_w.max(8), 20),
576            WidgetKind::Button => ((text_w + 24).max(64), 32),
577            #[cfg(feature = "widgets-choice")]
578            WidgetKind::Checkbox | WidgetKind::RadioButton => (text_w + 24, 24),
579            #[cfg(feature = "widgets-text")]
580            WidgetKind::TextInput => (160, 32),
581            #[cfg(feature = "widgets-text")]
582            WidgetKind::TextArea | WidgetKind::RichText => (240, 96),
583            #[cfg(feature = "widgets-choice")]
584            WidgetKind::ComboBox => (120, 32),
585            #[cfg(feature = "widgets-range")]
586            WidgetKind::Slider | WidgetKind::ProgressBar => (160, 24),
587            #[cfg(feature = "widgets-range")]
588            WidgetKind::SpinBox => (96, 32),
589            #[cfg(feature = "widgets-data")]
590            WidgetKind::DataGrid
591            | WidgetKind::DataList
592            | WidgetKind::ListView
593            | WidgetKind::TreeView => (240, 160),
594            _ => (100, 32),
595        })
596    }
597
598    fn default_image_resource_capabilities() -> ImageResourceCapabilities {
599        ImageResourceCapabilities {
600            rgba: true,
601            image_animation: true,
602            animation_decode: false,
603        }
604    }
605
606    /// Overrides typed image-resource support for refusal tests.
607    pub fn set_image_resource_capabilities(&mut self, capabilities: ImageResourceCapabilities) {
608        self.image_resource_capabilities_override = Some(capabilities);
609    }
610
611    /// Overrides the natural size reported for `widget_id`.
612    pub fn set_natural_size_override(&mut self, widget_id: WidgetId, size: (i32, i32)) {
613        self.natural_size_overrides.insert(widget_id, size);
614    }
615
616    /// Looks up the pixels retained for a live image resource.
617    pub fn image_resource(&self, resource: ImageResourceId) -> Option<&ImageData> {
618        self.image_resources.get(&resource)
619    }
620
621    /// Loads a pre-decoded animated image resource into this backend.
622    pub fn load_animation_resource(
623        &mut self,
624        data: &AnimationData,
625    ) -> GuiResult<AnimationResourceId> {
626        if !self.image_resource_capabilities().image_animation {
627            return Err(GuiError::UnsupportedCapability(
628                "image_animation".to_owned(),
629            ));
630        }
631        data.validate()?;
632        for frame in &data.frames {
633            if !self.image_resources.contains_key(&frame.image) {
634                return Err(GuiError::Backend(format!(
635                    "Image resource not found: {}",
636                    frame.image.0
637                )));
638            }
639        }
640        let next =
641            self.next_animation_resource_id
642                .checked_add(1)
643                .ok_or(GuiError::ResourceExhausted {
644                    operation: "animation resource id allocation",
645                    code: None,
646                })?;
647        let resource_id = AnimationResourceId(next);
648        self.next_animation_resource_id = next;
649        self.animation_resources.insert(resource_id, data.clone());
650        Ok(resource_id)
651    }
652
653    /// Releases a loaded animated image resource from this backend.
654    pub fn release_animation_resource(&mut self, id: AnimationResourceId) -> GuiResult<()> {
655        if !self.image_resource_capabilities().image_animation {
656            return Err(GuiError::UnsupportedCapability(
657                "image_animation".to_owned(),
658            ));
659        }
660        if self.animation_resources.remove(&id).is_none() {
661            return Err(GuiError::Backend(format!(
662                "Animation resource not found: {}",
663                id.0
664            )));
665        }
666        let widgets_using: Vec<WidgetId> = self
667            .active_animations
668            .iter()
669            .filter_map(|(wid, state)| (state.resource_id == id).then_some(*wid))
670            .collect();
671        for wid in widgets_using {
672            self.active_animations.remove(&wid);
673            self.widget_image_resources.remove(&wid);
674        }
675        Ok(())
676    }
677
678    /// Looks up a loaded animation resource.
679    pub fn animation_resource(&self, id: AnimationResourceId) -> Option<&AnimationData> {
680        self.animation_resources.get(&id)
681    }
682
683    /// Rejects encoded animation blobs with the typed gate `animation_decode`.
684    pub fn decode_animation_resource(&mut self, _bytes: &[u8]) -> GuiResult<AnimationResourceId> {
685        if !self.image_resource_capabilities().animation_decode {
686            return Err(GuiError::UnsupportedCapability(
687                "animation_decode".to_owned(),
688            ));
689        }
690        Err(GuiError::UnsupportedCapability(
691            "animation_decode".to_owned(),
692        ))
693    }
694
695    /// Assigns an animated image resource to an Image widget and autoplays from frame 0.
696    ///
697    /// Passing `None` stops and clears any active animation on the widget.
698    pub fn set_image_animation(
699        &mut self,
700        widget_id: WidgetId,
701        animation: Option<AnimationResourceId>,
702    ) -> GuiResult<()> {
703        let Some(spec) = self.created.get_mut(&widget_id) else {
704            return Err(GuiError::WidgetNotFound(widget_id.0));
705        };
706        spec.ensure_property(WidgetProperty::ImageSource)?;
707
708        if !self.image_resource_capabilities().image_animation {
709            return Err(GuiError::UnsupportedCapability(
710                "image_animation".to_owned(),
711            ));
712        }
713
714        let Some(anim_id) = animation else {
715            self.active_animations.remove(&widget_id);
716            self.widget_image_resources.remove(&widget_id);
717            return Ok(());
718        };
719
720        let data = self.animation_resources.get(&anim_id).ok_or_else(|| {
721            GuiError::Backend(format!("Animation resource not found: {}", anim_id.0))
722        })?;
723
724        let is_shown = self.shown.contains(&widget_id);
725        let first_frame_image = data.frames[0].image;
726        let first_frame_delay = data.frames[0].delay;
727
728        let state = MockAnimationState {
729            resource_id: anim_id,
730            current_frame: 0,
731            completed_loops: 0,
732            playing: true,
733            paused: !is_shown,
734            next_deadline: if is_shown {
735                Some(
736                    self.virtual_now
737                        .checked_add(first_frame_delay)
738                        .ok_or_else(|| {
739                            GuiError::Backend("Mock animation deadline overflow".to_owned())
740                        })?,
741                )
742            } else {
743                None
744            },
745            remaining_in_frame: if !is_shown {
746                Some(first_frame_delay)
747            } else {
748                None
749            },
750            finished: false,
751        };
752
753        self.active_animations.insert(widget_id, state);
754        self.widget_image_resources
755            .insert(widget_id, first_frame_image);
756        Ok(())
757    }
758
759    /// Restarts playback of an assigned animation from frame 0.
760    pub fn start_image_animation(&mut self, widget_id: WidgetId) -> GuiResult<()> {
761        let Some(spec) = self.created.get_mut(&widget_id) else {
762            return Err(GuiError::WidgetNotFound(widget_id.0));
763        };
764        spec.ensure_property(WidgetProperty::ImageSource)?;
765
766        if !self.image_resource_capabilities().image_animation {
767            return Err(GuiError::UnsupportedCapability(
768                "image_animation".to_owned(),
769            ));
770        }
771
772        let state = self.active_animations.get_mut(&widget_id).ok_or_else(|| {
773            GuiError::Backend(format!("No animation assigned to widget: {}", widget_id.0))
774        })?;
775
776        let data = self
777            .animation_resources
778            .get(&state.resource_id)
779            .ok_or_else(|| {
780                GuiError::Backend(format!(
781                    "Animation resource not found: {}",
782                    state.resource_id.0
783                ))
784            })?;
785
786        let is_shown = self.shown.contains(&widget_id);
787        let first_frame_image = data.frames[0].image;
788        let first_frame_delay = data.frames[0].delay;
789
790        state.current_frame = 0;
791        state.completed_loops = 0;
792        state.playing = true;
793        state.paused = !is_shown;
794        state.finished = false;
795        state.next_deadline = if is_shown {
796            Some(
797                self.virtual_now
798                    .checked_add(first_frame_delay)
799                    .ok_or_else(|| {
800                        GuiError::Backend("Mock animation deadline overflow".to_owned())
801                    })?,
802            )
803        } else {
804            None
805        };
806        state.remaining_in_frame = if !is_shown {
807            Some(first_frame_delay)
808        } else {
809            None
810        };
811
812        self.widget_image_resources
813            .insert(widget_id, first_frame_image);
814        Ok(())
815    }
816
817    /// Stops playback and resets the displayed frame to frame 0.
818    pub fn stop_image_animation(&mut self, widget_id: WidgetId) -> GuiResult<()> {
819        let Some(spec) = self.created.get_mut(&widget_id) else {
820            return Err(GuiError::WidgetNotFound(widget_id.0));
821        };
822        spec.ensure_property(WidgetProperty::ImageSource)?;
823
824        if !self.image_resource_capabilities().image_animation {
825            return Err(GuiError::UnsupportedCapability(
826                "image_animation".to_owned(),
827            ));
828        }
829
830        let state = self.active_animations.get_mut(&widget_id).ok_or_else(|| {
831            GuiError::Backend(format!("No animation assigned to widget: {}", widget_id.0))
832        })?;
833
834        let data = self
835            .animation_resources
836            .get(&state.resource_id)
837            .ok_or_else(|| {
838                GuiError::Backend(format!(
839                    "Animation resource not found: {}",
840                    state.resource_id.0
841                ))
842            })?;
843
844        state.playing = false;
845        state.paused = false;
846        state.finished = false;
847        state.current_frame = 0;
848        state.next_deadline = None;
849        state.remaining_in_frame = None;
850
851        self.widget_image_resources
852            .insert(widget_id, data.frames[0].image);
853        Ok(())
854    }
855
856    /// Returns the currently displayed image resource for an Image widget.
857    pub fn widget_current_image_resource(&self, widget_id: WidgetId) -> Option<ImageResourceId> {
858        self.widget_image_resources.get(&widget_id).copied()
859    }
860
861    /// Returns the animation playback state for an Image widget.
862    pub fn widget_animation_state(&self, widget_id: WidgetId) -> Option<&MockAnimationState> {
863        self.active_animations.get(&widget_id)
864    }
865
866    /// Returns recorded animation finished events.
867    pub fn animation_finished_events(&self) -> &[WidgetId] {
868        &self.animation_finished_events
869    }
870
871    /// Takes recorded animation finished events, draining the buffer.
872    pub fn take_animation_finished_events(&mut self) -> Vec<WidgetId> {
873        std::mem::take(&mut self.animation_finished_events)
874    }
875
876    fn pause_animation_on_hide(&mut self, widget_id: WidgetId) {
877        if let Some(state) = self.active_animations.get_mut(&widget_id) {
878            if state.playing && !state.paused && !state.finished {
879                let remaining = state
880                    .next_deadline
881                    .map(|dl| dl.saturating_sub(self.virtual_now))
882                    .unwrap_or(Duration::ZERO);
883                state.remaining_in_frame = Some(remaining);
884                state.next_deadline = None;
885                state.paused = true;
886            }
887        }
888    }
889
890    fn resume_animation_on_show(&mut self, widget_id: WidgetId) -> GuiResult<()> {
891        if let Some(state) = self.active_animations.get_mut(&widget_id) {
892            if state.playing && state.paused && !state.finished {
893                let delay = state.remaining_in_frame.take().unwrap_or(Duration::ZERO);
894                state.next_deadline =
895                    Some(self.virtual_now.checked_add(delay).ok_or_else(|| {
896                        GuiError::Backend("Mock animation deadline overflow".to_owned())
897                    })?);
898                state.paused = false;
899            }
900        }
901        Ok(())
902    }
903
904    fn cleanup_animation_on_remove(&mut self, widget_id: WidgetId) {
905        self.active_animations.remove(&widget_id);
906        self.widget_image_resources.remove(&widget_id);
907    }
908
909    fn next_animation_deadline(&self) -> Option<Duration> {
910        self.active_animations
911            .values()
912            .filter(|anim| anim.playing && !anim.paused && !anim.finished)
913            .filter_map(|anim| anim.next_deadline)
914            .min()
915    }
916
917    fn service_due_animations(&mut self) -> GuiResult<()> {
918        let active_widget_ids: Vec<WidgetId> = self.active_animations.keys().copied().collect();
919        let now = self.virtual_now;
920
921        for widget_id in active_widget_ids {
922            let Some(state) = self.active_animations.get_mut(&widget_id) else {
923                continue;
924            };
925            if !state.playing || state.paused || state.finished {
926                continue;
927            }
928
929            let Some(anim_data) = self.animation_resources.get(&state.resource_id) else {
930                continue;
931            };
932
933            let frames = &anim_data.frames;
934            if frames.is_empty() {
935                continue;
936            }
937
938            while let Some(deadline) = state.next_deadline {
939                if deadline > now {
940                    break;
941                }
942
943                let next_frame = state.current_frame + 1;
944                if next_frame < frames.len() {
945                    state.current_frame = next_frame;
946                    let next_delay = frames[next_frame].delay;
947                    let next_dl = deadline.checked_add(next_delay).ok_or_else(|| {
948                        GuiError::Backend("Mock animation deadline overflow".to_owned())
949                    })?;
950                    state.next_deadline = Some(next_dl);
951                    self.widget_image_resources
952                        .insert(widget_id, frames[next_frame].image);
953                } else {
954                    state.completed_loops += 1;
955                    match anim_data.loop_count {
956                        LoopCount::Count(max_loops) if state.completed_loops >= max_loops => {
957                            state.finished = true;
958                            state.playing = false;
959                            state.next_deadline = None;
960                            self.animation_finished_events.push(widget_id);
961                            break;
962                        }
963                        _ => {
964                            state.current_frame = 0;
965                            let next_delay = frames[0].delay;
966                            let next_dl = deadline.checked_add(next_delay).ok_or_else(|| {
967                                GuiError::Backend("Mock animation deadline overflow".to_owned())
968                            })?;
969                            state.next_deadline = Some(next_dl);
970                            self.widget_image_resources
971                                .insert(widget_id, frames[0].image);
972                        }
973                    }
974                }
975            }
976        }
977        Ok(())
978    }
979
980    fn default_timer_capabilities() -> TimerCapabilities {
981        TimerCapabilities {
982            timers: true,
983            widget_timers: true,
984        }
985    }
986
987    /// Overrides motion support for typed-refusal tests.
988    pub fn set_motion_capabilities(&mut self, capabilities: MotionCapabilities) {
989        self.motion_capabilities_override = Some(capabilities);
990    }
991
992    fn start_mock_timer(
993        &mut self,
994        timer: TimerId,
995        spec: TimerSpec,
996        widget_scope: Option<(WidgetId, TimerStopPolicy)>,
997    ) -> GuiResult<()> {
998        spec.validate()?;
999        let deadline = self
1000            .virtual_now
1001            .checked_add(spec.first_delay)
1002            .ok_or_else(|| GuiError::Backend("Timer deadline overflow".to_owned()))?;
1003        if self.timers.contains_key(&timer) {
1004            return Err(GuiError::Backend(format!(
1005                "Timer already exists: {}",
1006                timer.0
1007            )));
1008        }
1009        self.timers.insert(
1010            timer,
1011            MockTimer {
1012                spec,
1013                started_at: self.virtual_now,
1014                deadline,
1015                widget_scope,
1016            },
1017        );
1018        Ok(())
1019    }
1020
1021    /// Overrides the timer capability profile for refusal tests.
1022    pub fn set_timer_capabilities(&mut self, capabilities: TimerCapabilities) {
1023        self.timer_capabilities_override = Some(capabilities);
1024    }
1025
1026    /// Current virtual time. It advances only through `advance_time` or
1027    /// deterministic `wait_event` auto-advance.
1028    pub fn now(&self) -> Duration {
1029        self.virtual_now
1030    }
1031
1032    /// Advances virtual time and services all due timers without sleeping.
1033    pub fn advance_time(&mut self, amount: Duration) -> GuiResult<()> {
1034        self.virtual_now = self
1035            .virtual_now
1036            .checked_add(amount)
1037            .ok_or_else(|| GuiError::Backend("Mock virtual clock overflow".to_owned()))?;
1038        self.service_due_timers()?;
1039        self.service_due_animations()
1040    }
1041
1042    fn service_due_timers(&mut self) -> GuiResult<()> {
1043        const MAX_UNCOALESCED_FIRES: u128 = 1_000_000;
1044
1045        let now = self.virtual_now;
1046        let due: Vec<_> = self
1047            .timers
1048            .iter()
1049            .filter_map(|(id, timer)| (timer.deadline <= now).then_some((*id, *timer)))
1050            .collect();
1051        let mut deliveries = Vec::new();
1052        let mut completed = Vec::new();
1053        let mut rescheduled = Vec::new();
1054
1055        for (id, timer) in due {
1056            let elapsed = now - timer.started_at;
1057            let Some(interval) = timer.spec.interval else {
1058                deliveries.push(TimerDelivery {
1059                    deadline: timer.deadline,
1060                    fire: TimerFire {
1061                        timer: id,
1062                        elapsed,
1063                        missed: 0,
1064                    },
1065                    widget_scope: timer.widget_scope,
1066                });
1067                completed.push(id);
1068                continue;
1069            };
1070
1071            let due_count = (now - timer.deadline).as_nanos() / interval.as_nanos() + 1;
1072            if timer.spec.coalesce {
1073                let missed =
1074                    u32::try_from(due_count - 1).map_err(|_| GuiError::ResourceExhausted {
1075                        operation: "timer missed-deadline count",
1076                        code: None,
1077                    })?;
1078                deliveries.push(TimerDelivery {
1079                    deadline: timer.deadline,
1080                    fire: TimerFire {
1081                        timer: id,
1082                        elapsed,
1083                        missed,
1084                    },
1085                    widget_scope: timer.widget_scope,
1086                });
1087            } else {
1088                if due_count > MAX_UNCOALESCED_FIRES {
1089                    return Err(GuiError::ResourceExhausted {
1090                        operation: "Mock timer catch-up events",
1091                        code: None,
1092                    });
1093                }
1094                for deadline_index in 0..due_count {
1095                    let deadline_nanos = timer
1096                        .deadline
1097                        .as_nanos()
1098                        .checked_add(interval.as_nanos().checked_mul(deadline_index).ok_or(
1099                            GuiError::ResourceExhausted {
1100                                operation: "Mock timer deadline",
1101                                code: None,
1102                            },
1103                        )?)
1104                        .ok_or(GuiError::ResourceExhausted {
1105                            operation: "Mock timer deadline",
1106                            code: None,
1107                        })?;
1108                    let deadline =
1109                        duration_from_nanos(deadline_nanos).ok_or(GuiError::ResourceExhausted {
1110                            operation: "Mock timer deadline",
1111                            code: None,
1112                        })?;
1113                    deliveries.push(TimerDelivery {
1114                        deadline,
1115                        fire: TimerFire {
1116                            timer: id,
1117                            elapsed,
1118                            missed: 0,
1119                        },
1120                        widget_scope: timer.widget_scope,
1121                    });
1122                }
1123            }
1124
1125            let next_deadline_nanos = timer
1126                .deadline
1127                .as_nanos()
1128                .checked_add(interval.as_nanos().checked_mul(due_count).ok_or(
1129                    GuiError::ResourceExhausted {
1130                        operation: "Mock timer deadline",
1131                        code: None,
1132                    },
1133                )?)
1134                .ok_or(GuiError::ResourceExhausted {
1135                    operation: "Mock timer deadline",
1136                    code: None,
1137                })?;
1138            let next_deadline =
1139                duration_from_nanos(next_deadline_nanos).ok_or(GuiError::ResourceExhausted {
1140                    operation: "Mock timer deadline",
1141                    code: None,
1142                })?;
1143            rescheduled.push((id, next_deadline));
1144        }
1145
1146        deliveries.sort_by_key(|delivery| (delivery.deadline, delivery.fire.timer));
1147        for timer in completed {
1148            self.timers.remove(&timer);
1149        }
1150        for (timer, deadline) in rescheduled {
1151            if let Some(active) = self.timers.get_mut(&timer) {
1152                active.deadline = deadline;
1153            }
1154        }
1155        for delivery in deliveries {
1156            self.push_timer_event(
1157                UiEvent::TimerFired {
1158                    timer: delivery.fire.timer,
1159                    elapsed: delivery.fire.elapsed,
1160                    missed: delivery.fire.missed,
1161                },
1162                delivery.widget_scope,
1163            );
1164        }
1165        Ok(())
1166    }
1167
1168    fn push_timer_event(
1169        &mut self,
1170        event: UiEvent,
1171        widget_scope: Option<(WidgetId, TimerStopPolicy)>,
1172    ) {
1173        if let UiEvent::TimerFired { timer, .. } = &event {
1174            let pending = self
1175                .pending_timer_events
1176                .entry(*timer)
1177                .or_insert((widget_scope, 0));
1178            pending.1 += 1;
1179        }
1180        if let Some(frame) = self.modal_loops.last_mut() {
1181            frame.script.push_back(event);
1182            let (_, cvar) = &*self.wake_signal;
1183            cvar.notify_all();
1184        } else {
1185            self.push_event(event);
1186        }
1187    }
1188
1189    fn cancel_mock_timer(&mut self, timer: TimerId) -> GuiResult<()> {
1190        if self.timers.remove(&timer).is_none() {
1191            return Err(GuiError::Backend(format!("Timer not found: {}", timer.0)));
1192        }
1193        self.remove_queued_timer_events(timer);
1194        Ok(())
1195    }
1196
1197    fn remove_queued_timer_events(&mut self, timer: TimerId) {
1198        self.events.retain(
1199            |event| !matches!(event, UiEvent::TimerFired { timer: id, .. } if *id == timer),
1200        );
1201        for frame in &mut self.modal_loops {
1202            frame.script.retain(
1203                |event| !matches!(event, UiEvent::TimerFired { timer: id, .. } if *id == timer),
1204            );
1205        }
1206        self.pending_timer_events.remove(&timer);
1207    }
1208
1209    fn cancel_widget_timers(&mut self, widget_id: WidgetId, hiding: bool) {
1210        let timers: Vec<_> = self
1211            .timers
1212            .iter()
1213            .filter_map(|(timer, state)| {
1214                let (scope, policy) = state.widget_scope?;
1215                let within_scope = self.source_is_owned_by(scope, widget_id);
1216                (within_scope && (!hiding || policy == TimerStopPolicy::RemoveOrHide))
1217                    .then_some(*timer)
1218            })
1219            .collect();
1220        for timer in timers {
1221            self.cancel_mock_timer(timer)
1222                .expect("timer selected from the active timer map");
1223        }
1224        let pending: Vec<_> = self
1225            .pending_timer_events
1226            .iter()
1227            .filter_map(|(timer, (scope, _))| {
1228                let (scope, policy) = (*scope)?;
1229                let within_scope = self.source_is_owned_by(scope, widget_id);
1230                (within_scope && (!hiding || policy == TimerStopPolicy::RemoveOrHide))
1231                    .then_some(*timer)
1232            })
1233            .collect();
1234        for timer in pending {
1235            self.remove_queued_timer_events(timer);
1236        }
1237    }
1238
1239    fn next_timer_deadline(&self) -> Option<Duration> {
1240        self.timers.values().map(|timer| timer.deadline).min()
1241    }
1242
1243    fn next_combined_deadline(&self) -> Option<Duration> {
1244        match (self.next_timer_deadline(), self.next_animation_deadline()) {
1245            (Some(t), Some(a)) => Some(t.min(a)),
1246            (Some(t), None) => Some(t),
1247            (None, Some(a)) => Some(a),
1248            (None, None) => None,
1249        }
1250    }
1251
1252    fn advance_to_next_timer(&mut self) -> GuiResult<bool> {
1253        let Some(deadline) = self.next_combined_deadline() else {
1254            return Ok(false);
1255        };
1256        if deadline > self.virtual_now {
1257            self.virtual_now = deadline;
1258        }
1259        self.service_due_timers()?;
1260        self.service_due_animations()?;
1261        Ok(true)
1262    }
1263
1264    fn pop_pump_event(&mut self) -> Option<UiEvent> {
1265        let event = match self.modal_loops.last_mut() {
1266            Some(frame) => {
1267                let event = frame.script.pop_front();
1268                if event.is_some() {
1269                    frame.delivered += 1;
1270                }
1271                event
1272            }
1273            None => self.events.pop_front(),
1274        };
1275        if let Some(UiEvent::TimerFired { timer, .. }) = &event {
1276            let remove_entry = if let Some((_, count)) = self.pending_timer_events.get_mut(timer) {
1277                if *count <= 1 {
1278                    true
1279                } else {
1280                    *count -= 1;
1281                    false
1282                }
1283            } else {
1284                false
1285            };
1286            if remove_entry {
1287                self.pending_timer_events.remove(timer);
1288            }
1289        }
1290        event
1291    }
1292
1293    fn default_window_capabilities() -> WindowCapabilities {
1294        WindowCapabilities {
1295            anchored_popups: true,
1296            popup_focus_dismissal: true,
1297            transient_ownership: true,
1298            undecorated: true,
1299            always_on_top: true,
1300            uniform_translucency: true,
1301            shape_rounded: true,
1302            shape_region: false,
1303            show_fade: true,
1304            show_slide: true,
1305        }
1306    }
1307
1308    fn default_drag_capabilities() -> DragCapabilities {
1309        DragCapabilities {
1310            text: true,
1311            custom_mime: true,
1312            drop_feedback: true,
1313            preview: false,
1314        }
1315    }
1316
1317    /// Overrides the extended-window capability profile for typed-gate tests.
1318    pub fn set_window_capabilities(&mut self, capabilities: WindowCapabilities) {
1319        self.window_capabilities_override = Some(capabilities);
1320    }
1321
1322    /// Overrides text/custom-MIME support for typed-gate tests.
1323    pub fn set_drag_capabilities(&mut self, capabilities: DragCapabilities) {
1324        self.drag_capabilities_override = Some(capabilities);
1325    }
1326
1327    /// Starts a scripted drag-and-drop session from a configured source.
1328    pub fn mock_start_drag(&mut self, source: WidgetId) -> GuiResult<DragSessionId> {
1329        if self.active_drag.is_some() {
1330            return Err(GuiError::UnsupportedCapability("drag_busy".to_owned()));
1331        }
1332        if !self.created.contains_key(&source) {
1333            return Err(GuiError::WidgetNotFound(source.0));
1334        }
1335        let options = self
1336            .drag_source_options
1337            .get(&source)
1338            .cloned()
1339            .ok_or(GuiError::UnsupportedWidget("set_drag_source"))?;
1340        if options.kinds.is_empty() {
1341            return Err(GuiError::Backend(
1342                "Drag sources must offer at least one payload kind".to_owned(),
1343            ));
1344        }
1345        let next = self
1346            .next_drag_session
1347            .checked_add(1)
1348            .ok_or(GuiError::ResourceExhausted {
1349                operation: "drag session id allocation",
1350                code: None,
1351            })?;
1352        let session = DragSessionId(next);
1353        self.next_drag_session = next;
1354        self.active_drag = Some(MockDragSession {
1355            id: session,
1356            source,
1357            kinds: options.kinds.clone(),
1358            target: None,
1359        });
1360        self.push_drag_event(UiEvent::DragSessionStarted {
1361            widget_id: source,
1362            session,
1363            kinds: options.kinds,
1364        });
1365        Ok(session)
1366    }
1367
1368    /// Scripts entry onto a target, emitting its compatible offered MIME types.
1369    pub fn mock_drag_enter(
1370        &mut self,
1371        session: DragSessionId,
1372        target: WidgetId,
1373        position: (i32, i32),
1374    ) -> GuiResult<bool> {
1375        let Some(active) = self
1376            .active_drag
1377            .as_ref()
1378            .filter(|active| active.id == session)
1379            .cloned()
1380        else {
1381            return Ok(false);
1382        };
1383        if !self.created.contains_key(&target) {
1384            return Err(GuiError::WidgetNotFound(target.0));
1385        }
1386        let target_options = self
1387            .drag_target_options
1388            .get(&target)
1389            .ok_or(GuiError::UnsupportedWidget("set_drag_target_options"))?;
1390        let offered: Vec<_> = active
1391            .kinds
1392            .iter()
1393            .filter(|kind| target_options.kinds.contains(kind))
1394            .map(|kind| kind.mime_type().to_owned())
1395            .collect();
1396        if offered.is_empty() {
1397            if let Some(previous) = active.target {
1398                self.mock_drag_exit(session, previous);
1399            }
1400            return Ok(false);
1401        }
1402        if active.target == Some(target) {
1403            return Ok(true);
1404        }
1405        if let Some(previous) = active.target {
1406            self.mock_drag_exit(session, previous);
1407        }
1408        if let Some(active) = self.active_drag.as_mut() {
1409            active.target = Some(target);
1410        }
1411        self.push_drag_event(UiEvent::DragEntered {
1412            target,
1413            session,
1414            position,
1415            offered,
1416        });
1417        Ok(true)
1418    }
1419
1420    /// Scripts pointer motion over the active drag target.
1421    pub fn mock_drag_move(
1422        &mut self,
1423        session: DragSessionId,
1424        target: WidgetId,
1425        position: (i32, i32),
1426    ) -> bool {
1427        if !self
1428            .active_drag
1429            .as_ref()
1430            .is_some_and(|active| active.id == session && active.target == Some(target))
1431        {
1432            return false;
1433        }
1434        self.push_drag_event(UiEvent::DragMoved {
1435            target,
1436            session,
1437            position,
1438        });
1439        true
1440    }
1441
1442    /// Scripts leaving the current target without ending the drag session.
1443    pub fn mock_drag_exit(&mut self, session: DragSessionId, target: WidgetId) -> bool {
1444        let Some(active) = self
1445            .active_drag
1446            .as_mut()
1447            .filter(|active| active.id == session && active.target == Some(target))
1448        else {
1449            return false;
1450        };
1451        active.target = None;
1452        self.push_drag_event(UiEvent::DragExited { target, session });
1453        true
1454    }
1455
1456    /// Scripts a compatible drop and ends the session exactly once.
1457    pub fn mock_drag_drop(
1458        &mut self,
1459        session: DragSessionId,
1460        target: WidgetId,
1461        position: (i32, i32),
1462        payload: DragPayload,
1463    ) -> GuiResult<bool> {
1464        let Some(active) = self
1465            .active_drag
1466            .as_ref()
1467            .filter(|active| active.id == session && active.target == Some(target))
1468            .cloned()
1469        else {
1470            return Ok(false);
1471        };
1472        let payload = payload.normalized()?;
1473        let kind = payload.kind().ok_or_else(|| {
1474            GuiError::Backend("Row and file payloads use their existing drag events".to_owned())
1475        })?;
1476        let target_options = self
1477            .drag_target_options
1478            .get(&target)
1479            .ok_or(GuiError::UnsupportedWidget("set_drag_target_options"))?;
1480        if !active.kinds.contains(&kind) || !target_options.kinds.contains(&kind) {
1481            return Err(GuiError::Backend(
1482                "Drop payload kind is not accepted by both source and target".to_owned(),
1483            ));
1484        }
1485        let effect = target_options.effect;
1486        self.mock_drag_exit(session, target);
1487        self.push_drag_event(UiEvent::DragDropped {
1488            target,
1489            session,
1490            position,
1491            payload,
1492            effect,
1493        });
1494        self.active_drag = None;
1495        Ok(true)
1496    }
1497
1498    /// Cancels the matching live session once; stale ids return false.
1499    pub fn mock_cancel_drag(&mut self, session: DragSessionId, reason: DropCancelReason) -> bool {
1500        self.finish_drag_cancel(session, reason)
1501    }
1502
1503    fn cancel_drag_from_source(&mut self, source: WidgetId) {
1504        if let Some(session) = self
1505            .active_drag
1506            .as_ref()
1507            .filter(|active| active.source == source)
1508            .map(|active| active.id)
1509        {
1510            self.finish_drag_cancel(session, DropCancelReason::SourceRemoved);
1511        }
1512    }
1513
1514    fn finish_drag_cancel(&mut self, session: DragSessionId, reason: DropCancelReason) -> bool {
1515        let Some(active) = self
1516            .active_drag
1517            .as_ref()
1518            .filter(|active| active.id == session)
1519            .cloned()
1520        else {
1521            return false;
1522        };
1523        if let Some(target) = active.target {
1524            self.mock_drag_exit(session, target);
1525        }
1526        self.push_drag_event(UiEvent::DragCancelled { session, reason });
1527        self.active_drag = None;
1528        true
1529    }
1530
1531    fn source_is_owned_by(&self, source: WidgetId, owner: WidgetId) -> bool {
1532        let mut cursor = Some(source);
1533        while let Some(widget_id) = cursor {
1534            if widget_id == owner {
1535                return true;
1536            }
1537            cursor = self.created.get(&widget_id).and_then(|spec| spec.parent);
1538        }
1539        false
1540    }
1541
1542    fn push_drag_event(&mut self, event: UiEvent) {
1543        if let Some(frame) = self.modal_loops.last_mut() {
1544            frame.script.push_back(event);
1545            let (_, cvar) = &*self.wake_signal;
1546            cvar.notify_all();
1547        } else {
1548            self.push_event(event);
1549        }
1550    }
1551
1552    /// Injects one user- or OS-initiated popup dismissal.
1553    ///
1554    /// A popup session can be dismissed only once; the return value is false
1555    /// for a stale or already-ended session.
1556    pub fn inject_popup_dismissal(
1557        &mut self,
1558        widget_id: WidgetId,
1559        reason: PopupDismissReason,
1560    ) -> bool {
1561        self.end_popup_session(widget_id, Some(reason))
1562    }
1563
1564    /// Injects an owner-window close after dismissing its active popups.
1565    pub fn inject_window_closed(&mut self, widget_id: WidgetId) {
1566        if let Some(session) = self
1567            .active_drag
1568            .as_ref()
1569            .filter(|active| self.source_is_owned_by(active.source, widget_id))
1570            .map(|active| active.id)
1571        {
1572            self.finish_drag_cancel(session, DropCancelReason::OwnerClosed);
1573        }
1574        let mut popups: Vec<_> = self
1575            .active_popup_sessions
1576            .iter()
1577            .copied()
1578            .filter(|popup| {
1579                self.window_options
1580                    .get(popup)
1581                    .is_some_and(|options| options.transient_for == Some(widget_id))
1582            })
1583            .collect();
1584        popups.sort_by_key(|popup| popup.0);
1585        for popup in popups {
1586            self.end_popup_session(popup, Some(PopupDismissReason::OwnerClosed));
1587        }
1588        self.push_event(UiEvent::WindowClosed { widget_id });
1589    }
1590
1591    fn end_popup_session(
1592        &mut self,
1593        widget_id: WidgetId,
1594        reason: Option<PopupDismissReason>,
1595    ) -> bool {
1596        if !self.active_popup_sessions.remove(&widget_id) {
1597            return false;
1598        }
1599        if reason.is_some() {
1600            if let Some(effect) = self
1601                .window_options
1602                .get(&widget_id)
1603                .map(|options| options.hide_effect)
1604                .filter(|effect| *effect != ShowEffect::None)
1605            {
1606                self.window_effects
1607                    .push(MockWindowEffect::Hide { widget_id, effect });
1608            }
1609        }
1610        self.shown.retain(|shown| *shown != widget_id);
1611        if let Some(reason) = reason {
1612            self.push_event(UiEvent::PopupDismissed { widget_id, reason });
1613        }
1614        true
1615    }
1616
1617    /// Replaces the default GPU capability profile for a deterministic test.
1618    pub fn set_gpu_surface_capabilities(&mut self, capabilities: GpuSurfaceCapabilities) {
1619        self.gpu_surface_capabilities_override = Some(capabilities);
1620    }
1621
1622    /// Queues an event for the outer (flat) pump.
1623    ///
1624    /// While a scripted modal loop is open the queue is parked: the nested
1625    /// pump serves only its script, and pushed events are delivered once the
1626    /// loop closes. Outside a modal loop delivery is the
1627    /// usual FIFO order.
1628    pub fn push_event(&mut self, event: UiEvent) {
1629        self.events.push_back(event);
1630        // Wake a parked `wait_event` so fake events do not wait a full poll
1631        // interval.
1632        let (_, cvar) = &*self.wake_signal;
1633        cvar.notify_all();
1634    }
1635
1636    /// Opens a scripted modal loop: a nested pump frame
1637    /// whose script takes over event delivery until [`Self::end_modal_loop`].
1638    ///
1639    /// Frames nest, so a loop opened from inside another loop's handler
1640    /// models a dialog raised by a modal operation; the innermost frame owns
1641    /// delivery until it closes. Prefer driving loops through
1642    /// [`Ui::run_modal_loop`], which pairs the frame with re-entrant
1643    /// dispatch of its script.
1644    pub fn begin_modal_loop(&mut self) {
1645        self.modal_loops.push(MockModalFrame::default());
1646    }
1647
1648    /// Scripts one event for the innermost open modal loop, in delivery
1649    /// order. Returns `false` when no loop is open: injection reaches only a
1650    /// running pump, so a fixture must call [`Self::begin_modal_loop`] first.
1651    pub fn script_modal_event(&mut self, event: UiEvent) -> bool {
1652        match self.modal_loops.last_mut() {
1653            Some(frame) => {
1654                frame.script.push_back(event);
1655                // Wake a parked `wait_event` so a scripted delivery does not
1656                // wait a full poll interval.
1657                let (_, cvar) = &*self.wake_signal;
1658                cvar.notify_all();
1659                true
1660            }
1661            None => false,
1662        }
1663    }
1664
1665    /// Closes the innermost modal loop and returns the scripted events its
1666    /// pump never delivered. Closing with no loop open is a no-op that
1667    /// returns nothing.
1668    pub fn end_modal_loop(&mut self) -> Vec<UiEvent> {
1669        match self.modal_loops.pop() {
1670            Some(frame) => frame.script.into_iter().collect(),
1671            None => Vec::new(),
1672        }
1673    }
1674
1675    /// Depth of the open modal-loop stack (0 = no modal operation running).
1676    pub fn modal_loop_depth(&self) -> usize {
1677        self.modal_loops.len()
1678    }
1679
1680    /// Whether a modal loop is currently running.
1681    pub fn modal_loop_open(&self) -> bool {
1682        !self.modal_loops.is_empty()
1683    }
1684
1685    pub fn last_canvas_scene(&self) -> Option<&native_gui_core::CanvasScene> {
1686        self.last_canvas_scene.as_ref()
1687    }
1688
1689    /// Surface most recently recorded by `set_canvas_surface`.
1690    pub fn last_canvas_surface(&self) -> Option<&native_gui_core::CanvasSurface> {
1691        self.last_canvas_surface.as_ref()
1692    }
1693
1694    /// Virtual data-grid model retained for `widget_id`, or `None`
1695    /// when the widget was never given one. The Mock retains the model the
1696    /// manager handed to `set_data_grid_model` verbatim - it is never
1697    /// materialised into rows - so fixtures can read its shape back.
1698    pub fn data_grid_model(&self, widget_id: WidgetId) -> Option<&dyn DataGridModel> {
1699        self.data_grid_models
1700            .get(&widget_id)
1701            .map(|model| model.0.as_ref())
1702    }
1703
1704    /// Row count of the retained virtual model, or `None` when the widget has
1705    /// no model.
1706    pub fn data_grid_model_row_count(&self, widget_id: WidgetId) -> Option<usize> {
1707        self.data_grid_model(widget_id)
1708            .map(DataGridModel::row_count)
1709    }
1710
1711    /// Column count of the retained virtual model, or `None` when the widget
1712    /// has no model.
1713    pub fn data_grid_model_col_count(&self, widget_id: WidgetId) -> Option<usize> {
1714        self.data_grid_model(widget_id)
1715            .map(DataGridModel::col_count)
1716    }
1717
1718    /// Residency of one row of the retained virtual model, or `None` when
1719    /// the widget has no model. Uses the defaulted
1720    /// [`DataGridModel::is_row_resident`] hook, so an eager model reports
1721    /// `true` for every row while a windowed model reports whether the
1722    /// row's payload has been delivered.
1723    pub fn data_grid_model_is_row_resident(&self, widget_id: WidgetId, row: usize) -> Option<bool> {
1724        self.data_grid_model(widget_id)
1725            .map(|model| model.is_row_resident(row))
1726    }
1727
1728    /// Cell selection recorded by `set_data_grid_selection`.
1729    pub fn data_grid_selection(&self, widget_id: WidgetId) -> Option<&[(usize, usize)]> {
1730        self.data_grid_selections
1731            .get(&widget_id)
1732            .map(|s| s.as_slice())
1733    }
1734
1735    /// Injects the reported OS light/dark preference.
1736    ///
1737    /// The Mock never reads the operating system. Fixtures call this to model
1738    /// a system transition: the mode becomes readable through
1739    /// `system_theme_mode`, the detection capability flags switch to
1740    /// [`native_gui_core::ThemeCapabilities::all`], and the matching
1741    /// [`UiEvent::ThemeChanged`] is queued for the event loop.
1742    pub fn inject_system_theme_mode(&mut self, mode: native_gui_core::ThemeMode) {
1743        self.system_theme = Some(mode);
1744        self.theme_capabilities = native_gui_core::ThemeCapabilities::all();
1745        self.push_event(UiEvent::ThemeChanged {
1746            mode,
1747            high_contrast: self.system_high_contrast(),
1748        });
1749    }
1750
1751    /// Installs the display fixture reported by `displays`.
1752    ///
1753    /// The Mock never reads the operating system. Fixtures call this with a
1754    /// deterministic multi-display set; the enumeration capability flag
1755    /// switches on so `display_capabilities` stays consistent with the data.
1756    pub fn set_displays(&mut self, displays: Vec<native_gui_core::DisplayInfo>) {
1757        self.displays = displays;
1758        self.display_capabilities.enumeration = true;
1759    }
1760
1761    /// Sets the display capability flags directly.
1762    ///
1763    /// Lets fixtures model hostile lanes (data present but enumeration
1764    /// advertised as unsupported, or the reverse).
1765    pub fn set_display_capabilities(&mut self, capabilities: native_gui_core::DisplayCapabilities) {
1766        self.display_capabilities = capabilities;
1767    }
1768
1769    /// Injects a DPI/monitor transition.
1770    ///
1771    /// Models the platform event behind a display change: the event support
1772    /// flag switches on and the matching [`UiEvent::DisplayChanged`] is
1773    /// queued for the event loop with `display` as the fresh payload.
1774    pub fn inject_display_change(&mut self, display: native_gui_core::DisplayInfo) {
1775        self.display_capabilities.dpi_change_events = true;
1776        self.push_event(UiEvent::DisplayChanged { display });
1777    }
1778
1779    /// Injects an OS close request for a window.
1780    ///
1781    /// Models the platform message behind the X button/Alt+F4; guarded
1782    /// windows answer with `UiEvent::CloseRequested` through the event loop.
1783    pub fn inject_close_request(&mut self, widget_id: WidgetId) {
1784        self.push_event(UiEvent::CloseRequested { widget_id });
1785    }
1786
1787    /// Injects the outcome of an activated colour dialog.
1788    ///
1789    /// The Mock never opens a native chooser. Fixtures call this to script
1790    /// exactly what the user did: `Some(color)` accepts that colour (the
1791    /// activation emits a `ColorChanged` preview first, then
1792    /// `ColorSelected { color: Some(..) }`), and `None` models cancel (one
1793    /// `ColorSelected { color: None }`, with the stored initial colour
1794    /// untouched). An activation with no injected result is a cancel.
1795    pub fn inject_color_dialog_result(
1796        &mut self,
1797        widget_id: WidgetId,
1798        result: Option<native_gui_core::Rgba>,
1799    ) {
1800        self.color_dialog_results.insert(widget_id, result);
1801    }
1802
1803    /// Injects the outcome of an activated font dialog.
1804    ///
1805    /// Same scripted contract as [`Self::inject_color_dialog_result`]: with
1806    /// `Some((descriptor, effects))` the activation emits a `FontChanged`
1807    /// preview (the descriptor's size clamped to the configured range) and
1808    /// then `FontSelected { selection: Some(..) }`; `None` models cancel with
1809    /// a single `FontSelected { selection: None }` and the stored initial
1810    /// descriptor untouched. An activation with no injected result cancels.
1811    pub fn inject_font_dialog_result(
1812        &mut self,
1813        widget_id: WidgetId,
1814        result: Option<(FontDescriptor, FontEffects)>,
1815    ) {
1816        self.font_dialog_results.insert(widget_id, result);
1817    }
1818
1819    /// Injects an accepted completion suggestion for a `TextInput`
1820    /// (completion fixture).
1821    ///
1822    /// Models the native popup committing `text`: the matching
1823    /// [`UiEvent::SuggestionSelected`] is queued, and the shared model does
1824    /// **not** rewrite `spec.text` — the application applies the accepted
1825    /// text through [`native_gui_core::Ui::set_text`]. Widgets that are not
1826    /// `TextInput`s refuse with the shared typed error instead of producing
1827    /// a popup event.
1828    pub fn inject_suggestion_selected(
1829        &mut self,
1830        widget_id: WidgetId,
1831        text: impl Into<String>,
1832    ) -> GuiResult<()> {
1833        self.ensure_text_completion_target(widget_id)?;
1834        self.push_event(UiEvent::SuggestionSelected {
1835            widget_id,
1836            text: text.into(),
1837        });
1838        Ok(())
1839    }
1840
1841    /// Injects a completion-popup dismissal (completion fixture): the popup
1842    /// closed without acceptance (Escape, blur, or a click elsewhere).
1843    pub fn inject_suggestion_dismissed(&mut self, widget_id: WidgetId) -> GuiResult<()> {
1844        self.ensure_text_completion_target(widget_id)?;
1845        self.push_event(UiEvent::SuggestionDismissed { widget_id });
1846        Ok(())
1847    }
1848
1849    fn ensure_text_completion_target(&self, widget_id: WidgetId) -> GuiResult<()> {
1850        let spec = self
1851            .created
1852            .get(&widget_id)
1853            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
1854        spec.ensure_property(WidgetProperty::TextCompletion)
1855    }
1856
1857    /// Answers a pending `Ui::show_file_dialog` request as the user would:
1858    /// queues [`UiEvent::FileDialogResponse`] with `paths` (pass an empty
1859    /// vector to simulate Cancel). Unknown or already-answered tokens are
1860    /// refused, so a test cannot answer a dialog the app never opened.
1861    pub fn inject_file_dialog_result(
1862        &mut self,
1863        token: u64,
1864        paths: Vec<std::path::PathBuf>,
1865    ) -> GuiResult<()> {
1866        let Some(position) = self
1867            .file_dialog_requests
1868            .iter()
1869            .position(|(pending, _)| *pending == token)
1870        else {
1871            return Err(GuiError::Backend(format!(
1872                "no pending file dialog with token {token}"
1873            )));
1874        };
1875        let (_, request) = self.file_dialog_requests.remove(position);
1876        if !request.multiple && paths.len() > 1 {
1877            return Err(GuiError::Backend(
1878                "a single-selection file dialog answers with at most one path".to_owned(),
1879            ));
1880        }
1881        self.push_event(UiEvent::FileDialogResponse { token, paths });
1882        Ok(())
1883    }
1884
1885    /// Injects a divider movement on a `SplitPane` widget.
1886    ///
1887    /// Validates that `widget_id` exists and is a `SplitPane`, then queues
1888    /// [`UiEvent::SplitPaneMoved`].
1889    #[cfg(feature = "widgets-containers")]
1890    pub fn inject_split_pane_moved(
1891        &mut self,
1892        widget_id: WidgetId,
1893        position: i32,
1894        extent: i32,
1895    ) -> GuiResult<()> {
1896        let spec = self
1897            .created
1898            .get(&widget_id)
1899            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
1900        if spec.kind != WidgetKind::SplitPane {
1901            return Err(GuiError::UnsupportedWidget("SplitPaneMoved"));
1902        }
1903        self.push_event(UiEvent::SplitPaneMoved {
1904            widget_id,
1905            position,
1906            extent,
1907        });
1908        Ok(())
1909    }
1910
1911    /// Simulates a user click on a toolbar tool.
1912    ///
1913    /// Applies the shared [`native_gui_core::toolbar::click_tool`] rules to the stored
1914    /// rows and queues the resulting event: a plain tool reports
1915    /// `ToolActivated`, a dropdown tool `ToolDropdown`, a checkable tool one
1916    /// `ToolToggled` per changed tool (radio exclusivity can uncheck one
1917    /// peer), and a disabled or hidden tool consumes the click silently —
1918    /// exactly like the native controls.
1919    pub fn click_tool(&mut self, widget_id: WidgetId, tool_id: ToolId) -> GuiResult<()> {
1920        let Some(spec) = self.created.get_mut(&widget_id) else {
1921            return Err(GuiError::WidgetNotFound(widget_id.0));
1922        };
1923        spec.ensure_property(WidgetProperty::ToolbarItems)?;
1924        let interaction = toolbar::click_tool(&mut spec.toolbar_items, tool_id)
1925            .map_err(|error| GuiError::Backend(error.to_string()))?;
1926
1927        match interaction {
1928            ToolInteraction::Activated(tool_id) => {
1929                self.push_event(UiEvent::ToolActivated { widget_id, tool_id });
1930            }
1931            ToolInteraction::Dropdown(tool_id) => {
1932                self.push_event(UiEvent::ToolDropdown { widget_id, tool_id });
1933            }
1934            ToolInteraction::Toggled(changes) => {
1935                for (tool_id, checked) in changes {
1936                    self.push_event(UiEvent::ToolToggled {
1937                        widget_id,
1938                        tool_id,
1939                        checked,
1940                    });
1941                }
1942            }
1943            ToolInteraction::Ignored(_) => {}
1944        }
1945        Ok(())
1946    }
1947
1948    /// Simulates the pointer entering (`Some`) or leaving (`None`) a toolbar
1949    /// tool.
1950    pub fn hover_tool(&mut self, widget_id: WidgetId, tool_id: Option<ToolId>) -> GuiResult<()> {
1951        let Some(spec) = self.created.get(&widget_id) else {
1952            return Err(GuiError::WidgetNotFound(widget_id.0));
1953        };
1954        spec.ensure_property(WidgetProperty::ToolbarItems)?;
1955        if let Some(tool_id) = tool_id {
1956            if toolbar::find_tool(&spec.toolbar_items, tool_id).is_none() {
1957                return Err(GuiError::Backend(
1958                    native_gui_core::toolbar::ToolbarError::UnknownTool(tool_id).to_string(),
1959                ));
1960            }
1961        }
1962        self.push_event(UiEvent::ToolHovered { widget_id, tool_id });
1963        Ok(())
1964    }
1965
1966    /// Simulates a right-click on a toolbar tool, asking for a context menu.
1967    pub fn context_tool(&mut self, widget_id: WidgetId, tool_id: ToolId) -> GuiResult<()> {
1968        let Some(spec) = self.created.get(&widget_id) else {
1969            return Err(GuiError::WidgetNotFound(widget_id.0));
1970        };
1971        spec.ensure_property(WidgetProperty::ToolbarItems)?;
1972        if toolbar::find_tool(&spec.toolbar_items, tool_id).is_none() {
1973            return Err(GuiError::Backend(
1974                native_gui_core::toolbar::ToolbarError::UnknownTool(tool_id).to_string(),
1975            ));
1976        }
1977        self.push_event(UiEvent::ToolContext { widget_id, tool_id });
1978        Ok(())
1979    }
1980
1981    /// Simulates a user click on a calendar date.
1982    pub fn click_calendar_date(
1983        &mut self,
1984        widget_id: WidgetId,
1985        date: CalendarDate,
1986    ) -> GuiResult<()> {
1987        let Some(spec) = self.created.get_mut(&widget_id) else {
1988            return Err(GuiError::WidgetNotFound(widget_id.0));
1989        };
1990        spec.ensure_property(WidgetProperty::CalendarDates)?;
1991
1992        if let Some(min) = spec.calendar_min_date {
1993            if date < min {
1994                return Ok(());
1995            }
1996        }
1997        if let Some(max) = spec.calendar_max_date {
1998            if date > max {
1999                return Ok(());
2000            }
2001        }
2002
2003        match spec.calendar_selection_mode {
2004            CalendarSelectionMode::Single => {
2005                spec.calendar_selected_dates = vec![date];
2006            }
2007            CalendarSelectionMode::Multiple => {
2008                if let Some(pos) = spec.calendar_selected_dates.iter().position(|d| *d == date) {
2009                    spec.calendar_selected_dates.remove(pos);
2010                } else {
2011                    spec.calendar_selected_dates.push(date);
2012                    spec.calendar_selected_dates.sort();
2013                }
2014            }
2015            CalendarSelectionMode::Range => {
2016                if spec.calendar_selected_dates.len() == 1 {
2017                    let first = spec.calendar_selected_dates[0];
2018                    spec.calendar_selected_dates = vec![first.min(date), first.max(date)];
2019                } else {
2020                    spec.calendar_selected_dates = vec![date];
2021                }
2022            }
2023        }
2024
2025        let selected_dates = spec.calendar_selected_dates.clone();
2026        self.push_event(UiEvent::CalendarDateSelected {
2027            widget_id,
2028            date,
2029            selected_dates,
2030        });
2031        Ok(())
2032    }
2033
2034    /// Simulates navigating a calendar to a different month/year.
2035    pub fn navigate_calendar_month(
2036        &mut self,
2037        widget_id: WidgetId,
2038        year: i32,
2039        month: u32,
2040    ) -> GuiResult<()> {
2041        let Some(spec) = self.created.get_mut(&widget_id) else {
2042            return Err(GuiError::WidgetNotFound(widget_id.0));
2043        };
2044        spec.ensure_property(WidgetProperty::CalendarBounds)?;
2045        self.push_event(UiEvent::CalendarMonthChanged {
2046            widget_id,
2047            year,
2048            month,
2049        });
2050        Ok(())
2051    }
2052}
2053
2054impl native_gui_core::ui::TextMeasure for MockBackend {
2055    fn measure_text(
2056        &self,
2057        widget_id: native_gui_core::widgets::WidgetId,
2058        known_dimensions: native_gui_core::layout::Size<Option<f32>>,
2059        available_space: native_gui_core::layout::Size<native_gui_core::layout::AvailableSpace>,
2060    ) -> Option<native_gui_core::layout::Size<f32>> {
2061        let _ = (widget_id, known_dimensions, available_space);
2062        None
2063    }
2064}
2065
2066impl Backend for MockBackend {
2067    fn backend_name(&self) -> &'static str {
2068        "mock"
2069    }
2070
2071    fn image_resource_capabilities(&self) -> ImageResourceCapabilities {
2072        self.image_resource_capabilities_override
2073            .unwrap_or_else(Self::default_image_resource_capabilities)
2074    }
2075
2076    fn load_image_resource(
2077        &mut self,
2078        resource: ImageResourceId,
2079        data: &ImageData,
2080    ) -> GuiResult<()> {
2081        if !self.image_resource_capabilities().rgba {
2082            return Err(GuiError::UnsupportedCapability(
2083                "image_resource_rgba".to_owned(),
2084            ));
2085        }
2086        data.validate()?;
2087        if self.image_resources.contains_key(&resource) {
2088            return Err(GuiError::Backend(format!(
2089                "Image resource already exists: {}",
2090                resource.0
2091            )));
2092        }
2093        self.image_resources.insert(resource, data.clone());
2094        Ok(())
2095    }
2096
2097    fn release_image_resource(&mut self, resource: ImageResourceId) -> GuiResult<()> {
2098        if !self.image_resource_capabilities().rgba {
2099            return Err(GuiError::UnsupportedCapability(
2100                "image_resource_rgba".to_owned(),
2101            ));
2102        }
2103        self.image_resources
2104            .remove(&resource)
2105            .map(|_| ())
2106            .ok_or_else(|| GuiError::Backend(format!("Image resource not found: {}", resource.0)))
2107    }
2108
2109    fn timer_capabilities(&self) -> TimerCapabilities {
2110        self.timer_capabilities_override
2111            .unwrap_or_else(Self::default_timer_capabilities)
2112    }
2113
2114    fn motion_capabilities(&self) -> MotionCapabilities {
2115        self.motion_capabilities_override.unwrap_or_else(|| {
2116            let timers = self.timer_capabilities();
2117            MotionCapabilities {
2118                motions: timers.timers && timers.widget_timers,
2119            }
2120        })
2121    }
2122
2123    fn start_timer(&mut self, timer: TimerId, spec: TimerSpec) -> GuiResult<()> {
2124        if !self.timer_capabilities().timers {
2125            return Err(GuiError::UnsupportedCapability("ui_timer".to_owned()));
2126        }
2127        self.start_mock_timer(timer, spec, None)
2128    }
2129
2130    fn start_widget_timer(
2131        &mut self,
2132        timer: TimerId,
2133        widget_id: WidgetId,
2134        spec: TimerSpec,
2135        stop_policy: TimerStopPolicy,
2136    ) -> GuiResult<()> {
2137        if !self.created.contains_key(&widget_id) {
2138            return Err(GuiError::WidgetNotFound(widget_id.0));
2139        }
2140        let capabilities = self.timer_capabilities();
2141        if !capabilities.timers {
2142            return Err(GuiError::UnsupportedCapability("ui_timer".to_owned()));
2143        }
2144        if !capabilities.widget_timers {
2145            return Err(GuiError::UnsupportedCapability("widget_timer".to_owned()));
2146        }
2147        self.start_mock_timer(timer, spec, Some((widget_id, stop_policy)))
2148    }
2149
2150    fn cancel_timer(&mut self, timer: TimerId) -> GuiResult<()> {
2151        self.cancel_mock_timer(timer)
2152    }
2153
2154    fn drag_capabilities(&self) -> DragCapabilities {
2155        self.drag_capabilities_override
2156            .unwrap_or_else(Self::default_drag_capabilities)
2157    }
2158
2159    fn set_drag_source_options(
2160        &mut self,
2161        widget_id: WidgetId,
2162        options: &DragSourceOptions,
2163    ) -> GuiResult<()> {
2164        if !self.created.contains_key(&widget_id) {
2165            return Err(GuiError::WidgetNotFound(widget_id.0));
2166        }
2167        self.drag_source_options.insert(widget_id, options.clone());
2168        Ok(())
2169    }
2170
2171    fn set_drag_target_options(
2172        &mut self,
2173        widget_id: WidgetId,
2174        options: &DragTargetOptions,
2175    ) -> GuiResult<()> {
2176        if !self.created.contains_key(&widget_id) {
2177            return Err(GuiError::WidgetNotFound(widget_id.0));
2178        }
2179        self.drag_target_options.insert(widget_id, options.clone());
2180        Ok(())
2181    }
2182
2183    fn window_capabilities(&self) -> WindowCapabilities {
2184        self.window_capabilities_override
2185            .unwrap_or_else(Self::default_window_capabilities)
2186    }
2187
2188    fn set_window_options(
2189        &mut self,
2190        widget_id: WidgetId,
2191        options: &WindowOptions,
2192    ) -> GuiResult<()> {
2193        let spec = self
2194            .created
2195            .get(&widget_id)
2196            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
2197        if spec.kind != WidgetKind::Window {
2198            return Err(GuiError::UnsupportedWidget("set_window_options"));
2199        }
2200        self.window_options.insert(widget_id, *options);
2201        Ok(())
2202    }
2203
2204    fn dismiss_popup(&mut self, widget_id: WidgetId) -> GuiResult<()> {
2205        let spec = self
2206            .created
2207            .get(&widget_id)
2208            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
2209        if spec.kind != WidgetKind::Window {
2210            return Err(GuiError::UnsupportedWidget("dismiss_popup"));
2211        }
2212        self.hide(widget_id)
2213    }
2214
2215    fn e2e_poll_event(&mut self) -> GuiResult<Option<UiEvent>> {
2216        self.poll_event()
2217    }
2218
2219    #[cfg(feature = "e2e")]
2220    fn e2e_capability(
2221        &self,
2222        widget_id: WidgetId,
2223        operation: crate::e2e::Operation,
2224    ) -> GuiResult<crate::e2e::Capability> {
2225        use crate::e2e::{Capability, InputMode, Operation};
2226        let spec = self
2227            .created
2228            .get(&widget_id)
2229            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
2230        let supported = match operation {
2231            Operation::Click => {
2232                #[cfg(feature = "widgets-text")]
2233                let is_link = spec.kind == WidgetKind::LinkLabel;
2234                #[cfg(not(feature = "widgets-text"))]
2235                let is_link = false;
2236                spec.kind == WidgetKind::Button || is_link
2237            }
2238            Operation::TypeText => {
2239                #[cfg(feature = "widgets-text")]
2240                let is_text = matches!(spec.kind, WidgetKind::TextInput | WidgetKind::TextArea);
2241                #[cfg(not(feature = "widgets-text"))]
2242                let is_text = false;
2243                is_text
2244            }
2245            #[cfg(feature = "widgets-choice")]
2246            Operation::Check | Operation::Checked => spec.kind == WidgetKind::Checkbox,
2247            #[cfg(not(feature = "widgets-choice"))]
2248            Operation::Check | Operation::Checked => false,
2249            Operation::Text => true,
2250            _ => false,
2251        };
2252        Ok(if supported {
2253            Capability::Supported {
2254                mode: InputMode::Simulated,
2255            }
2256        } else {
2257            Capability::Unsupported {
2258                reason: format!(
2259                    "{} is not implemented for {:?}",
2260                    operation.name(),
2261                    spec.kind
2262                ),
2263            }
2264        })
2265    }
2266
2267    #[cfg(feature = "e2e")]
2268    fn e2e_click(&mut self, widget_id: WidgetId) -> GuiResult<()> {
2269        match self.e2e_capability(widget_id, crate::e2e::Operation::Click)? {
2270            crate::e2e::Capability::Supported { .. } => {
2271                #[cfg(feature = "widgets-text")]
2272                let is_link = self.created[&widget_id].kind == WidgetKind::LinkLabel;
2273                #[cfg(not(feature = "widgets-text"))]
2274                let is_link = false;
2275                if is_link {
2276                    let url = self.created[&widget_id]
2277                        .link_url
2278                        .clone()
2279                        .unwrap_or_default();
2280                    self.push_event(UiEvent::LinkActivated { widget_id, url });
2281                    Ok(())
2282                } else {
2283                    self.activate(widget_id)
2284                }
2285            }
2286            _ => Err(GuiError::UnsupportedWidget("e2e.click")),
2287        }
2288    }
2289
2290    #[cfg(feature = "e2e")]
2291    fn e2e_type_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
2292        self.e2e_mock_type_text(widget_id, text)
2293    }
2294
2295    #[cfg(feature = "e2e")]
2296    fn e2e_check(&mut self, widget_id: WidgetId, checked: bool) -> GuiResult<()> {
2297        #[cfg(feature = "widgets-choice")]
2298        let is_checkbox = self
2299            .created
2300            .get(&widget_id)
2301            .ok_or(GuiError::WidgetNotFound(widget_id.0))?
2302            .kind
2303            == WidgetKind::Checkbox;
2304        #[cfg(not(feature = "widgets-choice"))]
2305        let is_checkbox = false;
2306
2307        if !is_checkbox {
2308            return Err(GuiError::UnsupportedWidget("e2e.check"));
2309        }
2310        self.e2e_mock_check(widget_id, checked)
2311    }
2312
2313    #[cfg(feature = "e2e")]
2314    fn e2e_text(&self, widget_id: WidgetId) -> GuiResult<String> {
2315        Ok(self
2316            .created
2317            .get(&widget_id)
2318            .ok_or(GuiError::WidgetNotFound(widget_id.0))?
2319            .text
2320            .clone()
2321            .unwrap_or_default())
2322    }
2323
2324    #[cfg(feature = "e2e")]
2325    fn e2e_checked(&self, widget_id: WidgetId) -> GuiResult<bool> {
2326        let spec = self
2327            .created
2328            .get(&widget_id)
2329            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
2330        #[cfg(feature = "widgets-choice")]
2331        let is_checkbox = spec.kind == WidgetKind::Checkbox;
2332        #[cfg(not(feature = "widgets-choice"))]
2333        let is_checkbox = false;
2334
2335        if !is_checkbox {
2336            return Err(GuiError::UnsupportedWidget("e2e.checked"));
2337        }
2338        Ok(spec.checked.unwrap_or(false))
2339    }
2340    type NativeHandle = usize;
2341    #[cfg(feature = "property-grid")]
2342    fn host_advanced_control(
2343        &mut self,
2344        host: WidgetId,
2345        family: native_gui_core::advanced::AdvancedFamily,
2346    ) -> GuiResult<native_gui_core::advanced::AdvancedHostCapabilities> {
2347        if !self.created.contains_key(&host) {
2348            return Err(GuiError::WidgetNotFound(host.0));
2349        }
2350        match family {
2351            native_gui_core::advanced::AdvancedFamily::PropertyGrid => {
2352                self.advanced_hosts.insert(host);
2353                Ok(native_gui_core::advanced::AdvancedHostCapabilities {
2354                    supported: true,
2355                    portable: true,
2356                    engine: self.advanced_engine.clone(),
2357                    decisions: native_gui_core::advanced::DecisionCounters::new(),
2358                })
2359            }
2360            other => Err(GuiError::UnsupportedCapability(format!(
2361                "advanced_control_{}",
2362                other.as_str()
2363            ))),
2364        }
2365    }
2366
2367    fn create_widget(&mut self, spec: &WidgetSpec) -> GuiResult<()> {
2368        #[cfg(not(feature = "widgets-media"))]
2369        if WidgetProperty::ImageSource.supports(spec.kind) {
2370            return Err(GuiError::UnsupportedWidget("unsupported widget kind"));
2371        }
2372        self.created.insert(spec.id, spec.clone());
2373        Ok(())
2374    }
2375
2376    fn create_menu(&mut self, menu_id: MenuId) -> GuiResult<()> {
2377        self.menus.entry(menu_id).or_default();
2378        Ok(())
2379    }
2380
2381    fn add_submenu(
2382        &mut self,
2383        parent_id: MenuId,
2384        submenu_id: MenuId,
2385        slot_id: MenuItemId,
2386        _text: &str,
2387    ) -> GuiResult<()> {
2388        self.menus.entry(submenu_id).or_default();
2389        if let Some(items) = self.menus.get_mut(&parent_id) {
2390            items.push(slot_id);
2391        }
2392        self.menu_submenu_slots.insert(submenu_id, slot_id);
2393        Ok(())
2394    }
2395
2396    fn create_menu_item(
2397        &mut self,
2398        menu_id: MenuId,
2399        item_id: MenuItemId,
2400        text: &str,
2401        shortcut: Option<&str>,
2402    ) -> GuiResult<()> {
2403        let Some(items) = self.menus.get_mut(&menu_id) else {
2404            return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
2405        };
2406        items.push(item_id);
2407        self.menu_item_text.insert(item_id, text.to_owned());
2408        if let Some(value) = shortcut {
2409            self.menu_shortcuts.insert(item_id, value.to_owned());
2410        }
2411        Ok(())
2412    }
2413
2414    fn attach_menu_to_window(&mut self, window_id: WidgetId, menu_id: MenuId) -> GuiResult<()> {
2415        if !self.created.contains_key(&window_id) {
2416            return Err(GuiError::WidgetNotFound(window_id.0));
2417        }
2418        if !self.menus.contains_key(&menu_id) {
2419            return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
2420        }
2421        Ok(())
2422    }
2423
2424    fn attach_context_menu(&mut self, widget_id: WidgetId, menu_id: MenuId) -> GuiResult<()> {
2425        if !self.created.contains_key(&widget_id) {
2426            return Err(GuiError::WidgetNotFound(widget_id.0));
2427        }
2428        if !self.menus.contains_key(&menu_id) {
2429            return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
2430        }
2431        self.context_menus.insert(widget_id, menu_id);
2432        Ok(())
2433    }
2434
2435    fn show_confirm_dialog(&mut self, token: u64, title: &str, message: &str) -> GuiResult<()> {
2436        // Headless backend: record the request; tests push the matching
2437        // `UiEvent::DialogResponse` to simulate the user's answer.
2438        self.confirm_requests
2439            .push((token, title.to_owned(), message.to_owned()));
2440        Ok(())
2441    }
2442
2443    fn show_file_dialog(
2444        &mut self,
2445        token: u64,
2446        request: &native_gui_core::file_dialog::FileDialog,
2447    ) -> GuiResult<()> {
2448        // Headless backend: record the request; tests answer it with
2449        // `inject_file_dialog_result`.
2450        self.file_dialog_requests.push((token, request.clone()));
2451        Ok(())
2452    }
2453
2454    fn set_close_guard(&mut self, widget_id: WidgetId, guarded: bool) -> GuiResult<()> {
2455        if !self.created.contains_key(&widget_id) {
2456            return Err(GuiError::WidgetNotFound(widget_id.0));
2457        }
2458        self.close_guards.insert(widget_id, guarded);
2459        Ok(())
2460    }
2461
2462    fn set_menu_item_enabled(&mut self, item_id: MenuItemId, enabled: bool) -> GuiResult<()> {
2463        let known = self.menus.values().any(|items| items.contains(&item_id));
2464        if !known {
2465            return Err(GuiError::Backend(format!(
2466                "Menu item not found: {}",
2467                item_id.0
2468            )));
2469        }
2470        self.menu_item_enabled.insert(item_id, enabled);
2471        Ok(())
2472    }
2473
2474    fn set_menu_item_text(&mut self, item_id: MenuItemId, text: &str) -> GuiResult<()> {
2475        let known = self.menus.values().any(|items| items.contains(&item_id));
2476        if !known {
2477            return Err(GuiError::Backend(format!(
2478                "Menu item not found: {}",
2479                item_id.0
2480            )));
2481        }
2482        self.menu_item_text.insert(item_id, text.to_owned());
2483        Ok(())
2484    }
2485
2486    fn insert_menu_item(
2487        &mut self,
2488        menu_id: MenuId,
2489        item_id: MenuItemId,
2490        index: usize,
2491        text: &str,
2492        shortcut: Option<&str>,
2493    ) -> GuiResult<()> {
2494        let Some(items) = self.menus.get_mut(&menu_id) else {
2495            return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
2496        };
2497        let position = index.min(items.len());
2498        items.insert(position, item_id);
2499        self.menu_item_text.insert(item_id, text.to_owned());
2500        if let Some(value) = shortcut {
2501            self.menu_shortcuts.insert(item_id, value.to_owned());
2502        }
2503        Ok(())
2504    }
2505
2506    fn remove_menu_item(&mut self, item_id: MenuItemId) -> GuiResult<()> {
2507        let known = self.menus.values().any(|items| items.contains(&item_id));
2508        if !known {
2509            return Err(GuiError::Backend(format!(
2510                "Menu item not found: {}",
2511                item_id.0
2512            )));
2513        }
2514        for items in self.menus.values_mut() {
2515            items.retain(|item| *item != item_id);
2516        }
2517        self.menu_item_text.remove(&item_id);
2518        self.menu_item_enabled.remove(&item_id);
2519        self.menu_shortcuts.remove(&item_id);
2520        Ok(())
2521    }
2522
2523    fn remove_submenu(&mut self, submenu_id: MenuId) -> GuiResult<()> {
2524        let Some(slot) = self.menu_submenu_slots.remove(&submenu_id) else {
2525            return Err(GuiError::Backend(format!(
2526                "Submenu not found: {}",
2527                submenu_id.0
2528            )));
2529        };
2530        let Some(items) = self.menus.get_mut(&submenu_id) else {
2531            return Err(GuiError::Backend(format!(
2532                "Submenu not found: {}",
2533                submenu_id.0
2534            )));
2535        };
2536        let orphaned = std::mem::take(items);
2537        for owner in self.menus.values_mut() {
2538            owner.retain(|item| *item != slot);
2539        }
2540        self.menus.remove(&submenu_id);
2541        for item in orphaned {
2542            self.menu_item_text.remove(&item);
2543            self.menu_item_enabled.remove(&item);
2544            self.menu_shortcuts.remove(&item);
2545        }
2546        Ok(())
2547    }
2548
2549    fn set_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
2550        let Some(spec) = self.created.get_mut(&widget_id) else {
2551            return Err(GuiError::WidgetNotFound(widget_id.0));
2552        };
2553        spec.text = Some(text.to_owned());
2554        if let Some((start, end)) = spec.text_selection {
2555            let len = text.chars().count();
2556            spec.text_selection = Some((start.min(len), end.min(len)));
2557        }
2558        Ok(())
2559    }
2560
2561    fn set_label_alignment(
2562        &mut self,
2563        widget_id: WidgetId,
2564        alignment: LabelAlignment,
2565    ) -> GuiResult<()> {
2566        let Some(spec) = self.created.get_mut(&widget_id) else {
2567            return Err(GuiError::WidgetNotFound(widget_id.0));
2568        };
2569        spec.ensure_property(WidgetProperty::LabelAlignment)?;
2570        spec.label_alignment = alignment;
2571        Ok(())
2572    }
2573
2574    fn set_label_wrap(&mut self, widget_id: WidgetId, wrap: LabelWrap) -> GuiResult<()> {
2575        let Some(spec) = self.created.get_mut(&widget_id) else {
2576            return Err(GuiError::WidgetNotFound(widget_id.0));
2577        };
2578        spec.ensure_property(WidgetProperty::LabelWrap)?;
2579        spec.label_wrap = wrap;
2580        Ok(())
2581    }
2582
2583    fn text_selection(&self, widget_id: WidgetId) -> GuiResult<(usize, usize)> {
2584        if !self.created.contains_key(&widget_id) {
2585            return Err(GuiError::WidgetNotFound(widget_id.0));
2586        }
2587        self.user_text_selections
2588            .get(&widget_id)
2589            .copied()
2590            .ok_or_else(|| GuiError::UnsupportedCapability("text_selection".to_owned()))
2591    }
2592
2593    fn set_text_selection(
2594        &mut self,
2595        widget_id: WidgetId,
2596        start: usize,
2597        end: usize,
2598    ) -> GuiResult<()> {
2599        let Some(spec) = self.created.get_mut(&widget_id) else {
2600            return Err(GuiError::WidgetNotFound(widget_id.0));
2601        };
2602        spec.ensure_property(WidgetProperty::TextSelection)?;
2603        spec.text_selection = Some((start, end));
2604        Ok(())
2605    }
2606
2607    fn set_text_completion_items(
2608        &mut self,
2609        widget_id: WidgetId,
2610        items: &[String],
2611    ) -> GuiResult<()> {
2612        let Some(spec) = self.created.get_mut(&widget_id) else {
2613            return Err(GuiError::WidgetNotFound(widget_id.0));
2614        };
2615        spec.ensure_property(WidgetProperty::TextCompletion)?;
2616        spec.completion_items = items.to_vec();
2617        Ok(())
2618    }
2619
2620    fn set_placeholder_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
2621        let Some(spec) = self.created.get_mut(&widget_id) else {
2622            return Err(GuiError::WidgetNotFound(widget_id.0));
2623        };
2624        spec.ensure_property(WidgetProperty::PlaceholderText)?;
2625        spec.placeholder_text = if text.is_empty() {
2626            None
2627        } else {
2628            Some(text.to_owned())
2629        };
2630        Ok(())
2631    }
2632
2633    fn set_monospace(&mut self, widget_id: WidgetId, monospace: bool) -> GuiResult<()> {
2634        let Some(spec) = self.created.get_mut(&widget_id) else {
2635            return Err(GuiError::WidgetNotFound(widget_id.0));
2636        };
2637        spec.ensure_property(WidgetProperty::Monospace)?;
2638        spec.monospace = monospace;
2639        self.monospace.insert(widget_id, monospace);
2640        Ok(())
2641    }
2642
2643    fn set_font(
2644        &mut self,
2645        widget_id: WidgetId,
2646        font: Option<&native_gui_core::FontDescriptor>,
2647    ) -> GuiResult<()> {
2648        let Some(spec) = self.created.get_mut(&widget_id) else {
2649            return Err(GuiError::WidgetNotFound(widget_id.0));
2650        };
2651        spec.ensure_property(WidgetProperty::Font)?;
2652        if let Some(descriptor) = font {
2653            descriptor
2654                .validate()
2655                .map_err(|error| GuiError::Backend(error.to_string()))?;
2656        }
2657        spec.font = font.cloned();
2658        Ok(())
2659    }
2660
2661    fn set_row_icons(
2662        &mut self,
2663        widget_id: WidgetId,
2664        icons: &[Option<native_gui_core::IconRole>],
2665    ) -> GuiResult<()> {
2666        let Some(spec) = self.created.get_mut(&widget_id) else {
2667            return Err(GuiError::WidgetNotFound(widget_id.0));
2668        };
2669        spec.ensure_property(WidgetProperty::RowIcons)?;
2670        spec.row_icons = icons.to_vec();
2671        Ok(())
2672    }
2673
2674    fn set_spell_check(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
2675        if !self.created.contains_key(&widget_id) {
2676            return Err(GuiError::WidgetNotFound(widget_id.0));
2677        }
2678        self.spell_check.insert(widget_id, enabled);
2679        Ok(())
2680    }
2681
2682    fn set_rich_text_runs(&mut self, widget_id: WidgetId, runs: &[TextRun]) -> GuiResult<()> {
2683        let Some(spec) = self.created.get_mut(&widget_id) else {
2684            return Err(GuiError::WidgetNotFound(widget_id.0));
2685        };
2686        spec.ensure_property(WidgetProperty::RichTextRuns)?;
2687        spec.rich_text_runs = runs.to_vec();
2688        Ok(())
2689    }
2690
2691    fn set_rich_text_images(
2692        &mut self,
2693        widget_id: WidgetId,
2694        images: &[RichTextImage],
2695    ) -> GuiResult<()> {
2696        let Some(spec) = self.created.get_mut(&widget_id) else {
2697            return Err(GuiError::WidgetNotFound(widget_id.0));
2698        };
2699        spec.ensure_property(WidgetProperty::RichTextImages)?;
2700        spec.rich_text_images = images.to_vec();
2701        self.rich_text_images.insert(widget_id, images.to_vec());
2702        Ok(())
2703    }
2704
2705    fn set_checked(&mut self, widget_id: WidgetId, checked: bool) -> GuiResult<()> {
2706        let Some(spec) = self.created.get_mut(&widget_id) else {
2707            return Err(GuiError::WidgetNotFound(widget_id.0));
2708        };
2709        spec.ensure_property(WidgetProperty::Checked)?;
2710        spec.checked = Some(checked);
2711        Ok(())
2712    }
2713
2714    fn set_value(&mut self, widget_id: WidgetId, value: i32) -> GuiResult<()> {
2715        let Some(spec) = self.created.get_mut(&widget_id) else {
2716            return Err(GuiError::WidgetNotFound(widget_id.0));
2717        };
2718        spec.ensure_property(WidgetProperty::Value)?;
2719
2720        spec.value = Some(value);
2721        Ok(())
2722    }
2723
2724    fn set_range(&mut self, widget_id: WidgetId, min: i32, max: i32) -> GuiResult<()> {
2725        let Some(spec) = self.created.get_mut(&widget_id) else {
2726            return Err(GuiError::WidgetNotFound(widget_id.0));
2727        };
2728        spec.ensure_property(WidgetProperty::Range)?;
2729
2730        spec.range = Some((min, max));
2731        Ok(())
2732    }
2733
2734    fn set_step(&mut self, widget_id: WidgetId, step: i32) -> GuiResult<()> {
2735        let Some(spec) = self.created.get_mut(&widget_id) else {
2736            return Err(GuiError::WidgetNotFound(widget_id.0));
2737        };
2738        spec.ensure_property(WidgetProperty::Step)?;
2739
2740        spec.step = Some(step);
2741        Ok(())
2742    }
2743
2744    fn set_selected_index(&mut self, widget_id: WidgetId, index: usize) -> GuiResult<()> {
2745        let Some(spec) = self.created.get_mut(&widget_id) else {
2746            return Err(GuiError::WidgetNotFound(widget_id.0));
2747        };
2748        spec.ensure_property(WidgetProperty::SelectedIndex)?;
2749
2750        spec.selected_index = Some(index);
2751        Ok(())
2752    }
2753
2754    fn set_selected_indices(&mut self, widget_id: WidgetId, indices: &[usize]) -> GuiResult<()> {
2755        let Some(spec) = self.created.get_mut(&widget_id) else {
2756            return Err(GuiError::WidgetNotFound(widget_id.0));
2757        };
2758        spec.ensure_property(WidgetProperty::SelectedIndices)?;
2759
2760        spec.selected_indices = indices.to_vec();
2761        Ok(())
2762    }
2763
2764    fn set_row_drag(&mut self, widget_id: WidgetId, source: bool, target: bool) -> GuiResult<()> {
2765        let Some(spec) = self.created.get_mut(&widget_id) else {
2766            return Err(GuiError::WidgetNotFound(widget_id.0));
2767        };
2768        spec.ensure_property(WidgetProperty::RowDrag)?;
2769
2770        spec.row_drag_source = source;
2771        spec.row_drop_target = target;
2772        Ok(())
2773    }
2774
2775    fn set_file_drop_target(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
2776        let Some(spec) = self.created.get_mut(&widget_id) else {
2777            return Err(GuiError::WidgetNotFound(widget_id.0));
2778        };
2779        spec.file_drop_target = enabled;
2780        Ok(())
2781    }
2782
2783    fn set_size(&mut self, widget_id: WidgetId, width: i32, height: i32) -> GuiResult<()> {
2784        let Some(spec) = self.created.get_mut(&widget_id) else {
2785            return Err(GuiError::WidgetNotFound(widget_id.0));
2786        };
2787        spec.size = Some((width, height));
2788        *self.size_writes.entry(widget_id).or_insert(0) += 1;
2789        Ok(())
2790    }
2791
2792    /// Records the layout size floor forwarded by `Ui::set_min_size`.
2793    /// Mock owns no layout, so the floor is stored only for contract
2794    /// assertions and `(0, 0)` clears it.
2795    fn set_min_size(&mut self, widget_id: WidgetId, width: i32, height: i32) -> GuiResult<()> {
2796        if !self.created.contains_key(&widget_id) {
2797            return Err(GuiError::WidgetNotFound(widget_id.0));
2798        }
2799        if width == 0 && height == 0 {
2800            self.min_sizes.remove(&widget_id);
2801        } else {
2802            self.min_sizes
2803                .insert(widget_id, (width.max(0), height.max(0)));
2804        }
2805        Ok(())
2806    }
2807
2808    fn set_combo_box_items(&mut self, widget_id: WidgetId, _items: &[String]) -> GuiResult<()> {
2809        let Some(_spec) = self.created.get_mut(&widget_id) else {
2810            return Err(GuiError::WidgetNotFound(widget_id.0));
2811        };
2812        #[cfg(feature = "widgets-choice")]
2813        if _spec.kind != WidgetKind::ComboBox {
2814            return Err(GuiError::UnsupportedWidget("set_combo_box_items"));
2815        }
2816        #[cfg(not(feature = "widgets-choice"))]
2817        return Err(GuiError::UnsupportedWidget("set_combo_box_items"));
2818        #[cfg(feature = "widgets-choice")]
2819        {
2820            _spec.text = Some(_items.join("|"));
2821            _spec.selected_index = match _spec.selected_index {
2822                Some(index) if index < _items.len() => Some(index),
2823                _ if _items.is_empty() => None,
2824                _ => Some(0),
2825            };
2826            Ok(())
2827        }
2828    }
2829
2830    fn set_data_list_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()> {
2831        let Some(spec) = self.created.get_mut(&widget_id) else {
2832            return Err(GuiError::WidgetNotFound(widget_id.0));
2833        };
2834        spec.ensure_property(WidgetProperty::DataListItems)?;
2835
2836        spec.data_list_items = items.to_vec();
2837        *self.row_writes.entry(widget_id).or_insert(0) += 1;
2838        Ok(())
2839    }
2840
2841    fn set_list_columns(&mut self, widget_id: WidgetId, columns: &[ColumnSpec]) -> GuiResult<()> {
2842        let Some(spec) = self.created.get_mut(&widget_id) else {
2843            return Err(GuiError::WidgetNotFound(widget_id.0));
2844        };
2845        spec.ensure_property(WidgetProperty::ListViewColumns)?;
2846
2847        spec.list_columns = columns.to_vec();
2848        Ok(())
2849    }
2850
2851    fn set_list_rows(&mut self, widget_id: WidgetId, rows: &[Vec<String>]) -> GuiResult<()> {
2852        let Some(spec) = self.created.get_mut(&widget_id) else {
2853            return Err(GuiError::WidgetNotFound(widget_id.0));
2854        };
2855        spec.ensure_property(WidgetProperty::ListViewRows)?;
2856
2857        spec.list_rows = rows.to_vec();
2858        Ok(())
2859    }
2860
2861    fn clear_selection(&mut self, widget_id: WidgetId) -> GuiResult<()> {
2862        let Some(spec) = self.created.get_mut(&widget_id) else {
2863            return Err(GuiError::WidgetNotFound(widget_id.0));
2864        };
2865        spec.ensure_property(WidgetProperty::ClearSelection)?;
2866
2867        spec.selected_index = None;
2868        spec.selected_indices.clear();
2869        self.selection_clears.push(widget_id);
2870        Ok(())
2871    }
2872
2873    fn visible_anchor_index(&self, widget_id: WidgetId) -> GuiResult<Option<usize>> {
2874        if !self.created.contains_key(&widget_id) {
2875            return Err(GuiError::WidgetNotFound(widget_id.0));
2876        }
2877        Ok(self.scroll_anchors.get(&widget_id).copied())
2878    }
2879
2880    fn scroll_to_row(&mut self, widget_id: WidgetId, index: usize) -> GuiResult<()> {
2881        if !self.created.contains_key(&widget_id) {
2882            return Err(GuiError::WidgetNotFound(widget_id.0));
2883        }
2884        if let Some(error) = self.scroll_failures.get(&widget_id) {
2885            return Err(error.clone());
2886        }
2887        // Model a lane that really scrolls: the topmost visible row becomes
2888        // `index`, so a later `visible_anchor_index` reports the moved anchor.
2889        self.scroll_anchors.insert(widget_id, index);
2890        self.scroll_requests.push((widget_id, index));
2891        Ok(())
2892    }
2893
2894    #[cfg(feature = "widgets-data")]
2895    fn rows_end_visible(&self, widget_id: WidgetId) -> GuiResult<bool> {
2896        let spec = self
2897            .created
2898            .get(&widget_id)
2899            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
2900        let row_count = match spec.kind {
2901            WidgetKind::DataList => spec.data_list_items.len(),
2902            WidgetKind::ListView if spec.list_columns.is_empty() => spec.data_list_items.len(),
2903            WidgetKind::ListView => spec.list_rows.len(),
2904            WidgetKind::DataGrid => spec.data_grid_rows.len(),
2905            _ => return Err(GuiError::UnsupportedCapability("scroll_anchor".to_owned())),
2906        };
2907        if row_count == 0 {
2908            return Ok(false);
2909        }
2910        let top = self
2911            .scroll_anchors
2912            .get(&widget_id)
2913            .copied()
2914            .ok_or_else(|| GuiError::UnsupportedCapability("scroll_anchor".to_owned()))?;
2915        let visible_rows = self
2916            .visible_row_counts
2917            .get(&widget_id)
2918            .copied()
2919            .unwrap_or(1);
2920        Ok(top.saturating_add(visible_rows) >= row_count)
2921    }
2922
2923    #[cfg(not(feature = "widgets-data"))]
2924    fn rows_end_visible(&self, _widget_id: WidgetId) -> GuiResult<bool> {
2925        Err(GuiError::UnsupportedCapability("scroll_anchor".to_owned()))
2926    }
2927
2928    fn set_tab_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()> {
2929        let Some(spec) = self.created.get_mut(&widget_id) else {
2930            return Err(GuiError::WidgetNotFound(widget_id.0));
2931        };
2932        spec.ensure_property(WidgetProperty::TabItems)?;
2933        spec.tab_items = items.to_vec();
2934        Ok(())
2935    }
2936
2937    #[cfg(feature = "widgets-data")]
2938    fn apply_row_delta(
2939        &mut self,
2940        widget_id: WidgetId,
2941        ops: &[native_gui_core::widgets::RowOp],
2942    ) -> GuiResult<()> {
2943        let Some(spec) = self.created.get_mut(&widget_id) else {
2944            return Err(GuiError::WidgetNotFound(widget_id.0));
2945        };
2946        match spec.kind {
2947            WidgetKind::DataGrid => {
2948                spec.ensure_property(WidgetProperty::DataGridRows)?;
2949                let rows = Arc::make_mut(&mut spec.data_grid_rows);
2950                native_gui_core::widgets::apply_row_ops_to_cells(rows, ops);
2951            }
2952            WidgetKind::DataList => {
2953                spec.ensure_property(WidgetProperty::DataListItems)?;
2954                native_gui_core::widgets::apply_row_ops_to_items(&mut spec.data_list_items, ops);
2955            }
2956            WidgetKind::ListView => {
2957                if !spec.list_columns.is_empty() {
2958                    spec.ensure_property(WidgetProperty::ListViewRows)?;
2959                    native_gui_core::widgets::apply_row_ops_to_cells(&mut spec.list_rows, ops);
2960                } else {
2961                    spec.ensure_property(WidgetProperty::DataListItems)?;
2962                    native_gui_core::widgets::apply_row_ops_to_items(
2963                        &mut spec.data_list_items,
2964                        ops,
2965                    );
2966                }
2967            }
2968            _ => return Err(GuiError::UnsupportedWidget("apply_row_delta")),
2969        }
2970        *self.row_writes.entry(widget_id).or_insert(0) += 1;
2971        self.applied_row_ops.push((widget_id, ops.to_vec()));
2972        Ok(())
2973    }
2974
2975    #[cfg(not(feature = "widgets-data"))]
2976    fn apply_row_delta(
2977        &mut self,
2978        _widget_id: WidgetId,
2979        _ops: &[native_gui_core::widgets::RowOp],
2980    ) -> GuiResult<()> {
2981        Err(GuiError::UnsupportedWidget("apply_row_delta"))
2982    }
2983
2984    fn set_data_grid_rows(
2985        &mut self,
2986        widget_id: WidgetId,
2987        rows: Arc<Vec<Vec<String>>>,
2988    ) -> GuiResult<()> {
2989        let Some(spec) = self.created.get_mut(&widget_id) else {
2990            return Err(GuiError::WidgetNotFound(widget_id.0));
2991        };
2992        spec.ensure_property(WidgetProperty::DataGridRows)?;
2993
2994        // Shares the manager's allocation instead of copying it.
2995        spec.data_grid_rows = rows;
2996        *self.row_writes.entry(widget_id).or_insert(0) += 1;
2997        Ok(())
2998    }
2999
3000    fn set_data_grid_model(
3001        &mut self,
3002        widget_id: WidgetId,
3003        model: Box<dyn native_gui_core::widgets::DataGridModel>,
3004    ) -> GuiResult<()> {
3005        let Some(spec) = self.created.get(&widget_id) else {
3006            return Err(GuiError::WidgetNotFound(widget_id.0));
3007        };
3008        spec.ensure_property(WidgetProperty::DataGridModel)?;
3009        // Retain the model instead of dropping it. Row data stays
3010        // virtual: `WidgetSpec::data_grid_rows` is untouched and no
3011        // `row_writes` entry is recorded, so the two population paths remain
3012        // distinguishable.
3013        self.data_grid_models
3014            .insert(widget_id, RetainedDataGridModel(model));
3015        Ok(())
3016    }
3017
3018    fn set_data_grid_row_height(
3019        &mut self,
3020        widget_id: WidgetId,
3021        row: usize,
3022        height: i32,
3023    ) -> GuiResult<()> {
3024        let Some(spec) = self.created.get(&widget_id) else {
3025            return Err(GuiError::WidgetNotFound(widget_id.0));
3026        };
3027        spec.ensure_property(WidgetProperty::DataGridRowHeight)?;
3028        if height > 0 {
3029            self.data_grid_row_heights.insert((widget_id, row), height);
3030        } else {
3031            self.data_grid_row_heights.remove(&(widget_id, row));
3032        }
3033        Ok(())
3034    }
3035
3036    fn set_data_grid_col_width(
3037        &mut self,
3038        widget_id: WidgetId,
3039        col: usize,
3040        width: i32,
3041    ) -> GuiResult<()> {
3042        let Some(spec) = self.created.get(&widget_id) else {
3043            return Err(GuiError::WidgetNotFound(widget_id.0));
3044        };
3045        spec.ensure_property(WidgetProperty::DataGridColWidth)?;
3046        if width > 0 {
3047            self.data_grid_col_widths.insert((widget_id, col), width);
3048        } else {
3049            self.data_grid_col_widths.remove(&(widget_id, col));
3050        }
3051        Ok(())
3052    }
3053
3054    fn set_data_grid_frozen_panes(
3055        &mut self,
3056        widget_id: WidgetId,
3057        _rows: usize,
3058        _cols: usize,
3059    ) -> GuiResult<()> {
3060        let Some(spec) = self.created.get(&widget_id) else {
3061            return Err(GuiError::WidgetNotFound(widget_id.0));
3062        };
3063        spec.ensure_property(WidgetProperty::DataGridFrozenPanes)?;
3064        Ok(())
3065    }
3066
3067    fn set_data_grid_selection(
3068        &mut self,
3069        widget_id: WidgetId,
3070        selection: &[(usize, usize)],
3071    ) -> GuiResult<()> {
3072        let Some(spec) = self.created.get(&widget_id) else {
3073            return Err(GuiError::WidgetNotFound(widget_id.0));
3074        };
3075        spec.ensure_property(WidgetProperty::DataGridSelection)?;
3076        self.data_grid_selections
3077            .insert(widget_id, selection.to_vec());
3078        Ok(())
3079    }
3080
3081    fn set_tree_items(
3082        &mut self,
3083        widget_id: WidgetId,
3084        items: &[native_gui_core::TreeItem],
3085    ) -> GuiResult<()> {
3086        let Some(spec) = self.created.get_mut(&widget_id) else {
3087            return Err(GuiError::WidgetNotFound(widget_id.0));
3088        };
3089        spec.ensure_property(WidgetProperty::TreeItems)?;
3090
3091        spec.tree_items = items.to_vec();
3092        Ok(())
3093    }
3094
3095    fn set_position(&mut self, widget_id: WidgetId, x: i32, y: i32) -> GuiResult<()> {
3096        let Some(spec) = self.created.get_mut(&widget_id) else {
3097            return Err(GuiError::WidgetNotFound(widget_id.0));
3098        };
3099        spec.position = Some((x, y));
3100        *self.position_writes.entry(widget_id).or_insert(0) += 1;
3101        Ok(())
3102    }
3103
3104    fn natural_size(&self, widget_id: WidgetId) -> Option<(i32, i32)> {
3105        self.natural_size_probes.fetch_add(1, Ordering::Relaxed);
3106        if let Some(&override_size) = self.natural_size_overrides.get(&widget_id) {
3107            return Some(override_size);
3108        }
3109        if !self.natural_sizes {
3110            return None;
3111        }
3112        self.created
3113            .get(&widget_id)
3114            .and_then(Self::mock_natural_size)
3115    }
3116
3117    fn set_background_color(&mut self, widget_id: WidgetId, color: Color) -> GuiResult<()> {
3118        let Some(spec) = self.created.get_mut(&widget_id) else {
3119            return Err(GuiError::WidgetNotFound(widget_id.0));
3120        };
3121        spec.background_color = Some(color);
3122        Ok(())
3123    }
3124
3125    fn set_alert_level(&mut self, widget_id: WidgetId, level: AlertLevel) -> GuiResult<()> {
3126        let Some(spec) = self.created.get_mut(&widget_id) else {
3127            return Err(GuiError::WidgetNotFound(widget_id.0));
3128        };
3129        spec.ensure_property(WidgetProperty::AlertLevel)?;
3130
3131        spec.alert_level = Some(level);
3132        Ok(())
3133    }
3134
3135    fn set_image_source(&mut self, widget_id: WidgetId, source: &str) -> GuiResult<()> {
3136        let Some(spec) = self.created.get_mut(&widget_id) else {
3137            return Err(GuiError::WidgetNotFound(widget_id.0));
3138        };
3139        spec.ensure_property(WidgetProperty::ImageSource)?;
3140
3141        spec.image_source = Some(source.to_owned());
3142        Ok(())
3143    }
3144
3145    fn set_image_fit(&mut self, widget_id: WidgetId, fit: ImageFit) -> GuiResult<()> {
3146        let Some(spec) = self.created.get_mut(&widget_id) else {
3147            return Err(GuiError::WidgetNotFound(widget_id.0));
3148        };
3149        spec.ensure_property(WidgetProperty::ImageFit)?;
3150
3151        spec.image_fit = fit;
3152        Ok(())
3153    }
3154
3155    fn set_file_chooser_mode(
3156        &mut self,
3157        widget_id: WidgetId,
3158        mode: FileChooserMode,
3159    ) -> GuiResult<()> {
3160        let Some(spec) = self.created.get_mut(&widget_id) else {
3161            return Err(GuiError::WidgetNotFound(widget_id.0));
3162        };
3163        spec.ensure_property(WidgetProperty::FileChooserMode)?;
3164
3165        spec.file_chooser_mode = mode;
3166        Ok(())
3167    }
3168
3169    fn set_icon(&mut self, widget_id: WidgetId, icon: Option<IconRole>) -> GuiResult<()> {
3170        let Some(spec) = self.created.get_mut(&widget_id) else {
3171            return Err(GuiError::WidgetNotFound(widget_id.0));
3172        };
3173        spec.ensure_property(WidgetProperty::ButtonIcon)?;
3174
3175        spec.icon = icon;
3176        Ok(())
3177    }
3178
3179    fn set_date_value(&mut self, widget_id: WidgetId, iso_date: &str) -> GuiResult<()> {
3180        let Some(spec) = self.created.get_mut(&widget_id) else {
3181            return Err(GuiError::WidgetNotFound(widget_id.0));
3182        };
3183        spec.ensure_property(WidgetProperty::DateValue)?;
3184
3185        spec.date_value = Some(iso_date.to_owned());
3186        Ok(())
3187    }
3188
3189    fn set_link_url(&mut self, widget_id: WidgetId, url: &str) -> GuiResult<()> {
3190        let Some(spec) = self.created.get_mut(&widget_id) else {
3191            return Err(GuiError::WidgetNotFound(widget_id.0));
3192        };
3193        spec.ensure_property(WidgetProperty::LinkUrl)?;
3194
3195        spec.link_url = Some(url.to_owned());
3196        Ok(())
3197    }
3198
3199    fn set_container_direction(
3200        &mut self,
3201        widget_id: WidgetId,
3202        direction: ContainerDirection,
3203    ) -> GuiResult<()> {
3204        let Some(spec) = self.created.get_mut(&widget_id) else {
3205            return Err(GuiError::WidgetNotFound(widget_id.0));
3206        };
3207        spec.ensure_property(WidgetProperty::ContainerDirection)?;
3208
3209        spec.container_direction = Some(direction);
3210        Ok(())
3211    }
3212
3213    fn set_container_wrap(&mut self, widget_id: WidgetId, wrap: ContainerWrap) -> GuiResult<()> {
3214        let Some(spec) = self.created.get_mut(&widget_id) else {
3215            return Err(GuiError::WidgetNotFound(widget_id.0));
3216        };
3217        spec.ensure_property(WidgetProperty::ContainerWrap)?;
3218
3219        spec.container_wrap = Some(wrap);
3220        Ok(())
3221    }
3222
3223    fn set_container_scroll(
3224        &mut self,
3225        widget_id: WidgetId,
3226        vertical: bool,
3227        horizontal: bool,
3228    ) -> GuiResult<()> {
3229        let Some(spec) = self.created.get_mut(&widget_id) else {
3230            return Err(GuiError::WidgetNotFound(widget_id.0));
3231        };
3232        spec.ensure_property(WidgetProperty::ContainerScroll)?;
3233
3234        spec.container_scroll_vertical = vertical;
3235        spec.container_scroll_horizontal = horizontal;
3236        Ok(())
3237    }
3238
3239    fn set_container_gap(&mut self, widget_id: WidgetId, gap: i32) -> GuiResult<()> {
3240        let Some(spec) = self.created.get_mut(&widget_id) else {
3241            return Err(GuiError::WidgetNotFound(widget_id.0));
3242        };
3243        spec.ensure_property(WidgetProperty::ContainerGap)?;
3244
3245        spec.container_gap = Some(gap.max(0));
3246        Ok(())
3247    }
3248
3249    fn set_container_padding(&mut self, widget_id: WidgetId, padding: i32) -> GuiResult<()> {
3250        let Some(spec) = self.created.get_mut(&widget_id) else {
3251            return Err(GuiError::WidgetNotFound(widget_id.0));
3252        };
3253        spec.ensure_property(WidgetProperty::ContainerPadding)?;
3254
3255        spec.container_padding = Some(padding.max(0));
3256        Ok(())
3257    }
3258
3259    fn draw_demo_cube(&mut self, widget_id: WidgetId) -> GuiResult<()> {
3260        let Some(spec) = self.created.get(&widget_id) else {
3261            return Err(GuiError::WidgetNotFound(widget_id.0));
3262        };
3263        spec.ensure_property(WidgetProperty::DrawDemoCube)?;
3264        if self.gpu_fallbacks.contains_key(&widget_id) {
3265            #[cfg(feature = "widgets-canvas")]
3266            let cap = if spec.kind == WidgetKind::MetalCanvas {
3267                "metal_surface"
3268            } else {
3269                "vulkan_surface"
3270            };
3271            #[cfg(not(feature = "widgets-canvas"))]
3272            let cap = "vulkan_surface";
3273            return Err(GuiError::UnsupportedCapability(cap.to_owned()));
3274        }
3275        Ok(())
3276    }
3277
3278    fn create_gpu_fallback(
3279        &mut self,
3280        spec: &WidgetSpec,
3281        policy: GpuDegradationPolicy,
3282    ) -> GuiResult<()> {
3283        let _ = spec;
3284        let _ = policy;
3285        #[cfg(feature = "widgets-canvas")]
3286        if spec.kind != WidgetKind::VulkanCanvas && spec.kind != WidgetKind::MetalCanvas {
3287            return Err(GuiError::UnsupportedWidget("vulkan_canvas"));
3288        }
3289        #[cfg(not(feature = "widgets-canvas"))]
3290        return Err(GuiError::UnsupportedWidget("vulkan_canvas"));
3291        #[allow(unreachable_code)]
3292        let capabilities = self.gpu_surface_capabilities();
3293        let supported = match policy {
3294            GpuDegradationPolicy::StrictFail => false,
3295            GpuDegradationPolicy::DiagnosticPlaceholder => capabilities.diagnostic_placeholder,
3296            GpuDegradationPolicy::Canvas2DFallback => capabilities.headless_emulation,
3297        };
3298        if !supported {
3299            return Err(GuiError::UnsupportedCapability(
3300                "gpu_degradation_fallback".to_owned(),
3301            ));
3302        }
3303        self.created.insert(spec.id, spec.clone());
3304        self.gpu_fallbacks.insert(spec.id, policy);
3305        Ok(())
3306    }
3307
3308    fn set_canvas_scene(
3309        &mut self,
3310        widget_id: WidgetId,
3311        scene: &native_gui_core::CanvasScene,
3312    ) -> GuiResult<()> {
3313        let Some(spec) = self.created.get_mut(&widget_id) else {
3314            return Err(GuiError::WidgetNotFound(widget_id.0));
3315        };
3316        #[cfg(feature = "widgets-canvas")]
3317        let skip_property = spec.kind == WidgetKind::VulkanCanvas
3318            && self.gpu_fallbacks.get(&widget_id) == Some(&GpuDegradationPolicy::Canvas2DFallback);
3319        #[cfg(not(feature = "widgets-canvas"))]
3320        let skip_property = false;
3321        if !skip_property {
3322            spec.ensure_property(WidgetProperty::CanvasScene)?;
3323        }
3324        spec.canvas_scene = Some(scene.clone());
3325        self.last_canvas_scene = Some(scene.clone());
3326        Ok(())
3327    }
3328
3329    fn set_canvas_surface(
3330        &mut self,
3331        widget_id: WidgetId,
3332        surface: &native_gui_core::CanvasSurface,
3333    ) -> GuiResult<()> {
3334        let Some(spec) = self.created.get_mut(&widget_id) else {
3335            return Err(GuiError::WidgetNotFound(widget_id.0));
3336        };
3337        spec.ensure_property(WidgetProperty::CanvasSurface)?;
3338        spec.canvas_surface = Some(surface.clone());
3339        self.last_canvas_surface = Some(surface.clone());
3340        Ok(())
3341    }
3342
3343    fn native_handle(&self, widget_id: WidgetId) -> GuiResult<Self::NativeHandle> {
3344        let Some(spec) = self.created.get(&widget_id) else {
3345            return Err(GuiError::WidgetNotFound(widget_id.0));
3346        };
3347        spec.ensure_property(WidgetProperty::NativeHandle)?;
3348        if self.gpu_fallbacks.contains_key(&widget_id) {
3349            return Err(GuiError::UnsupportedCapability("vulkan_surface".to_owned()));
3350        }
3351
3352        Ok(widget_id.0 as usize)
3353    }
3354
3355    fn metal_canvas_handle(
3356        &self,
3357        widget_id: WidgetId,
3358    ) -> GuiResult<native_gui_core::ui::MetalCanvasHandle> {
3359        let Some(spec) = self.created.get(&widget_id) else {
3360            return Err(GuiError::WidgetNotFound(widget_id.0));
3361        };
3362        spec.ensure_property(WidgetProperty::MetalHandle)?;
3363        if self.gpu_fallbacks.contains_key(&widget_id) {
3364            return Err(GuiError::UnsupportedCapability("metal_surface".to_owned()));
3365        }
3366
3367        Ok(native_gui_core::ui::MetalCanvasHandle {
3368            ns_view: widget_id.0 as usize,
3369            ca_metal_layer: widget_id.0 as usize,
3370            mtl_device: widget_id.0 as usize,
3371        })
3372    }
3373
3374    fn add_child(&mut self, parent: WidgetId, child: WidgetId) -> GuiResult<()> {
3375        if !self.created.contains_key(&parent) {
3376            return Err(GuiError::WidgetNotFound(parent.0));
3377        }
3378        let Some(spec) = self.created.get_mut(&child) else {
3379            return Err(GuiError::WidgetNotFound(child.0));
3380        };
3381        spec.parent = Some(parent);
3382        Ok(())
3383    }
3384
3385    fn show(&mut self, widget_id: WidgetId) -> GuiResult<()> {
3386        let spec = self
3387            .created
3388            .get(&widget_id)
3389            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
3390        if spec.kind == WidgetKind::Window {
3391            if let Some(options) = self.window_options.get(&widget_id).copied() {
3392                if options.show_effect != ShowEffect::None {
3393                    self.window_effects.push(MockWindowEffect::Show {
3394                        widget_id,
3395                        effect: options.show_effect,
3396                    });
3397                }
3398                if options.role == WindowRole::Popup {
3399                    let mut replaced: Vec<_> = self
3400                        .active_popup_sessions
3401                        .iter()
3402                        .copied()
3403                        .filter(|popup| {
3404                            *popup != widget_id
3405                                && self.window_options.get(popup).is_some_and(|active| {
3406                                    active.transient_for == options.transient_for
3407                                })
3408                        })
3409                        .collect();
3410                    replaced.sort_by_key(|popup| popup.0);
3411                    for popup in replaced {
3412                        self.end_popup_session(popup, Some(PopupDismissReason::Replaced));
3413                    }
3414                    self.active_popup_sessions.insert(widget_id);
3415                }
3416            }
3417        }
3418        self.resume_animation_on_show(widget_id)?;
3419        self.shown.push(widget_id);
3420        Ok(())
3421    }
3422
3423    fn hide(&mut self, widget_id: WidgetId) -> GuiResult<()> {
3424        if !self.created.contains_key(&widget_id) {
3425            return Err(GuiError::WidgetNotFound(widget_id.0));
3426        }
3427        self.cancel_widget_timers(widget_id, true);
3428        self.pause_animation_on_hide(widget_id);
3429        if let Some(options) = self.window_options.get(&widget_id) {
3430            if options.hide_effect != ShowEffect::None {
3431                self.window_effects.push(MockWindowEffect::Hide {
3432                    widget_id,
3433                    effect: options.hide_effect,
3434                });
3435            }
3436        }
3437        self.end_popup_session(widget_id, None);
3438        self.shown.retain(|&id| id != widget_id);
3439        Ok(())
3440    }
3441
3442    fn remove(&mut self, widget_id: WidgetId) -> GuiResult<()> {
3443        if !self.created.contains_key(&widget_id) {
3444            return Err(GuiError::WidgetNotFound(widget_id.0));
3445        }
3446        self.cancel_widget_timers(widget_id, false);
3447        self.cleanup_animation_on_remove(widget_id);
3448        self.cancel_drag_from_source(widget_id);
3449        if let Some((session, target)) = self
3450            .active_drag
3451            .as_ref()
3452            .and_then(|active| active.target.map(|target| (active.id, target)))
3453            .filter(|(_, target)| *target == widget_id)
3454        {
3455            self.mock_drag_exit(session, target);
3456        }
3457        self.created
3458            .remove(&widget_id)
3459            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
3460        #[cfg(feature = "webview")]
3461        self.forget_webview(widget_id);
3462        let mut owned_popups: Vec<_> = self
3463            .active_popup_sessions
3464            .iter()
3465            .copied()
3466            .filter(|popup| {
3467                self.window_options
3468                    .get(popup)
3469                    .is_some_and(|options| options.transient_for == Some(widget_id))
3470            })
3471            .collect();
3472        owned_popups.sort_by_key(|popup| popup.0);
3473        for popup in owned_popups {
3474            self.end_popup_session(popup, None);
3475        }
3476        self.end_popup_session(widget_id, None);
3477        self.window_options.remove(&widget_id);
3478        self.drag_source_options.remove(&widget_id);
3479        self.drag_target_options.remove(&widget_id);
3480        self.gpu_fallbacks.remove(&widget_id);
3481        self.shown.retain(|&id| id != widget_id);
3482        Ok(())
3483    }
3484
3485    fn set_enabled(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
3486        let Some(spec) = self.created.get_mut(&widget_id) else {
3487            return Err(GuiError::WidgetNotFound(widget_id.0));
3488        };
3489        spec.enabled = Some(enabled);
3490        Ok(())
3491    }
3492
3493    fn activate(&mut self, widget_id: WidgetId) -> GuiResult<()> {
3494        let Some(spec) = self.created.get(&widget_id) else {
3495            return Err(GuiError::WidgetNotFound(widget_id.0));
3496        };
3497        let kind = spec.kind;
3498        #[cfg(feature = "widgets-pickers")]
3499        if kind == WidgetKind::ColorDialog {
3500            // Scripted outcome; nothing injected means the user cancelled.
3501            let result = self.color_dialog_results.remove(&widget_id).unwrap_or(None);
3502            if let Some(color) = result {
3503                self.push_event(UiEvent::ColorChanged { widget_id, color });
3504            }
3505            self.push_event(UiEvent::ColorSelected {
3506                widget_id,
3507                color: result,
3508            });
3509            return Ok(());
3510        }
3511        #[cfg(feature = "widgets-pickers")]
3512        if kind == WidgetKind::FontDialog {
3513            let dialog_data = spec.font_dialog_data.clone();
3514            let result = self.font_dialog_results.remove(&widget_id).unwrap_or(None);
3515            if let Some((descriptor, effects)) = result {
3516                // The shared clamp runs where the answer is produced, so the
3517                // preview and the selection agree on the same size.
3518                let size = dialog_data
3519                    .as_ref()
3520                    .map(|data| data.clamp_size(descriptor.size_pt))
3521                    .unwrap_or(descriptor.size_pt);
3522                let descriptor = FontDescriptor {
3523                    size_pt: size,
3524                    ..descriptor
3525                };
3526                self.push_event(UiEvent::FontChanged {
3527                    widget_id,
3528                    descriptor: descriptor.clone(),
3529                });
3530                self.push_event(UiEvent::FontSelected {
3531                    widget_id,
3532                    selection: Some((descriptor, effects)),
3533                });
3534            } else {
3535                self.push_event(UiEvent::FontSelected {
3536                    widget_id,
3537                    selection: None,
3538                });
3539            }
3540            return Ok(());
3541        }
3542        if kind == WidgetKind::Toolbar {
3543            // Generic activation clicks the first enabled, visible tool; the
3544            // targeted injector below models a click on a specific tool.
3545            let first = spec.toolbar_items.iter().find_map(|item| {
3546                item.tool_spec()
3547                    .filter(|tool| tool.enabled && tool.visible)
3548                    .map(|tool| tool.id)
3549            });
3550            return match first {
3551                Some(tool_id) => self.click_tool(widget_id, tool_id),
3552                None => Ok(()),
3553            };
3554        }
3555        self.events.push_back(UiEvent::Clicked { widget_id });
3556        Ok(())
3557    }
3558
3559    fn set_font_dialog_data(
3560        &mut self,
3561        widget_id: WidgetId,
3562        data: &FontDialogData,
3563    ) -> GuiResult<()> {
3564        let Some(spec) = self.created.get_mut(&widget_id) else {
3565            return Err(GuiError::WidgetNotFound(widget_id.0));
3566        };
3567        spec.ensure_property(WidgetProperty::FontDialogData)?;
3568        spec.font_dialog_data = Some(data.clone());
3569        Ok(())
3570    }
3571
3572    fn set_color_dialog_data(
3573        &mut self,
3574        widget_id: WidgetId,
3575        data: &ColorDialogData,
3576    ) -> GuiResult<()> {
3577        let Some(spec) = self.created.get_mut(&widget_id) else {
3578            return Err(GuiError::WidgetNotFound(widget_id.0));
3579        };
3580        spec.ensure_property(WidgetProperty::ColorDialogData)?;
3581        spec.color_dialog_data = Some(data.clone());
3582        Ok(())
3583    }
3584
3585    fn set_toolbar_items(&mut self, widget_id: WidgetId, items: &[ToolbarItem]) -> GuiResult<()> {
3586        let Some(spec) = self.created.get_mut(&widget_id) else {
3587            return Err(GuiError::WidgetNotFound(widget_id.0));
3588        };
3589        spec.ensure_property(WidgetProperty::ToolbarItems)?;
3590        spec.toolbar_items = items.to_vec();
3591        Ok(())
3592    }
3593
3594    fn set_toolbar_orientation(
3595        &mut self,
3596        widget_id: WidgetId,
3597        orientation: ToolbarOrientation,
3598    ) -> GuiResult<()> {
3599        let Some(spec) = self.created.get_mut(&widget_id) else {
3600            return Err(GuiError::WidgetNotFound(widget_id.0));
3601        };
3602        spec.ensure_property(WidgetProperty::ToolbarOrientation)?;
3603        spec.toolbar_orientation = orientation;
3604        Ok(())
3605    }
3606
3607    fn set_calendar_selected_dates(
3608        &mut self,
3609        widget_id: WidgetId,
3610        dates: &[CalendarDate],
3611    ) -> GuiResult<()> {
3612        let Some(spec) = self.created.get_mut(&widget_id) else {
3613            return Err(GuiError::WidgetNotFound(widget_id.0));
3614        };
3615        spec.ensure_property(WidgetProperty::CalendarDates)?;
3616        spec.calendar_selected_dates = dates.to_vec();
3617        Ok(())
3618    }
3619
3620    fn set_calendar_bounds(
3621        &mut self,
3622        widget_id: WidgetId,
3623        min_date: Option<CalendarDate>,
3624        max_date: Option<CalendarDate>,
3625    ) -> GuiResult<()> {
3626        let Some(spec) = self.created.get_mut(&widget_id) else {
3627            return Err(GuiError::WidgetNotFound(widget_id.0));
3628        };
3629        spec.ensure_property(WidgetProperty::CalendarBounds)?;
3630        spec.calendar_min_date = min_date;
3631        spec.calendar_max_date = max_date;
3632        Ok(())
3633    }
3634
3635    fn set_calendar_first_day_of_week(
3636        &mut self,
3637        widget_id: WidgetId,
3638        first_day: CalendarFirstDayOfWeek,
3639    ) -> GuiResult<()> {
3640        let Some(spec) = self.created.get_mut(&widget_id) else {
3641            return Err(GuiError::WidgetNotFound(widget_id.0));
3642        };
3643        spec.ensure_property(WidgetProperty::CalendarFirstDayOfWeek)?;
3644        spec.calendar_first_day_of_week = first_day;
3645        Ok(())
3646    }
3647
3648    fn set_calendar_selection_mode(
3649        &mut self,
3650        widget_id: WidgetId,
3651        mode: CalendarSelectionMode,
3652    ) -> GuiResult<()> {
3653        let Some(spec) = self.created.get_mut(&widget_id) else {
3654            return Err(GuiError::WidgetNotFound(widget_id.0));
3655        };
3656        spec.ensure_property(WidgetProperty::CalendarDates)?;
3657        spec.calendar_selection_mode = mode;
3658        spec.calendar_selected_dates.clear();
3659        Ok(())
3660    }
3661
3662    fn data_dir(&self) -> GuiResult<PathBuf> {
3663        Ok(self.app_data_dir.clone().unwrap_or_else(std::env::temp_dir))
3664    }
3665
3666    fn set_clipboard_text(&mut self, text: &str) -> GuiResult<()> {
3667        self.clipboard = Some(text.to_owned());
3668        Ok(())
3669    }
3670
3671    fn paste_image_from_clipboard(
3672        &mut self,
3673    ) -> GuiResult<Option<native_gui_core::widgets::ClipboardImage>> {
3674        Ok(self.clipboard_image.clone())
3675    }
3676
3677    fn clipboard_text(&mut self) -> GuiResult<Option<String>> {
3678        Ok(self.clipboard.clone())
3679    }
3680
3681    fn set_tooltip(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
3682        let Some(spec) = self.created.get_mut(&widget_id) else {
3683            return Err(GuiError::WidgetNotFound(widget_id.0));
3684        };
3685        spec.tooltip = Some(text.to_owned());
3686        Ok(())
3687    }
3688
3689    fn set_accessible_name(&mut self, widget_id: WidgetId, name: &str) -> GuiResult<()> {
3690        let Some(spec) = self.created.get_mut(&widget_id) else {
3691            return Err(GuiError::WidgetNotFound(widget_id.0));
3692        };
3693        spec.accessibility.name = Some(name.to_owned());
3694        Ok(())
3695    }
3696
3697    fn set_accessible_description(
3698        &mut self,
3699        widget_id: WidgetId,
3700        description: &str,
3701    ) -> GuiResult<()> {
3702        let Some(spec) = self.created.get_mut(&widget_id) else {
3703            return Err(GuiError::WidgetNotFound(widget_id.0));
3704        };
3705        spec.accessibility.description = Some(description.to_owned());
3706        Ok(())
3707    }
3708
3709    fn post_accessible_notification(
3710        &mut self,
3711        widget_id: WidgetId,
3712        notification: AccessibleNotification,
3713    ) -> GuiResult<()> {
3714        if !self.created.contains_key(&widget_id) {
3715            return Err(GuiError::WidgetNotFound(widget_id.0));
3716        }
3717        self.posted_accessible_notifications
3718            .push((widget_id, notification));
3719        Ok(())
3720    }
3721
3722    fn set_focus(&mut self, widget_id: WidgetId) -> GuiResult<()> {
3723        if !self.created.contains_key(&widget_id) {
3724            return Err(GuiError::WidgetNotFound(widget_id.0));
3725        }
3726        let previous = self.focused.replace(widget_id);
3727        if let Some(previous) = previous {
3728            if previous != widget_id {
3729                self.push_event(UiEvent::FocusChanged {
3730                    widget_id: previous,
3731                    focused: false,
3732                });
3733            }
3734        }
3735        self.push_event(UiEvent::FocusChanged {
3736            widget_id,
3737            focused: true,
3738        });
3739        Ok(())
3740    }
3741
3742    fn set_focusable(&mut self, widget_id: WidgetId, focusable: bool) -> GuiResult<()> {
3743        let Some(spec) = self.created.get_mut(&widget_id) else {
3744            return Err(GuiError::WidgetNotFound(widget_id.0));
3745        };
3746        spec.focusable = Some(focusable);
3747        Ok(())
3748    }
3749
3750    fn set_theme(&mut self, theme: &native_gui_core::Theme) -> GuiResult<()> {
3751        self.theme = Some(theme.clone());
3752        Ok(())
3753    }
3754
3755    fn set_theme_override(
3756        &mut self,
3757        widget_id: WidgetId,
3758        theme_override: native_gui_core::ThemeOverride,
3759    ) -> GuiResult<()> {
3760        if !self.created.contains_key(&widget_id) {
3761            return Err(GuiError::WidgetNotFound(widget_id.0));
3762        }
3763        self.theme_overrides
3764            .entry(widget_id)
3765            .or_default()
3766            .push(theme_override);
3767        Ok(())
3768    }
3769
3770    fn clear_theme_overrides(&mut self, widget_id: WidgetId) -> GuiResult<()> {
3771        if !self.created.contains_key(&widget_id) {
3772            return Err(GuiError::WidgetNotFound(widget_id.0));
3773        }
3774        self.theme_overrides.remove(&widget_id);
3775        Ok(())
3776    }
3777
3778    fn theme_capabilities(&self) -> native_gui_core::ThemeCapabilities {
3779        self.theme_capabilities
3780    }
3781
3782    fn system_theme_mode(&self) -> Option<native_gui_core::ThemeMode> {
3783        self.system_theme
3784    }
3785
3786    fn display_capabilities(&self) -> native_gui_core::DisplayCapabilities {
3787        self.display_capabilities
3788    }
3789
3790    fn gpu_surface_capabilities(&self) -> GpuSurfaceCapabilities {
3791        self.gpu_surface_capabilities_override
3792            .unwrap_or_else(GpuSurfaceCapabilities::all)
3793    }
3794
3795    fn displays(&self) -> GuiResult<Vec<native_gui_core::DisplayInfo>> {
3796        // Safe default: with no fixture and no advertised enumeration the
3797        // Mock answers like a lane without display metrics; as soon as a
3798        // fixture installs data (or advertises the capability) the recorded
3799        // set is returned verbatim, even for hostile combinations.
3800        if self.displays.is_empty() && !self.display_capabilities.enumeration {
3801            return Err(GuiError::UnsupportedCapability(
3802                "display_metrics".to_owned(),
3803            ));
3804        }
3805        Ok(self.displays.clone())
3806    }
3807
3808    /// The Mock reports the scale of the display fixture
3809    /// (primary, else the first display) so the physical-to-logical pointer
3810    /// projection is deterministic under test. With no fixture it reports
3811    /// `1.0`, the identity — the Mock emits logical coordinates, so a
3812    /// delivered [`native_gui_core::UiEvent::PointerMove`] passes through unchanged.
3813    ///
3814    /// A fixture whose `scale_factor` is above `1.0` makes the Mock simulate a
3815    /// physical-pixel lane (Win32 under Per-Monitor v2): a pushed pointer
3816    /// event then arrives divided by that scale, exactly as it would on a
3817    /// scaled display.
3818    fn widget_scale_factor(&self, _widget_id: WidgetId) -> f64 {
3819        self.displays
3820            .iter()
3821            .find(|display| display.primary)
3822            .or_else(|| self.displays.first())
3823            .map(|display| display.scale_factor)
3824            .unwrap_or(1.0)
3825    }
3826
3827    fn wake_handle(&self) -> Option<Arc<dyn Fn() + Send + Sync>> {
3828        let flag = Arc::clone(&self.wake_flag);
3829        let signal = Arc::clone(&self.wake_signal);
3830        Some(Arc::new(move || {
3831            flag.store(true, Ordering::SeqCst);
3832            let (_, cvar) = &*signal;
3833            cvar.notify_all();
3834        }))
3835    }
3836
3837    fn poll_event(&mut self) -> GuiResult<Option<UiEvent>> {
3838        self.service_due_timers()?;
3839        self.service_due_animations()?;
3840        if self.wake_flag.swap(false, Ordering::SeqCst) {
3841            return Ok(Some(UiEvent::TasksPending));
3842        }
3843        // A running modal loop owns delivery: its nested pump serves the
3844        // innermost frame's script and the outer queue stays parked until
3845        // the loop closes.
3846        Ok(self.pop_pump_event())
3847    }
3848
3849    fn wait_event(&mut self) -> GuiResult<UiEvent> {
3850        loop {
3851            self.service_due_timers()?;
3852            self.service_due_animations()?;
3853            if self.wake_flag.swap(false, Ordering::SeqCst) {
3854                return Ok(UiEvent::TasksPending);
3855            }
3856            // A running modal loop owns delivery: serve
3857            // its innermost script; an empty script parks, exactly like a
3858            // nested OS pump blocked on its modal operation.
3859            let next = self.pop_pump_event();
3860            if let Some(event) = next {
3861                return Ok(event);
3862            }
3863            if self.advance_to_next_timer()? {
3864                continue;
3865            }
3866            // Park briefly instead of busy-sleeping: `UiProxy` posts and
3867            // `push_event` both notify this condvar, and the timeout keeps
3868            // direct-backend tests prompt without a notification.
3869            let (lock, cvar) = &*self.wake_signal;
3870            let guard = lock.lock().unwrap_or_else(|poison| poison.into_inner());
3871            let _ = cvar.wait_timeout(guard, std::time::Duration::from_millis(5));
3872        }
3873    }
3874
3875    fn capture_window_rgba(
3876        &self,
3877        widget_id: WidgetId,
3878        include_decorations: bool,
3879    ) -> GuiResult<(u32, u32, Vec<u8>)> {
3880        let Some(spec) = self.created.get(&widget_id) else {
3881            return Err(GuiError::WidgetNotFound(widget_id.0));
3882        };
3883        if !spec.kind.is_window_like() {
3884            return Err(GuiError::UnsupportedWidget("capture_window_rgba"));
3885        }
3886        let (base_w, base_h) = spec
3887            .size
3888            .map(|(w, h)| (w.max(1) as u32, h.max(1) as u32))
3889            .unwrap_or_else(|| {
3890                if spec.kind.is_dialog() {
3891                    (420, 260)
3892                } else {
3893                    (800, 600)
3894                }
3895            });
3896        let (w, h) = if include_decorations {
3897            (base_w, base_h.saturating_add(30))
3898        } else {
3899            (base_w, base_h)
3900        };
3901        let mut pixels = Vec::with_capacity((w * h * 4) as usize);
3902        let bg = spec.background_color.unwrap_or(Color {
3903            r: 240,
3904            g: 240,
3905            b: 245,
3906        });
3907        for y in 0..h {
3908            for x in 0..w {
3909                if include_decorations && y < 30 {
3910                    pixels.extend_from_slice(&[210, 215, 225, 255]);
3911                } else {
3912                    let check = ((x / 16) + (y / 16)) % 2 == 0;
3913                    if check {
3914                        pixels.extend_from_slice(&[bg.r, bg.g, bg.b, 255]);
3915                    } else {
3916                        pixels.extend_from_slice(&[
3917                            bg.r.saturating_sub(20),
3918                            bg.g.saturating_sub(20),
3919                            bg.b.saturating_sub(20),
3920                            255,
3921                        ]);
3922                    }
3923                }
3924            }
3925        }
3926        Ok((w, h, pixels))
3927    }
3928
3929    fn capture_widget_rgba(&self, widget_id: WidgetId) -> GuiResult<(u32, u32, Vec<u8>)> {
3930        let Some(spec) = self.created.get(&widget_id) else {
3931            return Err(GuiError::WidgetNotFound(widget_id.0));
3932        };
3933        let (w, h) = spec
3934            .size
3935            .map(|(w, h)| (w.max(1) as u32, h.max(1) as u32))
3936            .unwrap_or_else(|| match spec.kind {
3937                WidgetKind::Window => (800, 600),
3938                WidgetKind::Button => (100, 32),
3939                #[cfg(feature = "widgets-text")]
3940                WidgetKind::TextInput => (160, 28),
3941                #[cfg(feature = "widgets-text")]
3942                WidgetKind::TextArea | WidgetKind::RichText => (240, 120),
3943                WidgetKind::Label => (120, 24),
3944                #[cfg(feature = "widgets-range")]
3945                WidgetKind::Slider | WidgetKind::ProgressBar => (150, 24),
3946                #[cfg(feature = "widgets-choice")]
3947                WidgetKind::Checkbox | WidgetKind::RadioButton => (120, 24),
3948                _ => (120, 32),
3949            });
3950        let mut pixels = Vec::with_capacity((w * h * 4) as usize);
3951        let id_factor = (widget_id.0 as u8).wrapping_mul(41);
3952        let bg = spec.background_color.unwrap_or(Color {
3953            r: 220u8.wrapping_add(id_factor),
3954            g: 225u8.wrapping_add(id_factor),
3955            b: 235u8.wrapping_add(id_factor),
3956        });
3957        for y in 0..h {
3958            for x in 0..w {
3959                let border = x == 0 || y == 0 || x == w - 1 || y == h - 1;
3960                if border {
3961                    pixels.extend_from_slice(&[100, 105, 115, 255]);
3962                } else {
3963                    let check = ((x / 8) + (y / 8)) % 2 == 0;
3964                    if check {
3965                        pixels.extend_from_slice(&[bg.r, bg.g, bg.b, 255]);
3966                    } else {
3967                        pixels.extend_from_slice(&[
3968                            bg.r.saturating_sub(15),
3969                            bg.g.saturating_sub(15),
3970                            bg.b.saturating_sub(15),
3971                            255,
3972                        ]);
3973                    }
3974                }
3975            }
3976        }
3977        Ok((w, h, pixels))
3978    }
3979
3980    fn native_read_text(&self, widget_id: WidgetId) -> GuiResult<Option<String>> {
3981        let Some(spec) = self.created.get(&widget_id) else {
3982            return Err(GuiError::WidgetNotFound(widget_id.0));
3983        };
3984        Ok(spec.text.clone())
3985    }
3986
3987    fn native_read_checked(&self, widget_id: WidgetId) -> GuiResult<Option<bool>> {
3988        let Some(spec) = self.created.get(&widget_id) else {
3989            return Err(GuiError::WidgetNotFound(widget_id.0));
3990        };
3991        Ok(spec.checked)
3992    }
3993
3994    fn native_click(&self, widget_id: WidgetId) -> GuiResult<bool> {
3995        let Some(spec) = self.created.get(&widget_id) else {
3996            return Err(GuiError::WidgetNotFound(widget_id.0));
3997        };
3998        #[cfg(feature = "widgets-choice")]
3999        let is_clickable = matches!(
4000            spec.kind,
4001            WidgetKind::Button | WidgetKind::Checkbox | WidgetKind::RadioButton
4002        );
4003        #[cfg(not(feature = "widgets-choice"))]
4004        let is_clickable = matches!(spec.kind, WidgetKind::Button);
4005        Ok(is_clickable)
4006    }
4007
4008    fn native_type_text(&self, widget_id: WidgetId, _text: &str) -> GuiResult<bool> {
4009        let Some(spec) = self.created.get(&widget_id) else {
4010            return Err(GuiError::WidgetNotFound(widget_id.0));
4011        };
4012        #[cfg(feature = "widgets-text")]
4013        let is_text = matches!(
4014            spec.kind,
4015            WidgetKind::TextInput | WidgetKind::TextArea | WidgetKind::RichText
4016        );
4017        #[cfg(not(feature = "widgets-text"))]
4018        let is_text = {
4019            let _ = spec;
4020            false
4021        };
4022        Ok(is_text)
4023    }
4024
4025    fn create_tray_icon(&mut self, spec: &TrayIconSpec) -> GuiResult<TrayIconId> {
4026        self.tray_icons
4027            .insert(spec.id, MockTrayIconState::from(spec));
4028        Ok(spec.id)
4029    }
4030
4031    fn destroy_tray_icon(&mut self, id: TrayIconId) -> GuiResult<()> {
4032        self.tray_icons.remove(&id);
4033        Ok(())
4034    }
4035
4036    fn set_tray_icon_tooltip(&mut self, id: TrayIconId, tooltip: &str) -> GuiResult<()> {
4037        if let Some(state) = self.tray_icons.get_mut(&id) {
4038            state.tooltip = tooltip.to_owned();
4039        }
4040        Ok(())
4041    }
4042
4043    fn set_tray_icon_menu(&mut self, id: TrayIconId, menu: Option<MenuId>) -> GuiResult<()> {
4044        if let Some(state) = self.tray_icons.get_mut(&id) {
4045            state.menu = menu;
4046        }
4047        Ok(())
4048    }
4049
4050    fn set_tray_icon_visible(&mut self, id: TrayIconId, visible: bool) -> GuiResult<()> {
4051        if let Some(state) = self.tray_icons.get_mut(&id) {
4052            state.visible = visible;
4053        }
4054        Ok(())
4055    }
4056
4057    fn set_tray_icon_icon(&mut self, id: TrayIconId, icon_bytes: Option<Vec<u8>>) -> GuiResult<()> {
4058        if let Some(state) = self.tray_icons.get_mut(&id) {
4059            state.icon_bytes = icon_bytes;
4060        }
4061        Ok(())
4062    }
4063}
4064
4065/// Outcome of [`Ui::run_modal_loop`].
4066#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4067pub enum ModalLoopOutcome {
4068    /// The terminator event was delivered, closing the loop the way a
4069    /// dismissed dialog ends its nested pump.
4070    Completed {
4071        /// Events the nested pump dispatched re-entrantly.
4072        dispatched: usize,
4073    },
4074    /// The script ran dry before the terminator arrived: the deterministic
4075    /// stand-in for the OS hang the flat-FIFO model cannot express.
4076    Deadlocked {
4077        /// Events the nested pump dispatched before stopping.
4078        dispatched: usize,
4079    },
4080}
4081
4082pub trait MockUiExt {
4083    fn run_modal_loop<F, T>(
4084        &mut self,
4085        script: Vec<UiEvent>,
4086        terminator: T,
4087        handler: F,
4088    ) -> GuiResult<ModalLoopOutcome>
4089    where
4090        F: FnMut(&mut Ui<MockBackend>, UiEvent) -> GuiResult<LoopFlow>,
4091        T: Fn(&UiEvent) -> bool;
4092}
4093
4094impl MockUiExt for Ui<MockBackend> {
4095    /// Runs a scripted OS-style modal loop on the Mock
4096    /// lane, re-entrantly dispatching its script before the outer queue.
4097    ///
4098    /// The Mock's plain event delivery models a single flat FIFO pump - sound
4099    /// for a normal message loop, but not for the *nested* loops behind
4100    /// `MessageBoxW`, drag-and-drop, and `gtk_dialog_run`. This driver
4101    /// reproduces the nested shape deterministically:
4102    ///
4103    /// - The `script` is delivered FIFO by the nested pump through the
4104    ///   standard dispatch path (layout recompute, focus bookkeeping,
4105    ///   registered callbacks, then `handler`), so its events run
4106    ///   re-entrantly while the modal operation that opened the loop is
4107    ///   still on the stack.
4108    /// - Events pushed to the outer queue meanwhile - including from the
4109    ///   handler - stay parked; they are delivered in their original order
4110    ///   only after the loop closes (the post-modal drain).
4111    /// - `terminator` closes the loop, e.g. the `DialogResponse` for the
4112    ///   token the modal operation opened. A script that runs dry first, and
4113    ///   a handler that exits early without the terminator, report
4114    ///   [`ModalLoopOutcome::Deadlocked`] instead of parking.
4115    /// - Calling this from a handler nests another loop, the way a dialog
4116    ///   raised by a drag-and-drop callback nests inside its pump; the inner
4117    ///   loop finishes before the outer pump resumes.
4118    ///
4119    /// The modal frame is closed on every path - normal completion, a
4120    /// deadlock report, a handler error - so a refused modal operation
4121    /// cannot leak an open pump into later work.
4122    fn run_modal_loop<F, T>(
4123        &mut self,
4124        script: Vec<UiEvent>,
4125        terminator: T,
4126        mut handler: F,
4127    ) -> GuiResult<ModalLoopOutcome>
4128    where
4129        F: FnMut(&mut Ui<MockBackend>, UiEvent) -> GuiResult<LoopFlow>,
4130        T: Fn(&UiEvent) -> bool,
4131    {
4132        self.backend_mut().begin_modal_loop();
4133        for event in script {
4134            let scripted = self.backend_mut().script_modal_event(event);
4135            debug_assert!(scripted, "the modal frame was opened just above");
4136        }
4137
4138        let mut terminated = false;
4139        let dispatched = self.dispatch_events_with(|ui, event| {
4140            let closes = terminator(&event);
4141            let flow = handler(ui, event)?;
4142            if closes {
4143                terminated = true;
4144                return Ok(LoopFlow::Exit);
4145            }
4146            Ok(flow)
4147        });
4148
4149        // Close the frame on every path, even when the handler failed.
4150        let _leftover = self.backend_mut().end_modal_loop();
4151        let dispatched = dispatched?;
4152
4153        Ok(if terminated {
4154            ModalLoopOutcome::Completed { dispatched }
4155        } else {
4156            ModalLoopOutcome::Deadlocked { dispatched }
4157        })
4158    }
4159}
4160
4161#[cfg(feature = "property-grid")]
4162impl native_gui_core::advanced::PropertyGridBackend for MockBackend {
4163    fn property_grid_capabilities(&self) -> native_gui_core::advanced::PropertyGridCapabilities {
4164        native_gui_core::advanced::PropertyGridCapabilities {
4165            supported: true,
4166            portable: true,
4167            engine: self.advanced_engine.clone(),
4168            native_editors: false,
4169            virtualization: false,
4170        }
4171    }
4172
4173    fn bind_property_model(
4174        &mut self,
4175        host: WidgetId,
4176        model: &native_gui_core::properties::PropertyModel,
4177    ) -> GuiResult<()> {
4178        self.property_grid_models.insert(host, model.clone());
4179        Ok(())
4180    }
4181
4182    fn set_property_value(
4183        &mut self,
4184        host: WidgetId,
4185        id: native_gui_core::properties::PropertyId,
4186        value: &native_gui_core::properties::PropertyValue,
4187    ) -> GuiResult<()> {
4188        let Some(model) = self.property_grid_models.get_mut(&host) else {
4189            return Err(GuiError::UnsupportedCapability(
4190                "property_grid_unbound".to_owned(),
4191            ));
4192        };
4193        model
4194            .set_value(id, value.clone())
4195            .map_err(|error| GuiError::Backend(format!("property model: {error}")))?;
4196        self.property_grid_applied.push((host, id));
4197        Ok(())
4198    }
4199
4200    fn refresh_property_grid(&mut self, host: WidgetId) -> GuiResult<()> {
4201        *self.property_grid_refreshes.entry(host).or_insert(0) += 1;
4202        Ok(())
4203    }
4204}
4205
4206#[cfg(test)]
4207mod tests {
4208    use super::*;
4209
4210    #[cfg(not(feature = "widgets-media"))]
4211    #[test]
4212    fn image_kind_is_refused_when_core_media_is_enabled_without_mock_media() {
4213        let image_kinds = native_gui_core::widgets::ALL_KINDS
4214            .iter()
4215            .copied()
4216            .filter(|kind| WidgetProperty::ImageSource.supports(*kind))
4217            .collect::<Vec<_>>();
4218
4219        let mut backend = MockBackend::default();
4220        if let Some(kind) = image_kinds.first().copied() {
4221            let spec = WidgetSpec::new(WidgetId(1), kind);
4222            assert_eq!(
4223                backend.create_widget(&spec),
4224                Err(GuiError::UnsupportedWidget("unsupported widget kind"))
4225            );
4226            assert!(backend.created.is_empty());
4227        } else {
4228            assert!(WidgetProperty::ImageSource.applicable_kinds().is_empty());
4229        }
4230    }
4231
4232    #[test]
4233    fn test_programmatic_setters_are_silent() {
4234        let mut backend = MockBackend::default();
4235        let _ = &mut backend;
4236
4237        // 1. Text input & text area: set_text is silent
4238        #[cfg(feature = "widgets-text")]
4239        {
4240            let text_input = WidgetId(101);
4241            backend
4242                .create_widget(&WidgetSpec::new(text_input, WidgetKind::TextInput))
4243                .unwrap();
4244            backend.set_text(text_input, "initial").unwrap();
4245            assert_eq!(backend.poll_event().unwrap(), None);
4246
4247            let text_area = WidgetId(102);
4248            backend
4249                .create_widget(&WidgetSpec::new(text_area, WidgetKind::TextArea))
4250                .unwrap();
4251            backend.set_text(text_area, "multiline content").unwrap();
4252            assert_eq!(backend.poll_event().unwrap(), None);
4253        }
4254
4255        // 2. Numeric / value widgets: set_value is silent
4256        #[cfg(feature = "widgets-range")]
4257        {
4258            let slider = WidgetId(201);
4259            backend
4260                .create_widget(&WidgetSpec::new(slider, WidgetKind::Slider))
4261                .unwrap();
4262            backend.set_value(slider, 42).unwrap();
4263            assert_eq!(backend.poll_event().unwrap(), None);
4264
4265            let spin_box = WidgetId(202);
4266            backend
4267                .create_widget(&WidgetSpec::new(spin_box, WidgetKind::SpinBox))
4268                .unwrap();
4269            backend.set_value(spin_box, 99).unwrap();
4270            assert_eq!(backend.poll_event().unwrap(), None);
4271
4272            let progress = WidgetId(203);
4273            backend
4274                .create_widget(&WidgetSpec::new(progress, WidgetKind::ProgressBar))
4275                .unwrap();
4276            backend.set_value(progress, 75).unwrap();
4277            assert_eq!(backend.poll_event().unwrap(), None);
4278        }
4279
4280        // 3. Checkbox and radio: set_checked is silent
4281        #[cfg(feature = "widgets-choice")]
4282        {
4283            let checkbox = WidgetId(301);
4284            backend
4285                .create_widget(&WidgetSpec::new(checkbox, WidgetKind::Checkbox))
4286                .unwrap();
4287            backend.set_checked(checkbox, true).unwrap();
4288            assert_eq!(backend.poll_event().unwrap(), None);
4289
4290            let radio = WidgetId(302);
4291            backend
4292                .create_widget(&WidgetSpec::new(radio, WidgetKind::RadioButton))
4293                .unwrap();
4294            backend.set_checked(radio, true).unwrap();
4295            assert_eq!(backend.poll_event().unwrap(), None);
4296        }
4297
4298        // 4. Selection widgets: set_selected_index & set_selected_indices are silent
4299        #[cfg(feature = "widgets-choice")]
4300        {
4301            let combo = WidgetId(401);
4302            backend
4303                .create_widget(&WidgetSpec::new(combo, WidgetKind::ComboBox))
4304                .unwrap();
4305            backend.set_selected_index(combo, 2).unwrap();
4306            assert_eq!(backend.poll_event().unwrap(), None);
4307        }
4308
4309        #[cfg(feature = "widgets-data")]
4310        {
4311            let datalist = WidgetId(402);
4312            backend
4313                .create_widget(&WidgetSpec::new(datalist, WidgetKind::DataList))
4314                .unwrap();
4315            backend.set_selected_index(datalist, 1).unwrap();
4316            assert_eq!(backend.poll_event().unwrap(), None);
4317            backend.set_selected_indices(datalist, &[0, 2]).unwrap();
4318            assert_eq!(backend.poll_event().unwrap(), None);
4319        }
4320
4321        // 5. Other property setters: range, step, date, link
4322        #[cfg(feature = "widgets-range")]
4323        {
4324            let slider = WidgetId(201);
4325            backend.set_range(slider, 0, 100).unwrap();
4326            backend.set_step(slider, 5).unwrap();
4327            assert_eq!(backend.poll_event().unwrap(), None);
4328        }
4329
4330        #[cfg(feature = "widgets-pickers")]
4331        {
4332            let date_picker = WidgetId(501);
4333            backend
4334                .create_widget(&WidgetSpec::new(date_picker, WidgetKind::DatePicker))
4335                .unwrap();
4336            backend.set_date_value(date_picker, "2026-10-08").unwrap();
4337            assert_eq!(backend.poll_event().unwrap(), None);
4338        }
4339
4340        #[cfg(feature = "widgets-text")]
4341        {
4342            let link = WidgetId(502);
4343            backend
4344                .create_widget(&WidgetSpec::new(link, WidgetKind::LinkLabel))
4345                .unwrap();
4346            backend.set_link_url(link, "https://example.com").unwrap();
4347            assert_eq!(backend.poll_event().unwrap(), None);
4348        }
4349    }
4350
4351    #[test]
4352    fn test_interaction_and_focus_transitions_emit_events() {
4353        let mut backend = MockBackend::default();
4354
4355        let button = WidgetId(601);
4356        backend
4357            .create_widget(&WidgetSpec::new(button, WidgetKind::Button))
4358            .unwrap();
4359        backend.activate(button).unwrap();
4360        assert_eq!(
4361            backend.poll_event().unwrap(),
4362            Some(UiEvent::Clicked { widget_id: button })
4363        );
4364
4365        // Focus transition reports FocusChanged
4366        let input1 = WidgetId(602);
4367        let input2 = WidgetId(603);
4368        backend
4369            .create_widget(&WidgetSpec::new(input1, WidgetKind::Button))
4370            .unwrap();
4371        backend
4372            .create_widget(&WidgetSpec::new(input2, WidgetKind::Button))
4373            .unwrap();
4374
4375        backend.set_focus(input1).unwrap();
4376        assert_eq!(
4377            backend.poll_event().unwrap(),
4378            Some(UiEvent::FocusChanged {
4379                widget_id: input1,
4380                focused: true
4381            })
4382        );
4383
4384        backend.set_focus(input2).unwrap();
4385        assert_eq!(
4386            backend.poll_event().unwrap(),
4387            Some(UiEvent::FocusChanged {
4388                widget_id: input1,
4389                focused: false
4390            })
4391        );
4392        assert_eq!(
4393            backend.poll_event().unwrap(),
4394            Some(UiEvent::FocusChanged {
4395                widget_id: input2,
4396                focused: true
4397            })
4398        );
4399    }
4400
4401    #[test]
4402    fn with_data_dir_overrides_default_temp_dir() {
4403        let default_backend = MockBackend::default();
4404        assert_eq!(default_backend.data_dir().unwrap(), std::env::temp_dir());
4405
4406        let isolated = PathBuf::from("isolated-mock-data-dir");
4407        let custom_backend = MockBackend::default().with_data_dir(&isolated);
4408        assert_eq!(custom_backend.data_dir().unwrap(), isolated);
4409    }
4410}