Skip to main content

native_gui_core/
ui.rs

1use std::collections::{HashMap, HashSet, VecDeque};
2use std::path::PathBuf;
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5
6use crate::access::AccessibilitySpec;
7use crate::artprov::{ArtCapabilities, IconRole, IconSize, StockIcon};
8#[cfg(feature = "async")]
9use crate::async_ui::{
10    TaskAbortReason, TaskCommand, TaskDrainReport, TaskEvent, UiProxy, DEFAULT_TASK_QUEUE_CAPACITY,
11};
12use crate::displays::DisplayCapabilities;
13#[cfg(feature = "displays")]
14use crate::displays::DisplayInfo;
15use crate::drag::{
16    normalize_kinds, DragCapabilities, DragPayloadKind, DragSourceOptions, DragTargetOptions,
17    DropEffect,
18};
19use crate::error::{GuiError, GuiResult};
20use crate::events::{AccessibleNotification, UiEvent};
21use crate::image_resource::{
22    checked_total_bytes, ImageData, ImageResourceCapabilities, ImageResourceId,
23};
24use crate::layout::{LayoutNodeId, LayoutTree};
25use crate::menus::{MenuId, MenuItemId};
26use crate::motion::{ActiveMotion, MotionCapabilities, MotionId, MotionSpec, MOTION_TICK_CADENCE};
27use crate::pickers::{ColorDialogData, FontDescriptor, FontDialogData};
28#[cfg(feature = "routes")]
29use crate::routes::Routes;
30use crate::theme::{Theme, ThemeCapabilities, ThemeMode, ThemeOverride};
31use crate::timer::{TimerCapabilities, TimerId, TimerSpec, TimerStopPolicy};
32use crate::toolbar::{self, ToolId, ToolUpdate, ToolbarItem, ToolbarOrientation};
33use crate::tray::{TrayIconId, TrayIconSpec};
34#[cfg(feature = "widgets-data")]
35use crate::widgets::diff_rows;
36use crate::widgets::{
37    AlertLevel, CalendarDate, CalendarFirstDayOfWeek, CalendarSelectionMode, ClipboardImage, Color,
38    ColumnSpec, ContainerDirection, ContainerWrap, FileChooserMode, GpuDegradationPolicy,
39    GpuSurfaceCapabilities, ImageFit, LabelAlignment, LabelWrap, RichTextImage, RowDelta, RowKey,
40    RowSet, TextRun, TreeItem, WidgetId, WidgetKind, WidgetProperty, WidgetSpec,
41};
42use crate::windowing::{
43    ShowEffect, Stacking, WindowCapabilities, WindowFocusPolicy, WindowOptions, WindowPlacement,
44    WindowRole, WindowShape,
45};
46
47type LayoutUpdate = (WidgetId, Option<(i32, i32)>, Option<(i32, i32)>);
48
49/// Native handle information for a `WidgetKind::VulkanCanvas`.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum VulkanCanvasHandle {
52    /// Win32 native handles.
53    Win32 { hwnd: usize, hinstance: usize },
54    /// Wayland native handles.
55    Wayland { surface: usize, display: usize },
56    /// X11 native handles.
57    X11 { window: u64, display: usize },
58    /// Mock backend token.
59    Mock { token: usize },
60}
61
62/// Native handle information for a `WidgetKind::MetalCanvas`.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct MetalCanvasHandle {
65    /// AppKit `NSView` pointer.
66    pub ns_view: usize,
67    /// AppKit `CAMetalLayer` pointer.
68    pub ca_metal_layer: usize,
69    /// System default `MTLDevice` pointer.
70    pub mtl_device: usize,
71}
72
73/// Control-flow answer for the UI event runners (`*_with` variants).
74///
75/// [`LoopFlow::Continue`] keeps the runner going; [`LoopFlow::Exit`] stops
76/// it after the current event. The `native-gui` facade's `app` module mirrors these
77/// values as `app::AppFlow` for its `App` trait.
78#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
79pub enum LoopFlow {
80    /// Keep dispatching events (the default).
81    #[default]
82    Continue,
83    /// Stop the runner after this event.
84    Exit,
85}
86
87/// Why a bounded UI run stopped.
88///
89/// Returned by [`Ui::run_bounded`] and [`Ui::run_bounded_with`], the
90/// autoclose-aware runners a capture or smoke harness uses to let an app end
91/// its own run instead of being killed by the script.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub enum RunStop {
94    /// The runner saw [`UiEvent::WindowClosed`].
95    WindowClosed,
96    /// The handler answered [`LoopFlow::Exit`].
97    Exit,
98    /// The autoclose budget elapsed first; the window is still open.
99    TimedOut,
100}
101
102/// Measures text for the shared layout pass (TEXT-004).
103///
104/// [`Backend`] inherits this trait so the shared layout can ask a lane
105/// for a widget's natural text dimensions without widening the backend
106/// contract itself.
107pub trait TextMeasure {
108    /// Measures the logical dimensions of a text-bearing widget given the available space (TEXT-004).
109    fn measure_text(
110        &self,
111        widget_id: crate::widgets::WidgetId,
112        known_dimensions: crate::layout::Size<Option<f32>>,
113        available_space: crate::layout::Size<crate::layout::AvailableSpace>,
114    ) -> Option<crate::layout::Size<f32>>;
115}
116
117/// The input path actually exercised by an operation.
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub enum InputMode {
120    Simulated,
121    SemanticNative,
122    HardwareNative,
123}
124
125/// Per-widget support for an E2E operation.
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub enum Capability {
128    Supported { mode: InputMode },
129    Unsupported { reason: String },
130}
131
132/// Independently queried actions and observations.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum Operation {
135    Click,
136    TypeText,
137    Check,
138    Text,
139    Checked,
140    Press,
141    Select,
142    SetValue,
143    Scroll,
144    DragTo,
145    Close,
146    Screenshot,
147}
148
149impl Operation {
150    /// Stable identifier used by unsupported-operation errors.
151    pub fn name(self) -> &'static str {
152        match self {
153            Self::Click => "e2e.click",
154            Self::TypeText => "e2e.type_text",
155            Self::Check => "e2e.check",
156            Self::Text => "e2e.text",
157            Self::Checked => "e2e.checked",
158            Self::Press => "e2e.press",
159            Self::Select => "e2e.select",
160            Self::SetValue => "e2e.set_value",
161            Self::Scroll => "e2e.scroll",
162            Self::DragTo => "e2e.drag_to",
163            Self::Close => "e2e.close",
164            Self::Screenshot => "e2e.screenshot",
165        }
166    }
167}
168
169/// Backend contract implemented by platform-specific renderers.
170///
171/// # Method Groups
172///
173/// The trait carries 162 items: 160 methods declared here, the inherited
174/// [`TextMeasure::measure_text`] supertrait method, and the
175/// [`Self::NativeHandle`] associated type. They fall into seventeen subsystems;
176/// the groups are stable, and a new method joins an existing group or argues
177/// for a new one (see `docs/guides/backend-development.md` section 10 for the
178/// expansion governance and Chapter 17 of the book for the narrative
179/// walkthrough).
180///
181/// | Group | Items | Covers |
182/// |---|---|---|
183/// | Lifecycle & hierarchy | 8 | create, attach child, reparent, show/hide, remove, enable, activate |
184/// | Menus & menu items | 10 | menu structure, attachment, item enablement/labels, dynamic insert/remove |
185/// | Text & input properties | 12 | text, label alignment/wrap, text selection, completion, placeholder, rich-text runs/images, monospace, explicit font, live selection readback, native spell checking |
186/// | Value & selection properties | 8 | checked, value/range/step, tab labels, selected index/indices, link URL |
187/// | Layout, containers & flow | 13 | size/min size/layout size, natural size, compressed-size floor, position, flow padding, container direction/wrap/scroll/gap/padding |
188/// | Collections, grids & trees | 18 | list items, runtime combo-box items, list columns/rows, per-row art-provider icons, selection clearing, anchor/scroll/end visibility, row drag, grid rows/model/metrics/selection, row deltas, tree items |
189/// | Calendar & date | 5 | selected dates, bounds, first day of week, selection mode, date value |
190/// | Presentation & tool strips | 10 | background, tooltip, alert level, image source/fit, toolbar items/orientation, typed image resources |
191/// | System tray & status icons | 6 | tray icon lifecycle, pixels, tooltip, context menu, visibility |
192/// | Dialogs & windowing | 11 | confirm dialog, function-style file dialog, close guard, file-chooser mode, color/font dialog data, window min size/resizable, extended window capabilities/options, popup dismissal |
193/// | Clipboard, drops & data directory | 9 | clipboard text/image, paste image, app data directory, file/URL/text drop targets, MIME drag capabilities/source/target options |
194/// | Focus & accessibility | 5 | focus/focusable, accessible name/description, post notification |
195/// | Theming & stock art | 9 | theme apply/override/capabilities, system mode/high contrast, stock-art icon set/query, art capabilities |
196/// | Events, tasks & lane introspection | 10 | event polling/blocking, wake hook, advanced-control hosting, backend name, timer and motion capabilities/start/scoped start/cancel |
197/// | Canvas, GPU & displays | 10 | scenes/surfaces, demo cube, GPU fallback/surface capabilities, display capabilities/enumeration/scale |
198/// | Native handles & text measurement | 4 | Vulkan-canvas native handle and its associated type, top-level window handle, inherited `measure_text` |
199/// | Screenshot & E2E adapters | 14 | window/widget capture, native readbacks and simulated input, E2E capability/actions/poll |
200///
201/// # Maintenance
202///
203/// The counts are verified mechanically - from the repository root:
204///
205/// ```text
206/// python -c "import re;s=open('crates/native-gui-core/src/ui.rs',encoding='utf-8').read();b=s.split('\npub trait Backend: TextMeasure {',1)[1].split('\n}\n',1)[0];t=s.split('\npub trait TextMeasure {',1)[1].split('\n}\n',1)[0];f=lambda x:len(re.findall(r'(?m)^    (?:unsafe )?fn \w+',x));a=len(re.findall(r'(?m)^    type \w+',b));print('Backend %d fns + %d assoc type + %d supertrait fn = %d trait items'%(f(b),a,f(t),f(b)+a+f(t)))"
207/// ```
208///
209/// It must print `Backend 160 fns + 1 assoc type + 1 supertrait fn = 162
210/// trait items`; adding, removing, or renaming a method updates this
211/// inventory (count and table) in the same commit - see "Backend work" in
212/// `CONTRIBUTING.md`.
213///
214/// # Operational contract (Pre / Post / Inv)
215///
216/// Every method obeys the same operational semantics; the deterministic
217/// contract tests in `tests/functional_flow.rs` and the unit
218/// tests in this module pin them:
219///
220/// - **Pre-conditions.** The widget id names a live widget; a kind-restricted
221///   operation is offered only when the kind is inside the property's
222///   [`WidgetProperty::applicable_kinds`] row; validated values reject before
223///   any mutation (`min <= max`, positive sizes/steps, finite canvas
224///   extents, `start <= end`).
225/// - **Post-conditions.** A successful call mirrors the new value on the
226///   shared [`WidgetSpec`] exactly once and forwards the same value to the
227///   native control; an unrelated widget and unrelated native handles are
228///   never touched. A refused call is transactional: the shared spec and the
229///   backend record are byte-identical to the pre-call state.
230/// - **Invariants.** Parent links form a strict acyclic forest (single
231///   parentage); [`WidgetId`]s are monotonic and never reused, including
232///   after removal; a removed widget takes its whole subtree with it
233///   ([`Ui::remove`]); and the shared spec stays in exact sync with the
234///   native value the backend reports (the Mock lane asserts full spec
235///   equality).
236///
237/// # FFI memory boundary and ownership
238///
239/// Chapter 17's first structural invariant (lossless strings, bounded
240/// closures) is asserted here so every lane implements the same seam; the
241/// digest lives in `docs/reference/architecture.md`:
242///
243/// - **String encodings.** Every `&str`/`String` crossing this trait is Rust
244///   UTF-8, and a lane transcodes it losslessly to its native format at the
245///   call site: Win32 builds UTF-16 (NUL-terminated) buffers through its
246///   `to_wide` helper, GTK consumes UTF-8 through gtk-rs (which owns the
247///   native conversion), and Cocoa builds `NSString`s from UTF-8. Borrowed
248///   text is strictly call-scoped: a lane must copy whatever it retains,
249///   no borrowed pointer outlives the call, and the [`WidgetSpec`] on the
250///   shared side stays the authoritative text.
251/// - **Closure lifetimes.** The trait takes and retains no closures.
252///   Application callbacks are `'static` values registered on [`Ui`]
253///   ([`Ui::on_window_close`], [`Ui::on_window_resize`],
254///   [`Ui::on_menu_item_selected`], the `run_until_closed*` handlers), owned
255///   by the `Ui` and dispatched from its staged event pump - never invoked
256///   directly inside a native signal handler. A lane that reaches a native
257///   event loop bridges through state owned for the widget's lifetime (GTK
258///   `Rc<RefCell<...>>` captures, Win32 window properties plus
259///   `WM_BRIDGED_*` messages), so the native loop can never dispatch into
260///   freed application state and no application closure is stored in a
261///   `WNDPROC` or a native delegate.
262/// - **Ownership and release.** [`Ui`] owns the widget tree and every value
263///   through [`WidgetSpec`]; a lane's per-widget state is an implementation
264///   record keyed by [`WidgetId`] (never a second source of truth, see the
265///   coherence invariant above), and every `remove` path releases the
266///   native handles, models, brushes, and parked properties it allocated.
267pub trait Backend: TextMeasure {
268    /// Creates a native widget from a shared specification.
269    ///
270    /// `spec` is borrowed for the duration of the call: the lane copies
271    /// every value it retains (strings included - see the trait's FFI memory
272    /// boundary section), while `Ui` keeps owning the authoritative spec.
273    fn create_widget(&mut self, spec: &WidgetSpec) -> GuiResult<()>;
274    /// Creates a native menu container.
275    fn create_menu(&mut self, menu_id: MenuId) -> GuiResult<()>;
276    /// Creates a submenu under `parent_id`.
277    ///
278    /// `slot_id` names the submenu's row inside the parent's ordered list;
279    /// it is minted from the item-id space so a submenu
280    /// row can never be mistaken for a real item, and lanes that record
281    /// order (Mock) store it next to the items.
282    fn add_submenu(
283        &mut self,
284        parent_id: MenuId,
285        submenu_id: MenuId,
286        slot_id: MenuItemId,
287        text: &str,
288    ) -> GuiResult<()>;
289    /// Creates a native menu item under an existing menu.
290    fn create_menu_item(
291        &mut self,
292        menu_id: MenuId,
293        item_id: MenuItemId,
294        text: &str,
295        shortcut: Option<&str>,
296    ) -> GuiResult<()>;
297    /// Attaches a menu to a window.
298    fn attach_menu_to_window(&mut self, window_id: WidgetId, menu_id: MenuId) -> GuiResult<()>;
299    /// Attaches a menu as a right-click context menu on a widget.
300    fn attach_context_menu(&mut self, widget_id: WidgetId, menu_id: MenuId) -> GuiResult<()>;
301    /// Sets text/value-like content for a widget.
302    fn set_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()>;
303    /// Sets horizontal alignment for a `Label`.
304    ///
305    /// Lanes without a native alignment mapping report the typed
306    /// `label_alignment` capability error.
307    fn set_label_alignment(
308        &mut self,
309        widget_id: WidgetId,
310        alignment: LabelAlignment,
311    ) -> GuiResult<()> {
312        let _ = (widget_id, alignment);
313        Err(GuiError::UnsupportedCapability(
314            "label_alignment".to_owned(),
315        ))
316    }
317    /// Sets line wrapping for a `Label`.
318    ///
319    /// Lanes without the requested wrapping behavior report the typed
320    /// `label_wrap` capability error.
321    fn set_label_wrap(&mut self, widget_id: WidgetId, wrap: LabelWrap) -> GuiResult<()> {
322        let _ = (widget_id, wrap);
323        Err(GuiError::UnsupportedCapability("label_wrap".to_owned()))
324    }
325    /// Reads the native text selection as ordered Unicode character offsets.
326    /// Unlike WidgetSpec's last programmatic selection, this reflects mouse
327    /// selection and caret navigation in the live text control.
328    fn text_selection(&self, _widget_id: WidgetId) -> GuiResult<(usize, usize)> {
329        Err(GuiError::UnsupportedCapability("text_selection".to_owned()))
330    }
331
332    /// Selects a character range (start inclusive, end exclusive) in a text
333    /// control.
334    ///
335    /// Backends without a native text-selection mapping report
336    /// [`GuiError::UnsupportedWidget`] instead of silently dropping the
337    /// call, so per-lane coverage stays accurate.
338    fn set_text_selection(
339        &mut self,
340        widget_id: WidgetId,
341        start: usize,
342        end: usize,
343    ) -> GuiResult<()> {
344        let _ = (widget_id, start, end);
345        Err(GuiError::UnsupportedWidget("set_text_selection"))
346    }
347    /// Sets the completion/suggestion item list for a `TextInput`.
348    ///
349    /// `items` is the full suggestion list; lanes filter it for the current
350    /// text (case-insensitive prefix by default) and own their popup.
351    /// Backends without a completion mapping report
352    /// [`GuiError::UnsupportedCapability`] with the `"text_completion"`
353    /// identifier instead of silently ignoring the request.
354    fn set_text_completion_items(
355        &mut self,
356        widget_id: WidgetId,
357        items: &[String],
358    ) -> GuiResult<()> {
359        let _ = (widget_id, items);
360        Err(GuiError::UnsupportedCapability(
361            "text_completion".to_owned(),
362        ))
363    }
364    /// Sets checked state for check-capable widgets.
365    fn set_checked(&mut self, widget_id: WidgetId, checked: bool) -> GuiResult<()>;
366    /// Sets numeric value for value-capable widgets.
367    fn set_value(&mut self, widget_id: WidgetId, value: i32) -> GuiResult<()>;
368    /// Sets numeric range for widgets supporting min/max semantics.
369    fn set_range(&mut self, widget_id: WidgetId, min: i32, max: i32) -> GuiResult<()>;
370    /// Sets numeric step for widgets supporting step semantics.
371    fn set_step(&mut self, widget_id: WidgetId, step: i32) -> GuiResult<()>;
372    /// Sets selected index for widgets exposing item/page selection.
373    fn set_selected_index(&mut self, widget_id: WidgetId, index: usize) -> GuiResult<()>;
374    /// Sets page labels for a tabs widget.
375    ///
376    /// Labels follow the attached pages in attach order. Backends relabel
377    /// pages they have already applied (Win32 strip items, GTK notebook
378    /// pages, Cocoa tab-view items) and use the labels for pages attached
379    /// later; pages without a label keep the backend placeholder header.
380    fn set_tab_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()>;
381    /// Sets multiple selected indices for multi-select list/tree widgets.
382    fn set_selected_indices(&mut self, widget_id: WidgetId, indices: &[usize]) -> GuiResult<()>;
383    /// Enables/disables row drag-source and drop-target behavior on a row widget.
384    fn set_row_drag(&mut self, widget_id: WidgetId, source: bool, target: bool) -> GuiResult<()>;
385    /// Reports support for the additive text/custom-MIME drag surface.
386    fn drag_capabilities(&self) -> DragCapabilities {
387        DragCapabilities::none()
388    }
389    /// Configures text/custom-MIME payloads offered by a source.
390    fn set_drag_source_options(
391        &mut self,
392        widget_id: WidgetId,
393        options: &DragSourceOptions,
394    ) -> GuiResult<()> {
395        let _ = widget_id;
396        if let Some(kind) = options.kinds.first() {
397            let capability = match kind {
398                DragPayloadKind::Text => "drag_text",
399                DragPayloadKind::Custom { .. } => "drag_custom_mime",
400            };
401            return Err(GuiError::UnsupportedCapability(capability.to_owned()));
402        }
403        Ok(())
404    }
405    /// Configures accepted payloads and the target's requested drop effect.
406    fn set_drag_target_options(
407        &mut self,
408        widget_id: WidgetId,
409        options: &DragTargetOptions,
410    ) -> GuiResult<()> {
411        let _ = widget_id;
412        if let Some(kind) = options.kinds.first() {
413            let capability = match kind {
414                DragPayloadKind::Text => "drag_text",
415                DragPayloadKind::Custom { .. } => "drag_custom_mime",
416            };
417            return Err(GuiError::UnsupportedCapability(capability.to_owned()));
418        }
419        if options.effect != DropEffect::None {
420            return Err(GuiError::UnsupportedCapability("drop_feedback".to_owned()));
421        }
422        Ok(())
423    }
424    /// Enables/disables accepting external file drops from the OS shell.
425    fn set_file_drop_target(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
426        let _ = (widget_id, enabled);
427        Ok(())
428    }
429    /// Enables/disables drop target support for files, URLs, and text.
430    fn set_drop_target(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
431        self.set_file_drop_target(widget_id, enabled)
432    }
433    /// Sets preferred dimensions for widgets.
434    fn set_size(&mut self, widget_id: WidgetId, width: i32, height: i32) -> GuiResult<()>;
435    /// Records a layout size floor for a widget.
436    ///
437    /// Forwarded by [`Ui::set_min_size`]. Backends with a native flow layout
438    /// consult the recorded minimum as a lower bound when they place
439    /// auto-sized children, so a widget the app sized with a minimum never
440    /// lays out smaller than that floor. Lanes that place every child from
441    /// the shared computed layout keep this default no-op, because the shared
442    /// layout pass already honours `set_min_size`; `(0, 0)` clears the floor.
443    fn set_min_size(&mut self, widget_id: WidgetId, width: i32, height: i32) -> GuiResult<()> {
444        let _ = (widget_id, width, height);
445        Ok(())
446    }
447    /// Applies computed layout dimensions and GTK-style expansion semantics.
448    ///
449    /// Backends with native flow layouts can use the expansion flags while
450    /// retaining `set_size`'s explicit-size behavior. The default preserves
451    /// existing backend behavior.
452    fn set_layout_size(
453        &mut self,
454        widget_id: WidgetId,
455        width: i32,
456        height: i32,
457        expand_width: bool,
458        expand_height: bool,
459    ) -> GuiResult<()> {
460        let _ = (expand_width, expand_height);
461        self.set_size(widget_id, width, height)
462    }
463    /// Natural (preferred) size of a leaf widget, when the backend can
464    /// measure it. `Ui::compute_layout` seeds layout leaf styles with this so
465    /// auto-sized rows and labels get real heights instead of measuring
466    /// zero; `None` keeps the node's flex style untouched.
467    fn natural_size(&self, widget_id: WidgetId) -> Option<(i32, i32)> {
468        let _ = widget_id;
469        None
470    }
471    /// Smallest size, `(width, height)` in logical pixels, a visible leaf
472    /// may be compressed to when its window is too small for its natural
473    /// content.
474    ///
475    /// `Ui::compute_layout` resets every non-root `min_size` to the app's own
476    /// minimum so natural sizes stay a shrinkable basis and rows compress to
477    /// the window. That suits lanes that can paint a control at any size. A
478    /// lane with quantized geometry (the TUI cell grid paints every widget
479    /// in whole cells) returns a floor here so compressed siblings cannot
480    /// land on the same cells and overprint each other or lose their labels.
481    /// The height floor always applies; the width floor applies only in row
482    /// parents, the same rule that seeds a leaf's natural width. `None`
483    /// (the default) keeps the shrink-to-zero behaviour.
484    fn min_compressed_size(&self, widget_id: WidgetId) -> Option<(i32, i32)> {
485        let _ = widget_id;
486        None
487    }
488    /// Mirrors a declarative container's flexbox padding (`[top, right,
489    /// bottom, left]`, logical pixels) onto lanes whose containers lay their
490    /// children out natively (GTK boxes). Lanes that place children
491    /// from the computed layout already honour the computed layout style and keep this
492    /// default no-op. The declarative gap is deliberately not mirrored: a
493    /// native box cannot shrink controls below their native minimum, so a
494    /// wide layout gap would push trailing controls out of their row; apps
495    /// opt in with `Ui::set_container_gap`.
496    fn apply_flow_padding(&mut self, widget_id: WidgetId, padding: [i32; 4]) -> GuiResult<()> {
497        let _ = (widget_id, padding);
498        Ok(())
499    }
500    /// Hosts an advanced-control family inside `host` and reports the
501    /// runtime capability record for that family.
502    ///
503    /// The default refuses with a typed error, so a lane never silently
504    /// pretends to host a family; Mock and Win32 override this behind the
505    /// family's Cargo feature.
506    fn host_advanced_control(
507        &mut self,
508        host: WidgetId,
509        family: crate::advanced::AdvancedFamily,
510    ) -> GuiResult<crate::advanced::AdvancedHostCapabilities> {
511        let _ = (host, family);
512        Err(GuiError::UnsupportedCapability(
513            "advanced_control".to_owned(),
514        ))
515    }
516    /// Sets items for a data list widget.
517    fn set_data_list_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()>;
518    /// Replaces a `ComboBox`'s options after creation (found while dogfooding).
519    /// Must not emit `SelectionChanged`. The default reports
520    /// `UnsupportedCapability("combo_box_items")`; options given at creation
521    /// (`Ui::create_combo_box`) work on every lane.
522    fn set_combo_box_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()> {
523        let _ = (widget_id, items);
524        Err(GuiError::UnsupportedCapability(
525            "combo_box_items".to_owned(),
526        ))
527    }
528    /// Sets column headers for the columned list contract.
529    ///
530    /// The default reports the typed [`GuiError::UnsupportedCapability`]
531    /// with the `"list_view_columns"` identifier, so a lane without a
532    /// columned mapping fails loudly instead of silently rendering a flat
533    /// list. Lanes override this when their mapping lands and must keep the
534    /// documented cell rule (`list_rows[r][c]` under column `c`).
535    fn set_list_columns(&mut self, widget_id: WidgetId, columns: &[ColumnSpec]) -> GuiResult<()> {
536        let _ = (widget_id, columns);
537        Err(GuiError::UnsupportedCapability(
538            "list_view_columns".to_owned(),
539        ))
540    }
541    /// Sets row cells for the columned list contract.
542    ///
543    /// Same capability contract as [`Self::set_list_columns`].
544    fn set_list_rows(&mut self, widget_id: WidgetId, rows: &[Vec<String>]) -> GuiResult<()> {
545        let _ = (widget_id, rows);
546        Err(GuiError::UnsupportedCapability(
547            "list_view_columns".to_owned(),
548        ))
549    }
550    /// Clears the native selection of a row widget.
551    ///
552    /// The default reports the typed [`GuiError::UnsupportedCapability`]
553    /// with the `"clear_selection"` identifier, so `Ui::clear_selection` and
554    /// a keyed apply that must drop a removed selection fail loudly instead
555    /// of leaving the native selection out of sync with the model.
556    fn clear_selection(&mut self, widget_id: WidgetId) -> GuiResult<()> {
557        let _ = widget_id;
558        Err(GuiError::UnsupportedCapability(
559            "clear_selection".to_owned(),
560        ))
561    }
562    /// Reports the index of the topmost visible row of a row widget, when the
563    /// lane can observe its scroll position (capability
564    /// `"scroll_anchor"`).
565    fn visible_anchor_index(&self, widget_id: WidgetId) -> GuiResult<Option<usize>> {
566        let _ = widget_id;
567        Err(GuiError::UnsupportedCapability("scroll_anchor".to_owned()))
568    }
569    /// Scrolls a row widget so `index` is its topmost visible row.
570    ///
571    /// Same capability contract as [`Self::visible_anchor_index`]: a lane
572    /// that cannot restore the anchor reports the typed `"scroll_anchor"`
573    /// refusal and the shared model skips re-anchoring instead of guessing.
574    fn scroll_to_row(&mut self, widget_id: WidgetId, index: usize) -> GuiResult<()> {
575        let _ = (widget_id, index);
576        Err(GuiError::UnsupportedCapability("scroll_anchor".to_owned()))
577    }
578    /// Reports whether the last row of a row widget is currently visible
579    /// (follow-tail detection): `true` when the lane can observe the
580    /// scroll position and the bottom-most row lies inside the viewport.
581    ///
582    /// Same capability contract as [`Self::visible_anchor_index`]: a lane
583    /// without the `"scroll_anchor"` capability reports the typed refusal,
584    /// and a widget with no rows answers `false` (nothing is at the end).
585    fn rows_end_visible(&self, widget_id: WidgetId) -> GuiResult<bool> {
586        let _ = widget_id;
587        Err(GuiError::UnsupportedCapability("scroll_anchor".to_owned()))
588    }
589    /// Applies incremental row operations to a row widget.
590    ///
591    /// Backends implement this to avoid full table reconstruction on single-cell
592    /// edits, inserts, removes, or moves. The default implementation returns
593    /// `Err(GuiError::UnsupportedCapability("row_delta".to_owned()))`.
594    fn apply_row_delta(
595        &mut self,
596        widget_id: WidgetId,
597        ops: &[crate::widgets::RowOp],
598    ) -> GuiResult<()> {
599        let _ = (widget_id, ops);
600        Err(GuiError::UnsupportedCapability("row_delta".to_owned()))
601    }
602    /// Sets row-major cell data for a data grid widget (legacy string matrix).
603    ///
604    /// The matrix is shared as one [`Arc`] between the manager's spec and the
605    /// backend, so neither keeps a private resident copy.
606    fn set_data_grid_rows(
607        &mut self,
608        widget_id: WidgetId,
609        rows: Arc<Vec<Vec<String>>>,
610    ) -> GuiResult<()>;
611    /// Sets a virtual data model for a data grid widget.
612    fn set_data_grid_model(
613        &mut self,
614        widget_id: WidgetId,
615        model: Box<dyn crate::widgets::DataGridModel>,
616    ) -> GuiResult<()>;
617    /// Sets the height of a specific row in a data grid widget.
618    fn set_data_grid_row_height(
619        &mut self,
620        widget_id: WidgetId,
621        row: usize,
622        height: i32,
623    ) -> GuiResult<()>;
624    /// Sets the width of a specific column in a data grid widget.
625    fn set_data_grid_col_width(
626        &mut self,
627        widget_id: WidgetId,
628        col: usize,
629        width: i32,
630    ) -> GuiResult<()>;
631    /// Sets the number of frozen rows and columns in a data grid widget.
632    fn set_data_grid_frozen_panes(
633        &mut self,
634        widget_id: WidgetId,
635        rows: usize,
636        cols: usize,
637    ) -> GuiResult<()>;
638    /// Sets the selected cells for a DataGrid.
639    fn set_data_grid_selection(
640        &mut self,
641        widget_id: WidgetId,
642        selection: &[(usize, usize)],
643    ) -> GuiResult<()>;
644    /// Sets hierarchical items for a tree view widget.
645    fn set_tree_items(&mut self, widget_id: WidgetId, items: &[TreeItem]) -> GuiResult<()>;
646    /// Sets preferred position for widgets.
647    fn set_position(&mut self, widget_id: WidgetId, x: i32, y: i32) -> GuiResult<()>;
648    /// Applies a computed layout position.
649    ///
650    /// Backends with native flow containers may let those containers place
651    /// children instead of translating the position into manual offsets.
652    /// The default preserves existing backend behavior.
653    fn set_layout_position(&mut self, widget_id: WidgetId, x: i32, y: i32) -> GuiResult<()> {
654        self.set_position(widget_id, x, y)
655    }
656    /// Sets background color for a widget.
657    fn set_background_color(&mut self, widget_id: WidgetId, color: Color) -> GuiResult<()>;
658    /// Sets alert severity for an alert dialog widget.
659    fn set_alert_level(&mut self, widget_id: WidgetId, level: AlertLevel) -> GuiResult<()>;
660    /// Sets image source for image-capable widgets.
661    fn set_image_source(&mut self, widget_id: WidgetId, source: &str) -> GuiResult<()>;
662
663    /// Reports support for bounded in-memory RGBA image resources.
664    fn image_resource_capabilities(&self) -> ImageResourceCapabilities {
665        ImageResourceCapabilities::none()
666    }
667    /// Loads a UI-allocated image resource into this backend.
668    ///
669    /// The default refuses explicitly so a backend without a pixel provider
670    /// never reports a success-shaped no-op.
671    fn load_image_resource(
672        &mut self,
673        _resource: ImageResourceId,
674        _data: &ImageData,
675    ) -> GuiResult<()> {
676        Err(GuiError::UnsupportedCapability(
677            "image_resource_rgba".to_owned(),
678        ))
679    }
680    /// Releases an image resource previously loaded into this backend.
681    fn release_image_resource(&mut self, _resource: ImageResourceId) -> GuiResult<()> {
682        Err(GuiError::UnsupportedCapability(
683            "image_resource_rgba".to_owned(),
684        ))
685    }
686
687    /// Sets how an image scales into its bounds.
688    ///
689    /// The default returns a typed capability error so a backend without an
690    /// image surface never silently ignores the request.
691    fn set_image_fit(&mut self, _widget_id: WidgetId, _fit: ImageFit) -> GuiResult<()> {
692        Err(GuiError::UnsupportedCapability("set_image_fit".to_owned()))
693    }
694
695    /// Sets what a `FileChooserDialog` lets the user pick.
696    ///
697    /// The default returns a typed capability error so a backend that cannot
698    /// present a folder picker never silently shows the wrong dialog.
699    fn set_file_chooser_mode(
700        &mut self,
701        _widget_id: WidgetId,
702        _mode: FileChooserMode,
703    ) -> GuiResult<()> {
704        Err(GuiError::UnsupportedCapability(
705            "file_chooser_pick_folder".to_owned(),
706        ))
707    }
708    /// Sets the stock-art icon rendered beside a button's label.
709    ///
710    /// `None` clears the icon. The default reports the typed unsupported
711    /// error: a lane without a button-art mapping must refuse instead of
712    /// silently leaving a text-only button behind.
713    fn set_icon(&mut self, _widget_id: WidgetId, _icon: Option<IconRole>) -> GuiResult<()> {
714        Err(GuiError::UnsupportedWidget("set_icon"))
715    }
716    /// Applies colour-dialog preferences to a live `ColorDialog`.
717    ///
718    /// The default reports the typed unsupported error: a lane that cannot
719    /// present the native chooser must refuse instead of pretending the
720    /// preferences took effect.
721    fn set_color_dialog_data(
722        &mut self,
723        _widget_id: WidgetId,
724        _data: &ColorDialogData,
725    ) -> GuiResult<()> {
726        Err(GuiError::UnsupportedWidget("color_dialog"))
727    }
728    /// Applies font-dialog preferences to a live `FontDialog`.
729    ///
730    /// The default reports the typed unsupported error: a lane that cannot
731    /// present the native chooser must refuse instead of pretending the
732    /// preferences took effect.
733    fn set_font_dialog_data(
734        &mut self,
735        _widget_id: WidgetId,
736        _data: &FontDialogData,
737    ) -> GuiResult<()> {
738        Err(GuiError::UnsupportedWidget("font_dialog"))
739    }
740    /// Replaces the tools of a `Toolbar` widget.
741    ///
742    /// The default reports the typed unsupported error: a lane that has not
743    /// composed the native toolbar refuses instead of pretending the items
744    /// took effect. GTK/Win32/Cocoa compositions land later.
745    fn set_toolbar_items(&mut self, _widget_id: WidgetId, _items: &[ToolbarItem]) -> GuiResult<()> {
746        Err(GuiError::UnsupportedWidget("toolbar"))
747    }
748    /// Sets the orientation of a `Toolbar` widget.
749    ///
750    /// The default reports the typed unsupported error for the same reason as
751    /// [`Backend::set_toolbar_items`]; a lane whose native control is
752    /// horizontal-only reports `UnsupportedCapability("toolbar_vertical")`
753    /// for a vertical request once its composition lands.
754    fn set_toolbar_orientation(
755        &mut self,
756        _widget_id: WidgetId,
757        _orientation: ToolbarOrientation,
758    ) -> GuiResult<()> {
759        Err(GuiError::UnsupportedWidget("toolbar"))
760    }
761    /// Sets selected dates for a calendar widget.
762    fn set_calendar_selected_dates(
763        &mut self,
764        _widget_id: WidgetId,
765        _dates: &[CalendarDate],
766    ) -> GuiResult<()> {
767        Err(GuiError::UnsupportedWidget("calendar"))
768    }
769    /// Sets selectable bounds for a calendar widget.
770    fn set_calendar_bounds(
771        &mut self,
772        _widget_id: WidgetId,
773        _min_date: Option<CalendarDate>,
774        _max_date: Option<CalendarDate>,
775    ) -> GuiResult<()> {
776        Err(GuiError::UnsupportedWidget("calendar"))
777    }
778    /// Sets the first day of the week convention for a calendar widget.
779    fn set_calendar_first_day_of_week(
780        &mut self,
781        _widget_id: WidgetId,
782        _first_day: CalendarFirstDayOfWeek,
783    ) -> GuiResult<()> {
784        Err(GuiError::UnsupportedWidget("calendar"))
785    }
786    /// Sets the selection mode for a calendar widget.
787    fn set_calendar_selection_mode(
788        &mut self,
789        _widget_id: WidgetId,
790        _mode: CalendarSelectionMode,
791    ) -> GuiResult<()> {
792        Err(GuiError::UnsupportedWidget("calendar"))
793    }
794    /// Sets date value (`YYYY-MM-DD`) for date-capable widgets.
795    fn set_date_value(&mut self, widget_id: WidgetId, iso_date: &str) -> GuiResult<()>;
796    /// Sets URL for link-capable widgets.
797    fn set_link_url(&mut self, widget_id: WidgetId, url: &str) -> GuiResult<()>;
798    /// Sets stacking direction for container widgets.
799    fn set_container_direction(
800        &mut self,
801        widget_id: WidgetId,
802        direction: ContainerDirection,
803    ) -> GuiResult<()>;
804    /// Sets wrap behavior for container widgets.
805    fn set_container_wrap(&mut self, widget_id: WidgetId, wrap: ContainerWrap) -> GuiResult<()> {
806        let _ = (widget_id, wrap);
807        Ok(())
808    }
809    /// Sets scroll capability for container widgets.
810    fn set_container_scroll(
811        &mut self,
812        widget_id: WidgetId,
813        vertical: bool,
814        horizontal: bool,
815    ) -> GuiResult<()>;
816    /// Sets the uniform spacing between a flow container's children.
817    fn set_container_gap(&mut self, widget_id: WidgetId, gap: i32) -> GuiResult<()>;
818    /// Sets the uniform inset between a container's edges and its children.
819    fn set_container_padding(&mut self, widget_id: WidgetId, padding: i32) -> GuiResult<()>;
820    /// Draws a built-in colored 3D cube demo into a Vulkan canvas widget.
821    fn draw_demo_cube(&mut self, widget_id: WidgetId) -> GuiResult<()>;
822    /// Creates a backend-native degraded replacement for an unavailable
823    /// Vulkan canvas. Backends must refuse rather than fabricate a fallback.
824    fn create_gpu_fallback(
825        &mut self,
826        _spec: &WidgetSpec,
827        _policy: GpuDegradationPolicy,
828    ) -> GuiResult<()> {
829        Err(GuiError::UnsupportedCapability(
830            "gpu_degradation_fallback".to_owned(),
831        ))
832    }
833    /// Sets the scene content for a `WidgetKind::Canvas` widget.
834    fn set_canvas_scene(
835        &mut self,
836        widget_id: WidgetId,
837        scene: &crate::CanvasScene,
838    ) -> GuiResult<()>;
839    /// Sets the raster surface painted beneath a `WidgetKind::Canvas` scene.
840    /// Backends without an implementation return a typed error.
841    fn set_canvas_surface(
842        &mut self,
843        _widget_id: WidgetId,
844        _surface: &crate::CanvasSurface,
845    ) -> GuiResult<()> {
846        Err(GuiError::UnsupportedWidget("set_canvas_surface"))
847    }
848    /// Returns backend-native handle information for a Vulkan canvas widget.
849    type NativeHandle;
850    fn native_handle(&self, widget_id: WidgetId) -> GuiResult<Self::NativeHandle>;
851    /// Returns backend-native handle information for a Metal canvas widget.
852    fn metal_canvas_handle(&self, _widget_id: WidgetId) -> GuiResult<MetalCanvasHandle> {
853        Err(GuiError::UnsupportedCapability("metal_surface".to_owned()))
854    }
855    /// Adds a child widget to a parent widget.
856    fn add_child(&mut self, parent: WidgetId, child: WidgetId) -> GuiResult<()>;
857    /// Reparents an existing child to a new parent.
858    fn reparent(&mut self, child: WidgetId, new_parent: WidgetId) -> GuiResult<()> {
859        self.add_child(new_parent, child)
860    }
861    /// Makes a widget visible.
862    fn show(&mut self, widget_id: WidgetId) -> GuiResult<()>;
863    /// Hides a widget without removing it.
864    fn hide(&mut self, widget_id: WidgetId) -> GuiResult<()>;
865    /// Removes a widget and its native counterpart.
866    fn remove(&mut self, widget_id: WidgetId) -> GuiResult<()>;
867    /// Enables or disables a widget.
868    fn set_enabled(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()>;
869    /// Programmatically activates a clickable widget, as if it were clicked.
870    fn activate(&mut self, widget_id: WidgetId) -> GuiResult<()>;
871    /// Returns the backend's short identifier (e.g. "mock", "win32", "gtk", "cocoa").
872    fn backend_name(&self) -> &'static str {
873        "unknown"
874    }
875
876    /// Captures a screenshot of the specified window as RGBA pixels.
877    fn capture_window_rgba(
878        &self,
879        _widget_id: WidgetId,
880        _include_decorations: bool,
881    ) -> GuiResult<(u32, u32, Vec<u8>)> {
882        Err(GuiError::UnsupportedWidget("capture_window_rgba"))
883    }
884
885    /// Captures a screenshot of the specified widget as RGBA pixels.
886    fn capture_widget_rgba(&self, _widget_id: WidgetId) -> GuiResult<(u32, u32, Vec<u8>)> {
887        Err(GuiError::UnsupportedWidget("capture_widget_rgba"))
888    }
889
890    /// Reads live text for a widget (E2E readback).
891    fn native_read_text(&self, _widget_id: WidgetId) -> GuiResult<Option<String>> {
892        Ok(None)
893    }
894
895    /// Reads live checked state for a checkbox (E2E readback).
896    fn native_read_checked(&self, _widget_id: WidgetId) -> GuiResult<Option<bool>> {
897        Ok(None)
898    }
899
900    /// Native click simulation (E2E).
901    fn native_click(&self, _widget_id: WidgetId) -> GuiResult<bool> {
902        Ok(false)
903    }
904
905    /// Native type text simulation (E2E).
906    fn native_type_text(&self, _widget_id: WidgetId, _text: &str) -> GuiResult<bool> {
907        let _ = _text;
908        Ok(false)
909    }
910
911    /// Native close simulation (E2E).
912    fn native_close(&self, _widget_id: WidgetId) -> GuiResult<bool> {
913        Ok(false)
914    }
915
916    /// Services a bounded native-work slice; unverified adapters refuse it.
917    fn e2e_capability(&self, _widget_id: WidgetId, _operation: Operation) -> GuiResult<Capability> {
918        Ok(Capability::Unsupported {
919            reason: "This backend has no E2E adapter".into(),
920        })
921    }
922
923    fn e2e_click(&mut self, _widget_id: WidgetId) -> GuiResult<()> {
924        Err(GuiError::UnsupportedWidget("e2e.click"))
925    }
926
927    fn e2e_type_text(&mut self, _widget_id: WidgetId, _text: &str) -> GuiResult<()> {
928        Err(GuiError::UnsupportedWidget("e2e.type_text"))
929    }
930
931    fn e2e_check(&mut self, _widget_id: WidgetId, _checked: bool) -> GuiResult<()> {
932        Err(GuiError::UnsupportedWidget("e2e.check"))
933    }
934
935    fn e2e_text(&self, _widget_id: WidgetId) -> GuiResult<String> {
936        Err(GuiError::UnsupportedWidget("e2e.text"))
937    }
938
939    fn e2e_checked(&self, _widget_id: WidgetId) -> GuiResult<bool> {
940        Err(GuiError::UnsupportedWidget("e2e.checked"))
941    }
942
943    fn e2e_poll_event(&mut self) -> GuiResult<Option<UiEvent>> {
944        Err(GuiError::UnsupportedWidget("e2e.poll"))
945    }
946    /// Writes text to the platform clipboard.
947    ///
948    /// Default: no-op — the `Ui` layer keeps an in-memory mirror so paste
949    /// still works. Native backends override this with real OS clipboard
950    /// writes (GTK today; Win32 tracked).
951    fn set_clipboard_text(&mut self, _text: &str) -> GuiResult<()> {
952        Ok(())
953    }
954    /// Reads text from the platform clipboard, when the backend can provide
955    /// it synchronously. `Ok(None)` means "unavailable" — callers fall back
956    /// to the `Ui`-level in-memory mirror.
957    fn clipboard_text(&mut self) -> GuiResult<Option<String>> {
958        Ok(None)
959    }
960    /// Reads an image from the platform clipboard, returning RGBA pixels and PNG bytes.
961    fn paste_image_from_clipboard(&mut self) -> GuiResult<Option<ClipboardImage>> {
962        Ok(None)
963    }
964    /// Returns the platform-specific application data directory.
965    fn data_dir(&self) -> GuiResult<PathBuf>;
966    /// Sets tooltip text for a widget.
967    fn set_tooltip(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()>;
968    /// Applies an accessible name to a widget.
969    ///
970    /// Default: returns [`GuiError::UnsupportedCapability`]; a backend
971    /// without a native accessibility bridge must not silently ignore the
972    /// request. GTK, Win32 and Cocoa apply the model in their own bridges.
973    fn set_accessible_name(&mut self, _widget_id: WidgetId, _name: &str) -> GuiResult<()> {
974        Err(GuiError::UnsupportedCapability(
975            "accessible name".to_owned(),
976        ))
977    }
978    /// Applies an accessible description to a widget.
979    ///
980    /// Default: returns [`GuiError::UnsupportedCapability`] (see
981    /// [`Backend::set_accessible_name`]).
982    fn set_accessible_description(
983        &mut self,
984        _widget_id: WidgetId,
985        _description: &str,
986    ) -> GuiResult<()> {
987        Err(GuiError::UnsupportedCapability(
988            "accessible description".to_owned(),
989        ))
990    }
991    /// Posts a dynamic accessibility update for a widget.
992    ///
993    /// The default is deliberately best-effort: some native controls announce
994    /// programmatic updates themselves, and notification delivery is not a
995    /// portable capability result. Backends may override this to post native
996    /// assistive-technology notifications.
997    fn post_accessible_notification(
998        &mut self,
999        widget_id: WidgetId,
1000        notification: AccessibleNotification,
1001    ) -> GuiResult<()> {
1002        let _ = (widget_id, notification);
1003        Ok(())
1004    }
1005    /// Moves keyboard focus to a widget.
1006    ///
1007    /// Default: returns [`GuiError::UnsupportedCapability`]; a backend
1008    /// without a native focus mapping must not silently ignore the request.
1009    /// GTK/Win32/Cocoa application lands.
1010    fn set_focus(&mut self, _widget_id: WidgetId) -> GuiResult<()> {
1011        Err(GuiError::UnsupportedCapability("focus".to_owned()))
1012    }
1013    /// Applies the focusable flag so native traversal can honor the override.
1014    ///
1015    /// Default: returns [`GuiError::UnsupportedCapability`] (see
1016    /// [`Backend::set_focus`]).
1017    fn set_focusable(&mut self, _widget_id: WidgetId, _focusable: bool) -> GuiResult<()> {
1018        Err(GuiError::UnsupportedCapability("focusable".to_owned()))
1019    }
1020    /// Applies a resolved theme so native controls can restyle.
1021    ///
1022    /// Default: returns [`GuiError::UnsupportedCapability`]; a backend
1023    /// without a native theming mapping must not silently ignore the request.
1024    /// GTK/Win32/Cocoa application lands.
1025    fn set_theme(&mut self, _theme: &Theme) -> GuiResult<()> {
1026        Err(GuiError::UnsupportedCapability("theme".to_owned()))
1027    }
1028    /// Applies a per-widget theme override.
1029    ///
1030    /// Default: returns [`GuiError::UnsupportedCapability`] (see
1031    /// [`Backend::set_theme`]).
1032    fn set_theme_override(
1033        &mut self,
1034        _widget_id: WidgetId,
1035        _theme_override: ThemeOverride,
1036    ) -> GuiResult<()> {
1037        Err(GuiError::UnsupportedCapability("theme override".to_owned()))
1038    }
1039    /// Clears the per-widget theme overrides.
1040    ///
1041    /// Default: returns [`GuiError::UnsupportedCapability`] (see
1042    /// [`Backend::set_theme`]).
1043    fn clear_theme_overrides(&mut self, _widget_id: WidgetId) -> GuiResult<()> {
1044        Err(GuiError::UnsupportedCapability("theme override".to_owned()))
1045    }
1046    /// Reports the backend's system light/dark detection support.
1047    ///
1048    /// Default: [`ThemeCapabilities::none`] — a capability query, so an
1049    /// safe default instead of the typed error used by setters.
1050    fn theme_capabilities(&self) -> ThemeCapabilities {
1051        ThemeCapabilities::none()
1052    }
1053    /// Returns the OS light/dark preference when the backend can detect it;
1054    /// `None` means unknown or unsupported.
1055    ///
1056    /// Change notifications arrive as [`UiEvent::ThemeChanged`].
1057    fn system_theme_mode(&self) -> Option<ThemeMode> {
1058        None
1059    }
1060    /// Returns whether the OS high-contrast accessibility mode is active.
1061    fn system_high_contrast(&self) -> bool {
1062        false
1063    }
1064    /// Reports the lane's native stock-art support.
1065    ///
1066    /// The portable renderer ([`Ui::stock_icon`]) is library-owned art and is
1067    /// available on every backend; this describes the optional OS-native
1068    /// lookup served by [`Backend::native_stock_icon`]. Default: no native
1069    /// art, so the capability query stays accurate without a typed error.
1070    fn art_capabilities(&self) -> ArtCapabilities {
1071        ArtCapabilities::none()
1072    }
1073    /// Resolves an OS-native stock icon for a role and DPI variant.
1074    ///
1075    /// Default: returns [`GuiError::UnsupportedCapability`] — a lane without
1076    /// a native mapping must not fabricate art or return a placeholder.
1077    /// Apps that want platform-independent art use [`Ui::stock_icon`] instead.
1078    fn native_stock_icon(&self, role: IconRole, size: IconSize) -> GuiResult<StockIcon> {
1079        Err(crate::artprov::unsupported_native_icon(
1080            role,
1081            size,
1082            "no native mapping on this backend",
1083        ))
1084    }
1085    /// Reports the lane's display-metric support.
1086    ///
1087    /// Capability query: [`DisplayCapabilities::none`] is a safe default
1088    /// (no detection) instead of the typed error used by setters.
1089    fn display_capabilities(&self) -> DisplayCapabilities {
1090        DisplayCapabilities::none()
1091    }
1092    /// Reports host GPU surface and degradation support.
1093    ///
1094    /// The default advertises no GPU integration. A capability means the
1095    /// backend can provide its documented host contract, not that a
1096    /// third-party renderer or device driver is installed.
1097    fn gpu_surface_capabilities(&self) -> GpuSurfaceCapabilities {
1098        GpuSurfaceCapabilities::none()
1099    }
1100    /// Enumerates connected displays.
1101    ///
1102    /// Default: returns [`GuiError::UnsupportedCapability`] — a lane that
1103    /// cannot enumerate must not fabricate monitor geometry. DPI/monitor
1104    /// transitions arrive as [`UiEvent::DisplayChanged`] when
1105    /// [`Backend::display_capabilities`] advertises `dpi_change_events`.
1106    #[cfg(feature = "displays")]
1107    fn displays(&self) -> GuiResult<Vec<DisplayInfo>> {
1108        Err(GuiError::UnsupportedCapability(
1109            "display_metrics".to_owned(),
1110        ))
1111    }
1112    /// Returns the primary display; derived from [`Backend::displays`].
1113    #[cfg(feature = "displays")]
1114    fn primary_display(&self) -> GuiResult<Option<DisplayInfo>> {
1115        Ok(self.displays()?.into_iter().find(|display| display.primary))
1116    }
1117    /// Reports the display scale factor (relative to 96 DPI) of the display
1118    /// hosting `widget_id`.
1119    ///
1120    /// [`Ui`] uses the value to project incoming pointer input: a lane that
1121    /// receives physical pixels from the OS (Win32 under Per-Monitor v2)
1122    /// reports the window's effective DPI divided by 96, and every
1123    /// [`UiEvent::PointerDown`], [`UiEvent::PointerMove`], and
1124    /// [`UiEvent::PointerUp`] the app observes has been divided by it, so a
1125    /// physical `(125, 250)` on a 125 % display arrives as the logical
1126    /// `(100, 200)` the layout engine lays the widget out against. Lanes that already
1127    /// receive logical coordinates (GTK4 gestures, Cocoa points) report `1.0`,
1128    /// making the projection the identity.
1129    ///
1130    /// Default: `1.0` — a neutral identity for a lane that does not report
1131    /// scaling, so the projection is a no-op rather than a guess. A lane must
1132    /// report `1.0` unless its pointer events really are in physical pixels.
1133    fn widget_scale_factor(&self, _widget_id: WidgetId) -> f64 {
1134        1.0
1135    }
1136    /// Blocks until the next UI event is available.
1137    ///
1138    /// Unlike `poll_event`, this parks the thread inside the platform's
1139    /// event system instead of busy-polling.
1140    fn poll_event(&mut self) -> GuiResult<Option<UiEvent>>;
1141    /// Blocks until the next UI event is available and returns it.
1142    fn wait_event(&mut self) -> GuiResult<UiEvent>;
1143    /// Returns a thread-safe callback that wakes this backend's event loop.
1144    ///
1145    /// `Ui::task_proxy` embeds it into every [`UiProxy`] so a command posted
1146    /// from a worker thread promptly interrupts a blocked `wait_event`; the
1147    /// transport marker itself is an internal `UiEvent::TasksPending` that
1148    /// `Ui` consumes while draining. Backends without a wake hook return
1149    /// `None` (the default); queued commands then apply at the next organic
1150    /// event.
1151    fn wake_handle(&self) -> Option<std::sync::Arc<dyn Fn() + Send + Sync>> {
1152        None
1153    }
1154    /// Shows a modal Yes/No confirm dialog; the answer is delivered as
1155    /// `UiEvent::DialogResponse { token, confirmed }`.
1156    fn show_confirm_dialog(&mut self, token: u64, title: &str, message: &str) -> GuiResult<()>;
1157
1158    /// Shows a native file dialog described by `request` (dogfood report
1159    /// #5). The answer must arrive later as
1160    /// `UiEvent::FileDialogResponse { token, paths }` (empty `paths` when
1161    /// cancelled). The default reports
1162    /// `UnsupportedCapability("file_dialog")`, so existing backends keep
1163    /// compiling; use the `FileChooserDialog` widget there.
1164    fn show_file_dialog(
1165        &mut self,
1166        token: u64,
1167        request: &crate::file_dialog::FileDialog,
1168    ) -> GuiResult<()> {
1169        let _ = (token, request);
1170        Err(GuiError::UnsupportedCapability("file_dialog".to_owned()))
1171    }
1172
1173    /// Returns the platform handles of a realized top-level window
1174    /// (found while dogfooding).
1175    ///
1176    /// The default reports `UnsupportedCapability("native_window_handle")`,
1177    /// so existing backends keep compiling. Backends return an error rather
1178    /// than a placeholder when the window is not realized yet.
1179    fn native_window_handle(
1180        &self,
1181        window_id: WidgetId,
1182    ) -> GuiResult<crate::window_handle::NativeWindowHandle> {
1183        let _ = window_id;
1184        Err(GuiError::UnsupportedCapability(
1185            "native_window_handle".to_owned(),
1186        ))
1187    }
1188
1189    /// Enables or disables close-request interception for a window.
1190    ///
1191    /// While guarded, an OS close request (the X button, Alt+F4, the system
1192    /// menu) emits [`UiEvent::CloseRequested`] and the window stays open; the
1193    /// app approves a close by lifting the guard and removing the window.
1194    /// Default: [`GuiError::UnsupportedCapability`] — a lane without close
1195    /// interception must not silently close.
1196    fn set_close_guard(&mut self, _widget_id: WidgetId, _guarded: bool) -> GuiResult<()> {
1197        Err(GuiError::UnsupportedCapability(
1198            "set_close_guard".to_owned(),
1199        ))
1200    }
1201    /// Reports the window features this backend can apply exactly.
1202    ///
1203    /// Native backends default to no extended-window support until their
1204    /// implementation has runtime evidence.
1205    fn window_capabilities(&self) -> WindowCapabilities {
1206        WindowCapabilities::none()
1207    }
1208    /// Applies options to an existing top-level window.
1209    ///
1210    /// The default permits the portable default options and refuses every
1211    /// extended behavior that a backend has not implemented.
1212    fn set_window_options(
1213        &mut self,
1214        widget_id: WidgetId,
1215        options: &WindowOptions,
1216    ) -> GuiResult<()> {
1217        let _ = widget_id;
1218        if *options == WindowOptions::default() {
1219            Ok(())
1220        } else {
1221            Err(GuiError::UnsupportedCapability("window_options".to_owned()))
1222        }
1223    }
1224    /// Hides a popup without synthesizing a user-dismissal event.
1225    fn dismiss_popup(&mut self, widget_id: WidgetId) -> GuiResult<()> {
1226        self.hide(widget_id)
1227    }
1228    /// Reports timer operations implemented by this backend.
1229    fn timer_capabilities(&self) -> TimerCapabilities {
1230        TimerCapabilities::none()
1231    }
1232    /// Reports support for timer-driven motions.
1233    ///
1234    /// Native backends without a motion implementation inherit an explicit
1235    /// false capability; `Ui::start_motion` then refuses with `ui_motion`.
1236    fn motion_capabilities(&self) -> MotionCapabilities {
1237        MotionCapabilities::none()
1238    }
1239    /// Starts a one-shot or repeating timer with a `Ui`-allocated id.
1240    fn start_timer(&mut self, timer: TimerId, spec: TimerSpec) -> GuiResult<()> {
1241        let _ = (timer, spec);
1242        Err(GuiError::UnsupportedCapability("ui_timer".to_owned()))
1243    }
1244    /// Starts a timer whose lifecycle is tied to one widget.
1245    fn start_widget_timer(
1246        &mut self,
1247        timer: TimerId,
1248        widget_id: WidgetId,
1249        spec: TimerSpec,
1250        stop_policy: TimerStopPolicy,
1251    ) -> GuiResult<()> {
1252        let _ = (timer, widget_id, spec, stop_policy);
1253        Err(GuiError::UnsupportedCapability("widget_timer".to_owned()))
1254    }
1255    /// Cancels a live timer id.
1256    fn cancel_timer(&mut self, timer: TimerId) -> GuiResult<()> {
1257        let _ = timer;
1258        Err(GuiError::UnsupportedCapability("ui_timer".to_owned()))
1259    }
1260
1261    /// Enables or disables a menu item.
1262    ///
1263    /// State-dependent commands (Undo, Redo, Clear) grey out instead of
1264    /// looking actionable. Default: [`GuiError::UnsupportedCapability`] —
1265    /// a lane without a mapping must not claim the item changed.
1266    fn set_menu_item_enabled(&mut self, _item_id: MenuItemId, _enabled: bool) -> GuiResult<()> {
1267        Err(GuiError::UnsupportedCapability(
1268            "set_menu_item_enabled".to_owned(),
1269        ))
1270    }
1271
1272    /// Relabels an existing menu item.
1273    ///
1274    /// State-driven menus (recent-file lists, session lists, plugin menus)
1275    /// relabel rows in place instead of rebuilding the whole bar. Default:
1276    /// [`GuiError::UnsupportedCapability`] — a lane without a mapping must
1277    /// not pretend the label changed.
1278    fn set_menu_item_text(&mut self, _item_id: MenuItemId, _text: &str) -> GuiResult<()> {
1279        Err(GuiError::UnsupportedCapability(
1280            "dynamic_menu_items".to_owned(),
1281        ))
1282    }
1283
1284    /// Inserts a menu item at `index` inside an existing menu; an index past the end
1285    /// appends.
1286    fn insert_menu_item(
1287        &mut self,
1288        _menu_id: MenuId,
1289        _item_id: MenuItemId,
1290        _index: usize,
1291        _text: &str,
1292        _shortcut: Option<&str>,
1293    ) -> GuiResult<()> {
1294        Err(GuiError::UnsupportedCapability(
1295            "dynamic_menu_items".to_owned(),
1296        ))
1297    }
1298
1299    /// Removes a menu item from its menu.
1300    fn remove_menu_item(&mut self, _item_id: MenuItemId) -> GuiResult<()> {
1301        Err(GuiError::UnsupportedCapability(
1302            "dynamic_menu_items".to_owned(),
1303        ))
1304    }
1305
1306    /// Detaches a submenu from its parent and drops it.
1307    fn remove_submenu(&mut self, _submenu_id: MenuId) -> GuiResult<()> {
1308        Err(GuiError::UnsupportedCapability(
1309            "dynamic_menu_items".to_owned(),
1310        ))
1311    }
1312
1313    /// Sets the minimum dimensions for a top-level window.
1314    ///
1315    /// Backends without window minimum size support report
1316    /// [`GuiError::UnsupportedCapability`].
1317    fn set_window_min_size(&mut self, _widget_id: WidgetId, _w: u32, _h: u32) -> GuiResult<()> {
1318        Err(GuiError::UnsupportedCapability(
1319            "set_window_min_size".to_owned(),
1320        ))
1321    }
1322
1323    /// Sets whether a top-level window can be resized by the user.
1324    ///
1325    /// Backends without resizable control report
1326    /// [`GuiError::UnsupportedCapability`].
1327    fn set_resizable(&mut self, _widget_id: WidgetId, _resizable: bool) -> GuiResult<()> {
1328        Err(GuiError::UnsupportedCapability("set_resizable".to_owned()))
1329    }
1330
1331    /// Sets placeholder/hint text on a text input widget.
1332    fn set_placeholder_text(&mut self, _widget_id: WidgetId, _text: &str) -> GuiResult<()> {
1333        Err(GuiError::UnsupportedCapability(
1334            "set_placeholder_text".to_owned(),
1335        ))
1336    }
1337
1338    /// Sets styled text runs for a rich text widget.
1339    fn set_rich_text_runs(&mut self, _widget_id: WidgetId, _runs: &[TextRun]) -> GuiResult<()> {
1340        Err(GuiError::UnsupportedCapability(
1341            "set_rich_text_runs".to_owned(),
1342        ))
1343    }
1344
1345    /// Sets inline images for a rich text widget.
1346    fn set_rich_text_images(
1347        &mut self,
1348        _widget_id: WidgetId,
1349        _images: &[RichTextImage],
1350    ) -> GuiResult<()> {
1351        Ok(())
1352    }
1353
1354    /// Turns the text control's built-in spell checking on or off
1355    /// (MD-PERF follow-up). Only flags the native control already provides
1356    /// are flipped; lanes without one report the typed unsupported error.
1357    fn set_spell_check(&mut self, _widget_id: WidgetId, _enabled: bool) -> GuiResult<()> {
1358        Err(GuiError::UnsupportedCapability("spell_check".to_owned()))
1359    }
1360
1361    /// Sets monospace font rendering for text-bearing widgets.
1362    fn set_monospace(&mut self, _widget_id: WidgetId, _monospace: bool) -> GuiResult<()> {
1363        Err(GuiError::UnsupportedWidget("set_monospace"))
1364    }
1365
1366    /// Sets an explicit widget font descriptor (`None` clears back to the active theme font).
1367    fn set_font(&mut self, _widget_id: WidgetId, _font: Option<&FontDescriptor>) -> GuiResult<()> {
1368        Err(GuiError::UnsupportedWidget("set_font"))
1369    }
1370
1371    /// Sets per-row stock-art icons for list controls (`DataList`, `ListView`).
1372    fn set_row_icons(
1373        &mut self,
1374        _widget_id: WidgetId,
1375        _icons: &[Option<IconRole>],
1376    ) -> GuiResult<()> {
1377        Err(GuiError::UnsupportedWidget("set_row_icons"))
1378    }
1379
1380    /// Creates a native system tray icon from a specification.
1381    ///
1382    /// Backends without system tray support return [`GuiError::UnsupportedCapability`].
1383    fn create_tray_icon(&mut self, _spec: &TrayIconSpec) -> GuiResult<TrayIconId> {
1384        Err(GuiError::UnsupportedCapability("tray_icon".to_owned()))
1385    }
1386
1387    /// Destroys a native system tray icon by id.
1388    fn destroy_tray_icon(&mut self, _id: TrayIconId) -> GuiResult<()> {
1389        Err(GuiError::UnsupportedCapability("tray_icon".to_owned()))
1390    }
1391
1392    /// Sets or updates the tooltip text for a system tray icon.
1393    fn set_tray_icon_tooltip(&mut self, _id: TrayIconId, _tooltip: &str) -> GuiResult<()> {
1394        Err(GuiError::UnsupportedCapability("tray_icon".to_owned()))
1395    }
1396
1397    /// Attaches or detaches a context menu for a system tray icon.
1398    fn set_tray_icon_menu(&mut self, _id: TrayIconId, _menu: Option<MenuId>) -> GuiResult<()> {
1399        Err(GuiError::UnsupportedCapability("tray_icon".to_owned()))
1400    }
1401
1402    /// Shows or hides a system tray icon.
1403    fn set_tray_icon_visible(&mut self, _id: TrayIconId, _visible: bool) -> GuiResult<()> {
1404        Err(GuiError::UnsupportedCapability("tray_icon".to_owned()))
1405    }
1406
1407    /// Replaces the icon pixels of a system tray icon.
1408    ///
1409    /// `None` restores the platform default image. The payload uses the same
1410    /// portable encoding as [`TrayIconSpec::icon_bytes`]; a backend that can
1411    /// create icons but cannot swap their pixels keeps this default and
1412    /// returns [`GuiError::UnsupportedCapability`] instead of reporting
1413    /// success for an icon it did not change.
1414    fn set_tray_icon_icon(
1415        &mut self,
1416        _id: TrayIconId,
1417        _icon_bytes: Option<Vec<u8>>,
1418    ) -> GuiResult<()> {
1419        Err(GuiError::UnsupportedCapability("tray_icon".to_owned()))
1420    }
1421}
1422
1423type WindowResizeCallback = Box<dyn FnMut(i32, i32)>;
1424type AutoLayoutFn<B> = fn(&mut Ui<B>, WidgetId, f32, f32) -> GuiResult<()>;
1425
1426/// Fallback minimum height for a `Tabs` widget strip, ensuring empty
1427/// tab pages do not collapse the tab bar to zero height when the backend does not
1428/// provide a natural size measurement.
1429pub const MIN_TABS_HEIGHT: f32 = 30.0;
1430
1431/// Cross-platform UI manager over a concrete backend implementation.
1432pub struct Ui<B: Backend> {
1433    backend: B,
1434    widgets: HashMap<WidgetId, WidgetSpec>,
1435    /// Adjacency index: parent id to its live children in registration order,
1436    /// maintained on every edge mutation (`create_with` with a configured
1437    /// parent, `attach`, `reparent`, `remove`) so subtree teardown visits
1438    /// each parent-child edge exactly once - O(N) - instead of rescanning
1439    /// the whole widget map per node. A child appears at
1440    /// most once, under at most one parent.
1441    children_index: HashMap<WidgetId, Vec<WidgetId>>,
1442    /// Branch roots whose subtree style seeding must be (re)applied by the
1443    /// next `compute_layout` pass. `invalidate_layout`
1444    /// keeps the schedule ancestor-free with an O(D) parent-chain walk, so
1445    /// the pass visits each invalidated branch exactly once and clean
1446    /// branches keep their layout caches, natural sizes, and geometry.
1447    layout_dirty: std::collections::HashSet<WidgetId>,
1448    /// Set when an imperative `set_position` moved a widget outside the layout
1449    /// engine. A warm pass must still write computed geometry back then, so
1450    /// the spec does not keep an app position the flow pass owns.
1451    layout_geometry_overridden: bool,
1452    /// Last applied keyed rows per widget (`set_rows_keyed`): the
1453    /// diff baseline for the next keyed apply.
1454    keyed_rows: HashMap<WidgetId, Vec<RowSet>>,
1455    /// Selected row keys per widget (`set_rows_keyed`).
1456    /// `set_selected_index`/`set_selected_indices` map their indices to keys
1457    /// while keyed rows are present, so a later apply can follow the
1458    /// selection by identity. Kept outside `WidgetSpec` so the
1459    /// spec/native-record mirror invariant stays exact.
1460    keyed_selection: HashMap<WidgetId, Vec<RowKey>>,
1461    menus: HashMap<MenuId, Vec<MenuItemId>>,
1462    menu_item_to_menu: HashMap<MenuItemId, MenuId>,
1463    /// Parent link for every submenu, so `remove_submenu` can detach it
1464    /// from the owning bar.
1465    menu_parents: HashMap<MenuId, MenuId>,
1466    /// Row slot minted for each submenu, kept out of the item-id space used
1467    /// by real items.
1468    submenu_slots: HashMap<MenuId, MenuItemId>,
1469    next_id: u64,
1470    next_menu_id: u64,
1471    next_menu_item_id: u64,
1472    next_dialog_token: u64,
1473    next_tray_icon_id: u64,
1474    next_timer_id: u64,
1475    next_motion_id: u64,
1476    next_image_resource_id: u64,
1477    image_resources: HashMap<ImageResourceId, usize>,
1478    image_resource_bytes: usize,
1479    motions: HashMap<MotionId, ActiveMotion>,
1480    motion_timers: HashMap<TimerId, MotionId>,
1481    tray_icons: HashMap<TrayIconId, TrayIconSpec>,
1482    on_window_close: HashMap<WidgetId, Vec<Box<dyn FnMut()>>>,
1483    on_window_resize: HashMap<WidgetId, Vec<WindowResizeCallback>>,
1484    on_menu_item_selected: HashMap<MenuItemId, Vec<Box<dyn FnMut()>>>,
1485    clipboard: Option<String>,
1486    /// Widget that currently holds keyboard focus; updated by
1487    /// programmatic focus and by `UiEvent::FocusChanged`.
1488    focused: Option<WidgetId>,
1489    /// Active theme tokens.
1490    theme: Theme,
1491    /// Per-widget theme overrides recorded by `set_theme_override`.
1492    theme_overrides: HashMap<WidgetId, Vec<ThemeOverride>>,
1493    /// Windows whose declarative layout is recomputed on resize events.
1494    layout_roots: HashSet<WidgetId>,
1495    /// Widgets currently hidden via `hide` or `set_visible`.
1496    hidden_widgets: HashSet<WidgetId>,
1497    /// Last client size each layout root was laid out at, so
1498    /// pending invalidations can be flushed before the next event wait.
1499    layout_root_sizes: HashMap<WidgetId, (f32, f32)>,
1500    /// Layout minimums recorded by `set_min_size`; `seed_branch`
1501    /// re-applies them on every pass.
1502    min_sizes: HashMap<WidgetId, (i32, i32)>,
1503    /// Declared DataGrid columns (`set_data_grid_columns`, dogfood report
1504    /// #6): the header is rendered as native row 0 and data rows are 0-based.
1505    data_grid_columns: HashMap<WidgetId, Vec<ColumnSpec>>,
1506    /// Data rows last set through `set_data_grid_data_rows`, kept so a later
1507    /// column change can re-render header + data.
1508    data_grid_data: HashMap<WidgetId, Vec<Vec<String>>>,
1509    /// Preferred width constraints recorded by `set_preferred_width`.
1510    preferred_widths: HashMap<WidgetId, u32>,
1511    /// Minimum window sizes recorded by `set_window_min_size`.
1512    window_min_sizes: HashMap<WidgetId, (u32, u32)>,
1513    /// Window resizable flags recorded by `set_resizable`.
1514    window_resizable: HashMap<WidgetId, bool>,
1515    /// Last successfully applied window options.
1516    window_options: HashMap<WidgetId, WindowOptions>,
1517    /// Drag-and-drop payload formats registered with each source and target.
1518    drag_sources: HashMap<WidgetId, DragSourceOptions>,
1519    drag_targets: HashMap<WidgetId, DragTargetOptions>,
1520    /// Degradation mode selected when a Vulkan canvas was created without a
1521    /// native surface.
1522    gpu_degraded: HashMap<WidgetId, GpuDegradationPolicy>,
1523    gpu_degradation_policy: GpuDegradationPolicy,
1524    /// Repository-owned layout tree.
1525    pub layout_tree: LayoutTree,
1526    /// Mapping of WidgetId to owned LayoutNodeId.
1527    pub layout_nodes: std::collections::HashMap<WidgetId, LayoutNodeId>,
1528    /// Auto-layout hook installed once layout sizing, container flow, or
1529    /// explicit layout roots are used so minimal apps that never configure
1530    /// layout do not statically link the full solver in `show`/`pre_dispatch`.
1531    auto_layout_fn: Option<AutoLayoutFn<B>>,
1532    /// Lifecycle events produced by `drain_task_commands`; the event
1533    /// functions return them before backend events.
1534    pending_events: VecDeque<UiEvent>,
1535    /// Lazily created background-command channel: shared proxy + receiver.
1536    #[cfg(feature = "async")]
1537    task_channel: Option<(UiProxy, std::sync::mpsc::Receiver<TaskCommand>)>,
1538    #[cfg(feature = "async")]
1539    #[allow(clippy::type_complexity)]
1540    task_completions: Option<(
1541        std::sync::mpsc::Sender<(crate::async_ui::TaskId, Box<dyn std::any::Any + Send>)>,
1542        std::sync::mpsc::Receiver<(crate::async_ui::TaskId, Box<dyn std::any::Any + Send>)>,
1543    )>,
1544    #[cfg(feature = "async")]
1545    #[allow(clippy::type_complexity)]
1546    task_callbacks: std::collections::HashMap<
1547        crate::async_ui::TaskId,
1548        Box<dyn FnOnce(&mut Ui<B>, Box<dyn std::any::Any + Send>) -> GuiResult<()>>,
1549    >,
1550    #[cfg(feature = "async")]
1551    task_handles: std::collections::HashMap<crate::async_ui::TaskId, crate::async_ui::TaskHandle>,
1552    /// Next advanced operation id; allocated by the
1553    /// feature-gated advanced facades.
1554    #[cfg(any(feature = "property-grid", feature = "webview"))]
1555    pub(crate) next_operation_id: u64,
1556    /// Pending advanced operations, allocated by the facade.
1557    pub(crate) pending_operations: std::collections::HashSet<crate::advanced::OperationId>,
1558    /// Property grids composed by `Ui::create_property_grid`.
1559    #[cfg(feature = "property-grid")]
1560    pub(crate) property_grids: crate::property_grid::PropertyGridRegistry,
1561    /// Styled text documents created by `Ui::create_styled_text`.
1562    #[cfg(feature = "styled-text")]
1563    pub(crate) styled_texts: crate::styled_text::StyledTextRegistry,
1564    /// WebViews created by `Ui::create_webview`.
1565    #[cfg(feature = "webview")]
1566    pub(crate) webviews: crate::webview::WebViewRegistry,
1567}
1568
1569impl<B: Backend> Ui<B> {
1570    /// Creates a new UI manager using the given backend.
1571    pub fn new(backend: B) -> Self {
1572        Self {
1573            backend,
1574            widgets: HashMap::new(),
1575            children_index: HashMap::new(),
1576            layout_dirty: std::collections::HashSet::new(),
1577            layout_geometry_overridden: false,
1578            keyed_rows: HashMap::new(),
1579            keyed_selection: HashMap::new(),
1580            menus: HashMap::new(),
1581            menu_item_to_menu: HashMap::new(),
1582            menu_parents: HashMap::new(),
1583            submenu_slots: HashMap::new(),
1584            next_id: 1,
1585            next_menu_id: 1,
1586            next_menu_item_id: 1,
1587            next_dialog_token: 1,
1588            next_tray_icon_id: 1,
1589            next_timer_id: 1,
1590            next_motion_id: 1,
1591            next_image_resource_id: 1,
1592            image_resources: HashMap::new(),
1593            image_resource_bytes: 0,
1594            motions: HashMap::new(),
1595            motion_timers: HashMap::new(),
1596            tray_icons: HashMap::new(),
1597            on_window_close: HashMap::new(),
1598            on_window_resize: HashMap::new(),
1599            layout_roots: HashSet::new(),
1600            hidden_widgets: HashSet::new(),
1601            min_sizes: HashMap::new(),
1602            data_grid_columns: HashMap::new(),
1603            data_grid_data: HashMap::new(),
1604            preferred_widths: HashMap::new(),
1605            window_min_sizes: HashMap::new(),
1606            window_resizable: HashMap::new(),
1607            window_options: HashMap::new(),
1608            drag_sources: HashMap::new(),
1609            drag_targets: HashMap::new(),
1610            layout_root_sizes: HashMap::new(),
1611            gpu_degraded: HashMap::new(),
1612            gpu_degradation_policy: GpuDegradationPolicy::StrictFail,
1613            on_menu_item_selected: HashMap::new(),
1614            clipboard: None,
1615            focused: None,
1616            theme: Theme::light(),
1617            theme_overrides: HashMap::new(),
1618            layout_tree: LayoutTree::new(),
1619            layout_nodes: std::collections::HashMap::new(),
1620            auto_layout_fn: None,
1621            pending_events: VecDeque::new(),
1622            #[cfg(any(feature = "property-grid", feature = "webview"))]
1623            next_operation_id: 1,
1624            pending_operations: std::collections::HashSet::new(),
1625            #[cfg(feature = "property-grid")]
1626            property_grids: Default::default(),
1627            #[cfg(feature = "styled-text")]
1628            styled_texts: Default::default(),
1629            #[cfg(feature = "webview")]
1630            webviews: Default::default(),
1631            #[cfg(feature = "async")]
1632            task_channel: None,
1633            #[cfg(feature = "async")]
1634            task_completions: None,
1635            #[cfg(feature = "async")]
1636            task_callbacks: std::collections::HashMap::new(),
1637            #[cfg(feature = "async")]
1638            task_handles: std::collections::HashMap::new(),
1639        }
1640    }
1641
1642    /// Returns an immutable reference to the backend.
1643    pub fn backend(&self) -> &B {
1644        &self.backend
1645    }
1646
1647    /// Returns a mutable reference to the backend.
1648    pub fn backend_mut(&mut self) -> &mut B {
1649        &mut self.backend
1650    }
1651
1652    /// Consumes `Ui` and returns the owned backend.
1653    pub fn into_backend(self) -> B {
1654        self.backend
1655    }
1656
1657    /// Creates a widget from a configured [`WidgetSpec`].
1658    ///
1659    /// The `Ui` allocates the identifier and keeps it authoritative: a closure
1660    /// that writes `spec.id` cannot break the bookkeeping. `configure` may set
1661    /// creation-time-only fields — `toolbar_orientation` (Win32 applies
1662    /// `CCS_VERT` when the native control is created), toolbar items, colors,
1663    /// size, position, `selected_index`, `parent` — that the `set_*` accessors
1664    /// can only update after creation; the `set_*` path stays the live-update
1665    /// route.
1666    pub fn create_with(
1667        &mut self,
1668        kind: WidgetKind,
1669        configure: impl FnOnce(&mut WidgetSpec),
1670    ) -> GuiResult<WidgetId> {
1671        let id = WidgetId(self.next_id);
1672        self.next_id += 1;
1673
1674        let mut spec = WidgetSpec::new(id, kind);
1675        configure(&mut spec);
1676        spec.id = id;
1677
1678        if let Some(ref text) = spec.text {
1679            Self::reject_embedded_nul(text)?;
1680        }
1681        if let Some(ref placeholder) = spec.placeholder_text {
1682            Self::reject_embedded_nul(placeholder)?;
1683        }
1684        if let Some(ref tooltip) = spec.tooltip {
1685            Self::reject_embedded_nul(tooltip)?;
1686        }
1687        if let Some(ref source) = spec.image_source {
1688            Self::reject_embedded_nul(source)?;
1689        }
1690
1691        // A parent configured at creation time joins the adjacency index
1692        // exactly like an `attach` would. Validate it before the
1693        // backend allocates anything: a bad parent must not leave an orphan
1694        // widget or an edge no widget owns.
1695        let configured_parent = spec.parent;
1696        if let Some(parent) = configured_parent {
1697            if !self.widgets.contains_key(&parent) {
1698                return Err(GuiError::WidgetNotFound(parent.0));
1699            }
1700            if self.widget_depth(parent) + 1 >= crate::layout::box_sizing::MAX_LAYOUT_DEPTH {
1701                return Err(GuiError::Backend(
1702                    "maximum layout recursion depth exceeded".to_string(),
1703                ));
1704            }
1705        }
1706
1707        let (is_gpu_canvas, capability_name) = match spec.kind {
1708            #[cfg(feature = "widgets-canvas")]
1709            WidgetKind::VulkanCanvas => (true, "vulkan_surface"),
1710            #[cfg(feature = "widgets-canvas")]
1711            WidgetKind::MetalCanvas => (true, "metal_surface"),
1712            _ => (false, ""),
1713        };
1714        let gpu_capabilities = if is_gpu_canvas {
1715            self.backend.gpu_surface_capabilities()
1716        } else {
1717            GpuSurfaceCapabilities::none()
1718        };
1719        let gpu_degraded = match spec.kind {
1720            #[cfg(feature = "widgets-canvas")]
1721            WidgetKind::VulkanCanvas => !gpu_capabilities.vulkan_surface,
1722            #[cfg(feature = "widgets-canvas")]
1723            WidgetKind::MetalCanvas => !gpu_capabilities.metal_surface,
1724            _ => false,
1725        };
1726        if gpu_degraded {
1727            match self.gpu_degradation_policy {
1728                GpuDegradationPolicy::StrictFail => {
1729                    return Err(GuiError::UnsupportedCapability(capability_name.to_owned()));
1730                }
1731                policy => {
1732                    if !gpu_capabilities.supports("gpu_degradation_fallback") {
1733                        return Err(GuiError::UnsupportedCapability(
1734                            "gpu_degradation_fallback".to_owned(),
1735                        ));
1736                    }
1737                    self.backend.create_gpu_fallback(&spec, policy)?;
1738                    self.gpu_degraded.insert(id, policy);
1739                }
1740            }
1741        } else {
1742            self.backend.create_widget(&spec)?;
1743        }
1744        let container_direction = spec.container_direction;
1745        let container_wrap = spec.container_wrap;
1746        self.widgets.insert(id, spec);
1747
1748        let mut owned_style = crate::layout::Style::default();
1749        // An unset direction follows every native backend's default (GTK,
1750        // Win32, Cocoa, Web and TUI stack a Container or GroupBox vertically;
1751        // only a SplitPane defaults to side-by-side panes). The layout
1752        // style's own default is CSS's `row`, so without this an app that
1753        // never called `set_container_direction` was stacked natively on GTK
1754        // but crushed into one row by `compute_layout` on Win32 and Cocoa,
1755        // which apply the computed geometry (`gui_widget_background_colors`
1756        // captures, Figure 12.2).
1757        let direction = container_direction.or(match kind {
1758            WidgetKind::Container => Some(ContainerDirection::Vertical),
1759            #[cfg(feature = "widgets-containers")]
1760            WidgetKind::GroupBox => Some(ContainerDirection::Vertical),
1761            _ => None,
1762        });
1763        if let Some(direction) = direction {
1764            owned_style.flex_direction = match direction {
1765                ContainerDirection::Horizontal => crate::layout::FlexDirection::Row,
1766                ContainerDirection::Vertical => crate::layout::FlexDirection::Column,
1767            };
1768        }
1769        if let Some(wrap) = container_wrap {
1770            owned_style.flex_wrap = match wrap {
1771                ContainerWrap::NoWrap => crate::layout::FlexWrap::NoWrap,
1772                ContainerWrap::Wrap => crate::layout::FlexWrap::Wrap,
1773                ContainerWrap::WrapReverse => crate::layout::FlexWrap::WrapReverse,
1774            };
1775        }
1776        // SplitPane panes fill the pane on the cross axis like a Container's
1777        // children (dogfooding: a padded Container in a SplitPane kept
1778        // its padding-only height instead of stretching).
1779        // Tabs pages fill the Tabs height the same way; see
1780        // `style_tab_page` for their width.
1781        #[cfg(feature = "widgets-containers")]
1782        let is_stretch_container = matches!(
1783            kind,
1784            WidgetKind::Container | WidgetKind::Window | WidgetKind::SplitPane | WidgetKind::Tabs
1785        );
1786        #[cfg(not(feature = "widgets-containers"))]
1787        let is_stretch_container = matches!(kind, WidgetKind::Container | WidgetKind::Window);
1788        if is_stretch_container {
1789            owned_style.align_items = Some(crate::layout::AlignItems::Stretch);
1790        }
1791        let is_intrinsic_leaf = match kind {
1792            WidgetKind::Button => true,
1793            #[cfg(feature = "widgets-pickers")]
1794            WidgetKind::DatePicker => true,
1795            #[cfg(feature = "widgets-choice")]
1796            WidgetKind::Checkbox | WidgetKind::RadioButton => true,
1797            #[cfg(feature = "widgets-range")]
1798            WidgetKind::SpinBox => true,
1799            _ => false,
1800        };
1801        if is_intrinsic_leaf {
1802            owned_style.align_self = Some(crate::layout::AlignSelf::Start);
1803        }
1804        if self.hidden_widgets.contains(&id) {
1805            owned_style.display = crate::layout::Display::None;
1806        }
1807        #[cfg(feature = "widgets-containers")]
1808        if kind == WidgetKind::Tabs {
1809            let min_tabs_h = self.min_tabs_height(id);
1810            owned_style.min_size.height = crate::layout::Dimension::length(min_tabs_h);
1811        }
1812
1813        let owned_node = self.layout_tree.create_node(owned_style);
1814        self.layout_nodes.insert(id, owned_node);
1815
1816        if let Some(parent) = configured_parent {
1817            // The native lane must actually parent the control: GTK and Cocoa
1818            // build it unparented at creation, so recording the edge without
1819            // this call left a widget the lane could never show.
1820            if let Err(error) = self.backend.add_child(parent, id) {
1821                self.discard_failed_create(id);
1822                return Err(error);
1823            }
1824            self.record_parent_edge(parent, id);
1825        }
1826
1827        // A creation-time size request (`WidgetSpec::with_size` and friends)
1828        // pins the layout style exactly like `Ui::set_size` does, so
1829        // spec-configured and imperatively sized widgets lay out the same.
1830        if let Some((width, height)) = self.widgets.get(&id).and_then(|spec| spec.size) {
1831            self.sync_layout_size(id, width, height);
1832        }
1833
1834        // A fresh node still needs its `min_size` reset and its leaf natural
1835        // size seeded.
1836        self.invalidate_layout(id);
1837
1838        Ok(id)
1839    }
1840
1841    /// Creates a widget and returns its identifier.
1842    ///
1843    /// `text` is optional and interpreted by each widget/backend.
1844    pub fn create(&mut self, kind: WidgetKind, text: Option<&str>) -> GuiResult<WidgetId> {
1845        self.create_with(kind, |spec| {
1846            if let Some(value) = text {
1847                spec.text = Some(value.to_owned());
1848            }
1849        })
1850    }
1851
1852    /// Creates a new menu and returns its identifier.
1853    pub fn create_menu(&mut self) -> GuiResult<MenuId> {
1854        let menu_id = MenuId(self.next_menu_id);
1855        self.next_menu_id += 1;
1856        self.backend.create_menu(menu_id)?;
1857        self.menus.insert(menu_id, Vec::new());
1858        Ok(menu_id)
1859    }
1860
1861    pub fn add_submenu(&mut self, parent_id: MenuId, text: &str) -> GuiResult<MenuId> {
1862        Self::reject_embedded_nul(text)?;
1863        let submenu_id = MenuId(self.next_menu_id);
1864        self.next_menu_id += 1;
1865        let slot_id = MenuItemId(self.next_menu_item_id);
1866        self.next_menu_item_id += 1;
1867        self.backend
1868            .add_submenu(parent_id, submenu_id, slot_id, text)?;
1869        self.menus.insert(submenu_id, Vec::new());
1870        // Track where the submenu hangs and hold its slot in the parent's
1871        // ordered item list so index math and removal stay correct.
1872        self.menu_parents.insert(submenu_id, parent_id);
1873        self.submenu_slots.insert(submenu_id, slot_id);
1874        if let Some(items) = self.menus.get_mut(&parent_id) {
1875            items.push(slot_id);
1876        }
1877        Ok(submenu_id)
1878    }
1879
1880    /// Adds an item to an existing menu.
1881    pub fn add_menu_item(&mut self, menu_id: MenuId, text: &str) -> GuiResult<MenuItemId> {
1882        self.add_menu_item_with_shortcut(menu_id, text, None)
1883    }
1884
1885    /// Adds an item to an existing menu with an optional keyboard shortcut.
1886    pub fn add_menu_item_with_shortcut(
1887        &mut self,
1888        menu_id: MenuId,
1889        text: &str,
1890        shortcut: Option<&str>,
1891    ) -> GuiResult<MenuItemId> {
1892        Self::reject_embedded_nul(text)?;
1893        if let Some(shortcut_text) = shortcut {
1894            Self::reject_embedded_nul(shortcut_text)?;
1895        }
1896        if !self.menus.contains_key(&menu_id) {
1897            return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
1898        }
1899
1900        let item_id = MenuItemId(self.next_menu_item_id);
1901        self.next_menu_item_id += 1;
1902
1903        self.backend
1904            .create_menu_item(menu_id, item_id, text, shortcut)?;
1905
1906        if let Some(items) = self.menus.get_mut(&menu_id) {
1907            items.push(item_id);
1908        }
1909        self.menu_item_to_menu.insert(item_id, menu_id);
1910        Ok(item_id)
1911    }
1912
1913    /// Attaches a menu to a window widget.
1914    pub fn attach_menu_to_window(&mut self, window_id: WidgetId, menu_id: MenuId) -> GuiResult<()> {
1915        self.ensure_window(window_id, WidgetProperty::WindowCallback)?;
1916        if !self.menus.contains_key(&menu_id) {
1917            return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
1918        }
1919        self.backend.attach_menu_to_window(window_id, menu_id)
1920    }
1921
1922    /// Enables or disables a menu item so state-dependent commands (Undo,
1923    /// Redo, Clear) grey out instead of looking actionable.
1924    ///
1925    /// Backends without a native mapping return
1926    /// [`GuiError::UnsupportedCapability`] instead of a silent no-op.
1927    pub fn set_menu_item_enabled(&mut self, item_id: MenuItemId, enabled: bool) -> GuiResult<()> {
1928        if !self.menu_item_to_menu.contains_key(&item_id) {
1929            return Err(GuiError::Backend(format!(
1930                "Menu item not found: {}",
1931                item_id.0
1932            )));
1933        }
1934        self.backend.set_menu_item_enabled(item_id, enabled)
1935    }
1936
1937    /// Relabels a menu item in place.
1938    ///
1939    /// State-driven menus (a recent-files list, session lists, plugin menus)
1940    /// update existing rows instead of closing and rebuilding the bar. The
1941    /// item must already exist; a lane without a native mapping answers the
1942    /// typed `dynamic_menu_items` capability error.
1943    pub fn set_menu_item_text(&mut self, item_id: MenuItemId, text: &str) -> GuiResult<()> {
1944        Self::reject_embedded_nul(text)?;
1945        if !self.menu_item_to_menu.contains_key(&item_id) {
1946            return Err(GuiError::Backend(format!(
1947                "Menu item not found: {}",
1948                item_id.0
1949            )));
1950        }
1951        self.backend.set_menu_item_text(item_id, text)
1952    }
1953
1954    /// Inserts an item into an existing menu at `index`.
1955    ///
1956    /// An index past the end appends, matching the slice-insert rule the
1957    /// bookkeeping uses, so a stale index can never panic a lane.
1958    pub fn insert_menu_item(
1959        &mut self,
1960        menu_id: MenuId,
1961        index: usize,
1962        text: &str,
1963    ) -> GuiResult<MenuItemId> {
1964        self.insert_menu_item_with_shortcut(menu_id, index, text, None)
1965    }
1966
1967    /// Inserts an item with an optional keyboard shortcut at `index`.
1968    pub fn insert_menu_item_with_shortcut(
1969        &mut self,
1970        menu_id: MenuId,
1971        index: usize,
1972        text: &str,
1973        shortcut: Option<&str>,
1974    ) -> GuiResult<MenuItemId> {
1975        Self::reject_embedded_nul(text)?;
1976        if let Some(shortcut_text) = shortcut {
1977            Self::reject_embedded_nul(shortcut_text)?;
1978        }
1979        if !self.menus.contains_key(&menu_id) {
1980            return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
1981        }
1982
1983        let item_id = MenuItemId(self.next_menu_item_id);
1984        self.next_menu_item_id += 1;
1985        let position = match self.menus.get(&menu_id) {
1986            Some(items) => index.min(items.len()),
1987            None => index,
1988        };
1989
1990        self.backend
1991            .insert_menu_item(menu_id, item_id, position, text, shortcut)?;
1992
1993        if let Some(items) = self.menus.get_mut(&menu_id) {
1994            items.insert(position, item_id);
1995        }
1996        self.menu_item_to_menu.insert(item_id, menu_id);
1997        Ok(item_id)
1998    }
1999
2000    /// Removes a menu item from its menu.
2001    ///
2002    /// Any `on_menu_item_selected` callback registered for the item is
2003    /// dropped with it, so a stale row cannot fire into a dead handler.
2004    pub fn remove_menu_item(&mut self, item_id: MenuItemId) -> GuiResult<()> {
2005        let Some(menu_id) = self.menu_item_to_menu.get(&item_id).copied() else {
2006            return Err(GuiError::Backend(format!(
2007                "Menu item not found: {}",
2008                item_id.0
2009            )));
2010        };
2011
2012        self.backend.remove_menu_item(item_id)?;
2013
2014        if let Some(items) = self.menus.get_mut(&menu_id) {
2015            items.retain(|item| *item != item_id);
2016        }
2017        self.menu_item_to_menu.remove(&item_id);
2018        self.on_menu_item_selected.remove(&item_id);
2019        Ok(())
2020    }
2021
2022    /// Detaches a submenu from its parent and drops it.
2023    ///
2024    /// The submenu's own rows and their callbacks go with it, mirroring
2025    /// `remove_menu_item`. Menus created with `create_menu` have no parent
2026    /// and are rejected.
2027    pub fn remove_submenu(&mut self, submenu_id: MenuId) -> GuiResult<()> {
2028        let Some(parent_id) = self.menu_parents.get(&submenu_id).copied() else {
2029            return Err(GuiError::Backend(format!(
2030                "Submenu not found: {}",
2031                submenu_id.0
2032            )));
2033        };
2034
2035        self.backend.remove_submenu(submenu_id)?;
2036
2037        if let Some(slot) = self.submenu_slots.remove(&submenu_id) {
2038            if let Some(items) = self.menus.get_mut(&parent_id) {
2039                items.retain(|item| *item != slot);
2040            }
2041        }
2042        // Walk the detached subtree so nested submenus leave the bookkeeping
2043        // with their parent instead of dangling.
2044        let mut detached = vec![submenu_id];
2045        let mut index = 0;
2046        while index < detached.len() {
2047            let current = detached[index];
2048            index += 1;
2049            for (child, parent) in &self.menu_parents {
2050                if *parent == current {
2051                    detached.push(*child);
2052                }
2053            }
2054        }
2055        for menu_id in detached {
2056            self.menu_parents.remove(&menu_id);
2057            for item in self.menus.remove(&menu_id).unwrap_or_default() {
2058                self.menu_item_to_menu.remove(&item);
2059                self.on_menu_item_selected.remove(&item);
2060            }
2061        }
2062        Ok(())
2063    }
2064
2065    /// Attaches a menu as a right-click context menu on any widget.
2066    ///
2067    /// Selecting an entry emits the usual `UiEvent::MenuItemSelected` with the
2068    /// same `MenuId`/`MenuItemId` pair that the menu bar would produce.
2069    pub fn attach_context_menu(&mut self, widget_id: WidgetId, menu_id: MenuId) -> GuiResult<()> {
2070        if !self.widgets.contains_key(&widget_id) {
2071            return Err(GuiError::WidgetNotFound(widget_id.0));
2072        }
2073        if !self.menus.contains_key(&menu_id) {
2074            return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
2075        }
2076        self.backend.attach_context_menu(widget_id, menu_id)
2077    }
2078
2079    // System tray & status icons
2080
2081    /// Creates a system tray icon with the given tooltip.
2082    ///
2083    /// The icon starts on the platform default image; pass pixels with
2084    /// [`Ui::create_tray_icon_with_icon`] or update them later with
2085    /// [`Ui::set_tray_icon_icon`].
2086    pub fn create_tray_icon(&mut self, tooltip: &str) -> GuiResult<TrayIconId> {
2087        self.create_tray_icon_with_icon_bytes(tooltip, None)
2088    }
2089
2090    /// Creates a system tray icon with the given tooltip and icon pixels.
2091    ///
2092    /// `icon_bytes` travels to the backend through
2093    /// [`TrayIconSpec::icon_bytes`], so the payload uses the shared encoding
2094    /// contract documented there: a square straight-alpha RGBA raster, or an
2095    /// encoded container the lane recognises. Cocoa decodes either; Win32
2096    /// consumes the RGBA raster. A lane that cannot decode the payload fails
2097    /// this call rather than silently showing an image the application never
2098    /// asked for.
2099    pub fn create_tray_icon_with_icon(
2100        &mut self,
2101        tooltip: &str,
2102        icon_bytes: Vec<u8>,
2103    ) -> GuiResult<TrayIconId> {
2104        self.create_tray_icon_with_icon_bytes(tooltip, Some(icon_bytes))
2105    }
2106
2107    fn create_tray_icon_with_icon_bytes(
2108        &mut self,
2109        tooltip: &str,
2110        icon_bytes: Option<Vec<u8>>,
2111    ) -> GuiResult<TrayIconId> {
2112        Self::reject_embedded_nul(tooltip)?;
2113        let id = TrayIconId(self.next_tray_icon_id);
2114        self.next_tray_icon_id += 1;
2115        let mut spec = TrayIconSpec::new(id, tooltip);
2116        spec.icon_bytes = icon_bytes;
2117        self.backend.create_tray_icon(&spec)?;
2118        self.tray_icons.insert(id, spec);
2119        Ok(id)
2120    }
2121
2122    /// Destroys a system tray icon by id.
2123    pub fn destroy_tray_icon(&mut self, id: TrayIconId) -> GuiResult<()> {
2124        self.backend.destroy_tray_icon(id)?;
2125        self.tray_icons.remove(&id);
2126        Ok(())
2127    }
2128
2129    /// Updates the hover tooltip for a system tray icon.
2130    pub fn set_tray_icon_tooltip(&mut self, id: TrayIconId, tooltip: &str) -> GuiResult<()> {
2131        Self::reject_embedded_nul(tooltip)?;
2132        self.backend.set_tray_icon_tooltip(id, tooltip)?;
2133        if let Some(spec) = self.tray_icons.get_mut(&id) {
2134            spec.tooltip = tooltip.to_owned();
2135        }
2136        Ok(())
2137    }
2138
2139    /// Attaches or detaches a context menu for a system tray icon.
2140    pub fn set_tray_icon_menu(&mut self, id: TrayIconId, menu: Option<MenuId>) -> GuiResult<()> {
2141        if let Some(menu_id) = menu {
2142            if !self.menus.contains_key(&menu_id) {
2143                return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
2144            }
2145        }
2146        self.backend.set_tray_icon_menu(id, menu)?;
2147        if let Some(spec) = self.tray_icons.get_mut(&id) {
2148            spec.menu = menu;
2149        }
2150        Ok(())
2151    }
2152
2153    /// Shows or hides a system tray icon.
2154    pub fn set_tray_icon_visible(&mut self, id: TrayIconId, visible: bool) -> GuiResult<()> {
2155        self.backend.set_tray_icon_visible(id, visible)?;
2156        if let Some(spec) = self.tray_icons.get_mut(&id) {
2157            spec.visible = visible;
2158        }
2159        Ok(())
2160    }
2161
2162    /// Replaces the icon pixels of a system tray icon.
2163    ///
2164    /// `None` restores the platform default image. The stored specification is
2165    /// only updated once the backend accepted the new payload, so a lane that
2166    /// cannot swap icon pixels reports
2167    /// [`GuiError::UnsupportedCapability`] and leaves the icon unchanged.
2168    pub fn set_tray_icon_icon(
2169        &mut self,
2170        id: TrayIconId,
2171        icon_bytes: Option<Vec<u8>>,
2172    ) -> GuiResult<()> {
2173        self.backend.set_tray_icon_icon(id, icon_bytes.clone())?;
2174        if let Some(spec) = self.tray_icons.get_mut(&id) {
2175            spec.icon_bytes = icon_bytes;
2176        }
2177        Ok(())
2178    }
2179
2180    /// Returns the specification of a registered system tray icon, if present.
2181    pub fn tray_icon(&self, id: TrayIconId) -> Option<&TrayIconSpec> {
2182        self.tray_icons.get(&id)
2183    }
2184
2185    /// Returns a map of all currently registered system tray icons.
2186    pub fn tray_icons(&self) -> &HashMap<TrayIconId, TrayIconSpec> {
2187        &self.tray_icons
2188    }
2189
2190    /// Shows a modal Yes/No confirm dialog and returns a token identifying
2191    /// it. The answer arrives as `UiEvent::DialogResponse { token, confirmed }`
2192    /// from the event queue. When a focused widget or window is available, its
2193    /// assistive technology receives an announcement before the modal backend
2194    /// call begins.
2195    pub fn show_confirm_dialog(&mut self, title: &str, message: &str) -> GuiResult<u64> {
2196        Self::reject_embedded_nul(title)?;
2197        Self::reject_embedded_nul(message)?;
2198        let announcement_target = self
2199            .focused
2200            .filter(|widget_id| self.widgets.contains_key(widget_id))
2201            .or_else(|| {
2202                self.widgets
2203                    .iter()
2204                    .find(|(_, spec)| spec.kind == WidgetKind::Window)
2205                    .map(|(widget_id, _)| *widget_id)
2206            });
2207        if let Some(widget_id) = announcement_target {
2208            self.backend.post_accessible_notification(
2209                widget_id,
2210                AccessibleNotification::Announcement(format!("{title}. {message}")),
2211            )?;
2212        }
2213        let token = self.next_dialog_token;
2214        self.next_dialog_token = self.next_dialog_token.saturating_add(1);
2215        self.backend.show_confirm_dialog(token, title, message)?;
2216        Ok(token)
2217    }
2218
2219    /// Opens a native file dialog without creating a widget (dogfood report
2220    /// #5) and returns a token. The answer arrives as
2221    /// [`UiEvent::FileDialogResponse`] `{ token, paths }`; `paths` is empty
2222    /// when the user cancelled. Lanes without a function-style dialog report
2223    /// `GuiError::UnsupportedCapability("file_dialog")` (Win32 and Cocoa
2224    /// today); the `FileChooserDialog` widget keeps working everywhere.
2225    ///
2226    /// ```
2227    /// use native_gui_core::file_dialog::FileDialog;
2228    /// # fn demo<B: native_gui_core::ui::Backend>(ui: &mut native_gui_core::ui::Ui<B>) -> native_gui_core::error::GuiResult<()> {
2229    /// let token = ui.show_file_dialog(
2230    ///     FileDialog::save()
2231    ///         .title("Save jobs")
2232    ///         .filter("JSON", &["*.json"])
2233    ///         .suggested_name("jobs.json"),
2234    /// )?;
2235    /// // later: UiEvent::FileDialogResponse { token, paths } => ...
2236    /// # let _ = token; Ok(())
2237    /// # }
2238    /// ```
2239    pub fn show_file_dialog(&mut self, request: crate::file_dialog::FileDialog) -> GuiResult<u64> {
2240        request.validate()?;
2241        let token = self.next_dialog_token;
2242        self.backend.show_file_dialog(token, &request)?;
2243        self.next_dialog_token = self.next_dialog_token.saturating_add(1);
2244        Ok(token)
2245    }
2246
2247    /// Returns the platform handles of a top-level window, for interop with
2248    /// renderers and native APIs (found while dogfooding).
2249    ///
2250    /// The window must exist and be realized (shown at least once). Backends
2251    /// without support (Mock, TUI, Web, and currently Win32/Cocoa unless they
2252    /// implement it) return [`GuiError::UnsupportedCapability`]. See also
2253    /// `Ui::window_handle` behind the `raw-window-handle` feature.
2254    pub fn native_window_handle(
2255        &self,
2256        window_id: WidgetId,
2257    ) -> GuiResult<crate::window_handle::NativeWindowHandle> {
2258        let spec = self
2259            .widgets
2260            .get(&window_id)
2261            .ok_or(GuiError::WidgetNotFound(window_id.0))?;
2262        if spec.kind != WidgetKind::Window {
2263            return Err(GuiError::UnsupportedWidget("native_window_handle"));
2264        }
2265        self.backend.native_window_handle(window_id)
2266    }
2267
2268    /// Returns a `raw-window-handle` 0.6 view of a top-level window that
2269    /// implements `HasWindowHandle` and `HasDisplayHandle`.
2270    ///
2271    /// The result borrows the `Ui`, so the window cannot be removed while it
2272    /// is in use. Requires the `raw-window-handle` feature.
2273    ///
2274    /// ```ignore
2275    /// let handle = ui.window_handle(window)?;
2276    /// let surface = wgpu_instance.create_surface(handle)?; // any rwh 0.6 consumer
2277    /// ```
2278    #[cfg(feature = "raw-window-handle")]
2279    pub fn window_handle(
2280        &self,
2281        window_id: WidgetId,
2282    ) -> GuiResult<crate::window_handle::UiWindowHandle<'_>> {
2283        self.native_window_handle(window_id)
2284            .map(crate::window_handle::UiWindowHandle::new)
2285    }
2286
2287    /// Enables or disables close-request interception for a window (GH-056).
2288    ///
2289    /// A guarded window reports [`UiEvent::CloseRequested`] instead of
2290    /// closing; the app answers the request (for example through
2291    /// [`Ui::show_confirm_dialog`]) and approves a close by disabling the
2292    /// guard and calling [`Ui::remove`]. Lanes without interception return
2293    /// [`GuiError::UnsupportedCapability`].
2294    pub fn set_close_guard(&mut self, widget_id: WidgetId, guarded: bool) -> GuiResult<()> {
2295        self.require_property(widget_id, WidgetProperty::CloseGuard)?;
2296        self.backend.set_close_guard(widget_id, guarded)
2297    }
2298
2299    /// Reports timer operations available on this backend.
2300    pub fn timer_capabilities(&self) -> TimerCapabilities {
2301        self.backend.timer_capabilities()
2302    }
2303
2304    /// Reports timer-driven motion support on this backend.
2305    pub fn motion_capabilities(&self) -> MotionCapabilities {
2306        self.backend.motion_capabilities()
2307    }
2308
2309    /// Starts a linear motion driven by the backend's timer event loop.
2310    ///
2311    /// Coalesced ticks use a bounded 16 ms cadence. The first tick is at
2312    /// `min(duration, 16 ms)` and completion is reported at the first tick at
2313    /// or after `duration`. Zero duration is invalid; exhausted motion/timer
2314    /// IDs and a backend deadline that overflows its clock return errors
2315    /// without registering a motion.
2316    pub fn start_motion(&mut self, widget_id: WidgetId, spec: MotionSpec) -> GuiResult<MotionId> {
2317        if !self.widgets.contains_key(&widget_id) {
2318            return Err(GuiError::WidgetNotFound(widget_id.0));
2319        }
2320        spec.validate()?;
2321        if !self.backend.motion_capabilities().motions {
2322            return Err(GuiError::UnsupportedCapability("ui_motion".to_owned()));
2323        }
2324
2325        let timer_capabilities = self.backend.timer_capabilities();
2326        if !timer_capabilities.timers {
2327            return Err(GuiError::UnsupportedCapability("ui_timer".to_owned()));
2328        }
2329        if !timer_capabilities.widget_timers {
2330            return Err(GuiError::UnsupportedCapability("widget_timer".to_owned()));
2331        }
2332
2333        let motion = MotionId(self.next_motion_id);
2334        let next_motion_id =
2335            self.next_motion_id
2336                .checked_add(1)
2337                .ok_or(GuiError::ResourceExhausted {
2338                    operation: "motion id allocation",
2339                    code: None,
2340                })?;
2341        let timer = self.allocate_timer_id()?;
2342        self.backend.start_widget_timer(
2343            timer,
2344            widget_id,
2345            TimerSpec {
2346                first_delay: spec.duration.min(MOTION_TICK_CADENCE),
2347                interval: Some(MOTION_TICK_CADENCE),
2348                coalesce: true,
2349            },
2350            TimerStopPolicy::Remove,
2351        )?;
2352
2353        self.next_motion_id = next_motion_id;
2354        self.motions.insert(
2355            motion,
2356            ActiveMotion {
2357                timer,
2358                widget_id,
2359                spec,
2360            },
2361        );
2362        self.motion_timers.insert(timer, motion);
2363        Ok(motion)
2364    }
2365
2366    /// Cancels a live motion and purges any not-yet-delivered progress events.
2367    pub fn cancel_motion(&mut self, motion: MotionId) -> GuiResult<()> {
2368        let active = self
2369            .motions
2370            .get(&motion)
2371            .copied()
2372            .ok_or_else(|| GuiError::Backend(format!("Motion not found: {}", motion.0)))?;
2373        self.backend.cancel_timer(active.timer)?;
2374        self.motions.remove(&motion);
2375        self.motion_timers.remove(&active.timer);
2376        self.purge_motion_events(motion, active.timer);
2377        Ok(())
2378    }
2379
2380    /// Starts a one-shot or repeating timer on the UI event loop.
2381    pub fn start_timer(&mut self, spec: TimerSpec) -> GuiResult<TimerId> {
2382        spec.validate()?;
2383        if !self.backend.timer_capabilities().timers {
2384            return Err(GuiError::UnsupportedCapability("ui_timer".to_owned()));
2385        }
2386        let timer = self.allocate_timer_id()?;
2387        self.backend.start_timer(timer, spec)?;
2388        Ok(timer)
2389    }
2390
2391    /// Starts a timer whose lifecycle follows a widget's removal/hide policy.
2392    pub fn start_widget_timer(
2393        &mut self,
2394        widget_id: WidgetId,
2395        spec: TimerSpec,
2396        stop_policy: TimerStopPolicy,
2397    ) -> GuiResult<TimerId> {
2398        if !self.widgets.contains_key(&widget_id) {
2399            return Err(GuiError::WidgetNotFound(widget_id.0));
2400        }
2401        spec.validate()?;
2402        let capabilities = self.backend.timer_capabilities();
2403        if !capabilities.timers {
2404            return Err(GuiError::UnsupportedCapability("ui_timer".to_owned()));
2405        }
2406        if !capabilities.widget_timers {
2407            return Err(GuiError::UnsupportedCapability("widget_timer".to_owned()));
2408        }
2409        let timer = self.allocate_timer_id()?;
2410        self.backend
2411            .start_widget_timer(timer, widget_id, spec, stop_policy)?;
2412        Ok(timer)
2413    }
2414
2415    /// Cancels a live timer; unknown, cancelled, or fired ids use the backend's
2416    /// `Timer not found: {id}` error convention.
2417    pub fn cancel_timer(&mut self, timer: TimerId) -> GuiResult<()> {
2418        self.backend.cancel_timer(timer)
2419    }
2420
2421    fn allocate_timer_id(&mut self) -> GuiResult<TimerId> {
2422        let timer = TimerId(self.next_timer_id);
2423        self.next_timer_id =
2424            self.next_timer_id
2425                .checked_add(1)
2426                .ok_or(GuiError::ResourceExhausted {
2427                    operation: "timer id allocation",
2428                    code: None,
2429                })?;
2430        Ok(timer)
2431    }
2432
2433    /// Reports the extended window features available from this backend.
2434    pub fn window_capabilities(&self) -> WindowCapabilities {
2435        self.backend.window_capabilities()
2436    }
2437
2438    /// Validates and applies portable options to a top-level window.
2439    pub fn set_window_options(
2440        &mut self,
2441        widget_id: WidgetId,
2442        options: WindowOptions,
2443    ) -> GuiResult<()> {
2444        let spec = self
2445            .widgets
2446            .get(&widget_id)
2447            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
2448        if spec.kind != WidgetKind::Window {
2449            return Err(GuiError::UnsupportedWidget("set_window_options"));
2450        }
2451
2452        self.validate_window_options(widget_id, &options)?;
2453        self.backend.set_window_options(widget_id, &options)?;
2454        self.window_options.insert(widget_id, options);
2455        Ok(())
2456    }
2457
2458    /// Returns the options last applied to a window, or the portable defaults.
2459    pub fn window_options(&self, widget_id: WidgetId) -> GuiResult<WindowOptions> {
2460        let spec = self
2461            .widgets
2462            .get(&widget_id)
2463            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
2464        if spec.kind != WidgetKind::Window {
2465            return Err(GuiError::UnsupportedWidget("window_options"));
2466        }
2467        Ok(self
2468            .window_options
2469            .get(&widget_id)
2470            .copied()
2471            .unwrap_or_default())
2472    }
2473
2474    /// Hides an active popup at the backend without reporting a user-dismissal event.
2475    ///
2476    /// User- and OS-initiated dismissals arrive separately as
2477    /// [`UiEvent::PopupDismissed`].
2478    pub fn dismiss_popup(&mut self, widget_id: WidgetId) -> GuiResult<()> {
2479        let spec = self
2480            .widgets
2481            .get(&widget_id)
2482            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
2483        if spec.kind != WidgetKind::Window {
2484            return Err(GuiError::UnsupportedWidget("dismiss_popup"));
2485        }
2486        if self
2487            .window_options
2488            .get(&widget_id)
2489            .is_none_or(|options| options.role != WindowRole::Popup)
2490        {
2491            return Err(GuiError::Backend(format!(
2492                "Widget {} is not a popup window",
2493                widget_id.0
2494            )));
2495        }
2496        if !self.backend.window_capabilities().anchored_popups {
2497            return Err(GuiError::UnsupportedCapability("window_popup".to_owned()));
2498        }
2499        self.backend.dismiss_popup(widget_id)?;
2500        self.hidden_widgets.insert(widget_id);
2501        Ok(())
2502    }
2503
2504    fn validate_window_options(
2505        &self,
2506        widget_id: WidgetId,
2507        options: &WindowOptions,
2508    ) -> GuiResult<()> {
2509        if !options.opacity.is_finite() || !(0.0..=1.0).contains(&options.opacity) {
2510            return Err(GuiError::Backend(
2511                "Window opacity must be finite and between 0.0 and 1.0".to_owned(),
2512            ));
2513        }
2514        if let WindowShape::Rounded { radius } = options.shape {
2515            if radius <= 0 {
2516                return Err(GuiError::Backend(
2517                    "Rounded window radius must be positive".to_owned(),
2518                ));
2519            }
2520        }
2521        if let WindowPlacement::Anchored {
2522            widget_id: anchor, ..
2523        } = options.placement
2524        {
2525            if !self.widgets.contains_key(&anchor) {
2526                return Err(GuiError::WidgetNotFound(anchor.0));
2527            }
2528            if anchor == widget_id {
2529                return Err(GuiError::Backend(
2530                    "A window cannot be anchored to itself".to_owned(),
2531                ));
2532            }
2533        }
2534        if let Some(owner) = options.transient_for {
2535            let owner_spec = self
2536                .widgets
2537                .get(&owner)
2538                .ok_or(GuiError::WidgetNotFound(owner.0))?;
2539            if owner == widget_id || owner_spec.kind != WidgetKind::Window {
2540                return Err(GuiError::UnsupportedWidget("window_transient"));
2541            }
2542            let mut cursor = Some(owner);
2543            while let Some(current) = cursor {
2544                if current == widget_id {
2545                    return Err(GuiError::Backend(
2546                        "Transient window ownership cannot form a cycle".to_owned(),
2547                    ));
2548                }
2549                cursor = self
2550                    .window_options
2551                    .get(&current)
2552                    .and_then(|parent| parent.transient_for);
2553            }
2554        }
2555
2556        let capabilities = self.backend.window_capabilities();
2557        if options.role == WindowRole::Popup && !capabilities.anchored_popups {
2558            return Err(GuiError::UnsupportedCapability("window_popup".to_owned()));
2559        }
2560        if options.role == WindowRole::Splash
2561            && (!capabilities.undecorated
2562                || !capabilities.always_on_top
2563                || options.decorations
2564                || options.stacking != Stacking::AlwaysOnTop
2565                || options.focus != WindowFocusPolicy::NoTake)
2566        {
2567            return Err(GuiError::UnsupportedCapability("window_splash".to_owned()));
2568        }
2569        if options.dismiss_on_focus_loss && !capabilities.popup_focus_dismissal {
2570            return Err(GuiError::UnsupportedCapability(
2571                "window_popup_focus_dismiss".to_owned(),
2572            ));
2573        }
2574        if options.transient_for.is_some() && !capabilities.transient_ownership {
2575            return Err(GuiError::UnsupportedCapability(
2576                "window_transient".to_owned(),
2577            ));
2578        }
2579        if !options.decorations && !capabilities.undecorated {
2580            return Err(GuiError::UnsupportedCapability(
2581                "window_undecorated".to_owned(),
2582            ));
2583        }
2584        if options.stacking == Stacking::AlwaysOnTop && !capabilities.always_on_top {
2585            return Err(GuiError::UnsupportedCapability(
2586                "window_always_on_top".to_owned(),
2587            ));
2588        }
2589        if options.opacity < 1.0 && !capabilities.uniform_translucency {
2590            return Err(GuiError::UnsupportedCapability(
2591                "window_translucent".to_owned(),
2592            ));
2593        }
2594        if matches!(options.shape, WindowShape::Rounded { .. }) && !capabilities.shape_rounded {
2595            return Err(GuiError::UnsupportedCapability(
2596                "window_shape_rounded".to_owned(),
2597            ));
2598        }
2599        for effect in [options.show_effect, options.hide_effect] {
2600            match effect {
2601                ShowEffect::None => {}
2602                ShowEffect::Fade { .. } if !capabilities.show_fade => {
2603                    return Err(GuiError::UnsupportedCapability(
2604                        "window_show_fade".to_owned(),
2605                    ));
2606                }
2607                ShowEffect::Slide { .. } if !capabilities.show_slide => {
2608                    return Err(GuiError::UnsupportedCapability(
2609                        "window_show_slide".to_owned(),
2610                    ));
2611                }
2612                _ => {}
2613            }
2614        }
2615        if options.role == WindowRole::Popup
2616            && (!matches!(options.placement, WindowPlacement::Anchored { .. })
2617                || options.transient_for.is_none())
2618        {
2619            return Err(GuiError::Backend(
2620                "Popup windows require an anchor and a transient owner".to_owned(),
2621            ));
2622        }
2623        if options.dismiss_on_focus_loss && options.role != WindowRole::Popup {
2624            return Err(GuiError::Backend(
2625                "Focus-loss dismissal is only valid for popup windows".to_owned(),
2626            ));
2627        }
2628        Ok(())
2629    }
2630
2631    /// Updates text content for a widget.
2632    ///
2633    /// An embedded NUL is rejected before the spec or the backend changes.
2634    /// Native string APIs (`SetWindowTextW`, GTK C strings, `NSString`)
2635    /// truncate at the first NUL, so accepting one would store a suffix the
2636    /// control never shows.
2637    pub fn set_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
2638        Self::reject_embedded_nul(text)?;
2639        let Some(spec) = self.widgets.get_mut(&widget_id) else {
2640            return Err(GuiError::WidgetNotFound(widget_id.0));
2641        };
2642        let previous_text = spec.text.replace(text.to_owned());
2643        let previous_selection = spec.text_selection;
2644        if let Some((start, end)) = spec.text_selection {
2645            let len = text.chars().count();
2646            spec.text_selection = Some((start.min(len), end.min(len)));
2647        }
2648        if let Err(error) = self.backend.set_text(widget_id, text) {
2649            if let Some(spec) = self.widgets.get_mut(&widget_id) {
2650                spec.text = previous_text;
2651                spec.text_selection = previous_selection;
2652            }
2653            return Err(error);
2654        }
2655        self.backend
2656            .post_accessible_notification(widget_id, AccessibleNotification::TextChanged)
2657    }
2658
2659    /// Sets horizontal alignment for a label.
2660    ///
2661    /// The value is stored only after the backend accepts it, so a lane
2662    /// without this mapping leaves the shared spec unchanged.
2663    pub fn set_label_alignment(
2664        &mut self,
2665        widget_id: WidgetId,
2666        alignment: LabelAlignment,
2667    ) -> GuiResult<()> {
2668        self.widget_spec(widget_id)?
2669            .ensure_property(WidgetProperty::LabelAlignment)?;
2670        self.backend.set_label_alignment(widget_id, alignment)?;
2671        self.widgets
2672            .get_mut(&widget_id)
2673            .expect("widget spec remains present during setter")
2674            .label_alignment = alignment;
2675        Ok(())
2676    }
2677
2678    /// Sets the line-wrapping mode for a label.
2679    ///
2680    /// The value is stored only after the backend accepts it, so an
2681    /// unsupported wrapping mode leaves the shared spec unchanged.
2682    pub fn set_label_wrap(&mut self, widget_id: WidgetId, wrap: LabelWrap) -> GuiResult<()> {
2683        self.widget_spec(widget_id)?
2684            .ensure_property(WidgetProperty::LabelWrap)?;
2685        self.backend.set_label_wrap(widget_id, wrap)?;
2686        self.widgets
2687            .get_mut(&widget_id)
2688            .expect("widget spec remains present during setter")
2689            .label_wrap = wrap;
2690        Ok(())
2691    }
2692
2693    /// Reads the live text selection, in Unicode characters (not bytes/UTF-16).
2694    pub fn text_selection(&self, widget_id: WidgetId) -> GuiResult<(usize, usize)> {
2695        let spec = self
2696            .widgets
2697            .get(&widget_id)
2698            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
2699        spec.ensure_property(WidgetProperty::TextSelection)?;
2700        self.backend.text_selection(widget_id)
2701    }
2702
2703    /// Selects a character range in a text control.
2704    ///
2705    /// Offsets are character positions (Unicode scalar values): `start`
2706    /// inclusive, `end` exclusive, so `(0, 0)` places a caret at the start.
2707    /// The range is mirrored in the widget spec and forwarded to the
2708    /// backend's native selection mapping (`TextInput`, `TextArea`, `RichText`).
2709    pub fn set_text_selection(
2710        &mut self,
2711        widget_id: WidgetId,
2712        start: usize,
2713        end: usize,
2714    ) -> GuiResult<()> {
2715        if start > end {
2716            return Err(GuiError::Backend(
2717                "Text selection start must be <= end".to_owned(),
2718            ));
2719        }
2720        self.require_property(widget_id, WidgetProperty::TextSelection)?;
2721        self.backend.set_text_selection(widget_id, start, end)?;
2722        if let Some(spec) = self.widgets.get_mut(&widget_id) {
2723            spec.text_selection = Some((start, end));
2724        }
2725        Ok(())
2726    }
2727
2728    /// Sets the completion/suggestion item list for a `TextInput`.
2729    ///
2730    /// The shared model stores the full list and the backend applies it to
2731    /// its native completion source; the lane owns filtering and its popup
2732    /// (see `docs/widget-expansion-roadmap.md`, "TextInput completion").
2733    /// The call is transactional: the shared spec records `items` only after
2734    /// the backend accepted them, so a lane without a completion mapping
2735    /// (typed [`GuiError::UnsupportedCapability`] with the `"text_completion"`
2736    /// identifier) leaves the model exactly as it was.
2737    pub fn set_text_completion_items(
2738        &mut self,
2739        widget_id: WidgetId,
2740        items: &[String],
2741    ) -> GuiResult<()> {
2742        self.widget_spec(widget_id)?
2743            .ensure_property(WidgetProperty::TextCompletion)?;
2744        self.backend.set_text_completion_items(widget_id, items)?;
2745        if let Some(spec) = self.widgets.get_mut(&widget_id) {
2746            spec.completion_items = items.to_vec();
2747        }
2748        Ok(())
2749    }
2750
2751    /// Sets placeholder/hint text on a `TextInput` widget.
2752    ///
2753    /// An embedded NUL is rejected before the spec or the backend changes:
2754    /// cue-banner APIs (`EM_SETCUEBANNER`, GTK placeholder, AppKit
2755    /// `setPlaceholderString:`) truncate at the first NUL.
2756    pub fn set_placeholder_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
2757        Self::reject_embedded_nul(text)?;
2758        let spec = self.require_property(widget_id, WidgetProperty::PlaceholderText)?;
2759        let previous = spec.placeholder_text.clone();
2760        spec.placeholder_text = if text.is_empty() {
2761            None
2762        } else {
2763            Some(text.to_owned())
2764        };
2765        if let Err(error) = self.backend.set_placeholder_text(widget_id, text) {
2766            if let Some(spec) = self.widgets.get_mut(&widget_id) {
2767                spec.placeholder_text = previous;
2768            }
2769            return Err(error);
2770        }
2771        Ok(())
2772    }
2773
2774    /// Sets monospace font rendering on a supported widget (`TextArea`, `TextInput`, `Label`,
2775    /// `RichText`).
2776    pub fn set_monospace(&mut self, widget_id: WidgetId, monospace: bool) -> GuiResult<()> {
2777        self.require_property(widget_id, WidgetProperty::Monospace)?;
2778        self.backend.set_monospace(widget_id, monospace)?;
2779        if let Some(spec) = self.widgets.get_mut(&widget_id) {
2780            spec.monospace = monospace;
2781        }
2782        Ok(())
2783    }
2784
2785    /// Sets an explicit font family, size, weight, and slant on a supported widget (`Label`, `Button`, `TextInput`, `TextArea`).
2786    ///
2787    /// Passing `None` clears the custom font back to the active theme/platform default.
2788    pub fn set_font(
2789        &mut self,
2790        widget_id: WidgetId,
2791        font: Option<&FontDescriptor>,
2792    ) -> GuiResult<()> {
2793        self.require_property(widget_id, WidgetProperty::Font)?;
2794        if let Some(descriptor) = font {
2795            descriptor
2796                .validate()
2797                .map_err(|error| GuiError::Backend(error.to_string()))?;
2798        }
2799        let previous = self
2800            .widgets
2801            .get(&widget_id)
2802            .and_then(|spec| spec.font.clone());
2803        if let Some(spec) = self.widgets.get_mut(&widget_id) {
2804            spec.font = font.cloned();
2805        }
2806        if let Err(error) = self.backend.set_font(widget_id, font) {
2807            if let Some(spec) = self.widgets.get_mut(&widget_id) {
2808                spec.font = previous;
2809            }
2810            return Err(error);
2811        }
2812        Ok(())
2813    }
2814
2815    /// Sets per-row [`IconRole`] icons on a `DataList` or `ListView` widget.
2816    ///
2817    /// Each slot aligns by row index (`None` omits an icon for that row); passing
2818    /// an empty slice clears all row icons.
2819    pub fn set_row_icons(
2820        &mut self,
2821        widget_id: WidgetId,
2822        icons: &[Option<IconRole>],
2823    ) -> GuiResult<()> {
2824        let spec = self.require_property(widget_id, WidgetProperty::RowIcons)?;
2825        let previous = std::mem::replace(&mut spec.row_icons, icons.to_vec());
2826        if let Err(error) = self.backend.set_row_icons(widget_id, icons) {
2827            if let Some(spec) = self.widgets.get_mut(&widget_id) {
2828                spec.row_icons = previous;
2829            }
2830            return Err(error);
2831        }
2832        Ok(())
2833    }
2834
2835    /// Enables or disables the native control's built-in spell checking on a
2836    /// `TextArea` or `RichText` (NSTextView continuous checking, RichEdit
2837    /// `IMF_SPELLCHECKING`). No dictionary engine is bundled: lanes whose
2838    /// control has no built-in checker (GTK4 `GtkTextView`, TUI, Web) return
2839    /// [`GuiError::UnsupportedCapability`].
2840    pub fn set_spell_check(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
2841        let Some(spec) = self.widgets.get(&widget_id) else {
2842            return Err(GuiError::WidgetNotFound(widget_id.0));
2843        };
2844        #[cfg(feature = "widgets-text")]
2845        let is_text = matches!(spec.kind, WidgetKind::TextArea | WidgetKind::RichText);
2846        #[cfg(not(feature = "widgets-text"))]
2847        let is_text = {
2848            let _ = spec;
2849            false
2850        };
2851        if !is_text {
2852            return Err(GuiError::UnsupportedWidget("set_spell_check"));
2853        }
2854        self.backend.set_spell_check(widget_id, enabled)
2855    }
2856
2857    /// Sets styled text runs on a `RichText` widget.
2858    pub fn set_rich_text_runs(&mut self, widget_id: WidgetId, runs: &[TextRun]) -> GuiResult<()> {
2859        self.require_property(widget_id, WidgetProperty::RichTextRuns)?;
2860        self.backend.set_rich_text_runs(widget_id, runs)?;
2861        if let Some(spec) = self.widgets.get_mut(&widget_id) {
2862            spec.rich_text_runs = runs.to_vec();
2863        }
2864        Ok(())
2865    }
2866
2867    /// Sets inline images on a `RichText` widget.
2868    pub fn set_rich_text_images(
2869        &mut self,
2870        widget_id: WidgetId,
2871        images: &[RichTextImage],
2872    ) -> GuiResult<()> {
2873        self.require_property(widget_id, WidgetProperty::RichTextImages)?;
2874        self.backend.set_rich_text_images(widget_id, images)?;
2875        if let Some(spec) = self.widgets.get_mut(&widget_id) {
2876            spec.rich_text_images = images.to_vec();
2877        }
2878        Ok(())
2879    }
2880
2881    /// Updates checked state for a widget that supports it.
2882    pub fn set_checked(&mut self, widget_id: WidgetId, checked: bool) -> GuiResult<()> {
2883        let spec = self.require_property(widget_id, WidgetProperty::Checked)?;
2884        let previous = spec.checked;
2885        spec.checked = Some(checked);
2886        if let Err(error) = self.backend.set_checked(widget_id, checked) {
2887            if let Some(spec) = self.widgets.get_mut(&widget_id) {
2888                spec.checked = previous;
2889            }
2890            return Err(error);
2891        }
2892        Ok(())
2893    }
2894
2895    /// Sets numeric value for widgets that support it.
2896    pub fn set_value(&mut self, widget_id: WidgetId, value: i32) -> GuiResult<()> {
2897        let spec = self.require_property(widget_id, WidgetProperty::Value)?;
2898        let previous = spec.value;
2899        spec.value = Some(value);
2900        if let Err(error) = self.backend.set_value(widget_id, value) {
2901            if let Some(spec) = self.widgets.get_mut(&widget_id) {
2902                spec.value = previous;
2903            }
2904            return Err(error);
2905        }
2906        self.backend
2907            .post_accessible_notification(widget_id, AccessibleNotification::ValueChanged)
2908    }
2909
2910    /// Sets numeric range for widgets that support it.
2911    pub fn set_range(&mut self, widget_id: WidgetId, min: i32, max: i32) -> GuiResult<()> {
2912        if min > max {
2913            return Err(GuiError::Backend(
2914                "Widget range min must be <= max".to_owned(),
2915            ));
2916        }
2917
2918        let spec = self.require_property(widget_id, WidgetProperty::Range)?;
2919        let previous = spec.range;
2920        spec.range = Some((min, max));
2921        if let Err(error) = self.backend.set_range(widget_id, min, max) {
2922            if let Some(spec) = self.widgets.get_mut(&widget_id) {
2923                spec.range = previous;
2924            }
2925            return Err(error);
2926        }
2927        Ok(())
2928    }
2929
2930    /// Sets step value for widgets that support it.
2931    pub fn set_step(&mut self, widget_id: WidgetId, step: i32) -> GuiResult<()> {
2932        if step <= 0 {
2933            return Err(GuiError::Backend("Widget step must be positive".to_owned()));
2934        }
2935
2936        let spec = self.require_property(widget_id, WidgetProperty::Step)?;
2937        let previous = spec.step;
2938        spec.step = Some(step);
2939        if let Err(error) = self.backend.set_step(widget_id, step) {
2940            if let Some(spec) = self.widgets.get_mut(&widget_id) {
2941                spec.step = previous;
2942            }
2943            return Err(error);
2944        }
2945        Ok(())
2946    }
2947
2948    /// Sets selected index for widgets that support item/page selection.
2949    ///
2950    /// On a widget with keyed rows, the index is also mapped to its
2951    /// [`RowKey`] so a later [`Self::set_rows_keyed`] follows the selection
2952    /// by identity instead of by position.
2953    pub fn set_selected_index(&mut self, widget_id: WidgetId, index: usize) -> GuiResult<()> {
2954        let spec = self.require_property(widget_id, WidgetProperty::SelectedIndex)?;
2955        let previous = spec.selected_index;
2956        spec.selected_index = Some(index);
2957        if let Err(error) = self.backend.set_selected_index(widget_id, index) {
2958            if let Some(spec) = self.widgets.get_mut(&widget_id) {
2959                spec.selected_index = previous;
2960            }
2961            return Err(error);
2962        }
2963        self.record_keyed_selection(widget_id, &[index]);
2964        Ok(())
2965    }
2966
2967    /// Sets page labels for a tabs widget.
2968    ///
2969    /// Labels follow the attached pages in attach order; pages without a
2970    /// label keep the backend placeholder header. The WYSIWYG inspector and
2971    /// app code can now drive `WidgetSpec.tab_items` at runtime.
2972    pub fn set_tab_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()> {
2973        for item in items {
2974            Self::reject_embedded_nul(item)?;
2975        }
2976        let spec = self.require_property(widget_id, WidgetProperty::TabItems)?;
2977        let previous = spec.tab_items.clone();
2978        spec.tab_items = items.to_vec();
2979        self.invalidate_layout(widget_id);
2980        if let Err(error) = self.backend.set_tab_items(widget_id, items) {
2981            if let Some(spec) = self.widgets.get_mut(&widget_id) {
2982                spec.tab_items = previous;
2983            }
2984            return Err(error);
2985        }
2986        Ok(())
2987    }
2988
2989    /// Resolves the dynamic minimum height floor for a `Tabs` widget strip.
2990    ///
2991    /// If the backend provides a positive natural height for the widget (e.g.
2992    /// measured tab strip typography, platform theme metrics, or DPI-scaled tab buttons),
2993    /// that height is used as the floor. Otherwise, falls back to [`MIN_TABS_HEIGHT`] (30.0 pt).
2994    pub fn min_tabs_height(&self, widget_id: WidgetId) -> f32 {
2995        self.backend
2996            .natural_size(widget_id)
2997            .map(|(_, h)| h as f32)
2998            .filter(|h| *h > 0.0)
2999            .unwrap_or(MIN_TABS_HEIGHT)
3000    }
3001
3002    /// Alias for [`Self::min_tabs_height`] for ergonomic naming.
3003    pub fn tabs_min_height(&self, widget_id: WidgetId) -> f32 {
3004        self.min_tabs_height(widget_id)
3005    }
3006
3007    /// Sets multiple selected indices for multi-select list/tree widgets.
3008    ///
3009    /// On a widget with keyed rows, the indices are also mapped to
3010    /// their [`RowKey`]s so a later [`Self::set_rows_keyed`] keeps the
3011    /// surviving members selected.
3012    pub fn set_selected_indices(
3013        &mut self,
3014        widget_id: WidgetId,
3015        indices: &[usize],
3016    ) -> GuiResult<()> {
3017        let spec = self.require_property(widget_id, WidgetProperty::SelectedIndices)?;
3018        let previous = spec.selected_indices.clone();
3019        spec.selected_indices = indices.to_vec();
3020        if let Err(error) = self.backend.set_selected_indices(widget_id, indices) {
3021            if let Some(spec) = self.widgets.get_mut(&widget_id) {
3022                spec.selected_indices = previous;
3023            }
3024            return Err(error);
3025        }
3026        self.record_keyed_selection(widget_id, indices);
3027        Ok(())
3028    }
3029
3030    /// Enables/disables row drag-source and drop-target behavior on a row
3031    /// widget (ListView/DataList/DataGrid/TreeView).
3032    ///
3033    /// Drags started from a source widget emit `UiEvent::DragStarted` with the
3034    /// dragged row indices; dropping onto a target emits `UiEvent::Dropped`
3035    /// with the hit-tested `target_index` and the `source_indices`.
3036    pub fn set_row_drag(
3037        &mut self,
3038        widget_id: WidgetId,
3039        source: bool,
3040        target: bool,
3041    ) -> GuiResult<()> {
3042        let spec = self.require_property(widget_id, WidgetProperty::RowDrag)?;
3043        let previous_source = spec.row_drag_source;
3044        let previous_target = spec.row_drop_target;
3045        spec.row_drag_source = source;
3046        spec.row_drop_target = target;
3047        if let Err(error) = self.backend.set_row_drag(widget_id, source, target) {
3048            if let Some(spec) = self.widgets.get_mut(&widget_id) {
3049                spec.row_drag_source = previous_source;
3050                spec.row_drop_target = previous_target;
3051            }
3052            return Err(error);
3053        }
3054        Ok(())
3055    }
3056
3057    /// Configures an additive text/custom-MIME drag source.
3058    ///
3059    /// MIME values are normalized to lowercase and duplicate kinds are
3060    /// removed while preserving preference order. Existing row drags remain
3061    /// configured independently through [`Self::set_row_drag`].
3062    pub fn set_drag_source(
3063        &mut self,
3064        widget_id: WidgetId,
3065        mut options: DragSourceOptions,
3066    ) -> GuiResult<()> {
3067        if !self.widgets.contains_key(&widget_id) {
3068            return Err(GuiError::WidgetNotFound(widget_id.0));
3069        }
3070        options.kinds = normalize_kinds(options.kinds)?;
3071        let capabilities = self.backend.drag_capabilities();
3072        for kind in &options.kinds {
3073            if !capabilities.supports_kind(kind) {
3074                let identifier = match kind {
3075                    DragPayloadKind::Text => "drag_text",
3076                    DragPayloadKind::Custom { .. } => "drag_custom_mime",
3077                };
3078                return Err(GuiError::UnsupportedCapability(identifier.to_owned()));
3079            }
3080        }
3081        self.backend.set_drag_source_options(widget_id, &options)?;
3082        self.drag_sources.insert(widget_id, options);
3083        Ok(())
3084    }
3085
3086    /// Configures accepted text/custom-MIME kinds and the requested drop effect.
3087    ///
3088    /// This is separate from [`Self::set_drop_target`], which retains its
3089    /// existing boolean file/URL/text API.
3090    pub fn set_drag_target_options(
3091        &mut self,
3092        widget_id: WidgetId,
3093        mut options: DragTargetOptions,
3094    ) -> GuiResult<()> {
3095        if !self.widgets.contains_key(&widget_id) {
3096            return Err(GuiError::WidgetNotFound(widget_id.0));
3097        }
3098        options.kinds = normalize_kinds(options.kinds)?;
3099        let capabilities = self.backend.drag_capabilities();
3100        for kind in &options.kinds {
3101            if !capabilities.supports_kind(kind) {
3102                let identifier = match kind {
3103                    DragPayloadKind::Text => "drag_text",
3104                    DragPayloadKind::Custom { .. } => "drag_custom_mime",
3105                };
3106                return Err(GuiError::UnsupportedCapability(identifier.to_owned()));
3107            }
3108        }
3109        if options.effect != DropEffect::None && !capabilities.drop_feedback {
3110            return Err(GuiError::UnsupportedCapability("drop_feedback".to_owned()));
3111        }
3112        self.backend.set_drag_target_options(widget_id, &options)?;
3113        self.drag_targets.insert(widget_id, options);
3114        Ok(())
3115    }
3116
3117    /// Reports support for text, custom-MIME, feedback, and preview operations.
3118    pub fn drag_capabilities(&self) -> DragCapabilities {
3119        self.backend.drag_capabilities()
3120    }
3121
3122    /// Enables/disables accepting external file drops from the OS shell.
3123    ///
3124    /// When enabled, files dragged and dropped from native shell file managers
3125    /// (e.g. Windows Explorer, macOS Finder, GNOME Files/Nautilus) emit
3126    /// `UiEvent::FilesDropped { widget_id, paths }`.
3127    pub fn set_file_drop_target(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
3128        self.set_drop_target(widget_id, enabled)
3129    }
3130
3131    /// Enables or disables drop target support on a widget for files, URLs, and text.
3132    ///
3133    /// When enabled, dropping files emits [`UiEvent::FilesDropped`], dropping
3134    /// URLs emits [`UiEvent::UrlsDropped`], and dropping plain text emits
3135    /// [`UiEvent::TextDropped`]. When dropped onto text widgets (such as
3136    /// [`WidgetKind::RichText`] or [`WidgetKind::TextArea`]), the drop event
3137    /// includes the character caret offset where the drop occurred.
3138    pub fn set_drop_target(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
3139        if !self.widgets.contains_key(&widget_id) {
3140            return Err(GuiError::WidgetNotFound(widget_id.0));
3141        }
3142
3143        self.backend.set_drop_target(widget_id, enabled)?;
3144        let spec = self
3145            .widgets
3146            .get_mut(&widget_id)
3147            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
3148        spec.file_drop_target = enabled;
3149        Ok(())
3150    }
3151
3152    /// Sets preferred dimensions for a widget.
3153    ///
3154    /// The request is written into the widget's layout style as well as the
3155    /// spec and the backend, mirroring [`Self::set_container_direction`], so
3156    /// a later `compute_layout` pass honours it instead of rewriting it with
3157    /// the computed value (imperative and declarative authoring must produce
3158    /// the same result).
3159    pub fn set_size(&mut self, widget_id: WidgetId, width: i32, height: i32) -> GuiResult<()> {
3160        if width <= 0 || height <= 0 {
3161            return Err(GuiError::Backend("Widget size must be positive".to_owned()));
3162        }
3163
3164        let Some(spec) = self.widgets.get_mut(&widget_id) else {
3165            return Err(GuiError::WidgetNotFound(widget_id.0));
3166        };
3167
3168        let previous_size = spec.size;
3169        spec.size = Some((width, height));
3170        if let Err(error) = self.backend.set_size(widget_id, width, height) {
3171            if let Some(spec) = self.widgets.get_mut(&widget_id) {
3172                spec.size = previous_size;
3173            }
3174            return Err(error);
3175        }
3176        self.sync_layout_size(widget_id, width, height);
3177        self.enable_auto_layout();
3178        if self.layout_roots.contains(&widget_id) {
3179            self.layout_root_sizes
3180                .insert(widget_id, (width as f32, height as f32));
3181            self.invalidate_layout(widget_id);
3182        }
3183        Ok(())
3184    }
3185
3186    /// Sets how much of its parent container's spare main-axis space a
3187    /// widget absorbs on each layout pass.
3188    ///
3189    /// This is the imperative counterpart of the declarative
3190    /// [`crate::declarative::Node::flex_grow`]: `0.0` (the default) keeps
3191    /// the widget at its requested or natural size, while positive factors
3192    /// split the remaining space between growing siblings proportionally. A
3193    /// [`Self::set_size`] request becomes the widget's basis, so a pinned
3194    /// pane still grows when its window is enlarged. The main axis is the
3195    /// parent's [`ContainerDirection`]; layout roots registered with
3196    /// [`Self::set_layout_root`] apply the change on their next resize, and
3197    /// [`Self::compute_layout`] applies it immediately.
3198    pub fn set_flex_grow(&mut self, widget_id: WidgetId, grow: f32) -> GuiResult<()> {
3199        if !grow.is_finite() || grow < 0.0 {
3200            return Err(GuiError::Backend(
3201                "Flex grow must be a finite, non-negative number".to_owned(),
3202            ));
3203        }
3204        if !self.widgets.contains_key(&widget_id) {
3205            return Err(GuiError::WidgetNotFound(widget_id.0));
3206        }
3207        self.enable_auto_layout();
3208        if let Some(&lnode) = self.layout_nodes.get(&widget_id) {
3209            if let Ok(mut lstyle) = self.layout_tree.style(lnode).cloned() {
3210                if lstyle.flex_grow != grow {
3211                    lstyle.flex_grow = grow;
3212                    let _ = self.layout_tree.set_style(lnode, lstyle);
3213                    self.invalidate_layout(widget_id);
3214                }
3215            }
3216        }
3217        Ok(())
3218    }
3219
3220    /// Returns the flex-grow factor set by [`Self::set_flex_grow`].
3221    pub fn flex_grow(&self, widget_id: WidgetId) -> GuiResult<f32> {
3222        if !self.widgets.contains_key(&widget_id) {
3223            return Err(GuiError::WidgetNotFound(widget_id.0));
3224        }
3225        let node = self
3226            .layout_nodes
3227            .get(&widget_id)
3228            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
3229        self.layout_tree.style(*node).map(|style| style.flex_grow)
3230    }
3231
3232    /// Sets the smallest size layout passes may give a widget.
3233    ///
3234    /// Unlike [`Self::set_size`], which pins both axes, a minimum leaves the
3235    /// widget free to stretch across its parent's cross axis and, with
3236    /// [`Self::set_flex_grow`], along the main axis - the usual way to keep a
3237    /// designed size for a pane while letting it fill a larger window. A `0`
3238    /// component leaves that axis unconstrained; `(0, 0)` clears the minimum.
3239    /// Applies on the next [`Self::compute_layout`] or layout-root resize.
3240    ///
3241    /// The floor is recorded on the shared model and forwarded to the backend
3242    /// so lanes that own their automatic layout (Win32) honour it too, not
3243    /// just the shared pass.
3244    pub fn set_min_size(&mut self, widget_id: WidgetId, width: i32, height: i32) -> GuiResult<()> {
3245        if width < 0 || height < 0 {
3246            return Err(GuiError::Backend(
3247                "Minimum size must not be negative".to_owned(),
3248            ));
3249        }
3250        if !self.widgets.contains_key(&widget_id) || !self.layout_nodes.contains_key(&widget_id) {
3251            return Err(GuiError::WidgetNotFound(widget_id.0));
3252        }
3253        self.enable_auto_layout();
3254        self.backend.set_min_size(widget_id, width, height)?;
3255        let previous = if width == 0 && height == 0 {
3256            self.min_sizes.remove(&widget_id)
3257        } else {
3258            self.min_sizes.insert(widget_id, (width, height))
3259        };
3260        if previous.unwrap_or((0, 0)) != (width, height) {
3261            self.invalidate_layout(widget_id);
3262        }
3263        Ok(())
3264    }
3265
3266    /// Returns the minimum recorded by [`Self::set_min_size`], `(0, 0)` when
3267    /// none is set.
3268    pub fn min_size(&self, widget_id: WidgetId) -> GuiResult<(i32, i32)> {
3269        if !self.widgets.contains_key(&widget_id) {
3270            return Err(GuiError::WidgetNotFound(widget_id.0));
3271        }
3272        Ok(self.min_sizes.get(&widget_id).copied().unwrap_or((0, 0)))
3273    }
3274
3275    /// Sets a width-only constraint on a widget's layout node, leaving its
3276    /// height unconstrained.
3277    ///
3278    /// This allows panels and inspectors (such as in `gui_photo_gallery`)
3279    /// to fix their width without having to re-pin their height to match
3280    /// their container when the window resizes.
3281    pub fn set_preferred_width(&mut self, widget_id: WidgetId, width: u32) -> GuiResult<()> {
3282        if !self.widgets.contains_key(&widget_id) {
3283            return Err(GuiError::WidgetNotFound(widget_id.0));
3284        }
3285        self.enable_auto_layout();
3286        let Some(&lnode) = self.layout_nodes.get(&widget_id) else {
3287            return Err(GuiError::WidgetNotFound(widget_id.0));
3288        };
3289        if let Ok(mut lstyle) = self.layout_tree.style(lnode).cloned() {
3290            if width == 0 {
3291                self.preferred_widths.remove(&widget_id);
3292                lstyle.min_size.width = crate::layout::Dimension::length(0.0);
3293                lstyle.min_size.height = crate::layout::Dimension::Auto;
3294            } else {
3295                self.preferred_widths.insert(widget_id, width);
3296                lstyle.min_size.width = crate::layout::Dimension::length(width as f32);
3297                lstyle.min_size.height = crate::layout::Dimension::Auto;
3298            }
3299            let _ = self.layout_tree.set_style(lnode, lstyle);
3300        }
3301
3302        self.invalidate_layout(widget_id);
3303        Ok(())
3304    }
3305
3306    /// Returns the preferred width set by [`Self::set_preferred_width`], or `None` if not set.
3307    pub fn preferred_width(&self, widget_id: WidgetId) -> GuiResult<Option<u32>> {
3308        if !self.widgets.contains_key(&widget_id) {
3309            return Err(GuiError::WidgetNotFound(widget_id.0));
3310        }
3311        Ok(self.preferred_widths.get(&widget_id).copied())
3312    }
3313
3314    /// Sets the layout style on a widget using Native GUI-owned layout types.
3315    ///
3316    /// Validates all numeric constraints (finite numbers, non-negative factors and dimensions)
3317    /// before applying the style and schedules an incremental layout invalidation pass.
3318    pub fn set_layout_style(
3319        &mut self,
3320        widget_id: WidgetId,
3321        style: crate::layout::Style,
3322    ) -> GuiResult<()> {
3323        if !self.widgets.contains_key(&widget_id) {
3324            return Err(GuiError::WidgetNotFound(widget_id.0));
3325        }
3326        let Some(&lnode) = self.layout_nodes.get(&widget_id) else {
3327            return Err(GuiError::WidgetNotFound(widget_id.0));
3328        };
3329        self.enable_auto_layout();
3330        style.validate()?;
3331        self.layout_tree.set_style(lnode, style)?;
3332        self.invalidate_layout(widget_id);
3333        Ok(())
3334    }
3335
3336    /// Returns the current layout style of a widget as an native-gui-owned
3337    /// [`crate::layout::Style`].
3338    pub fn layout_style(&self, widget_id: WidgetId) -> GuiResult<crate::layout::Style> {
3339        if !self.widgets.contains_key(&widget_id) {
3340            return Err(GuiError::WidgetNotFound(widget_id.0));
3341        }
3342        let Some(&node) = self.layout_nodes.get(&widget_id) else {
3343            return Err(GuiError::WidgetNotFound(widget_id.0));
3344        };
3345        self.layout_tree.style(node).cloned()
3346    }
3347
3348    /// Returns the computed layout rectangle for a widget in parent-local coordinates.
3349    pub fn layout_rect(&self, widget_id: WidgetId) -> GuiResult<crate::layout::LayoutRect> {
3350        if !self.widgets.contains_key(&widget_id) {
3351            return Err(GuiError::WidgetNotFound(widget_id.0));
3352        }
3353        let Some(&node) = self.layout_nodes.get(&widget_id) else {
3354            return Err(GuiError::WidgetNotFound(widget_id.0));
3355        };
3356        let rect = self.layout_tree.layout(node)?;
3357        self.parent_local_layout_rect(widget_id, rect)
3358    }
3359
3360    /// Renders the computed layout of `root` and its descendants as an
3361    /// indented text tree, one widget per line: id, kind, text, the
3362    /// parent-local rect from the last [`Self::compute_layout`], and flags
3363    /// for hidden widgets, `flex_grow`, and app minimum sizes. A debugging
3364    /// aid for "why is this row zero pixels tall?" (found while dogfooding);
3365    /// the format is for humans and may change.
3366    ///
3367    /// ```
3368    /// # use native_gui_core::ui::Ui;
3369    /// # use native_gui_core::widgets::WidgetKind;
3370    /// # fn demo<B: native_gui_core::ui::Backend>(ui: &mut Ui<B>) -> native_gui_core::error::GuiResult<()> {
3371    /// let window = ui.create(WidgetKind::Window, Some("Main"))?;
3372    /// ui.compute_layout(window, 640.0, 480.0)?;
3373    /// eprintln!("{}", ui.debug_layout(window)?);
3374    /// # Ok(())
3375    /// # }
3376    /// ```
3377    pub fn debug_layout(&self, root: WidgetId) -> GuiResult<String> {
3378        use std::fmt::Write as _;
3379        if !self.widgets.contains_key(&root) {
3380            return Err(GuiError::WidgetNotFound(root.0));
3381        }
3382        let mut out = String::new();
3383        let mut stack = vec![(root, 0usize)];
3384        while let Some((id, depth)) = stack.pop() {
3385            let Some(spec) = self.widgets.get(&id) else {
3386                continue;
3387            };
3388            let _ = write!(
3389                out,
3390                "{:indent$}#{} {:?}",
3391                "",
3392                id.0,
3393                spec.kind,
3394                indent = depth * 2
3395            );
3396            if let Some(text) = spec.text.as_deref().filter(|text| !text.is_empty()) {
3397                let short: String = text.chars().take(32).collect();
3398                let ellipsis = if text.chars().count() > 32 { "…" } else { "" };
3399                let _ = write!(out, " {short:?}{ellipsis}");
3400            }
3401            match self.layout_rect(id) {
3402                Ok(rect) => {
3403                    let _ = write!(
3404                        out,
3405                        " @({}, {}) {}x{}",
3406                        rect.x, rect.y, rect.width, rect.height
3407                    );
3408                    if !self.is_effectively_hidden(id) && (rect.width <= 0.0 || rect.height <= 0.0)
3409                    {
3410                        out.push_str(" [ZERO-SIZE]");
3411                    }
3412                }
3413                Err(_) => out.push_str(" @(no layout node)"),
3414            }
3415            if self.is_effectively_hidden(id) {
3416                out.push_str(" [hidden]");
3417            }
3418            if let Some(&node) = self.layout_nodes.get(&id) {
3419                if let Ok(style) = self.layout_tree.style(node) {
3420                    if style.flex_grow > 0.0 {
3421                        let _ = write!(out, " grow={}", style.flex_grow);
3422                    }
3423                }
3424            }
3425            if let Some((w, h)) = self.min_sizes.get(&id) {
3426                let _ = write!(out, " min={w}x{h}");
3427            }
3428            out.push('\n');
3429            if let Some(children) = self.children_index.get(&id) {
3430                for child in children.iter().rev() {
3431                    stack.push((*child, depth + 1));
3432                }
3433            }
3434        }
3435        Ok(out)
3436    }
3437
3438    fn parent_local_layout_rect(
3439        &self,
3440        widget_id: WidgetId,
3441        rect: crate::layout::LayoutRect,
3442    ) -> GuiResult<crate::layout::LayoutRect> {
3443        let spec = self
3444            .widgets
3445            .get(&widget_id)
3446            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
3447        let Some(parent_id) = spec.parent else {
3448            return Ok(rect);
3449        };
3450        let parent_node = self
3451            .layout_nodes
3452            .get(&parent_id)
3453            .ok_or(GuiError::WidgetNotFound(parent_id.0))?;
3454        let parent_rect = self.layout_tree.layout(*parent_node)?;
3455        Ok(crate::layout::LayoutRect::new(
3456            rect.x - parent_rect.x,
3457            rect.y - parent_rect.y,
3458            rect.width,
3459            rect.height,
3460        ))
3461    }
3462
3463    /// Sets the minimum dimensions for a top-level window.
3464    ///
3465    /// Returns [`GuiError::UnsupportedWidget`] if `widget_id` is not a window.
3466    pub fn set_window_min_size(
3467        &mut self,
3468        widget_id: WidgetId,
3469        width: u32,
3470        height: u32,
3471    ) -> GuiResult<()> {
3472        let spec = self
3473            .widgets
3474            .get(&widget_id)
3475            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
3476        if spec.kind != WidgetKind::Window {
3477            return Err(GuiError::UnsupportedWidget("set_window_min_size"));
3478        }
3479        self.window_min_sizes.insert(widget_id, (width, height));
3480        self.backend.set_window_min_size(widget_id, width, height)
3481    }
3482
3483    /// Returns the minimum size set on a window via [`Self::set_window_min_size`],
3484    /// or derived from its layout root content minimum.
3485    pub fn window_min_size(&self, widget_id: WidgetId) -> GuiResult<Option<(u32, u32)>> {
3486        let spec = self
3487            .widgets
3488            .get(&widget_id)
3489            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
3490        if spec.kind != WidgetKind::Window {
3491            return Err(GuiError::UnsupportedWidget("set_window_min_size"));
3492        }
3493        if let Some(&min) = self.window_min_sizes.get(&widget_id) {
3494            return Ok(Some(min));
3495        }
3496        // Derive from children content minimums if it is a layout root
3497        if self.layout_roots.contains(&widget_id) {
3498            if let Some(children) = self.children_index.get(&widget_id) {
3499                let mut max_min_w: u32 = 0;
3500                let mut max_min_h: u32 = 0;
3501                for &child in children {
3502                    let (cw, ch) = self.min_sizes.get(&child).copied().unwrap_or((0, 0));
3503                    let pw = self.preferred_widths.get(&child).copied().unwrap_or(0);
3504                    let w = (cw as u32).max(pw);
3505                    let h = ch as u32;
3506                    max_min_w = max_min_w.max(w);
3507                    max_min_h = max_min_h.max(h);
3508                }
3509                if max_min_w > 0 || max_min_h > 0 {
3510                    return Ok(Some((max_min_w, max_min_h)));
3511                }
3512            }
3513        }
3514        Ok(None)
3515    }
3516
3517    /// Returns only the explicit minimum size set on a window via [`Self::set_window_min_size`].
3518    pub fn explicit_window_min_size(&self, widget_id: WidgetId) -> GuiResult<Option<(u32, u32)>> {
3519        let spec = self
3520            .widgets
3521            .get(&widget_id)
3522            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
3523        if spec.kind != WidgetKind::Window {
3524            return Err(GuiError::UnsupportedWidget("set_window_min_size"));
3525        }
3526        Ok(self.window_min_sizes.get(&widget_id).copied())
3527    }
3528
3529    /// Sets whether a top-level window can be resized by the user.
3530    ///
3531    /// Returns [`GuiError::UnsupportedWidget`] if `widget_id` is not a window.
3532    pub fn set_resizable(&mut self, widget_id: WidgetId, resizable: bool) -> GuiResult<()> {
3533        let spec = self
3534            .widgets
3535            .get(&widget_id)
3536            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
3537        if spec.kind != WidgetKind::Window {
3538            return Err(GuiError::UnsupportedWidget("set_resizable"));
3539        }
3540        self.window_resizable.insert(widget_id, resizable);
3541        self.backend.set_resizable(widget_id, resizable)
3542    }
3543
3544    /// Returns whether a window is resizable. Defaults to `true`.
3545    pub fn is_resizable(&self, widget_id: WidgetId) -> GuiResult<bool> {
3546        let spec = self
3547            .widgets
3548            .get(&widget_id)
3549            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
3550        if spec.kind != WidgetKind::Window {
3551            return Err(GuiError::UnsupportedWidget("set_resizable"));
3552        }
3553        Ok(self
3554            .window_resizable
3555            .get(&widget_id)
3556            .copied()
3557            .unwrap_or(true))
3558    }
3559
3560    /// Alias for [`Self::is_resizable`].
3561    pub fn resizable(&self, widget_id: WidgetId) -> GuiResult<bool> {
3562        self.is_resizable(widget_id)
3563    }
3564
3565    /// Returns backend-native handle information for a Vulkan canvas widget.
3566    pub fn native_handle(&self, widget_id: WidgetId) -> GuiResult<B::NativeHandle> {
3567        self.widget_spec(widget_id)?
3568            .ensure_property(WidgetProperty::NativeHandle)?;
3569
3570        self.backend.native_handle(widget_id)
3571    }
3572
3573    /// Returns backend-native handle information for a Vulkan canvas widget.
3574    pub fn vulkan_canvas_handle(&self, widget_id: WidgetId) -> GuiResult<B::NativeHandle> {
3575        self.native_handle(widget_id)
3576    }
3577
3578    /// Returns backend-native handle information for a Metal canvas widget.
3579    pub fn metal_canvas_handle(&self, widget_id: WidgetId) -> GuiResult<MetalCanvasHandle> {
3580        self.widget_spec(widget_id)?
3581            .ensure_property(WidgetProperty::MetalHandle)?;
3582
3583        self.backend.metal_canvas_handle(widget_id)
3584    }
3585
3586    /// Validates choice items for `ComboBox`/`MultiSelect` (found while dogfooding):
3587    /// every item must be non-empty after trimming and must not contain `|`
3588    /// (the legacy creation-text separator) or NUL.
3589    fn validate_choice_items<S: AsRef<str>>(items: &[S]) -> GuiResult<Vec<String>> {
3590        items
3591            .iter()
3592            .map(|item| {
3593                let item = item.as_ref();
3594                if item.trim().is_empty() {
3595                    return Err(GuiError::Backend(
3596                        "choice items must not be empty".to_owned(),
3597                    ));
3598                }
3599                if item.contains('|') || item.contains('\0') {
3600                    return Err(GuiError::Backend(format!(
3601                        "choice item {item:?} must not contain '|' or NUL"
3602                    )));
3603                }
3604                Ok(item.trim().to_owned())
3605            })
3606            .collect()
3607    }
3608
3609    /// Creates a `ComboBox` with typed options (found while dogfooding),
3610    /// replacing the legacy `create(WidgetKind::ComboBox, Some("A|B|C"))`
3611    /// form (still accepted, but deprecated in the docs). Works on every lane.
3612    /// The first option is selected.
3613    #[cfg(feature = "widgets-choice")]
3614    pub fn create_combo_box<S: AsRef<str>>(&mut self, items: &[S]) -> GuiResult<WidgetId> {
3615        let items = Self::validate_choice_items(items)?;
3616        self.create(WidgetKind::ComboBox, Some(&items.join("|")))
3617    }
3618
3619    /// Replaces the options of a choice widget from a slice (dogfood report
3620    /// #7). `ComboBox` goes through `Backend::set_combo_box_items` (supported
3621    /// across Mock, GTK, Win32, Cocoa, Web, and TUI when `widgets-choice` is
3622    /// enabled), keeping the selected index in `Ui`'s model when it is still in
3623    /// range and otherwise selecting the first option, silently. `MultiSelect`,
3624    /// `DataList` and `ListView` forward to [`Self::set_data_list_items`].
3625    pub fn set_items<S: AsRef<str>>(&mut self, widget_id: WidgetId, items: &[S]) -> GuiResult<()> {
3626        #[cfg(feature = "widgets-choice")]
3627        let kind = self.widget_spec(widget_id)?.kind;
3628        #[cfg(not(feature = "widgets-choice"))]
3629        let _ = self.widget_spec(widget_id)?;
3630
3631        #[cfg(feature = "widgets-choice")]
3632        if kind == WidgetKind::ComboBox {
3633            let items = Self::validate_choice_items(items)?;
3634            self.backend.set_combo_box_items(widget_id, &items)?;
3635            let previous = self
3636                .widgets
3637                .get(&widget_id)
3638                .and_then(|spec| spec.selected_index);
3639            let selected = match previous {
3640                Some(index) if index < items.len() => Some(index),
3641                _ if items.is_empty() => None,
3642                _ => Some(0),
3643            };
3644            if let Some(spec) = self.widgets.get_mut(&widget_id) {
3645                spec.text = Some(items.join("|"));
3646                spec.selected_index = selected;
3647            }
3648            return Ok(());
3649        }
3650
3651        #[cfg(feature = "widgets-choice")]
3652        let is_multi_select = kind == WidgetKind::MultiSelect;
3653        #[cfg(not(feature = "widgets-choice"))]
3654        let is_multi_select = false;
3655
3656        let items: Vec<String> = if is_multi_select {
3657            Self::validate_choice_items(items)?
3658        } else {
3659            items.iter().map(|item| item.as_ref().to_owned()).collect()
3660        };
3661        self.set_data_list_items(widget_id, &items)
3662    }
3663
3664    /// The options of a choice widget: a `ComboBox`/`MultiSelect`'s options
3665    /// (parsed from the creation text, or the last [`Self::set_items`]), or a
3666    /// `DataList`/`ListView`'s items.
3667    pub fn items(&self, widget_id: WidgetId) -> GuiResult<Vec<String>> {
3668        let spec = self.widget_spec(widget_id)?;
3669        Ok(match spec.kind {
3670            #[cfg(feature = "widgets-choice")]
3671            WidgetKind::ComboBox | WidgetKind::MultiSelect if spec.data_list_items.is_empty() => {
3672                spec.text
3673                    .as_deref()
3674                    .unwrap_or("")
3675                    .split('|')
3676                    .map(str::trim)
3677                    .filter(|item| !item.is_empty())
3678                    .map(ToOwned::to_owned)
3679                    .collect()
3680            }
3681            _ => spec.data_list_items.clone(),
3682        })
3683    }
3684
3685    /// Sets items for a data list widget.
3686    #[cfg(any(feature = "widgets-data", feature = "widgets-choice"))]
3687    pub fn set_data_list_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()> {
3688        // Store only after the lane accepts the write, so a refusal leaves the
3689        // shared model and the native record in agreement.
3690        self.widget_spec(widget_id)?
3691            .ensure_property(WidgetProperty::DataListItems)?;
3692        self.backend.set_data_list_items(widget_id, items)?;
3693        if let Some(spec) = self.widgets.get_mut(&widget_id) {
3694            spec.data_list_items = items.to_vec();
3695        }
3696        Ok(())
3697    }
3698
3699    #[cfg(not(any(feature = "widgets-data", feature = "widgets-choice")))]
3700    pub fn set_data_list_items(
3701        &mut self,
3702        _widget_id: WidgetId,
3703        _items: &[String],
3704    ) -> GuiResult<()> {
3705        Err(GuiError::UnsupportedWidget("set_data_list_items"))
3706    }
3707
3708    /// Replaces the column headers of a columned list.
3709    ///
3710    /// Validates the widget kind through the shared applicability table
3711    /// (`ListView` only), records the columns on the spec, and forwards to
3712    /// the backend. Passing an empty slice returns the widget to the
3713    /// shipped single-column row contract, where rows come from
3714    /// [`Self::set_data_list_items`]. A lane without a columned mapping
3715    /// reports the typed `UnsupportedCapability("list_view_columns")`
3716    /// refusal (native mappings are follow-ups).
3717    #[cfg(feature = "widgets-data")]
3718    pub fn set_list_columns(
3719        &mut self,
3720        widget_id: WidgetId,
3721        columns: &[ColumnSpec],
3722    ) -> GuiResult<()> {
3723        let spec = self.require_property(widget_id, WidgetProperty::ListViewColumns)?;
3724        let previous = spec.list_columns.clone();
3725        spec.list_columns = columns.to_vec();
3726        if let Err(error) = self.backend.set_list_columns(widget_id, columns) {
3727            if let Some(spec) = self.widgets.get_mut(&widget_id) {
3728                spec.list_columns = previous;
3729            }
3730            return Err(error);
3731        }
3732        Ok(())
3733    }
3734
3735    #[cfg(not(feature = "widgets-data"))]
3736    pub fn set_list_columns(
3737        &mut self,
3738        _widget_id: WidgetId,
3739        _columns: &[ColumnSpec],
3740    ) -> GuiResult<()> {
3741        Err(GuiError::UnsupportedWidget("set_list_columns"))
3742    }
3743
3744    /// Replaces the row cells of a columned list.
3745    ///
3746    /// Row `r`, cell `c` renders column `c`'s header with the text
3747    /// `rows[r][c]`; missing trailing cells render empty and cells beyond
3748    /// the column count are ignored. Shares the kind guard and the lane
3749    /// capability refusal with [`Self::set_list_columns`].
3750    #[cfg(feature = "widgets-data")]
3751    pub fn set_list_rows(&mut self, widget_id: WidgetId, rows: &[Vec<String>]) -> GuiResult<()> {
3752        let spec = self.require_property(widget_id, WidgetProperty::ListViewRows)?;
3753        let previous = spec.list_rows.clone();
3754        spec.list_rows = rows.to_vec();
3755        if let Err(error) = self.backend.set_list_rows(widget_id, rows) {
3756            if let Some(spec) = self.widgets.get_mut(&widget_id) {
3757                spec.list_rows = previous;
3758            }
3759            return Err(error);
3760        }
3761        Ok(())
3762    }
3763
3764    #[cfg(not(feature = "widgets-data"))]
3765    pub fn set_list_rows(&mut self, _widget_id: WidgetId, _rows: &[Vec<String>]) -> GuiResult<()> {
3766        Err(GuiError::UnsupportedWidget("set_list_rows"))
3767    }
3768
3769    /// Applies a keyed row update to a row widget.
3770    ///
3771    /// Identity is the application-owned [`RowKey`]: the submitted vector
3772    /// defines display order, cells replace verbatim, and the returned
3773    /// [`RowDelta`] classifies what changed. Equal keys, order, and cells are
3774    /// a free no-op (no backend call at all). Duplicate keys are rejected
3775    /// with `GuiError::Backend("duplicate row key")` before anything is
3776    /// touched, and a lane that cannot drop a removed selection reports the
3777    /// typed `UnsupportedCapability("clear_selection")` refusal, also before
3778    /// the rows change.
3779    ///
3780    /// The selection follows the *key* the widget kept (recorded when
3781    /// [`Self::set_selected_index`]/[`Self::set_selected_indices`] ran on
3782    /// keyed rows): an index move writes the new index and emits one
3783    /// `SelectionChanged` carrying it; a removed key clears the selection
3784    /// and emits the clear through [`Self::clear_selection`]. The scroll
3785    /// anchor follows the same rule through the lane's `scroll_anchor`
3786    /// capability; a lane that cannot report it is skipped rather than
3787    /// guessed.
3788    ///
3789    /// Keyed bookkeeping tracks keyed applies; calling the plain population
3790    /// setters in between resets the baseline, so the next keyed apply
3791    /// reports everything it writes as inserted. `TreeView` keeps its flat
3792    /// indented-row contract for this cut.
3793    #[cfg(feature = "widgets-data")]
3794    pub fn set_rows_keyed(&mut self, widget_id: WidgetId, rows: &[RowSet]) -> GuiResult<RowDelta> {
3795        let plain_selected_index = self
3796            .require_property(widget_id, WidgetProperty::KeyedRows)?
3797            .selected_index;
3798        // Diff against a borrowed baseline: the no-op path is common (an app
3799        // re-applying its model each tick) and previously cloned the whole
3800        // table before discovering there was nothing to do.
3801        let delta = match self.keyed_rows.get(&widget_id) {
3802            Some(previous) => diff_rows(previous, rows)?,
3803            None => diff_rows(&[], rows)?,
3804        };
3805        if delta.is_noop() {
3806            return Ok(delta);
3807        }
3808
3809        let tracked_selection = self
3810            .keyed_selection
3811            .get(&widget_id)
3812            .cloned()
3813            .unwrap_or_default();
3814
3815        // Read the pre-apply scroll anchor through the lane's capability
3816        // before touching rows; a refusal skips re-anchoring.
3817        let anchor_key = match self.visible_anchor(widget_id) {
3818            Ok(anchor) => anchor,
3819            Err(GuiError::UnsupportedCapability(_)) => None,
3820            Err(error) => return Err(error),
3821        };
3822
3823        // Resolve the old anchor position and the index-only selection
3824        // fallback against the stored baseline without cloning it; only a
3825        // real change needs the new baseline copy.
3826        let (anchor_old_index, selection_keys) = {
3827            let previous = self.keyed_rows.get(&widget_id);
3828            let anchor_old_index = anchor_key.and_then(|key| {
3829                previous.and_then(|old_rows| old_rows.iter().position(|row| row.key == key))
3830            });
3831            // The selection follows the remembered keys; a selection made
3832            // before keyed rows existed falls back to the previous rows'
3833            // keys, so an index-only selection is preserved too.
3834            let selection_keys = if tracked_selection.is_empty() {
3835                plain_selected_index
3836                    .and_then(|index| previous.and_then(|rows| rows.get(index)))
3837                    .map(|row| vec![row.key])
3838                    .unwrap_or_default()
3839            } else {
3840                tracked_selection
3841            };
3842            (anchor_old_index, selection_keys)
3843        };
3844        let selection_indices: Vec<usize> = selection_keys
3845            .iter()
3846            .filter_map(|key| rows.iter().position(|row| row.key == *key))
3847            .collect();
3848        let multi_select = self
3849            .widget(widget_id)
3850            .is_some_and(|spec| !spec.selected_indices.is_empty());
3851        let selection_removed = !selection_keys.is_empty() && selection_indices.is_empty();
3852
3853        // Try applying incremental delta ops first if available
3854        let mut applied_incrementally = false;
3855        if let Some(previous) = self.keyed_rows.get(&widget_id) {
3856            if let Some(ops) = crate::widgets::diff_row_ops(previous, rows, &delta) {
3857                match self.backend.apply_row_delta(widget_id, &ops) {
3858                    Ok(()) => {
3859                        if let Some(spec) = self.widgets.get_mut(&widget_id) {
3860                            match spec.kind {
3861                                WidgetKind::DataGrid => {
3862                                    let grid_rows = Arc::make_mut(&mut spec.data_grid_rows);
3863                                    crate::widgets::apply_row_ops_to_cells(grid_rows, &ops);
3864                                }
3865                                WidgetKind::DataList => {
3866                                    crate::widgets::apply_row_ops_to_items(
3867                                        &mut spec.data_list_items,
3868                                        &ops,
3869                                    );
3870                                }
3871                                WidgetKind::ListView => {
3872                                    if !spec.list_columns.is_empty() {
3873                                        crate::widgets::apply_row_ops_to_cells(
3874                                            &mut spec.list_rows,
3875                                            &ops,
3876                                        );
3877                                    } else {
3878                                        crate::widgets::apply_row_ops_to_items(
3879                                            &mut spec.data_list_items,
3880                                            &ops,
3881                                        );
3882                                    }
3883                                }
3884                                _ => {}
3885                            }
3886                        }
3887                        if let Some(baseline) = self.keyed_rows.get_mut(&widget_id) {
3888                            crate::widgets::apply_row_ops_to_rows(baseline, &ops);
3889                        }
3890                        applied_incrementally = true;
3891                    }
3892                    Err(GuiError::UnsupportedCapability(_)) => {}
3893                    Err(error) => return Err(error),
3894                }
3895            }
3896        }
3897
3898        if !applied_incrementally {
3899            // Apply the rows to the backend first. On failure (backend refusal),
3900            // return Err with rows, selection, anchor, and keyed baseline all unchanged.
3901            match self.widget(widget_id).map(|spec| spec.kind) {
3902                Some(WidgetKind::DataList) => {
3903                    let items: Vec<String> = rows.iter().map(RowSet::text).collect();
3904                    self.set_data_list_items(widget_id, &items)?;
3905                }
3906                Some(WidgetKind::ListView) => {
3907                    // A columned ListView renders `list_rows`, not the
3908                    // single-column `data_list_items` contract; keyed rows must
3909                    // feed the model the lane actually shows.
3910                    let columned = self
3911                        .widget(widget_id)
3912                        .is_some_and(|spec| !spec.list_columns.is_empty());
3913                    if columned {
3914                        let cells: Vec<Vec<String>> =
3915                            rows.iter().map(|row| row.cells.clone()).collect();
3916                        self.set_list_rows(widget_id, &cells)?;
3917                    } else {
3918                        let items: Vec<String> = rows.iter().map(RowSet::text).collect();
3919                        self.set_data_list_items(widget_id, &items)?;
3920                    }
3921                }
3922                Some(WidgetKind::DataGrid) => {
3923                    // Build the shared cell matrix directly: the previous path
3924                    // cloned every cell into a temporary and `set_data_grid_rows`
3925                    // cloned it again.
3926                    let cells: Arc<Vec<Vec<String>>> =
3927                        Arc::new(rows.iter().map(|row| row.cells.clone()).collect());
3928                    self.set_data_grid_rows_shared(widget_id, cells)?;
3929                }
3930                _ => return Err(GuiError::UnsupportedWidget("set_rows_keyed")),
3931            }
3932
3933            // Move the keyed rows baseline now that the backend write succeeded,
3934            // so that selection setters (which call record_keyed_selection) look up
3935            // indices against the new row set.
3936            self.keyed_rows.insert(widget_id, rows.to_vec());
3937        }
3938
3939        if selection_removed {
3940            // A refused clear leaves rows and selection untouched.
3941            self.clear_selection(widget_id)?;
3942        } else if !selection_keys.is_empty() {
3943            if multi_select {
3944                let current: Vec<usize> = self
3945                    .widget(widget_id)
3946                    .map(|spec| spec.selected_indices.clone())
3947                    .unwrap_or_default();
3948                if current != selection_indices {
3949                    self.set_selected_indices(widget_id, &selection_indices)?;
3950                    self.pending_events
3951                        .push_back(UiEvent::MultiSelectionChanged {
3952                            widget_id,
3953                            indices: selection_indices.clone(),
3954                        });
3955                }
3956            } else if let Some(&index) = selection_indices.first() {
3957                let current = self.widget(widget_id).and_then(|spec| spec.selected_index);
3958                if current != Some(index) {
3959                    self.set_selected_index(widget_id, index)?;
3960                    self.pending_events.push_back(UiEvent::SelectionChanged {
3961                        widget_id,
3962                        selected: rows.get(index).map(RowSet::text),
3963                        index: Some(index),
3964                    });
3965                }
3966            }
3967        }
3968
3969        // Re-anchor the topmost visible row: by key when it survived, else
3970        // clamped from its previous index. A lane that refuses the scroll is
3971        // reported instead of dropped.
3972        if let Some(key) = anchor_key {
3973            if !rows.is_empty() {
3974                let new_index = rows
3975                    .iter()
3976                    .position(|row| row.key == key)
3977                    .or(anchor_old_index)
3978                    .map(|index| index.min(rows.len() - 1));
3979                if let Some(index) = new_index {
3980                    // A refused restoration is reported, not dropped -
3981                    // the apply otherwise left rows written and the viewport
3982                    // silently off-anchor.
3983                    self.backend.scroll_to_row(widget_id, index)?;
3984                }
3985            }
3986        }
3987
3988        let surviving: Vec<RowKey> = selection_keys
3989            .iter()
3990            .copied()
3991            .filter(|key| rows.iter().any(|row| row.key == *key))
3992            .collect();
3993        if surviving.is_empty() {
3994            self.keyed_selection.remove(&widget_id);
3995        } else {
3996            self.keyed_selection.insert(widget_id, surviving);
3997        }
3998
3999        Ok(delta)
4000    }
4001
4002    #[cfg(not(feature = "widgets-data"))]
4003    pub fn set_rows_keyed(
4004        &mut self,
4005        _widget_id: WidgetId,
4006        _rows: &[RowSet],
4007    ) -> GuiResult<RowDelta> {
4008        Err(GuiError::UnsupportedWidget("set_rows_keyed"))
4009    }
4010
4011    /// Clears the selection of a row widget.
4012    ///
4013    /// Clears the shared index and multi-selection state, drops the keyed
4014    /// selection, asks the backend to clear its native selection (the
4015    /// `"clear_selection"` capability; lanes without a mapping report the
4016    /// typed refusal), and emits one
4017    /// `UiEvent::SelectionChanged { selected: None, index: None }` when a
4018    /// selection was actually cleared, so observers never miss a silent
4019    /// reset. The backend is consulted before the shared model changes, so a
4020    /// refused call leaves the previous selection untouched.
4021    pub fn clear_selection(&mut self, widget_id: WidgetId) -> GuiResult<()> {
4022        let had_selection = {
4023            let spec = self.require_property(widget_id, WidgetProperty::ClearSelection)?;
4024            spec.selected_index.is_some() || !spec.selected_indices.is_empty()
4025        };
4026        self.backend.clear_selection(widget_id)?;
4027        if let Some(spec) = self.widgets.get_mut(&widget_id) {
4028            spec.selected_index = None;
4029            spec.selected_indices.clear();
4030        }
4031        self.keyed_selection.remove(&widget_id);
4032        if had_selection {
4033            self.pending_events.push_back(UiEvent::SelectionChanged {
4034                widget_id,
4035                selected: None,
4036                index: None,
4037            });
4038        }
4039        Ok(())
4040    }
4041
4042    /// Returns the application-owned key of a keyed row widget's topmost
4043    /// visible row.
4044    ///
4045    /// The backend reports the anchor row's index through the
4046    /// `"scroll_anchor"` capability; a lane that cannot observe its scroll
4047    /// position returns the typed [`GuiError::UnsupportedCapability`]
4048    /// refusal, and a widget without keyed rows answers `None`.
4049    pub fn visible_anchor(&self, widget_id: WidgetId) -> GuiResult<Option<RowKey>> {
4050        self.widget_spec(widget_id)?
4051            .ensure_property(WidgetProperty::VisibleAnchor)?;
4052        let index = self.backend.visible_anchor_index(widget_id)?;
4053        Ok(index.and_then(|index| {
4054            self.keyed_rows
4055                .get(&widget_id)
4056                .and_then(|rows| rows.get(index))
4057                .map(|row| row.key)
4058        }))
4059    }
4060
4061    /// Reports whether the last row of a keyed row widget is currently
4062    /// visible (follow-tail detection).
4063    ///
4064    /// Forwarded to the backend's [`Backend::rows_end_visible`] capability
4065    /// (the same `"scroll_anchor"` family as
4066    /// [`Self::visible_anchor`]): a lane that cannot observe its scroll
4067    /// position reports the typed [`GuiError::UnsupportedCapability`]
4068    /// refusal, and a widget whose rows are all above the viewport answers
4069    /// `false`.
4070    pub fn rows_end_visible(&self, widget_id: WidgetId) -> GuiResult<bool> {
4071        self.widget_spec(widget_id)?
4072            .ensure_property(WidgetProperty::VisibleAnchor)?;
4073        self.backend.rows_end_visible(widget_id)
4074    }
4075
4076    /// Scrolls a row widget so `index` is the topmost visible row.
4077    ///
4078    /// Forwarded to the backend's [`Backend::scroll_to_row`] capability
4079    /// (the same `"scroll_anchor"` family as [`Self::visible_anchor`]). A
4080    /// lane that cannot move the viewport reports the typed
4081    /// [`GuiError::UnsupportedCapability`] refusal.
4082    pub fn scroll_to_row(&mut self, widget_id: WidgetId, index: usize) -> GuiResult<()> {
4083        self.widget_spec(widget_id)?
4084            .ensure_property(WidgetProperty::VisibleAnchor)?;
4085        self.backend.scroll_to_row(widget_id, index)
4086    }
4087
4088    /// Returns the keyed selection of a row widget, if any.
4089    ///
4090    /// Populated when [`Self::set_selected_index`]/[`Self::set_selected_indices`]
4091    /// run on a widget with keyed rows, and kept in step by
4092    /// [`Self::set_rows_keyed`] and [`Self::clear_selection`]. For a
4093    /// multi-selection this reports the lowest-index surviving member.
4094    pub fn selected_row_key(&self, widget_id: WidgetId) -> Option<RowKey> {
4095        self.keyed_selection
4096            .get(&widget_id)
4097            .and_then(|keys| keys.first().copied())
4098    }
4099
4100    /// Maps selection indices to row keys for a widget with keyed rows,
4101    /// so a later [`Self::set_rows_keyed`] follows the selection by
4102    /// identity. Out-of-range indices record nothing.
4103    fn record_keyed_selection(&mut self, widget_id: WidgetId, indices: &[usize]) {
4104        let Some(rows) = self.keyed_rows.get(&widget_id) else {
4105            return;
4106        };
4107        let keys: Vec<RowKey> = indices
4108            .iter()
4109            .filter_map(|index| rows.get(*index))
4110            .map(|row| row.key)
4111            .collect();
4112        if keys.is_empty() {
4113            self.keyed_selection.remove(&widget_id);
4114        } else {
4115            self.keyed_selection.insert(widget_id, keys);
4116        }
4117    }
4118
4119    /// Sets row-major cell values for a data grid widget.
4120    #[cfg(feature = "widgets-data")]
4121    pub fn set_data_grid_rows(
4122        &mut self,
4123        widget_id: WidgetId,
4124        rows: &[Vec<String>],
4125    ) -> GuiResult<()> {
4126        self.set_data_grid_rows_shared(widget_id, Arc::new(rows.to_vec()))
4127    }
4128
4129    /// Declares a `DataGrid`'s columns separately from its data (dogfood
4130    /// report #6), so the header is no longer data row 0 by convention.
4131    ///
4132    /// The header row is rendered natively as row 0 (on every lane), data
4133    /// rows set with [`Self::set_data_grid_data_rows`] follow it, and
4134    /// [`Self::data_grid_data_row`] maps the raw row of a
4135    /// `SelectionChanged`/`GridCellClicked`/`Activated` event back to a
4136    /// 0-based data index. Column widths are applied best-effort: lanes that
4137    /// report `UnsupportedCapability` for `set_data_grid_col_width` keep
4138    /// their default widths. Passing an empty slice removes the header.
4139    ///
4140    /// Non-breaking: grids that never call this keep the raw
4141    /// [`Self::set_data_grid_rows`] behaviour.
4142    #[cfg(feature = "widgets-data")]
4143    pub fn set_data_grid_columns(
4144        &mut self,
4145        widget_id: WidgetId,
4146        columns: &[ColumnSpec],
4147    ) -> GuiResult<()> {
4148        self.widget_spec(widget_id)?
4149            .ensure_property(WidgetProperty::DataGridRows)?;
4150        if columns.is_empty() {
4151            self.data_grid_columns.remove(&widget_id);
4152        } else {
4153            self.data_grid_columns.insert(widget_id, columns.to_vec());
4154        }
4155        let data = self
4156            .data_grid_data
4157            .get(&widget_id)
4158            .cloned()
4159            .unwrap_or_default();
4160        self.set_data_grid_data_rows(widget_id, &data)?;
4161        for (index, column) in columns.iter().enumerate() {
4162            if let Some(width) = column.width {
4163                match self.set_data_grid_col_width(widget_id, index, width) {
4164                    Ok(()) | Err(GuiError::UnsupportedCapability(_)) => {}
4165                    Err(error) => return Err(error),
4166                }
4167            }
4168        }
4169        Ok(())
4170    }
4171
4172    /// Sets a `DataGrid`'s data rows (0-based), rendering the header from
4173    /// [`Self::set_data_grid_columns`] above them when columns are declared.
4174    #[cfg(feature = "widgets-data")]
4175    pub fn set_data_grid_data_rows(
4176        &mut self,
4177        widget_id: WidgetId,
4178        rows: &[Vec<String>],
4179    ) -> GuiResult<()> {
4180        self.widget_spec(widget_id)?
4181            .ensure_property(WidgetProperty::DataGridRows)?;
4182        let mut native = Vec::with_capacity(rows.len() + 1);
4183        if let Some(columns) = self.data_grid_columns.get(&widget_id) {
4184            native.push(columns.iter().map(|column| column.title.clone()).collect());
4185        }
4186        native.extend(rows.iter().cloned());
4187        self.set_data_grid_rows_shared(widget_id, Arc::new(native))?;
4188        self.data_grid_data.insert(widget_id, rows.to_vec());
4189        Ok(())
4190    }
4191
4192    /// The declared columns of a `DataGrid` (empty when none).
4193    #[cfg(feature = "widgets-data")]
4194    pub fn data_grid_columns(&self, widget_id: WidgetId) -> &[ColumnSpec] {
4195        self.data_grid_columns
4196            .get(&widget_id)
4197            .map(Vec::as_slice)
4198            .unwrap_or(&[])
4199    }
4200
4201    /// Maps a raw grid row (as reported by `SelectionChanged`,
4202    /// `GridCellClicked`, `GridSelectionChanged` or `Activated`) to a 0-based
4203    /// data row: `None` for the header row. Without declared columns the raw
4204    /// row is returned unchanged.
4205    #[cfg(feature = "widgets-data")]
4206    pub fn data_grid_data_row(&self, widget_id: WidgetId, raw_row: usize) -> Option<usize> {
4207        if self.data_grid_columns.contains_key(&widget_id) {
4208            raw_row.checked_sub(1)
4209        } else {
4210            Some(raw_row)
4211        }
4212    }
4213
4214    /// Highlights one whole data row (0-based; header-aware) or clears the
4215    /// highlight with `None` - the one-call form of building a
4216    /// `(row, col)` list for [`Self::set_data_grid_selection`].
4217    #[cfg(feature = "widgets-data")]
4218    pub fn select_data_grid_row(
4219        &mut self,
4220        widget_id: WidgetId,
4221        data_row: Option<usize>,
4222    ) -> GuiResult<()> {
4223        let header = usize::from(self.data_grid_columns.contains_key(&widget_id));
4224        let columns = self
4225            .data_grid_columns
4226            .get(&widget_id)
4227            .map(Vec::len)
4228            .or_else(|| {
4229                self.widgets
4230                    .get(&widget_id)
4231                    .and_then(|spec| spec.data_grid_rows.first().map(Vec::len))
4232            })
4233            .unwrap_or(0);
4234        let selection: Vec<(usize, usize)> = match data_row {
4235            Some(row) => (0..columns).map(|col| (row + header, col)).collect(),
4236            None => Vec::new(),
4237        };
4238        self.set_data_grid_selection(widget_id, &selection)
4239    }
4240
4241    /// Installs an already-shared row matrix on the spec and the backend,
4242    /// skipping the second copy a `&[Vec<String>]` round-trip costs.
4243    #[cfg(feature = "widgets-data")]
4244    fn set_data_grid_rows_shared(
4245        &mut self,
4246        widget_id: WidgetId,
4247        rows: Arc<Vec<Vec<String>>>,
4248    ) -> GuiResult<()> {
4249        // Same ordering as `set_data_list_items`: the spec mirrors a write the
4250        // lane actually accepted.
4251        self.widget_spec(widget_id)?
4252            .ensure_property(WidgetProperty::DataGridRows)?;
4253        self.backend
4254            .set_data_grid_rows(widget_id, Arc::clone(&rows))?;
4255        if let Some(spec) = self.widgets.get_mut(&widget_id) {
4256            spec.data_grid_rows = rows;
4257        }
4258        Ok(())
4259    }
4260
4261    /// Sets a virtual data model for a data grid widget.
4262    #[cfg(feature = "widgets-data")]
4263    pub fn set_data_grid_model(
4264        &mut self,
4265        widget_id: WidgetId,
4266        model: Box<dyn crate::widgets::DataGridModel>,
4267    ) -> GuiResult<()> {
4268        self.widget_spec(widget_id)?
4269            .ensure_property(WidgetProperty::DataGridModel)?;
4270        self.backend.set_data_grid_model(widget_id, model)
4271    }
4272
4273    /// Sets the height of a specific row in a data grid widget.
4274    #[cfg(feature = "widgets-data")]
4275    pub fn set_data_grid_row_height(
4276        &mut self,
4277        widget_id: WidgetId,
4278        row: usize,
4279        height: i32,
4280    ) -> GuiResult<()> {
4281        self.widget_spec(widget_id)?
4282            .ensure_property(WidgetProperty::DataGridRowHeight)?;
4283        self.backend
4284            .set_data_grid_row_height(widget_id, row, height)
4285    }
4286
4287    /// Sets the width of a specific column in a data grid widget.
4288    #[cfg(feature = "widgets-data")]
4289    pub fn set_data_grid_col_width(
4290        &mut self,
4291        widget_id: WidgetId,
4292        col: usize,
4293        width: i32,
4294    ) -> GuiResult<()> {
4295        self.widget_spec(widget_id)?
4296            .ensure_property(WidgetProperty::DataGridColWidth)?;
4297        self.backend.set_data_grid_col_width(widget_id, col, width)
4298    }
4299
4300    /// Sets the number of frozen rows and columns in a data grid widget.
4301    #[cfg(feature = "widgets-data")]
4302    pub fn set_data_grid_frozen_panes(
4303        &mut self,
4304        widget_id: WidgetId,
4305        rows: usize,
4306        cols: usize,
4307    ) -> GuiResult<()> {
4308        self.widget_spec(widget_id)?
4309            .ensure_property(WidgetProperty::DataGridFrozenPanes)?;
4310        self.backend
4311            .set_data_grid_frozen_panes(widget_id, rows, cols)
4312    }
4313
4314    #[cfg(feature = "widgets-data")]
4315    pub fn set_data_grid_selection(
4316        &mut self,
4317        widget_id: WidgetId,
4318        selection: &[(usize, usize)],
4319    ) -> GuiResult<()> {
4320        self.require_property(widget_id, WidgetProperty::DataGridSelection)?;
4321        self.backend.set_data_grid_selection(widget_id, selection)
4322    }
4323
4324    /// Sets hierarchical items for a tree view widget.
4325    #[cfg(feature = "widgets-data")]
4326    pub fn set_tree_items(&mut self, widget_id: WidgetId, items: &[TreeItem]) -> GuiResult<()> {
4327        let spec = self.require_property(widget_id, WidgetProperty::TreeItems)?;
4328        let previous = spec.tree_items.clone();
4329        spec.tree_items = items.to_vec();
4330        if let Err(error) = self.backend.set_tree_items(widget_id, items) {
4331            if let Some(spec) = self.widgets.get_mut(&widget_id) {
4332                spec.tree_items = previous;
4333            }
4334            return Err(error);
4335        }
4336        Ok(())
4337    }
4338
4339    #[cfg(not(feature = "widgets-data"))]
4340    pub fn set_data_grid_rows(
4341        &mut self,
4342        _widget_id: WidgetId,
4343        _rows: &[Vec<String>],
4344    ) -> GuiResult<()> {
4345        Err(GuiError::UnsupportedWidget("set_data_grid_rows"))
4346    }
4347
4348    #[cfg(not(feature = "widgets-data"))]
4349    pub fn set_data_grid_columns(
4350        &mut self,
4351        _widget_id: WidgetId,
4352        _columns: &[ColumnSpec],
4353    ) -> GuiResult<()> {
4354        Err(GuiError::UnsupportedWidget("set_data_grid_columns"))
4355    }
4356
4357    #[cfg(not(feature = "widgets-data"))]
4358    pub fn set_data_grid_data_rows(
4359        &mut self,
4360        _widget_id: WidgetId,
4361        _rows: &[Vec<String>],
4362    ) -> GuiResult<()> {
4363        Err(GuiError::UnsupportedWidget("set_data_grid_data_rows"))
4364    }
4365
4366    #[cfg(not(feature = "widgets-data"))]
4367    pub fn data_grid_columns(&self, _widget_id: WidgetId) -> &[ColumnSpec] {
4368        &[]
4369    }
4370
4371    #[cfg(not(feature = "widgets-data"))]
4372    pub fn data_grid_data_row(&self, _widget_id: WidgetId, _raw_row: usize) -> Option<usize> {
4373        None
4374    }
4375
4376    #[cfg(not(feature = "widgets-data"))]
4377    pub fn select_data_grid_row(
4378        &mut self,
4379        _widget_id: WidgetId,
4380        _data_row: Option<usize>,
4381    ) -> GuiResult<()> {
4382        Err(GuiError::UnsupportedWidget("select_data_grid_row"))
4383    }
4384
4385    #[cfg(not(feature = "widgets-data"))]
4386    pub fn set_data_grid_model(
4387        &mut self,
4388        _widget_id: WidgetId,
4389        _model: Box<dyn crate::widgets::DataGridModel>,
4390    ) -> GuiResult<()> {
4391        Err(GuiError::UnsupportedWidget("set_data_grid_model"))
4392    }
4393
4394    #[cfg(not(feature = "widgets-data"))]
4395    pub fn set_data_grid_row_height(
4396        &mut self,
4397        _widget_id: WidgetId,
4398        _row: usize,
4399        _height: i32,
4400    ) -> GuiResult<()> {
4401        Err(GuiError::UnsupportedWidget("set_data_grid_row_height"))
4402    }
4403
4404    #[cfg(not(feature = "widgets-data"))]
4405    pub fn set_data_grid_col_width(
4406        &mut self,
4407        _widget_id: WidgetId,
4408        _col: usize,
4409        _width: i32,
4410    ) -> GuiResult<()> {
4411        Err(GuiError::UnsupportedWidget("set_data_grid_col_width"))
4412    }
4413
4414    #[cfg(not(feature = "widgets-data"))]
4415    pub fn set_data_grid_frozen_panes(
4416        &mut self,
4417        _widget_id: WidgetId,
4418        _rows: usize,
4419        _cols: usize,
4420    ) -> GuiResult<()> {
4421        Err(GuiError::UnsupportedWidget("set_data_grid_frozen_panes"))
4422    }
4423
4424    #[cfg(not(feature = "widgets-data"))]
4425    pub fn set_data_grid_selection(
4426        &mut self,
4427        _widget_id: WidgetId,
4428        _selection: &[(usize, usize)],
4429    ) -> GuiResult<()> {
4430        Err(GuiError::UnsupportedWidget("set_data_grid_selection"))
4431    }
4432
4433    #[cfg(not(feature = "widgets-data"))]
4434    pub fn set_tree_items(&mut self, _widget_id: WidgetId, _items: &[TreeItem]) -> GuiResult<()> {
4435        Err(GuiError::UnsupportedWidget("set_tree_items"))
4436    }
4437
4438    /// Sets the current scene for a canvas widget.
4439    pub fn set_canvas_scene(
4440        &mut self,
4441        widget_id: WidgetId,
4442        scene: &crate::CanvasScene,
4443    ) -> GuiResult<()> {
4444        if !scene.logical_width.is_finite()
4445            || !scene.logical_height.is_finite()
4446            || scene.logical_width <= 0.0
4447            || scene.logical_height <= 0.0
4448        {
4449            return Err(GuiError::Backend(
4450                "Canvas scene logical size must be finite and positive".to_owned(),
4451            ));
4452        }
4453
4454        #[cfg(feature = "widgets-canvas")]
4455        let gpu_canvas_fallback =
4456            self.gpu_degraded.get(&widget_id) == Some(&GpuDegradationPolicy::Canvas2DFallback);
4457        let spec = self
4458            .widgets
4459            .get_mut(&widget_id)
4460            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
4461        #[cfg(feature = "widgets-canvas")]
4462        let skip_property_check = spec.kind == WidgetKind::VulkanCanvas && gpu_canvas_fallback;
4463        #[cfg(not(feature = "widgets-canvas"))]
4464        let skip_property_check = false;
4465        if !skip_property_check {
4466            spec.ensure_property(WidgetProperty::CanvasScene)?;
4467        }
4468        let previous = spec.canvas_scene.clone();
4469        spec.canvas_scene = Some(scene.clone());
4470        if let Err(error) = self.backend.set_canvas_scene(widget_id, scene) {
4471            if let Some(spec) = self.widgets.get_mut(&widget_id) {
4472                spec.canvas_scene = previous;
4473            }
4474            return Err(error);
4475        }
4476        Ok(())
4477    }
4478
4479    /// Sets the raster surface painted beneath a canvas widget's scene.
4480    ///
4481    /// The surface is clipped to the widget and composited over the canvas
4482    /// background, so transparent pixels display as the background while the
4483    /// stored buffer keeps its alpha. Replacing the surface repaints it
4484    /// immediately; full typed image resources remain the scope.
4485    pub fn set_canvas_surface(
4486        &mut self,
4487        widget_id: WidgetId,
4488        surface: &crate::CanvasSurface,
4489    ) -> GuiResult<()> {
4490        let spec = self.require_property(widget_id, WidgetProperty::CanvasSurface)?;
4491        let previous = spec.canvas_surface.clone();
4492        spec.canvas_surface = Some(surface.clone());
4493        if let Err(error) = self.backend.set_canvas_surface(widget_id, surface) {
4494            if let Some(spec) = self.widgets.get_mut(&widget_id) {
4495                spec.canvas_surface = previous;
4496            }
4497            return Err(error);
4498        }
4499        Ok(())
4500    }
4501
4502    /// Copies a widget's content into the shared clipboard.
4503    ///
4504    /// Supported kinds: `DataList`/`ListView` (rows joined with newlines),
4505    /// `DataGrid` (rows serialized), and text widgets (`TextInput`,
4506    /// `TextArea`, `Label`). The text is mirrored in the `Ui` and forwarded
4507    /// to the backend's platform clipboard where supported (GTK today;
4508    /// Win32 tracked).
4509    pub fn copy_to_clipboard(&mut self, widget_id: WidgetId) -> GuiResult<()> {
4510        let spec = self.widget_spec(widget_id)?;
4511        spec.ensure_property(WidgetProperty::CopyToClipboard)?;
4512
4513        let content = match spec.kind {
4514            #[cfg(feature = "widgets-data")]
4515            WidgetKind::DataList | WidgetKind::ListView => spec.data_list_items.join("\n"),
4516            #[cfg(feature = "widgets-data")]
4517            WidgetKind::DataGrid => serialize_data_grid_rows(&spec.data_grid_rows),
4518            #[cfg(feature = "widgets-text")]
4519            WidgetKind::TextInput | WidgetKind::TextArea => spec.text.clone().unwrap_or_default(),
4520            WidgetKind::Label => spec.text.clone().unwrap_or_default(),
4521            _ => return Err(GuiError::UnsupportedWidget("copy_to_clipboard")),
4522        };
4523
4524        self.clipboard = Some(content.clone());
4525        self.backend.set_clipboard_text(&content)
4526    }
4527
4528    /// Pastes the shared clipboard into a widget.
4529    ///
4530    /// Supported kinds: `DataList`/`ListView`, `DataGrid`, and text widgets
4531    /// (`TextInput`, `TextArea`, `Label` — a label's text is replaced).
4532    /// Prefers the backend's platform clipboard (GTK reads the OS
4533    /// clipboard); falls back to the in-memory `Ui` mirror.
4534    pub fn paste_from_clipboard(&mut self, widget_id: WidgetId) -> GuiResult<()> {
4535        let platform_text = self.backend.clipboard_text()?;
4536        let clipboard = platform_text
4537            .filter(|text| !text.is_empty())
4538            .unwrap_or_else(|| self.clipboard.clone().unwrap_or_default());
4539
4540        let spec = self.widget_spec(widget_id)?;
4541        spec.ensure_property(WidgetProperty::PasteFromClipboard)?;
4542        let kind = spec.kind;
4543
4544        match kind {
4545            #[cfg(feature = "widgets-data")]
4546            WidgetKind::DataList | WidgetKind::ListView => {
4547                let items = parse_data_list_items(&clipboard);
4548                self.set_data_list_items(widget_id, &items)
4549            }
4550            #[cfg(feature = "widgets-data")]
4551            WidgetKind::DataGrid => {
4552                let rows = parse_data_grid_rows(&clipboard);
4553                self.set_data_grid_rows(widget_id, &rows)
4554            }
4555            #[cfg(feature = "widgets-text")]
4556            WidgetKind::TextInput | WidgetKind::TextArea => self.set_text(widget_id, &clipboard),
4557            WidgetKind::Label => self.set_text(widget_id, &clipboard),
4558            _ => Err(GuiError::UnsupportedWidget("paste_from_clipboard")),
4559        }
4560    }
4561
4562    /// Pastes an image from the platform clipboard, returning raw RGBA pixels and encoded PNG bytes.
4563    pub fn paste_image_from_clipboard(&mut self) -> GuiResult<Option<ClipboardImage>> {
4564        self.backend.paste_image_from_clipboard()
4565    }
4566
4567    /// Sets preferred position for a widget.
4568    pub fn set_position(&mut self, widget_id: WidgetId, x: i32, y: i32) -> GuiResult<()> {
4569        let Some(spec) = self.widgets.get_mut(&widget_id) else {
4570            return Err(GuiError::WidgetNotFound(widget_id.0));
4571        };
4572
4573        let previous = spec.position;
4574        spec.position = Some((x, y));
4575        if let Err(error) = self.backend.set_position(widget_id, x, y) {
4576            if let Some(spec) = self.widgets.get_mut(&widget_id) {
4577                spec.position = previous;
4578            }
4579            return Err(error);
4580        }
4581        // The engine still owns flow geometry; the next pass must restore it
4582        // even when the root layout cache is warm.
4583        self.layout_geometry_overridden = true;
4584        Ok(())
4585    }
4586
4587    /// Sets background color for a widget.
4588    pub fn set_background_color(&mut self, widget_id: WidgetId, color: Color) -> GuiResult<()> {
4589        let Some(spec) = self.widgets.get_mut(&widget_id) else {
4590            return Err(GuiError::WidgetNotFound(widget_id.0));
4591        };
4592
4593        let previous = spec.background_color;
4594        spec.background_color = Some(color);
4595        if let Err(error) = self.backend.set_background_color(widget_id, color) {
4596            if let Some(spec) = self.widgets.get_mut(&widget_id) {
4597                spec.background_color = previous;
4598            }
4599            return Err(error);
4600        }
4601        Ok(())
4602    }
4603
4604    /// Sets alert severity for an alert dialog widget.
4605    pub fn set_alert_level(&mut self, widget_id: WidgetId, level: AlertLevel) -> GuiResult<()> {
4606        let spec = self.require_property(widget_id, WidgetProperty::AlertLevel)?;
4607        let previous = spec.alert_level;
4608        spec.alert_level = Some(level);
4609        if let Err(error) = self.backend.set_alert_level(widget_id, level) {
4610            if let Some(spec) = self.widgets.get_mut(&widget_id) {
4611                spec.alert_level = previous;
4612            }
4613            return Err(error);
4614        }
4615        Ok(())
4616    }
4617
4618    /// Sets image source for an image widget.
4619    pub fn set_image_source(&mut self, widget_id: WidgetId, source: &str) -> GuiResult<()> {
4620        Self::reject_embedded_nul(source)?;
4621        let spec = self.require_property(widget_id, WidgetProperty::ImageSource)?;
4622        let previous = spec.image_source.clone();
4623        spec.image_source = Some(source.to_owned());
4624        if let Err(error) = self.backend.set_image_source(widget_id, source) {
4625            if let Some(spec) = self.widgets.get_mut(&widget_id) {
4626                spec.image_source = previous;
4627            }
4628            return Err(error);
4629        }
4630        Ok(())
4631    }
4632
4633    /// Reports bounded in-memory RGBA image-resource support on this backend.
4634    pub fn image_resource_capabilities(&self) -> ImageResourceCapabilities {
4635        self.backend.image_resource_capabilities()
4636    }
4637
4638    /// Loads validated RGBA8 pixels as a resource owned by this `Ui`.
4639    ///
4640    /// Image dimensions must be positive, the buffer must contain exactly
4641    /// four bytes per pixel, each image is limited to 64 MiB, and all live
4642    /// images together are limited to 256 MiB. Encoded formats and filesystem
4643    /// paths are not accepted.
4644    pub fn load_image_resource(&mut self, data: &ImageData) -> GuiResult<ImageResourceId> {
4645        data.validate()?;
4646        if !self.backend.image_resource_capabilities().rgba {
4647            return Err(GuiError::UnsupportedCapability(
4648                "image_resource_rgba".to_owned(),
4649            ));
4650        }
4651
4652        let bytes = data.byte_len();
4653        let total_bytes = checked_total_bytes(self.image_resource_bytes, bytes)?;
4654        let resource = ImageResourceId(self.next_image_resource_id);
4655        let next_id =
4656            self.next_image_resource_id
4657                .checked_add(1)
4658                .ok_or(GuiError::ResourceExhausted {
4659                    operation: "image resource id allocation",
4660                    code: None,
4661                })?;
4662
4663        self.backend.load_image_resource(resource, data)?;
4664        self.image_resources.insert(resource, bytes);
4665        self.image_resource_bytes = total_bytes;
4666        self.next_image_resource_id = next_id;
4667        Ok(resource)
4668    }
4669
4670    /// Returns whether `resource` is still live in this UI's registry.
4671    pub fn image_resource_is_live(&self, resource: ImageResourceId) -> bool {
4672        self.image_resources.contains_key(&resource)
4673    }
4674
4675    /// Releases a live image resource from its backend and this UI.
4676    ///
4677    /// Unknown and already-released identifiers return a deterministic
4678    /// backend error. A refused backend release leaves the UI registry intact.
4679    pub fn release_image_resource(&mut self, resource: ImageResourceId) -> GuiResult<()> {
4680        let bytes = self
4681            .image_resources
4682            .get(&resource)
4683            .copied()
4684            .ok_or_else(|| {
4685                GuiError::Backend(format!("Image resource not found: {}", resource.0))
4686            })?;
4687        if !self.backend.image_resource_capabilities().rgba {
4688            return Err(GuiError::UnsupportedCapability(
4689                "image_resource_rgba".to_owned(),
4690            ));
4691        }
4692
4693        self.backend.release_image_resource(resource)?;
4694        self.image_resources.remove(&resource);
4695        self.image_resource_bytes -= bytes;
4696        Ok(())
4697    }
4698
4699    /// Sets how an image scales into its bounds.
4700    ///
4701    /// Validates the widget kind, records the mode on the shared spec, then
4702    /// forwards to the backend so unsupported lanes report a typed error.
4703    pub fn set_image_fit(&mut self, widget_id: WidgetId, fit: ImageFit) -> GuiResult<()> {
4704        let spec = self.require_property(widget_id, WidgetProperty::ImageFit)?;
4705        let previous = spec.image_fit;
4706        spec.image_fit = fit;
4707        if let Err(error) = self.backend.set_image_fit(widget_id, fit) {
4708            if let Some(spec) = self.widgets.get_mut(&widget_id) {
4709                spec.image_fit = previous;
4710            }
4711            return Err(error);
4712        }
4713        Ok(())
4714    }
4715
4716    /// Sets what a `FileChooserDialog` lets the user pick.
4717    ///
4718    /// Validates the widget kind, records the mode on the shared spec, then
4719    /// forwards to the backend so an unsupported picker reports a typed
4720    /// error instead of showing the wrong dialog.
4721    pub fn set_file_chooser_mode(
4722        &mut self,
4723        widget_id: WidgetId,
4724        mode: FileChooserMode,
4725    ) -> GuiResult<()> {
4726        let spec = self.require_property(widget_id, WidgetProperty::FileChooserMode)?;
4727        let previous = spec.file_chooser_mode;
4728        spec.file_chooser_mode = mode;
4729        if let Err(error) = self.backend.set_file_chooser_mode(widget_id, mode) {
4730            if let Some(spec) = self.widgets.get_mut(&widget_id) {
4731                spec.file_chooser_mode = previous;
4732            }
4733            return Err(error);
4734        }
4735        Ok(())
4736    }
4737
4738    /// Sets the stock-art icon rendered beside a button's label.
4739    ///
4740    /// Validates the widget kind (`Button` and `FileChooserDialog`), records
4741    /// the role on the shared spec, then forwards to the backend, which
4742    /// resolves it through the portable art provider for the active theme;
4743    /// `None` clears the icon. Lanes that cannot render button art report
4744    /// the typed unsupported error instead of silently dropping the call.
4745    pub fn set_icon(&mut self, widget_id: WidgetId, icon: Option<IconRole>) -> GuiResult<()> {
4746        let spec = self.require_property(widget_id, WidgetProperty::ButtonIcon)?;
4747        let previous = spec.icon;
4748        spec.icon = icon;
4749        if let Err(error) = self.backend.set_icon(widget_id, icon) {
4750            if let Some(spec) = self.widgets.get_mut(&widget_id) {
4751                spec.icon = previous;
4752            }
4753            return Err(error);
4754        }
4755        Ok(())
4756    }
4757
4758    /// Sets the preferences of a colour-dialog widget.
4759    ///
4760    /// Validates the widget kind, applies the shared data rules (the
4761    /// [`crate::MAX_CUSTOM_COLORS`] palette cap), records the data on the
4762    /// shared spec, and forwards to the backend. Native lanes without a
4763    /// mapping for the chooser report the typed unsupported error from the
4764    /// backend default, so a caller never believes the preferences applied.
4765    pub fn set_color_dialog_data(
4766        &mut self,
4767        widget_id: WidgetId,
4768        data: ColorDialogData,
4769    ) -> GuiResult<()> {
4770        let spec = self.require_property(widget_id, WidgetProperty::ColorDialogData)?;
4771        data.validate()
4772            .map_err(|error| GuiError::Backend(error.to_string()))?;
4773
4774        let previous = spec.color_dialog_data.clone();
4775        spec.color_dialog_data = Some(data.clone());
4776        if let Err(error) = self.backend.set_color_dialog_data(widget_id, &data) {
4777            if let Some(spec) = self.widgets.get_mut(&widget_id) {
4778                spec.color_dialog_data = previous;
4779            }
4780            return Err(error);
4781        }
4782        Ok(())
4783    }
4784
4785    /// Sets the preferences of a font-dialog widget.
4786    ///
4787    /// Validates the widget kind and the shared data rules (finite,
4788    /// non-inverted size range), records the data on the shared spec, and
4789    /// forwards to the backend. Native lanes without a mapping for the
4790    /// chooser report the typed unsupported error from the backend default.
4791    pub fn set_font_dialog_data(
4792        &mut self,
4793        widget_id: WidgetId,
4794        data: FontDialogData,
4795    ) -> GuiResult<()> {
4796        let spec = self.require_property(widget_id, WidgetProperty::FontDialogData)?;
4797        data.validate()
4798            .map_err(|error| GuiError::Backend(error.to_string()))?;
4799
4800        let previous = spec.font_dialog_data.clone();
4801        spec.font_dialog_data = Some(data.clone());
4802        if let Err(error) = self.backend.set_font_dialog_data(widget_id, &data) {
4803            if let Some(spec) = self.widgets.get_mut(&widget_id) {
4804                spec.font_dialog_data = previous;
4805            }
4806            return Err(error);
4807        }
4808        Ok(())
4809    }
4810
4811    /// Replaces the rows of a toolbar widget.
4812    ///
4813    /// Validates the widget kind and the shared model rules (unique tool ids,
4814    /// radio groups anchored on a checkable owner) before anything is
4815    /// recorded, so a rejected list leaves the previous rows untouched. The
4816    /// accepted list is stored on the shared spec and forwarded to the
4817    /// backend; lanes without a native toolbar report the typed unsupported
4818    /// error (composes them).
4819    pub fn set_toolbar_items(
4820        &mut self,
4821        widget_id: WidgetId,
4822        items: Vec<ToolbarItem>,
4823    ) -> GuiResult<()> {
4824        let spec = self.require_property(widget_id, WidgetProperty::ToolbarItems)?;
4825        toolbar::validate_toolbar_items(&items)
4826            .map_err(|error| GuiError::Backend(error.to_string()))?;
4827
4828        let previous = spec.toolbar_items.clone();
4829        spec.toolbar_items = items.clone();
4830        if let Err(error) = self.backend.set_toolbar_items(widget_id, &items) {
4831            if let Some(spec) = self.widgets.get_mut(&widget_id) {
4832                spec.toolbar_items = previous;
4833            }
4834            return Err(error);
4835        }
4836        Ok(())
4837    }
4838
4839    /// Sets the stacking orientation of a toolbar widget.
4840    pub fn set_toolbar_orientation(
4841        &mut self,
4842        widget_id: WidgetId,
4843        orientation: ToolbarOrientation,
4844    ) -> GuiResult<()> {
4845        let spec = self.require_property(widget_id, WidgetProperty::ToolbarOrientation)?;
4846        let previous = spec.toolbar_orientation;
4847        spec.toolbar_orientation = orientation;
4848        if let Err(error) = self.backend.set_toolbar_orientation(widget_id, orientation) {
4849            if let Some(spec) = self.widgets.get_mut(&widget_id) {
4850                spec.toolbar_orientation = previous;
4851            }
4852            return Err(error);
4853        }
4854        Ok(())
4855    }
4856
4857    /// Applies a programmatic checked-state change to a toolbar tool.
4858    ///
4859    /// Radio exclusivity is enforced by the shared rules: checking a member
4860    /// unchecks the other members of its group. This is the programmatic
4861    /// path, so it never emits `ToolToggled`/`ToolActivated` events — the
4862    /// tools whose state actually changed are returned in toolbar order
4863    /// (empty for a no-op), which is what an application mirrors into its own
4864    /// model. Non-checkable tools report the typed model error.
4865    pub fn set_tool_state(
4866        &mut self,
4867        widget_id: WidgetId,
4868        tool_id: ToolId,
4869        checked: bool,
4870    ) -> GuiResult<Vec<(ToolId, bool)>> {
4871        let spec = self.require_property(widget_id, WidgetProperty::ToolbarItems)?;
4872        let mut updated_items = spec.toolbar_items.clone();
4873        let changes = toolbar::set_tool_state(&mut updated_items, tool_id, checked)
4874            .map_err(|error| GuiError::Backend(error.to_string()))?;
4875        if !changes.is_empty() {
4876            self.backend.set_toolbar_items(widget_id, &updated_items)?;
4877            if let Some(spec) = self.widgets.get_mut(&widget_id) {
4878                spec.toolbar_items = updated_items;
4879            }
4880        }
4881        Ok(changes)
4882    }
4883
4884    /// Patches one toolbar tool in place: label, tooltip, icon,
4885    /// display mode, enabled/visible state, and the dropdown flag.
4886    ///
4887    /// `checked` is deliberately not part of [`ToolUpdate`]; use
4888    /// [`Ui::set_tool_state`] so radio exclusivity and the silent-programmatic
4889    /// rule apply. The patched list is forwarded to the backend like
4890    /// [`Ui::set_toolbar_items`].
4891    pub fn update_tool(
4892        &mut self,
4893        widget_id: WidgetId,
4894        tool_id: ToolId,
4895        update: ToolUpdate,
4896    ) -> GuiResult<()> {
4897        let spec = self.require_property(widget_id, WidgetProperty::ToolbarItems)?;
4898        toolbar::apply_tool_update(&mut spec.toolbar_items, tool_id, &update)
4899            .map_err(|error| GuiError::Backend(error.to_string()))?;
4900        let items = spec.toolbar_items.clone();
4901        self.backend.set_toolbar_items(widget_id, &items)
4902    }
4903
4904    /// Sets the selected dates of a calendar widget.
4905    pub fn set_calendar_selected_dates(
4906        &mut self,
4907        widget_id: WidgetId,
4908        dates: &[CalendarDate],
4909    ) -> GuiResult<()> {
4910        {
4911            self.require_property(widget_id, WidgetProperty::CalendarDates)?;
4912            for date in dates {
4913                if !date.is_valid() {
4914                    return Err(GuiError::Backend(format!(
4915                        "Invalid calendar date: {}-{}-{}",
4916                        date.year, date.month, date.day
4917                    )));
4918                }
4919            }
4920        }
4921        self.backend.set_calendar_selected_dates(widget_id, dates)?;
4922        self.require_property(widget_id, WidgetProperty::CalendarDates)?
4923            .calendar_selected_dates = dates.to_vec();
4924        Ok(())
4925    }
4926
4927    /// Sets selectable date bounds for a calendar widget.
4928    pub fn set_calendar_bounds(
4929        &mut self,
4930        widget_id: WidgetId,
4931        min_date: Option<CalendarDate>,
4932        max_date: Option<CalendarDate>,
4933    ) -> GuiResult<()> {
4934        {
4935            self.require_property(widget_id, WidgetProperty::CalendarBounds)?;
4936            if let Some(min) = min_date {
4937                if !min.is_valid() {
4938                    return Err(GuiError::Backend(format!(
4939                        "Invalid minimum calendar date: {}-{}-{}",
4940                        min.year, min.month, min.day
4941                    )));
4942                }
4943            }
4944            if let Some(max) = max_date {
4945                if !max.is_valid() {
4946                    return Err(GuiError::Backend(format!(
4947                        "Invalid maximum calendar date: {}-{}-{}",
4948                        max.year, max.month, max.day
4949                    )));
4950                }
4951            }
4952            if let (Some(min), Some(max)) = (min_date, max_date) {
4953                if min > max {
4954                    return Err(GuiError::Backend(
4955                        "Minimum calendar date must not exceed maximum date".to_owned(),
4956                    ));
4957                }
4958            }
4959        }
4960        self.backend
4961            .set_calendar_bounds(widget_id, min_date, max_date)?;
4962        let spec = self.require_property(widget_id, WidgetProperty::CalendarBounds)?;
4963        spec.calendar_min_date = min_date;
4964        spec.calendar_max_date = max_date;
4965        Ok(())
4966    }
4967
4968    /// Sets the first day of the week convention for a calendar widget.
4969    pub fn set_calendar_first_day_of_week(
4970        &mut self,
4971        widget_id: WidgetId,
4972        first_day: CalendarFirstDayOfWeek,
4973    ) -> GuiResult<()> {
4974        self.require_property(widget_id, WidgetProperty::CalendarFirstDayOfWeek)?;
4975        self.backend
4976            .set_calendar_first_day_of_week(widget_id, first_day)?;
4977        self.require_property(widget_id, WidgetProperty::CalendarFirstDayOfWeek)?
4978            .calendar_first_day_of_week = first_day;
4979        Ok(())
4980    }
4981
4982    /// Sets the selection mode for a calendar widget.
4983    pub fn set_calendar_selection_mode(
4984        &mut self,
4985        widget_id: WidgetId,
4986        mode: CalendarSelectionMode,
4987    ) -> GuiResult<()> {
4988        self.require_property(widget_id, WidgetProperty::CalendarSelectionMode)?;
4989        self.backend.set_calendar_selection_mode(widget_id, mode)?;
4990        let spec = self.require_property(widget_id, WidgetProperty::CalendarSelectionMode)?;
4991        spec.calendar_selection_mode = mode;
4992        spec.calendar_selected_dates.clear();
4993        Ok(())
4994    }
4995
4996    /// Sets date value (`YYYY-MM-DD`) for a date picker widget.
4997    pub fn set_date_value(&mut self, widget_id: WidgetId, iso_date: &str) -> GuiResult<()> {
4998        let spec = self.require_property(widget_id, WidgetProperty::DateValue)?;
4999        let previous = spec.date_value.clone();
5000        spec.date_value = Some(iso_date.to_owned());
5001        if let Err(error) = self.backend.set_date_value(widget_id, iso_date) {
5002            if let Some(spec) = self.widgets.get_mut(&widget_id) {
5003                spec.date_value = previous;
5004            }
5005            return Err(error);
5006        }
5007        Ok(())
5008    }
5009
5010    /// Sets URL for a link label widget.
5011    pub fn set_link_url(&mut self, widget_id: WidgetId, url: &str) -> GuiResult<()> {
5012        let spec = self.require_property(widget_id, WidgetProperty::LinkUrl)?;
5013        let previous = spec.link_url.clone();
5014        spec.link_url = Some(url.to_owned());
5015        if let Err(error) = self.backend.set_link_url(widget_id, url) {
5016            if let Some(spec) = self.widgets.get_mut(&widget_id) {
5017                spec.link_url = previous;
5018            }
5019            return Err(error);
5020        }
5021        Ok(())
5022    }
5023
5024    /// Sets stacking direction for a container widget.
5025    pub fn set_container_direction(
5026        &mut self,
5027        widget_id: WidgetId,
5028        direction: ContainerDirection,
5029    ) -> GuiResult<()> {
5030        let spec = self.require_property(widget_id, WidgetProperty::ContainerDirection)?;
5031        let previous = spec.container_direction;
5032        spec.container_direction = Some(direction);
5033        if let Err(error) = self.backend.set_container_direction(widget_id, direction) {
5034            if let Some(spec) = self.widgets.get_mut(&widget_id) {
5035                spec.container_direction = previous;
5036            }
5037            return Err(error);
5038        }
5039        self.enable_auto_layout();
5040        // Keep the layout tree in sync so `compute_layout` agrees with the
5041        // native auto-layout direction (imperative and declarative authoring
5042        // must produce the same result).
5043        if let Some(&node) = self.layout_nodes.get(&widget_id) {
5044            if let Ok(mut style) = self.layout_tree.style(node).cloned() {
5045                style.flex_direction = match direction {
5046                    ContainerDirection::Horizontal => crate::layout::FlexDirection::Row,
5047                    ContainerDirection::Vertical => crate::layout::FlexDirection::Column,
5048                };
5049                let _ = self.layout_tree.set_style(node, style);
5050            }
5051        }
5052        // The children's natural-width rule follows the parent's direction,
5053        // so a direction change reschedules the subtree.
5054        self.invalidate_layout(widget_id);
5055        Ok(())
5056    }
5057
5058    /// Sets wrap behavior for a container widget (`Container`, `GroupBox`, `SplitPane`).
5059    pub fn set_container_wrap(
5060        &mut self,
5061        widget_id: WidgetId,
5062        wrap: ContainerWrap,
5063    ) -> GuiResult<()> {
5064        let spec = self.require_property(widget_id, WidgetProperty::ContainerWrap)?;
5065        let previous = spec.container_wrap;
5066        spec.container_wrap = Some(wrap);
5067        if let Err(error) = self.backend.set_container_wrap(widget_id, wrap) {
5068            if let Some(spec) = self.widgets.get_mut(&widget_id) {
5069                spec.container_wrap = previous;
5070            }
5071            return Err(error);
5072        }
5073        self.enable_auto_layout();
5074        if let Some(&node) = self.layout_nodes.get(&widget_id) {
5075            if let Ok(mut style) = self.layout_tree.style(node).cloned() {
5076                style.flex_wrap = match wrap {
5077                    ContainerWrap::NoWrap => crate::layout::FlexWrap::NoWrap,
5078                    ContainerWrap::Wrap => crate::layout::FlexWrap::Wrap,
5079                    ContainerWrap::WrapReverse => crate::layout::FlexWrap::WrapReverse,
5080                };
5081                let _ = self.layout_tree.set_style(node, style);
5082            }
5083        }
5084        self.invalidate_layout(widget_id);
5085        Ok(())
5086    }
5087
5088    /// Creates a flow container with horizontal direction, wrapping enabled,
5089    /// and the specified uniform gap between children (`Container`).
5090    pub fn create_flow_container(
5091        &mut self,
5092        parent: Option<WidgetId>,
5093        gap: i32,
5094    ) -> GuiResult<WidgetId> {
5095        let id = self.create(WidgetKind::Container, None)?;
5096        self.set_container_direction(id, ContainerDirection::Horizontal)?;
5097        self.set_container_wrap(id, ContainerWrap::Wrap)?;
5098        self.set_container_gap(id, gap)?;
5099        if let Some(p) = parent {
5100            self.attach(p, id)?;
5101        }
5102        Ok(id)
5103    }
5104
5105    /// Sets the uniform spacing between a flow container's children, in
5106    /// logical pixels (`Container`, `GroupBox`). Negative values clamp to 0.
5107    ///
5108    /// The shared model keeps the layout tree in sync (both axes) so
5109    /// `compute_layout` and the native auto-layout agree, mirroring
5110    /// [`Ui::set_container_direction`]. Lanes that position children through
5111    /// the computed layout honour this directly; lanes with native boxes map
5112    /// it to their own spacing (GTK box `spacing`).
5113    pub fn set_container_gap(&mut self, widget_id: WidgetId, gap: i32) -> GuiResult<()> {
5114        let spec = self.require_property(widget_id, WidgetProperty::ContainerGap)?;
5115        let previous = spec.container_gap;
5116        let gap = gap.max(0);
5117        spec.container_gap = Some(gap);
5118        self.enable_auto_layout();
5119        if let Some(&node) = self.layout_nodes.get(&widget_id) {
5120            if let Ok(mut style) = self.layout_tree.style(node).cloned() {
5121                let length = crate::layout::LengthPercentage::length(gap as f32);
5122                style.gap = crate::layout::Size {
5123                    width: length,
5124                    height: length,
5125                };
5126                let _ = self.layout_tree.set_style(node, style);
5127            }
5128        }
5129        if let Err(error) = self.backend.set_container_gap(widget_id, gap) {
5130            if let Some(spec) = self.widgets.get_mut(&widget_id) {
5131                spec.container_gap = previous;
5132            }
5133            if let Some(&node) = self.layout_nodes.get(&widget_id) {
5134                if let Ok(mut style) = self.layout_tree.style(node).cloned() {
5135                    let prev_gap = previous.unwrap_or(0);
5136                    let length = crate::layout::LengthPercentage::length(prev_gap as f32);
5137                    style.gap = crate::layout::Size {
5138                        width: length,
5139                        height: length,
5140                    };
5141                    let _ = self.layout_tree.set_style(node, style);
5142                }
5143            }
5144            return Err(error);
5145        }
5146        Ok(())
5147    }
5148
5149    /// Sets the uniform inset between a flow container's edges and its flow
5150    /// children, in logical pixels (`Container`, `GroupBox`). Negative values
5151    /// clamp to 0.
5152    pub fn set_container_padding(&mut self, widget_id: WidgetId, padding: i32) -> GuiResult<()> {
5153        let spec = self.require_property(widget_id, WidgetProperty::ContainerPadding)?;
5154        let previous = spec.container_padding;
5155        let padding = padding.max(0);
5156        spec.container_padding = Some(padding);
5157        self.enable_auto_layout();
5158        if let Some(&node) = self.layout_nodes.get(&widget_id) {
5159            if let Ok(mut style) = self.layout_tree.style(node).cloned() {
5160                let length = crate::layout::LengthPercentage::length(padding as f32);
5161                style.padding = crate::layout::Rect {
5162                    left: length,
5163                    right: length,
5164                    top: length,
5165                    bottom: length,
5166                };
5167                let _ = self.layout_tree.set_style(node, style);
5168            }
5169        }
5170        if let Err(error) = self.backend.set_container_padding(widget_id, padding) {
5171            if let Some(spec) = self.widgets.get_mut(&widget_id) {
5172                spec.container_padding = previous;
5173            }
5174            if let Some(&node) = self.layout_nodes.get(&widget_id) {
5175                if let Ok(mut style) = self.layout_tree.style(node).cloned() {
5176                    let prev_pad = previous.unwrap_or(0);
5177                    let length = crate::layout::LengthPercentage::length(prev_pad as f32);
5178                    style.padding = crate::layout::Rect {
5179                        left: length,
5180                        right: length,
5181                        top: length,
5182                        bottom: length,
5183                    };
5184                    let _ = self.layout_tree.set_style(node, style);
5185                }
5186            }
5187            return Err(error);
5188        }
5189        Ok(())
5190    }
5191
5192    /// Sets scroll configuration for a container widget.
5193    pub fn set_container_scroll(
5194        &mut self,
5195        widget_id: WidgetId,
5196        vertical: bool,
5197        horizontal: bool,
5198    ) -> GuiResult<()> {
5199        let spec = self.require_property(widget_id, WidgetProperty::ContainerScroll)?;
5200        let previous_vert = spec.container_scroll_vertical;
5201        let previous_horiz = spec.container_scroll_horizontal;
5202        spec.container_scroll_vertical = vertical;
5203        spec.container_scroll_horizontal = horizontal;
5204        if let Err(error) = self
5205            .backend
5206            .set_container_scroll(widget_id, vertical, horizontal)
5207        {
5208            if let Some(spec) = self.widgets.get_mut(&widget_id) {
5209                spec.container_scroll_vertical = previous_vert;
5210                spec.container_scroll_horizontal = previous_horiz;
5211            }
5212            return Err(error);
5213        }
5214        Ok(())
5215    }
5216
5217    /// Draws the built-in colored cube demo into a `WidgetKind::VulkanCanvas`.
5218    pub fn draw_demo_cube(&mut self, widget_id: WidgetId) -> GuiResult<()> {
5219        self.widget_spec(widget_id)?
5220            .ensure_property(WidgetProperty::DrawDemoCube)?;
5221        self.backend.draw_demo_cube(widget_id)
5222    }
5223
5224    fn enable_auto_layout(&mut self) {
5225        self.auto_layout_fn = Some(Self::compute_layout);
5226    }
5227
5228    /// Computes and applies layout for `root_id`.
5229    ///
5230    /// The pass is bounded by the strict topological dirty flags maintained
5231    /// by `invalidate_layout`: only the scheduled branches are re-seeded,
5232    /// clean branches keep their layout caches and are never re-measured, and
5233    /// native geometry is written only for widgets whose computed values
5234    /// changed. An unchanged pass performs no measurements and no writes
5235    /// while still applying any layout the tree reports as changed.
5236    pub fn compute_layout(&mut self, root_id: WidgetId, width: f32, height: f32) -> GuiResult<()> {
5237        self.enable_auto_layout();
5238        let Some(root_owned_node) = self.layout_nodes.get(&root_id).copied() else {
5239            return Err(GuiError::WidgetNotFound(root_id.0));
5240        };
5241        if self.layout_roots.contains(&root_id) {
5242            self.layout_root_sizes.insert(root_id, (width, height));
5243        }
5244
5245        let root_width = crate::layout::Dimension::length(width);
5246        let root_height = crate::layout::Dimension::length(height);
5247        if let Ok(mut style) = self.layout_tree.style(root_owned_node).cloned() {
5248            if style.size.width != root_width || style.size.height != root_height {
5249                style.size.width = root_width;
5250                style.size.height = root_height;
5251                let _ = self.layout_tree.set_style(root_owned_node, style);
5252            }
5253        }
5254
5255        if self
5256            .widgets
5257            .get(&root_id)
5258            .is_some_and(|spec| spec.kind == WidgetKind::Window)
5259        {
5260            if let Ok(mut root_style) = self.layout_tree.style(root_owned_node).cloned() {
5261                // Value-guard the normalization: rewriting an unchanged style
5262                // bumps `style_revision` and re-dirties the root, which would
5263                // defeat the layout cache on every pass.
5264                if root_style.align_items != Some(crate::layout::AlignItems::Stretch) {
5265                    root_style.align_items = Some(crate::layout::AlignItems::Stretch);
5266                    let _ = self.layout_tree.set_style(root_owned_node, root_style);
5267                }
5268            }
5269            let children: Vec<LayoutNodeId> = self
5270                .layout_tree
5271                .children(root_owned_node)
5272                .map(|c| c.to_vec())
5273                .unwrap_or_default();
5274            for child in children {
5275                // Check before cloning: most children are already normalized,
5276                // and a 10k-child window would otherwise clone 10k Styles
5277                // (304 B each) on every pass.
5278                let needs_normalizing = self.layout_tree.style(child).is_ok_and(|style| {
5279                    style.size.width == crate::layout::Dimension::Auto
5280                        && style.size.height == crate::layout::Dimension::Auto
5281                        && style.flex_grow == 0.0
5282                });
5283                if !needs_normalizing {
5284                    continue;
5285                }
5286                if let Ok(mut style) = self.layout_tree.style(child).cloned() {
5287                    style.flex_grow = 1.0;
5288                    style.align_self = Some(crate::layout::AlignSelf::Stretch);
5289                    style.min_size.width = crate::layout::Dimension::length(0.0);
5290                    style.min_size.height = crate::layout::Dimension::length(0.0);
5291                    let _ = self.layout_tree.set_style(child, style);
5292                }
5293            }
5294        }
5295
5296        let scheduled: Vec<WidgetId> = std::mem::take(&mut self.layout_dirty).into_iter().collect();
5297        let mut pending: std::collections::HashSet<WidgetId> = std::collections::HashSet::new();
5298        for widget_id in scheduled {
5299            if self.chain_reaches_root(widget_id, root_id) {
5300                pending.insert(widget_id);
5301            } else {
5302                self.layout_dirty.insert(widget_id);
5303            }
5304        }
5305        if !pending.is_empty() {
5306            let boundaries: Vec<WidgetId> = pending
5307                .iter()
5308                .copied()
5309                .filter(|widget_id| !self.has_scheduled_ancestor(*widget_id, &pending))
5310                .collect();
5311            for branch_root in boundaries {
5312                self.seed_branch(branch_root, root_id);
5313            }
5314        }
5315
5316        let available_space = crate::layout::Size {
5317            width: crate::layout::AvailableSpace::Definite(width),
5318            height: crate::layout::AvailableSpace::Definite(height),
5319        };
5320
5321        let cache_hits_before = self.layout_tree.metrics().cache_hits;
5322        if let Err(err) = self
5323            .layout_tree
5324            .compute_layout(root_owned_node, available_space)
5325        {
5326            self.layout_dirty.extend(pending);
5327            return Err(err);
5328        }
5329
5330        // A root cache hit means no style or measurement revision in the
5331        // subtree changed, so the cached geometry is already applied: skip
5332        // the whole-tree write-back scan unless an
5333        // imperative `set_position` left a spec position the engine owns.
5334        if self.layout_tree.metrics().cache_hits == cache_hits_before
5335            || self.layout_geometry_overridden
5336        {
5337            let mut widget_updates: Vec<LayoutUpdate> = Vec::new();
5338            for (id, node) in &self.layout_nodes {
5339                if *id == root_id {
5340                    continue;
5341                }
5342                if let Ok(layout) = self.layout_tree.layout(*node) {
5343                    let layout = self.parent_local_layout_rect(*id, layout)?;
5344                    let is_hidden = self.is_effectively_hidden(*id);
5345                    let (w, h) = if is_hidden {
5346                        (0, 0)
5347                    } else {
5348                        (layout.width as i32, layout.height as i32)
5349                    };
5350                    let (x, y) = (layout.x as i32, layout.y as i32);
5351                    let spec = self.widgets.get(id);
5352                    let size_changed = if is_hidden {
5353                        spec.is_some_and(|spec| spec.size != Some((0, 0)))
5354                    } else {
5355                        w > 0 && h > 0 && spec.is_some_and(|spec| spec.size != Some((w, h)))
5356                    };
5357                    let position_changed =
5358                        !is_hidden && spec.is_some_and(|spec| spec.position != Some((x, y)));
5359                    if size_changed || position_changed {
5360                        widget_updates.push((
5361                            *id,
5362                            size_changed.then_some((w, h)),
5363                            position_changed.then_some((x, y)),
5364                        ));
5365                    }
5366                }
5367            }
5368            // Native coordinate conversion can depend on the parent's current size.
5369            self.sort_layout_updates_parent_first(&mut widget_updates);
5370            for (id, size, position) in widget_updates {
5371                if let Some((w, h)) = size {
5372                    let (expand_width, expand_height) = self.computed_layout_expansion(id);
5373                    self.apply_computed_size(id, w, h, expand_width, expand_height);
5374                }
5375                if let Some((x, y)) = position {
5376                    self.apply_computed_position(id, x, y);
5377                }
5378            }
5379            self.layout_geometry_overridden = false;
5380        }
5381        Ok(())
5382    }
5383
5384    fn sort_layout_updates_parent_first(&self, updates: &mut [LayoutUpdate]) {
5385        // `sort_by_cached_key` computes each depth once instead of walking
5386        // the parent chain on every comparison. Tie-break by
5387        // `widget_id.0` so sibling order (such as `SplitPane` panes) never
5388        // depends on `HashMap` iteration order.
5389        updates.sort_by_cached_key(|(widget_id, _, _)| {
5390            let mut depth = 0;
5391            let mut parent = self.widgets.get(widget_id).and_then(|spec| spec.parent);
5392            while let Some(parent_id) = parent {
5393                depth += 1;
5394                parent = self.widgets.get(&parent_id).and_then(|spec| spec.parent);
5395            }
5396            (depth, widget_id.0)
5397        });
5398    }
5399
5400    /// Schedules a widget's branch for style seeding at the next layout pass.
5401    ///
5402    /// The propagation is strictly topological: the parent chain is walked
5403    /// only until an ancestor is already scheduled for a subtree recompute
5404    /// (that branch subsumes this widget), so one invalidation costs `O(D)`
5405    /// parent hops in the depth of the invalidated branch - never a
5406    /// whole-tree scan - and the schedule stays ancestor-free. Clean
5407    /// branches keep their layout caches, seeded leaf styles, and applied
5408    /// geometry.
5409    fn invalidate_layout(&mut self, widget_id: WidgetId) {
5410        let mut cursor = Some(widget_id);
5411        while let Some(id) = cursor {
5412            if self.layout_dirty.contains(&id) {
5413                return;
5414            }
5415            cursor = self.widgets.get(&id).and_then(|spec| spec.parent);
5416        }
5417        self.layout_dirty.insert(widget_id);
5418    }
5419
5420    /// Pins an app-requested size into the widget's layout style.
5421    ///
5422    /// [`Self::set_size`] and creation-time `spec.size` requests take this
5423    /// path so `compute_layout` and the native auto-layout agree, and
5424    /// `seed_branch` stops re-seeding a natural size over the request (an
5425    /// explicit axis is never `auto`). Value-guarded so a no-op never
5426    /// clears layout caches.
5427    fn sync_layout_size(&mut self, widget_id: WidgetId, width: i32, height: i32) {
5428        if let Some(&node) = self.layout_nodes.get(&widget_id) {
5429            if let Ok(mut style) = self.layout_tree.style(node).cloned() {
5430                let size = crate::layout::Size {
5431                    width: crate::layout::Dimension::length(width as f32),
5432                    height: crate::layout::Dimension::length(height as f32),
5433                };
5434                if style.size != size {
5435                    style.size = size;
5436                    let _ = self.layout_tree.set_style(node, style);
5437                }
5438            }
5439        }
5440    }
5441
5442    /// Applies one layout pass's computed size to the spec and the backend
5443    /// without re-pinning layout styles.
5444    ///
5445    /// Computed geometry is pass output, not an app request: routing it
5446    /// through [`Self::set_size`] would pin it into the layout style and stop
5447    /// auto axes from being re-seeded with natural sizes on later passes.
5448    fn apply_computed_size(
5449        &mut self,
5450        widget_id: WidgetId,
5451        width: i32,
5452        height: i32,
5453        expand_width: bool,
5454        expand_height: bool,
5455    ) {
5456        let Some(spec) = self.widgets.get_mut(&widget_id) else {
5457            return;
5458        };
5459        spec.size = Some((width, height));
5460        let _ = self
5461            .backend
5462            .set_layout_size(widget_id, width, height, expand_width, expand_height);
5463    }
5464
5465    fn apply_computed_position(&mut self, widget_id: WidgetId, x: i32, y: i32) {
5466        let Some(spec) = self.widgets.get_mut(&widget_id) else {
5467            return;
5468        };
5469        spec.position = Some((x, y));
5470        let _ = self.backend.set_layout_position(widget_id, x, y);
5471    }
5472
5473    fn computed_layout_expansion(&self, widget_id: WidgetId) -> (bool, bool) {
5474        let Some(&node) = self.layout_nodes.get(&widget_id) else {
5475            return (false, false);
5476        };
5477        let Ok(style) = self.layout_tree.style(node) else {
5478            return (false, false);
5479        };
5480        let Ok(Some(parent)) = self.layout_tree.parent(node) else {
5481            return (false, false);
5482        };
5483        let Ok(parent_style) = self.layout_tree.style(parent) else {
5484            return (false, false);
5485        };
5486        let horizontal_main_axis = matches!(
5487            parent_style.flex_direction,
5488            crate::layout::FlexDirection::Row | crate::layout::FlexDirection::RowReverse
5489        );
5490        let cross_axis_stretches = style
5491            .align_self
5492            .or_else(|| {
5493                parent_style
5494                    .align_items
5495                    .map(crate::layout::flex::to_align_self)
5496            })
5497            .unwrap_or(crate::layout::AlignSelf::Stretch)
5498            == crate::layout::AlignSelf::Stretch;
5499        let width_auto = style.size.width == crate::layout::Dimension::Auto;
5500        let height_auto = style.size.height == crate::layout::Dimension::Auto;
5501        let grow = style.flex_grow > 0.0;
5502        let expand_width = matches!(style.size.width, crate::layout::Dimension::Percent(_))
5503            || (horizontal_main_axis && grow)
5504            || (!horizontal_main_axis && width_auto && cross_axis_stretches);
5505        let expand_height = matches!(style.size.height, crate::layout::Dimension::Percent(_))
5506            || (!horizontal_main_axis && grow)
5507            || (horizontal_main_axis && height_auto && cross_axis_stretches);
5508        (expand_width, expand_height)
5509    }
5510
5511    /// Whether `widget_id` lies inside the subtree of `root_id` (following
5512    /// parent links), deciding which scheduled branches a pass consumes.
5513    fn chain_reaches_root(&self, widget_id: WidgetId, root_id: WidgetId) -> bool {
5514        let mut cursor = Some(widget_id);
5515        while let Some(id) = cursor {
5516            if id == root_id {
5517                return true;
5518            }
5519            cursor = self.widgets.get(&id).and_then(|spec| spec.parent);
5520        }
5521        false
5522    }
5523
5524    /// Whether an ancestor of `widget_id` is already in the scheduled set,
5525    /// so its subtree walk subsumes this widget.
5526    fn has_scheduled_ancestor(
5527        &self,
5528        widget_id: WidgetId,
5529        scheduled: &std::collections::HashSet<WidgetId>,
5530    ) -> bool {
5531        let mut cursor = self.widgets.get(&widget_id).and_then(|spec| spec.parent);
5532        while let Some(id) = cursor {
5533            if scheduled.contains(&id) {
5534                return true;
5535            }
5536            cursor = self.widgets.get(&id).and_then(|spec| spec.parent);
5537        }
5538        false
5539    }
5540
5541    /// Applies the pass's style seeding to one scheduled branch.
5542    ///
5543    /// The rules are the ones the earlier whole-tree sweep used: every
5544    /// non-root node's `min_size` resets to zero (those natural sizes stay a
5545    /// shrinkable basis, so rows compress to the window instead of
5546    /// overflowing it), and a leaf's natural size is seeded for the axes
5547    /// whose styles are still automatic - heights always, widths only in row
5548    /// parents so a leaf in a column still stretches across the column.
5549    /// Backend measurement is skipped when no axis would take a value, and
5550    /// every style write is value-guarded so a no-op never clears layout
5551    /// caches.
5552    fn seed_branch(&mut self, branch_root: WidgetId, layout_root: WidgetId) {
5553        let mut stack = vec![branch_root];
5554        // Visible row containers in visit (pre-) order and the nodes that
5555        // got a quantized-lane floor; see the pass after the loop.
5556        let mut row_containers = Vec::new();
5557        let mut floored = HashSet::new();
5558        while let Some(id) = stack.pop() {
5559            if let Some(children) = self.children_index.get(&id) {
5560                stack.extend(children.iter().copied());
5561            }
5562            if id == layout_root {
5563                continue;
5564            }
5565            let Some(&node) = self.layout_nodes.get(&id) else {
5566                continue;
5567            };
5568            let is_leaf = self
5569                .layout_tree
5570                .children(node)
5571                .map(|children| children.is_empty())
5572                .unwrap_or(true);
5573            let Ok(style) = self.layout_tree.style(node).cloned() else {
5574                continue;
5575            };
5576            // A leaf's natural width is seeded only in a row parent - the
5577            // same rule the old parent-direction map applied.
5578            let parent_row = self
5579                .layout_tree
5580                .parent(node)
5581                .ok()
5582                .flatten()
5583                .and_then(|parent| self.layout_tree.style(parent).ok())
5584                .is_some_and(|style| {
5585                    matches!(
5586                        style.flex_direction,
5587                        crate::layout::FlexDirection::Row
5588                            | crate::layout::FlexDirection::RowReverse
5589                    )
5590                });
5591            let is_hidden = self.is_effectively_hidden(id);
5592            // A SplitPane pane fills its pane on both axes, so its natural
5593            // size is never pinned (found while dogfooding).
5594            #[cfg(feature = "widgets-containers")]
5595            let in_split_pane = self
5596                .widgets
5597                .get(&id)
5598                .and_then(|spec| spec.parent)
5599                .and_then(|parent| self.widgets.get(&parent))
5600                .is_some_and(|parent| parent.kind == WidgetKind::SplitPane);
5601            #[cfg(not(feature = "widgets-containers"))]
5602            let in_split_pane = false;
5603            let is_intrinsic_control = self.widgets.get(&id).is_some_and(|spec| match spec.kind {
5604                WidgetKind::Button => true,
5605                #[cfg(feature = "widgets-pickers")]
5606                WidgetKind::DatePicker => true,
5607                #[cfg(feature = "widgets-choice")]
5608                WidgetKind::Checkbox | WidgetKind::RadioButton => true,
5609                #[cfg(feature = "widgets-range")]
5610                WidgetKind::SpinBox => true,
5611                _ => false,
5612            });
5613            let is_toolbar = self
5614                .widgets
5615                .get(&id)
5616                .is_some_and(|spec| spec.kind == WidgetKind::Toolbar);
5617            let wants_width = !in_split_pane
5618                && (parent_row || is_intrinsic_control)
5619                && style.size.width == crate::layout::Dimension::Auto;
5620            let wants_height =
5621                !in_split_pane && style.size.height == crate::layout::Dimension::Auto;
5622            let natural = if !is_hidden && is_leaf && (wants_width || wants_height || is_toolbar) {
5623                self.backend.natural_size(id)
5624            } else {
5625                None
5626            };
5627            let is_chrome_toolbar = !is_hidden && is_toolbar && matches!(natural, Some((_, 0)));
5628            let mut next = style;
5629            let mut changed = false;
5630            let expected_display = if is_hidden || is_chrome_toolbar {
5631                crate::layout::Display::None
5632            } else {
5633                crate::layout::Display::Flex
5634            };
5635            if next.display != expected_display {
5636                next.display = expected_display;
5637                changed = true;
5638            }
5639            // App minimums (`set_min_size`) and preferred width (`set_preferred_width`) survive the
5640            // reset.
5641            let (app_min_width, app_min_height) =
5642                self.min_sizes.get(&id).copied().unwrap_or((0, 0));
5643            let min_width = if let Some(&pref_w) = self.preferred_widths.get(&id) {
5644                pref_w as f32
5645            } else {
5646                app_min_width as f32
5647            };
5648            // Quantized lanes (TUI) keep a visible leaf at least as large as
5649            // its paint unit, so compression never overprints (r6b review).
5650            // An explicit app size caps the floor: the floor only stops the
5651            // pass compressing a leaf below what it asked for.
5652            let compressed_floor = if is_leaf && !is_hidden {
5653                self.backend.min_compressed_size(id).map(|(w, h)| {
5654                    let cap = |floor: i32, dim: crate::layout::Dimension| match dim {
5655                        crate::layout::Dimension::Length(px) => floor.min(px.max(0.0) as i32),
5656                        _ => floor,
5657                    };
5658                    (cap(w, next.size.width), cap(h, next.size.height))
5659                })
5660            } else {
5661                None
5662            };
5663            // Only button rows (toolbars, action rows) propagate: a button
5664            // paints as one block and vanishes when its row is clipped,
5665            // while a label/field row compresses gracefully.
5666            if compressed_floor.is_some()
5667                && self.widgets.get(&id).map(|spec| spec.kind) == Some(WidgetKind::Button)
5668            {
5669                floored.insert(node);
5670            }
5671            if !is_leaf
5672                && !is_hidden
5673                && matches!(
5674                    next.flex_direction,
5675                    crate::layout::FlexDirection::Row | crate::layout::FlexDirection::RowReverse
5676                )
5677            {
5678                row_containers.push(node);
5679            }
5680            let min_width = match compressed_floor {
5681                Some((floor, _)) if parent_row && !in_split_pane => {
5682                    min_width.max(floor.max(0) as f32)
5683                }
5684                _ => min_width,
5685            };
5686            let owned_min_w = crate::layout::Dimension::length(min_width);
5687            if next.min_size.width != owned_min_w {
5688                next.min_size.width = owned_min_w;
5689                changed = true;
5690            }
5691            #[cfg(feature = "widgets-containers")]
5692            let is_tabs = self.widgets.get(&id).map(|s| s.kind) == Some(WidgetKind::Tabs);
5693            #[cfg(not(feature = "widgets-containers"))]
5694            let is_tabs = false;
5695
5696            if self.preferred_widths.contains_key(&id) && app_min_height == 0 && !is_tabs {
5697                if next.min_size.height != crate::layout::Dimension::Auto {
5698                    next.min_size.height = crate::layout::Dimension::Auto;
5699                    changed = true;
5700                }
5701            } else {
5702                let min_height = if is_tabs {
5703                    self.min_tabs_height(id)
5704                } else {
5705                    0.0
5706                }
5707                .max(app_min_height as f32);
5708                // Quantized lanes (TUI) keep a visible leaf at least as tall
5709                // as their paint unit, so compression never overprints.
5710                let min_height = match compressed_floor {
5711                    Some((_, floor)) => min_height.max(floor.max(0) as f32),
5712                    None => min_height,
5713                };
5714                let owned_min_h = crate::layout::Dimension::length(min_height);
5715                if next.min_size.height != owned_min_h {
5716                    next.min_size.height = owned_min_h;
5717                    changed = true;
5718                }
5719            }
5720            if let Some((natural_width, natural_height)) = natural {
5721                if wants_width {
5722                    next.size.width = crate::layout::Dimension::length(natural_width as f32);
5723                    changed = true;
5724                }
5725                if wants_height {
5726                    next.size.height = crate::layout::Dimension::length(natural_height as f32);
5727                    changed = true;
5728                }
5729            }
5730            if changed {
5731                let _ = self.layout_tree.set_style(node, next);
5732            }
5733        }
5734        // A row of buttons (a toolbar, an action row) must not be compressed
5735        // below its tallest button's floor plus its vertical padding, or the
5736        // quantized painter clips the whole row away (r7: the TUI Text
5737        // Editor toolbar went blank). Only direct button children count, so
5738        // the floor never spreads to the rows that contain a toolbar.
5739        for node in row_containers.into_iter().rev() {
5740            let Ok(children) = self.layout_tree.children(node).map(|c| c.to_vec()) else {
5741                continue;
5742            };
5743            let mut tallest = None::<f32>;
5744            for child in children {
5745                if !floored.contains(&child) {
5746                    continue;
5747                }
5748                if let Ok(style) = self.layout_tree.style(child) {
5749                    if let crate::layout::Dimension::Length(h) = style.min_size.height {
5750                        tallest = Some(tallest.unwrap_or(0.0).max(h));
5751                    }
5752                }
5753            }
5754            let Some(tallest) = tallest else {
5755                continue;
5756            };
5757            let Ok(mut style) = self.layout_tree.style(node).cloned() else {
5758                continue;
5759            };
5760            let pad = |value: crate::layout::LengthPercentage| match value {
5761                crate::layout::LengthPercentage::Length(px) => px.max(0.0),
5762                crate::layout::LengthPercentage::Percent(_) => 0.0,
5763            };
5764            let mut floor = tallest + pad(style.padding.top) + pad(style.padding.bottom);
5765            if let crate::layout::Dimension::Length(px) = style.size.height {
5766                floor = floor.min(px.max(0.0));
5767            }
5768            let current = match style.min_size.height {
5769                crate::layout::Dimension::Length(px) => px,
5770                _ => 0.0,
5771            };
5772            if floor > current {
5773                style.min_size.height = crate::layout::Dimension::length(floor);
5774                let _ = self.layout_tree.set_style(node, style);
5775            }
5776        }
5777    }
5778
5779    /// Attaches `child` beneath `parent` in the UI tree.
5780    ///
5781    /// # Contract (Pre / Post / Inv)
5782    ///
5783    /// - **Pre:** both ids are live and attaching does not close a parent
5784    ///   cycle (self-parentage counts as a one-node cycle).
5785    /// - **Post:** `child`'s parent pointer is `parent` and the backend
5786    ///   mirror was asked to attach the same pair. On any error the shared
5787    ///   model is untouched, so a refused call never leaves a partial edge.
5788    /// - **Inv:** parent links stay acyclic. `Ui::remove` cascades and
5789    ///   `focus_chain_enabled` walks rely on this to terminate.
5790    ///   Depth is bounded by the layout engine (`MAX_LAYOUT_DEPTH = 128`).
5791    ///   Attaching a leaf child short-circuits cycle validation in O(1);
5792    ///   attaching an internal subtree walks ancestors in O(depth).
5793    pub fn attach(&mut self, parent: WidgetId, child: WidgetId) -> GuiResult<()> {
5794        if !self.widgets.contains_key(&parent) {
5795            return Err(GuiError::WidgetNotFound(parent.0));
5796        }
5797        if !self.widgets.contains_key(&child) {
5798            return Err(GuiError::WidgetNotFound(child.0));
5799        }
5800        if self.creates_parent_cycle(child, parent) {
5801            return Err(GuiError::Backend(
5802                "cannot create a widget parent cycle".to_owned(),
5803            ));
5804        }
5805        if self.widget_depth(parent) + self.widget_subtree_height(child)
5806            >= crate::layout::box_sizing::MAX_LAYOUT_DEPTH
5807        {
5808            return Err(GuiError::Backend(
5809                "maximum layout recursion depth exceeded".to_string(),
5810            ));
5811        }
5812
5813        // Attach natively first: a lane that refuses (an invalid parent kind,
5814        // a lost native handle) must leave the shared model untouched, so the
5815        // app can retry or reparent without a phantom edge.
5816        self.backend.add_child(parent, child)?;
5817        self.record_parent_edge(parent, child);
5818        Ok(())
5819    }
5820
5821    /// Rolls back a widget whose creation-time attachment the backend
5822    /// refused, so a failed create leaves no phantom widget in the model.
5823    fn discard_failed_create(&mut self, id: WidgetId) {
5824        let _ = self.backend.remove(id);
5825        if let Some(node) = self.layout_nodes.remove(&id) {
5826            let _ = self.layout_tree.remove_node(node);
5827        }
5828        self.widgets.remove(&id);
5829        self.gpu_degraded.remove(&id);
5830        self.layout_dirty.remove(&id);
5831        self.hidden_widgets.remove(&id);
5832    }
5833
5834    /// Records an already-attached parent edge in the shared model and layout
5835    /// tree, then schedules the child's branch for style seeding.
5836    ///
5837    /// Used after the backend accepted the attachment, so the model never
5838    /// claims an edge the lane refused.
5839    fn record_parent_edge(&mut self, parent: WidgetId, child: WidgetId) {
5840        // Move the child's edge in the adjacency index: release the previous
5841        // parent's entry before recording the new one, so re-attaching or
5842        // moving a widget never leaves a stale or duplicated edge.
5843        if let Some(previous) = self.widgets.get(&child).and_then(|spec| spec.parent) {
5844            self.detach_child_edge(previous, child);
5845        }
5846
5847        if let Some(child_spec) = self.widgets.get_mut(&child) {
5848            child_spec.parent = Some(parent);
5849        }
5850        self.children_index.entry(parent).or_default().push(child);
5851        if let (Some(&parent_node), Some(&child_node)) = (
5852            self.layout_nodes.get(&parent),
5853            self.layout_nodes.get(&child),
5854        ) {
5855            let _ = self.layout_tree.attach_child(parent_node, child_node);
5856        }
5857        #[cfg(feature = "widgets-containers")]
5858        if self.widgets.get(&parent).map(|spec| spec.kind) == Some(WidgetKind::Tabs) {
5859            self.style_tab_page(child);
5860        }
5861        // The new parent's direction can wake an auto axis of the child's
5862        // leaves.
5863        self.invalidate_layout(child);
5864    }
5865
5866    /// Lays a `Tabs` page out at the full width of its `Tabs`.
5867    ///
5868    /// Only one page is visible at a time, but the shared layout tree keeps
5869    /// every page as a flex child of the `Tabs` row. With the default style
5870    /// the pages split the width between them and shrank to fit, and lanes
5871    /// that draw page content from the computed geometry (TUI, and the
5872    /// children of Win32's natively sized pages) squeezed every control onto
5873    /// the first few rows: overprinted checkboxes in the Preferences General
5874    /// tab. Each page now takes the whole box (`100%` on both axes, no
5875    /// shrink), so its children keep their natural heights; pages
5876    /// after the first sit beyond the visible area in the shared tree, which
5877    /// no lane uses for the page box itself, since every lane places the
5878    /// selected page in its own tab body.
5879    #[cfg(feature = "widgets-containers")]
5880    fn style_tab_page(&mut self, page: WidgetId) {
5881        let Some(&node) = self.layout_nodes.get(&page) else {
5882            return;
5883        };
5884        let Ok(mut style) = self.layout_tree.style(node).cloned() else {
5885            return;
5886        };
5887        let mut changed = false;
5888        if style.size.width == crate::layout::Dimension::Auto {
5889            style.size.width = crate::layout::Dimension::percent(1.0);
5890            changed = true;
5891        }
5892        if style.size.height == crate::layout::Dimension::Auto {
5893            style.size.height = crate::layout::Dimension::percent(1.0);
5894            changed = true;
5895        }
5896        if style.flex_shrink != 0.0 {
5897            style.flex_shrink = 0.0;
5898            changed = true;
5899        }
5900        if changed {
5901            let _ = self.layout_tree.set_style(node, style);
5902        }
5903    }
5904
5905    /// Reparents an existing child to a new parent.
5906    ///
5907    /// Refuses self-reparenting and any move that would close a parent cycle;
5908    /// a refused call leaves the previous parent edge in place.
5909    pub fn reparent(&mut self, child: WidgetId, new_parent: WidgetId) -> GuiResult<()> {
5910        if child == new_parent {
5911            return Err(GuiError::Backend(
5912                "cannot reparent a widget to itself".to_owned(),
5913            ));
5914        }
5915
5916        if !self.widgets.contains_key(&child) {
5917            return Err(GuiError::WidgetNotFound(child.0));
5918        }
5919        if !self.widgets.contains_key(&new_parent) {
5920            return Err(GuiError::WidgetNotFound(new_parent.0));
5921        }
5922
5923        if self.creates_parent_cycle(child, new_parent) {
5924            return Err(GuiError::Backend(
5925                "cannot create a widget parent cycle".to_owned(),
5926            ));
5927        }
5928        if self.widget_depth(new_parent) + self.widget_subtree_height(child)
5929            >= crate::layout::box_sizing::MAX_LAYOUT_DEPTH
5930        {
5931            return Err(GuiError::Backend(
5932                "maximum layout recursion depth exceeded".to_string(),
5933            ));
5934        }
5935
5936        // Same ordering as `attach`: the lane decides first, the shared model
5937        // records only what the lane actually did.
5938        self.backend.reparent(child, new_parent)?;
5939        self.record_parent_edge(new_parent, child);
5940        Ok(())
5941    }
5942
5943    /// Returns `true` when making `child` a child of `new_parent` would close
5944    /// a parent cycle (walking up from `new_parent` reaches `child`).
5945    ///
5946    /// This is the single source of truth for the acyclic-parentage invariant
5947    /// shared by [`Ui::attach`] and [`Ui::reparent`].
5948    fn creates_parent_cycle(&self, child: WidgetId, new_parent: WidgetId) -> bool {
5949        if child == new_parent {
5950            return true;
5951        }
5952        // If child has no children in the index, it cannot be an ancestor of any node.
5953        if self.children_index.get(&child).is_none_or(|c| c.is_empty()) {
5954            return false;
5955        }
5956        let mut cursor = Some(new_parent);
5957        while let Some(id) = cursor {
5958            if id == child {
5959                return true;
5960            }
5961            cursor = self.widgets.get(&id).and_then(|spec| spec.parent);
5962        }
5963        false
5964    }
5965
5966    /// Returns the tree depth of `widget_id` (0 for root with no parent, 1 for child of root, etc.).
5967    pub fn widget_depth(&self, widget_id: WidgetId) -> usize {
5968        let mut depth = 0;
5969        let mut parent = self.widgets.get(&widget_id).and_then(|spec| spec.parent);
5970        while let Some(parent_id) = parent {
5971            depth += 1;
5972            parent = self.widgets.get(&parent_id).and_then(|spec| spec.parent);
5973        }
5974        depth
5975    }
5976
5977    /// Returns the height of the subtree rooted at `widget_id` (1 for a leaf, 1 + max(child heights)).
5978    pub fn widget_subtree_height(&self, widget_id: WidgetId) -> usize {
5979        let mut max_child_height = 0;
5980        if let Some(children) = self.children_index.get(&widget_id) {
5981            for &child in children {
5982                max_child_height = max_child_height.max(self.widget_subtree_height(child));
5983            }
5984        }
5985        1 + max_child_height
5986    }
5987
5988    /// Removes one parent-child edge from the adjacency index, dropping the
5989    /// parent's key once it has no children left.
5990    fn detach_child_edge(&mut self, parent: WidgetId, child: WidgetId) {
5991        let became_empty = match self.children_index.get_mut(&parent) {
5992            Some(children) => {
5993                if let Some(pos) = children.iter().position(|&id| id == child) {
5994                    children.remove(pos);
5995                }
5996                children.is_empty()
5997            }
5998            None => false,
5999        };
6000        if became_empty {
6001            self.children_index.remove(&parent);
6002        }
6003        if let Some(&child_node) = self.layout_nodes.get(&child) {
6004            let _ = self.layout_tree.detach_child(child_node);
6005        }
6006    }
6007
6008    /// Shows a widget, typically a top-level window.
6009    pub fn show(&mut self, widget_id: WidgetId) -> GuiResult<()> {
6010        if !self.widgets.contains_key(&widget_id) {
6011            return Err(GuiError::WidgetNotFound(widget_id.0));
6012        }
6013        let announcement = self.widgets.get(&widget_id).and_then(|spec| {
6014            #[cfg(feature = "widgets-containers")]
6015            let is_alert = spec.kind == WidgetKind::AlertDialog;
6016            #[cfg(not(feature = "widgets-containers"))]
6017            let is_alert = false;
6018            is_alert
6019                .then(|| {
6020                    spec.accessibility
6021                        .name
6022                        .clone()
6023                        .or_else(|| spec.text.clone())
6024                })
6025                .flatten()
6026        });
6027        self.hidden_widgets.remove(&widget_id);
6028        if let Some(&node) = self.layout_nodes.get(&widget_id) {
6029            if let Ok(mut style) = self.layout_tree.style(node).cloned() {
6030                if style.display != crate::layout::Display::Flex {
6031                    style.display = crate::layout::Display::Flex;
6032                    let _ = self.layout_tree.set_style(node, style);
6033                }
6034            }
6035        }
6036        self.invalidate_layout(widget_id);
6037        if self.widgets.get(&widget_id).map(|s| s.kind) == Some(WidgetKind::Window) {
6038            self.layout_roots.insert(widget_id);
6039            if let Some((w, h)) = self.widgets.get(&widget_id).and_then(|spec| spec.size) {
6040                self.layout_root_sizes
6041                    .insert(widget_id, (w as f32, h as f32));
6042                if let Some(compute) = self.auto_layout_fn {
6043                    let _ = compute(self, widget_id, w as f32, h as f32);
6044                }
6045            }
6046        }
6047        self.backend.show(widget_id)?;
6048        if let Some(text) = announcement {
6049            self.backend.post_accessible_notification(
6050                widget_id,
6051                AccessibleNotification::Announcement(text),
6052            )?;
6053        }
6054        Ok(())
6055    }
6056
6057    /// Hides a widget without removing it from the tree.
6058    pub fn hide(&mut self, widget_id: WidgetId) -> GuiResult<()> {
6059        if !self.widgets.contains_key(&widget_id) {
6060            return Err(GuiError::WidgetNotFound(widget_id.0));
6061        }
6062        for popup in self.transient_popups(widget_id) {
6063            self.hide(popup)?;
6064        }
6065        self.hidden_widgets.insert(widget_id);
6066        if let Some(&node) = self.layout_nodes.get(&widget_id) {
6067            if let Ok(mut style) = self.layout_tree.style(node).cloned() {
6068                if style.display != crate::layout::Display::None {
6069                    style.display = crate::layout::Display::None;
6070                    let _ = self.layout_tree.set_style(node, style);
6071                }
6072            }
6073        }
6074        self.invalidate_layout(widget_id);
6075        self.backend.hide(widget_id)
6076    }
6077
6078    /// Sets whether a widget is visible or hidden.
6079    ///
6080    /// Hidden widgets are given `display: Display::None` in the layout tree so
6081    /// they do not occupy layout space during `compute_layout`.
6082    pub fn set_visible(&mut self, widget_id: WidgetId, visible: bool) -> GuiResult<()> {
6083        if visible {
6084            self.show(widget_id)
6085        } else {
6086            self.hide(widget_id)
6087        }
6088    }
6089
6090    /// Whether the widget is currently visible (not hidden via [`Self::hide`]).
6091    pub fn is_visible(&self, widget_id: WidgetId) -> bool {
6092        self.widgets.contains_key(&widget_id) && !self.is_effectively_hidden(widget_id)
6093    }
6094
6095    /// Whether the widget is effectively hidden, either directly via [`Self::hide`]
6096    /// or by having an ancestor that is hidden.
6097    pub fn is_effectively_hidden(&self, widget_id: WidgetId) -> bool {
6098        // Most UIs never hide anything; avoid walking the parent chain for
6099        // every widget on every layout pass.
6100        if self.hidden_widgets.is_empty() {
6101            return false;
6102        }
6103        let mut cursor = Some(widget_id);
6104        while let Some(id) = cursor {
6105            if self.hidden_widgets.contains(&id) {
6106                return true;
6107            }
6108            cursor = self.widgets.get(&id).and_then(|spec| spec.parent);
6109        }
6110        false
6111    }
6112
6113    fn transient_popups(&self, owner: WidgetId) -> Vec<WidgetId> {
6114        let mut popups: Vec<_> = self
6115            .window_options
6116            .iter()
6117            .filter_map(|(widget_id, options)| {
6118                (options.transient_for == Some(owner)).then_some(*widget_id)
6119            })
6120            .collect();
6121        popups.sort_by_key(|widget_id| widget_id.0);
6122        popups
6123    }
6124
6125    /// Captures a screenshot of the specified window as top-down RGBA pixels.
6126    ///
6127    /// Validates that `window_id` exists and is a [`WidgetKind::Window`], then forwards
6128    /// to the backend implementation.
6129    pub fn capture_window_rgba(
6130        &self,
6131        window_id: WidgetId,
6132        include_decorations: bool,
6133    ) -> GuiResult<(u32, u32, Vec<u8>)> {
6134        let Some(spec) = self.widgets.get(&window_id) else {
6135            return Err(GuiError::WidgetNotFound(window_id.0));
6136        };
6137        if !spec.kind.is_window_like() {
6138            return Err(GuiError::UnsupportedWidget("capture_window"));
6139        }
6140        self.backend
6141            .capture_window_rgba(window_id, include_decorations)
6142    }
6143
6144    /// Captures a screenshot of the specified widget as top-down RGBA pixels.
6145    ///
6146    /// Validates that `widget_id` exists, then forwards to the backend implementation.
6147    pub fn capture_widget_rgba(&self, widget_id: WidgetId) -> GuiResult<(u32, u32, Vec<u8>)> {
6148        if !self.widgets.contains_key(&widget_id) {
6149            return Err(GuiError::WidgetNotFound(widget_id.0));
6150        }
6151        self.backend.capture_widget_rgba(widget_id)
6152    }
6153
6154    /// Reads live text for a widget (E2E readback).
6155    ///
6156    /// Validates `widget_id`, attempts live backend readback, and gracefully falls
6157    /// back to the cached `spec.text` if the backend returns `Ok(None)`.
6158    pub fn native_read_text(&self, widget_id: WidgetId) -> GuiResult<Option<String>> {
6159        let Some(spec) = self.widgets.get(&widget_id) else {
6160            return Err(GuiError::WidgetNotFound(widget_id.0));
6161        };
6162        match self.backend.native_read_text(widget_id)? {
6163            Some(live) => Ok(Some(live)),
6164            None => Ok(spec.text.clone()),
6165        }
6166    }
6167
6168    /// Reads live checked state for a checkbox/radio widget (E2E readback).
6169    ///
6170    /// Validates `widget_id`, attempts live backend readback, and gracefully falls
6171    /// back to the cached `spec.checked` if the backend returns `Ok(None)`.
6172    pub fn native_read_checked(&self, widget_id: WidgetId) -> GuiResult<Option<bool>> {
6173        let Some(spec) = self.widgets.get(&widget_id) else {
6174            return Err(GuiError::WidgetNotFound(widget_id.0));
6175        };
6176        match self.backend.native_read_checked(widget_id)? {
6177            Some(live) => Ok(Some(live)),
6178            None => Ok(spec.checked),
6179        }
6180    }
6181
6182    /// Simulates a native click on an actionable widget (E2E action).
6183    ///
6184    /// Validates `widget_id` and forwards to the backend implementation.
6185    pub fn native_click(&self, widget_id: WidgetId) -> GuiResult<bool> {
6186        if !self.widgets.contains_key(&widget_id) {
6187            return Err(GuiError::WidgetNotFound(widget_id.0));
6188        }
6189        self.backend.native_click(widget_id)
6190    }
6191
6192    /// Simulates native text input on an editable widget (E2E action).
6193    ///
6194    /// Validates `widget_id` and forwards to the backend implementation.
6195    pub fn native_type_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<bool> {
6196        let Some(spec) = self.widgets.get_mut(&widget_id) else {
6197            return Err(GuiError::WidgetNotFound(widget_id.0));
6198        };
6199        let handled = self.backend.native_type_text(widget_id, text)?;
6200        if handled {
6201            spec.text = Some(text.to_owned());
6202            let _ = self.backend.set_text(widget_id, text);
6203        }
6204        Ok(handled)
6205    }
6206
6207    /// Removes a widget (and, recursively, its descendants) from the UI tree.
6208    ///
6209    /// The child walk follows the adjacency index (`children_index`), so
6210    /// tearing down a subtree of size `N` visits each parent-child edge
6211    /// exactly once: `O(N)` in the subtree size, independent of the total
6212    /// widget count. Descendants are still removed first
6213    /// so no child outlives its parent, and index edges are only released
6214    /// after a removal has actually succeeded, so a backend refusal leaves
6215    /// the surviving edges intact for a retry.
6216    pub fn remove(&mut self, widget_id: WidgetId) -> GuiResult<()> {
6217        if !self.widgets.contains_key(&widget_id) {
6218            return Err(GuiError::WidgetNotFound(widget_id.0));
6219        }
6220
6221        // Snapshot and clear this node's children from the index in one O(1) pass.
6222        // This avoids quadratic sibling scanning.
6223        let children = self.children_index.remove(&widget_id).unwrap_or_default();
6224        let mut all_children = children;
6225        for popup in self.transient_popups(widget_id) {
6226            if !all_children.contains(&popup) {
6227                all_children.push(popup);
6228            }
6229        }
6230
6231        if let Some(&p_node) = self.layout_nodes.get(&widget_id) {
6232            let _ = self.layout_tree.detach_all_children(p_node);
6233        }
6234
6235        for (idx, &child_id) in all_children.iter().enumerate() {
6236            if let Err(err) = self.remove(child_id) {
6237                // Restore surviving tail on failure to maintain retryability
6238                let surviving: Vec<WidgetId> = all_children[idx..].to_vec();
6239                self.children_index.insert(widget_id, surviving);
6240                return Err(err);
6241            }
6242        }
6243
6244        self.backend.remove(widget_id)?;
6245        self.remove_widget_motions(widget_id);
6246
6247        // The node is gone: release its parent edge and drop its (by now
6248        // empty) child list from the index.
6249        if let Some(parent) = self.widgets.get(&widget_id).and_then(|spec| spec.parent) {
6250            self.detach_child_edge(parent, widget_id);
6251        }
6252        self.children_index.remove(&widget_id);
6253        self.widgets.remove(&widget_id);
6254        self.gpu_degraded.remove(&widget_id);
6255        if let Some(node) = self.layout_nodes.remove(&widget_id) {
6256            let _ = self.layout_tree.remove_node(node);
6257        }
6258        self.layout_dirty.remove(&widget_id);
6259        self.keyed_rows.remove(&widget_id);
6260        self.keyed_selection.remove(&widget_id);
6261        self.layout_roots.remove(&widget_id);
6262        self.hidden_widgets.remove(&widget_id);
6263        self.min_sizes.remove(&widget_id);
6264        self.preferred_widths.remove(&widget_id);
6265        self.window_min_sizes.remove(&widget_id);
6266        self.data_grid_columns.remove(&widget_id);
6267        self.data_grid_data.remove(&widget_id);
6268        self.window_resizable.remove(&widget_id);
6269        self.window_options.remove(&widget_id);
6270        self.drag_sources.remove(&widget_id);
6271        self.drag_targets.remove(&widget_id);
6272        self.layout_root_sizes.remove(&widget_id);
6273        // Registered callbacks and theme overrides are keyed by widget id;
6274        // dropping them here keeps repeated dialog/multi-window teardown from
6275        // retaining every closed window's closures.
6276        self.on_window_close.remove(&widget_id);
6277        self.on_window_resize.remove(&widget_id);
6278        self.theme_overrides.remove(&widget_id);
6279        #[cfg(feature = "property-grid")]
6280        self.property_grids.forget(widget_id);
6281        #[cfg(feature = "styled-text")]
6282        self.styled_texts.forget(widget_id);
6283        #[cfg(feature = "webview")]
6284        self.webviews.forget(widget_id);
6285        if self.focused == Some(widget_id) {
6286            self.focused = None;
6287        }
6288        Ok(())
6289    }
6290
6291    /// Enables or disables a widget.
6292    pub fn set_enabled(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
6293        let Some(spec) = self.widgets.get_mut(&widget_id) else {
6294            return Err(GuiError::WidgetNotFound(widget_id.0));
6295        };
6296
6297        let previous = spec.enabled;
6298        spec.enabled = Some(enabled);
6299        if let Err(error) = self.backend.set_enabled(widget_id, enabled) {
6300            if let Some(spec) = self.widgets.get_mut(&widget_id) {
6301                spec.enabled = previous;
6302            }
6303            return Err(error);
6304        }
6305        Ok(())
6306    }
6307
6308    /// Programmatically activates a clickable widget (button, file chooser,
6309    /// link label) exactly as if the user clicked it.
6310    pub fn activate(&mut self, widget_id: WidgetId) -> GuiResult<()> {
6311        if !self.widgets.contains_key(&widget_id) {
6312            return Err(GuiError::WidgetNotFound(widget_id.0));
6313        }
6314        self.backend.activate(widget_id)
6315    }
6316
6317    /// Returns the platform-specific application data directory
6318    /// (XDG data home on Linux, `%APPDATA%` on Windows, the temp directory on
6319    /// the Mock backend). Apps should persist their state under a
6320    /// subdirectory of this path instead of the current working directory.
6321    pub fn app_data_dir(&self) -> GuiResult<PathBuf> {
6322        self.backend.data_dir()
6323    }
6324
6325    /// Sets tooltip text for a widget.
6326    pub fn set_tooltip(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
6327        Self::reject_embedded_nul(text)?;
6328        let Some(spec) = self.widgets.get_mut(&widget_id) else {
6329            return Err(GuiError::WidgetNotFound(widget_id.0));
6330        };
6331        let previous = spec.tooltip.clone();
6332        spec.tooltip = Some(text.to_owned());
6333        if let Err(error) = self.backend.set_tooltip(widget_id, text) {
6334            if let Some(spec) = self.widgets.get_mut(&widget_id) {
6335                spec.tooltip = previous;
6336            }
6337            return Err(error);
6338        }
6339        Ok(())
6340    }
6341
6342    /// Sets the accessible name announced by assistive technology.
6343    ///
6344    /// Updates the shared spec and forwards to the backend; a backend whose
6345    /// native accessibility bridge has not landed returns
6346    /// [`GuiError::UnsupportedCapability`] instead of silently ignoring the
6347    /// request.
6348    pub fn set_accessible_name(&mut self, widget_id: WidgetId, name: &str) -> GuiResult<()> {
6349        Self::reject_embedded_nul(name)?;
6350        let Some(spec) = self.widgets.get_mut(&widget_id) else {
6351            return Err(GuiError::WidgetNotFound(widget_id.0));
6352        };
6353        let previous = spec.accessibility.name.clone();
6354        spec.accessibility.name = Some(name.to_owned());
6355        if let Err(error) = self.backend.set_accessible_name(widget_id, name) {
6356            if let Some(spec) = self.widgets.get_mut(&widget_id) {
6357                spec.accessibility.name = previous;
6358            }
6359            return Err(error);
6360        }
6361        Ok(())
6362    }
6363
6364    /// Sets the accessible description announced after the name.
6365    pub fn set_accessible_description(
6366        &mut self,
6367        widget_id: WidgetId,
6368        description: &str,
6369    ) -> GuiResult<()> {
6370        Self::reject_embedded_nul(description)?;
6371        let Some(spec) = self.widgets.get_mut(&widget_id) else {
6372            return Err(GuiError::WidgetNotFound(widget_id.0));
6373        };
6374        let previous = spec.accessibility.description.clone();
6375        spec.accessibility.description = Some(description.to_owned());
6376        if let Err(error) = self
6377            .backend
6378            .set_accessible_description(widget_id, description)
6379        {
6380            if let Some(spec) = self.widgets.get_mut(&widget_id) {
6381                spec.accessibility.description = previous;
6382            }
6383            return Err(error);
6384        }
6385        Ok(())
6386    }
6387
6388    /// Returns the accessibility metadata of a widget, when it exists.
6389    pub fn accessibility(&self, widget_id: WidgetId) -> Option<&AccessibilitySpec> {
6390        self.widget(widget_id).map(|spec| &spec.accessibility)
6391    }
6392
6393    /// Marks a widget as focusable (or not) for tab traversal.
6394    pub fn set_focusable(&mut self, widget_id: WidgetId, focusable: bool) -> GuiResult<()> {
6395        let Some(spec) = self.widgets.get_mut(&widget_id) else {
6396            return Err(GuiError::WidgetNotFound(widget_id.0));
6397        };
6398        let previous = spec.focusable;
6399        spec.focusable = Some(focusable);
6400        if let Err(error) = self.backend.set_focusable(widget_id, focusable) {
6401            if let Some(spec) = self.widgets.get_mut(&widget_id) {
6402                spec.focusable = previous;
6403            }
6404            return Err(error);
6405        }
6406        Ok(())
6407    }
6408
6409    /// Returns whether a widget is focusable, respecting per-kind defaults.
6410    pub fn is_focusable(&self, widget_id: WidgetId) -> Option<bool> {
6411        self.widget(widget_id).map(crate::focus::is_focusable)
6412    }
6413
6414    /// Moves keyboard focus to a widget.
6415    ///
6416    /// Any existing widget can receive programmatic focus; traversal
6417    /// ([`Self::focus_next`], [`Self::focus_previous`]) visits focusable,
6418    /// enabled widgets only. The previous focus is reported as
6419    /// `UiEvent::FocusChanged { focused: false }` by backends that can report
6420    /// focus (Mock and Win32 report every programmatic change; GTK and Cocoa
6421    /// emit the focus-in/out transitions they observe).
6422    pub fn focus(&mut self, widget_id: WidgetId) -> GuiResult<()> {
6423        if !self.widgets.contains_key(&widget_id) {
6424            return Err(GuiError::WidgetNotFound(widget_id.0));
6425        }
6426        self.backend.set_focus(widget_id)?;
6427        self.focused = Some(widget_id);
6428        self.backend
6429            .post_accessible_notification(widget_id, AccessibleNotification::FocusChanged)
6430    }
6431
6432    /// Returns the widget that currently holds keyboard focus, when known.
6433    pub fn focused(&self) -> Option<WidgetId> {
6434        self.focused
6435    }
6436
6437    /// Focus candidates in tab order: focusable widgets whose own and
6438    /// ancestors' `enabled` flags allow input, in creation order (which is
6439    /// also `WidgetId` order).
6440    pub fn focus_order(&self) -> Vec<WidgetId> {
6441        let mut ids: Vec<WidgetId> = self.widgets.keys().copied().collect();
6442        ids.sort_by_key(|id| id.0);
6443        ids.retain(|id| {
6444            let popup_takes_focus = self.window_options.get(id).is_some_and(|options| {
6445                options.role == WindowRole::Popup && options.focus == WindowFocusPolicy::Take
6446            });
6447            self.widgets.get(id).is_some_and(|spec| {
6448                (crate::focus::is_focusable(spec) || popup_takes_focus)
6449                    && self.focus_chain_enabled(*id)
6450            })
6451        });
6452        ids
6453    }
6454
6455    /// Returns focus candidates in 2D spatial reading order (top-to-bottom, left-to-right).
6456    ///
6457    /// Unlike [`Self::focus_order`], which returns candidates in monotonic `WidgetId`
6458    /// creation order, `spatial_focus_order` queries layout coordinates and partitions
6459    /// widgets into visual row bands (using vertical tolerance threshold), sorting
6460    /// primary by row band and secondary by horizontal offset `x`.
6461    ///
6462    /// This ensures accessible Tab navigation strictly conforms to WCAG 2.1 reading order
6463    /// in auto-wrapping flex containers (`ContainerWrap::Wrap`) and multi-row forms.
6464    pub fn spatial_focus_order(&self) -> Vec<WidgetId> {
6465        let candidates = self.focus_order();
6466        if candidates.len() <= 1 {
6467            return candidates;
6468        }
6469
6470        let mut with_pos: Vec<(WidgetId, f32, f32)> = candidates
6471            .into_iter()
6472            .map(|id| {
6473                if let Some(spec) = self.widgets.get(&id) {
6474                    if let Some((x, y)) = spec.position {
6475                        return (id, x as f32, y as f32);
6476                    }
6477                }
6478                if let Ok(rect) = self.layout_rect(id) {
6479                    (id, rect.x, rect.y)
6480                } else {
6481                    (id, 0.0, 0.0)
6482                }
6483            })
6484            .collect();
6485
6486        const ROW_TOLERANCE: f32 = 12.0;
6487        with_pos.sort_by(|a, b| {
6488            let row_a = (a.2 / ROW_TOLERANCE).floor() as i32;
6489            let row_b = (b.2 / ROW_TOLERANCE).floor() as i32;
6490            if row_a != row_b {
6491                row_a.cmp(&row_b)
6492            } else {
6493                a.1.total_cmp(&b.1).then_with(|| a.0 .0.cmp(&b.0 .0))
6494            }
6495        });
6496
6497        with_pos.into_iter().map(|(id, _, _)| id).collect()
6498    }
6499
6500    fn focus_chain_enabled(&self, widget_id: WidgetId) -> bool {
6501        let mut cursor = Some(widget_id);
6502        while let Some(id) = cursor {
6503            let Some(spec) = self.widgets.get(&id) else {
6504                return false;
6505            };
6506            if spec.enabled == Some(false) {
6507                return false;
6508            }
6509            cursor = spec.parent;
6510        }
6511        true
6512    }
6513
6514    /// Moves focus to the next focus candidate, wrapping at the end.
6515    ///
6516    /// Returns the newly focused widget, or `None` when nothing is
6517    /// focusable.
6518    pub fn focus_next(&mut self) -> GuiResult<Option<WidgetId>> {
6519        self.focus_step(1)
6520    }
6521
6522    /// Moves focus to the previous focus candidate, wrapping at the start.
6523    pub fn focus_previous(&mut self) -> GuiResult<Option<WidgetId>> {
6524        self.focus_step(-1)
6525    }
6526
6527    fn focus_step(&mut self, direction: isize) -> GuiResult<Option<WidgetId>> {
6528        let order = self.focus_order();
6529        if order.is_empty() {
6530            self.focused = None;
6531            return Ok(None);
6532        }
6533        let next = match self
6534            .focused
6535            .and_then(|current| order.iter().position(|id| *id == current))
6536        {
6537            Some(position) => {
6538                let len = order.len() as isize;
6539                let target = (position as isize + direction).rem_euclid(len) as usize;
6540                order[target]
6541            }
6542            None if direction >= 0 => order[0],
6543            None => *order.last().expect("order is not empty"),
6544        };
6545        self.focus(next)?;
6546        Ok(Some(next))
6547    }
6548
6549    /// Replaces the active theme.
6550    ///
6551    /// Switches to the given theme.
6552    ///
6553    /// The resolved theme is stored on the `Ui` record only after the backend
6554    /// accepts it; on failure the previous theme is preserved.
6555    pub fn set_theme(&mut self, theme: Theme) -> GuiResult<()> {
6556        self.backend.set_theme(&theme)?;
6557        self.theme = theme;
6558        Ok(())
6559    }
6560
6561    /// Switches to the built-in light or dark theme.
6562    pub fn set_theme_mode(&mut self, mode: ThemeMode) -> GuiResult<()> {
6563        self.set_theme(Theme::for_mode(mode))
6564    }
6565
6566    /// Returns the active theme.
6567    pub fn theme(&self) -> &Theme {
6568        &self.theme
6569    }
6570
6571    /// Returns the active theme mode.
6572    pub fn theme_mode(&self) -> ThemeMode {
6573        self.theme.mode
6574    }
6575
6576    /// Returns the backend's system theme detection capabilities.
6577    pub fn theme_capabilities(&self) -> ThemeCapabilities {
6578        self.backend.theme_capabilities()
6579    }
6580
6581    /// Reports the active backend's GPU host-surface capabilities.
6582    pub fn gpu_surface_capabilities(&self) -> GpuSurfaceCapabilities {
6583        self.backend.gpu_surface_capabilities()
6584    }
6585
6586    /// Tests a standard GPU-surface capability identifier. Unknown identifiers
6587    /// return `false`.
6588    pub fn supports_capability(&self, capability: &str) -> bool {
6589        self.gpu_surface_capabilities().supports(capability)
6590    }
6591
6592    /// Selects the policy for future Vulkan canvas creations whose backend
6593    /// does not advertise a Vulkan surface.
6594    pub fn set_gpu_degradation_policy(&mut self, policy: GpuDegradationPolicy) {
6595        self.gpu_degradation_policy = policy;
6596    }
6597
6598    /// Returns whether `widget_id` was created through a GPU degradation
6599    /// path. Unknown ids and native Vulkan canvases return `false`.
6600    pub fn is_gpu_degraded(&self, widget_id: WidgetId) -> bool {
6601        self.gpu_degraded.contains_key(&widget_id)
6602    }
6603
6604    /// Returns the backend's display-metric capabilities.
6605    pub fn display_capabilities(&self) -> DisplayCapabilities {
6606        self.backend.display_capabilities()
6607    }
6608
6609    /// Enumerates the connected displays.
6610    ///
6611    /// On lanes that cannot enumerate this returns the typed
6612    /// [`GuiError::UnsupportedCapability`]; check [`Ui::display_capabilities`]
6613    /// first when the app has a fallback path. DPI/monitor transitions arrive
6614    /// as [`UiEvent::DisplayChanged`].
6615    #[cfg(feature = "displays")]
6616    pub fn displays(&self) -> GuiResult<Vec<DisplayInfo>> {
6617        self.backend.displays()
6618    }
6619
6620    /// Returns the primary display, or `None` when enumeration
6621    /// succeeds but reports no primary.
6622    #[cfg(feature = "displays")]
6623    pub fn primary_display(&self) -> GuiResult<Option<DisplayInfo>> {
6624        self.backend.primary_display()
6625    }
6626
6627    /// Projects a pointer coordinate from the display's native pixel space
6628    /// into logical (96-DPI) coordinates for `widget_id`.
6629    ///
6630    /// [`Ui`] already applies this to every [`UiEvent::PointerDown`],
6631    /// [`UiEvent::PointerMove`], and [`UiEvent::PointerUp`] it dispatches, so
6632    /// app code never needs to call it for event coordinates: they arrive in
6633    /// the logical space this returns. It stays public for the other sources
6634    /// of a raw position — a drag payload, a native handle, a scripted
6635    /// physical coordinate — where the scaling still has to be inverted
6636    /// explicitly to line the value up with layout targets.
6637    ///
6638    /// It resolves the widget's display scale through
6639    /// [`Backend::widget_scale_factor`] and inverts the OS scaling matrix via
6640    /// [`crate::logical_pointer_projection`]. On lanes that report a scale of
6641    /// `1.0` (GTK4, Cocoa, Mock without a scaled display fixture) the
6642    /// projection is the identity; on a 125 % Win32 display a physical
6643    /// `(125, 250)` maps to logical `(100, 200)`.
6644    pub fn logical_pointer_projection(&self, widget_id: WidgetId, x: f32, y: f32) -> (f32, f32) {
6645        let scale = self.backend.widget_scale_factor(widget_id);
6646        crate::logical_pointer_projection(x, y, scale)
6647    }
6648
6649    /// Returns the OS light/dark preference when the backend can detect it.
6650    pub fn system_theme_mode(&self) -> Option<ThemeMode> {
6651        self.backend.system_theme_mode()
6652    }
6653
6654    /// Returns whether the OS high-contrast accessibility mode is active.
6655    pub fn system_high_contrast(&self) -> bool {
6656        self.backend.system_high_contrast()
6657    }
6658
6659    /// Resolves a portable stock icon at the 96 dpi baseline.
6660    ///
6661    /// The icon's palette follows the active theme (light/dark), so callers
6662    /// re-resolve after [`Ui::set_theme_mode`]; see
6663    /// [`Ui::stock_icon_at_scale`] for DPI variants.
6664    pub fn stock_icon(&self, role: IconRole, size: IconSize) -> StockIcon {
6665        self.stock_icon_at_scale(role, size, 1)
6666    }
6667
6668    /// Resolves a portable stock icon at an explicit DPI scale factor.
6669    ///
6670    /// `scale` models the display density (1 = 96 dpi, 2 = 200 %, …) and is
6671    /// clamped to `1..=4`; the raster edge is `size.pixels() * scale`.
6672    ///
6673    /// Every call re-rasterizes the glyph (there is no cache), so resolve an
6674    /// icon once and reuse the returned value when drawing it repeatedly.
6675    pub fn stock_icon_at_scale(&self, role: IconRole, size: IconSize, scale: u32) -> StockIcon {
6676        crate::artprov::render_stock_icon(role, size, self.theme.mode, scale)
6677    }
6678
6679    /// Resolves an OS-native stock icon when the lane provides one.
6680    ///
6681    /// Lanes without a native mapping return the typed
6682    /// [`GuiError::UnsupportedCapability`]; portable art is always available
6683    /// through [`Ui::stock_icon`].
6684    pub fn native_stock_icon(&self, role: IconRole, size: IconSize) -> GuiResult<StockIcon> {
6685        self.backend.native_stock_icon(role, size)
6686    }
6687
6688    /// Returns the lane's native stock-art capabilities.
6689    pub fn art_capabilities(&self) -> ArtCapabilities {
6690        self.backend.art_capabilities()
6691    }
6692
6693    /// Adds a theme override for one widget.
6694    ///
6695    /// The override is stored on the `Ui` record only after the backend accepts
6696    /// it, so a refusing backend never leaves a phantom override.
6697    pub fn set_theme_override(
6698        &mut self,
6699        widget_id: WidgetId,
6700        theme_override: ThemeOverride,
6701    ) -> GuiResult<()> {
6702        if !self.widgets.contains_key(&widget_id) {
6703            return Err(GuiError::WidgetNotFound(widget_id.0));
6704        }
6705        self.backend.set_theme_override(widget_id, theme_override)?;
6706        self.theme_overrides
6707            .entry(widget_id)
6708            .or_default()
6709            .push(theme_override);
6710        Ok(())
6711    }
6712
6713    /// Returns the theme overrides registered for a widget.
6714    pub fn theme_overrides(&self, widget_id: WidgetId) -> &[ThemeOverride] {
6715        self.theme_overrides
6716            .get(&widget_id)
6717            .map(Vec::as_slice)
6718            .unwrap_or(&[])
6719    }
6720
6721    /// Clears all theme overrides for a widget.
6722    pub fn clear_theme_overrides(&mut self, widget_id: WidgetId) -> GuiResult<()> {
6723        if !self.widgets.contains_key(&widget_id) {
6724            return Err(GuiError::WidgetNotFound(widget_id.0));
6725        }
6726        self.backend.clear_theme_overrides(widget_id)?;
6727        self.theme_overrides.remove(&widget_id);
6728        Ok(())
6729    }
6730
6731    /// Returns a cloneable handle for posting commands from worker threads.
6732    ///
6733    /// The first call creates one bounded command channel for this `Ui`
6734    /// (capacity [`DEFAULT_TASK_QUEUE_CAPACITY`]) wired to the backend's wake
6735    /// hook; later calls return clones of the same handle. See the
6736    /// [`crate::async_ui`] module docs for the worker/UI-thread contract.
6737    #[cfg(feature = "async")]
6738    pub fn task_proxy(&mut self) -> UiProxy {
6739        if self.task_channel.is_none() {
6740            let (proxy, receiver) =
6741                UiProxy::new(self.backend.wake_handle(), DEFAULT_TASK_QUEUE_CAPACITY);
6742            self.task_channel = Some((proxy, receiver));
6743        }
6744        self.task_channel
6745            .as_ref()
6746            .map(|(proxy, _)| proxy.clone())
6747            .expect("task channel initialized above")
6748    }
6749
6750    /// Tears the `Ui` down explicitly and returns how many queued
6751    /// background-task commands were discarded unapplied.
6752    ///
6753    /// Dropping a `Ui` (or [`Ui::into_backend`]) has the same effect — `Ui`
6754    /// deliberately has no `Drop` impl so `into_backend` can move the backend
6755    /// out; the channel receiver drops with it (see the drop contract in
6756    /// [`crate::async_ui`]): the command channel closes, every
6757    /// [`UiProxy`] clone then reports [`crate::TaskSendError::Closed`], and
6758    /// commands still queued are discarded without being applied. Call
6759    /// `shutdown` after the final [`Ui::drain_task_commands`] when you need
6760    /// to know whether any worker commit was lost.
6761    #[cfg(feature = "async")]
6762    pub fn shutdown(mut self) -> usize {
6763        self.discard_pending_tasks()
6764    }
6765
6766    #[cfg(feature = "async")]
6767    fn discard_pending_tasks(&mut self) -> usize {
6768        let mut discarded = 0;
6769        if let Some((_, receiver)) = self.task_channel.take() {
6770            while receiver.try_recv().is_ok() {
6771                discarded += 1;
6772            }
6773        }
6774        self.task_callbacks.clear();
6775        self.task_handles.clear();
6776        self.task_completions = None;
6777        discarded
6778    }
6779
6780    /// Applies queued background-task commands in FIFO order.
6781    ///
6782    /// Widget commands go through the same `set_*` paths as direct calls, so
6783    /// shared specs and native widgets stay in sync; a command for a removed
6784    /// widget is rejected instead of panicking and emits a
6785    /// [`TaskEvent::Aborted`] dead-letter notification, so a teardown race
6786    /// can never swallow a worker's commit silently. Lifecycle
6787    /// commands queue `UiEvent::Task` notifications for the next `wait_event`
6788    /// / `poll_event` call. The event functions call this automatically; call
6789    /// it directly before screenshots or assertions.
6790    #[cfg(feature = "async")]
6791    pub fn drain_task_commands(&mut self) -> TaskDrainReport {
6792        let mut report = TaskDrainReport::default();
6793
6794        let mut queued = Vec::new();
6795        if let Some((_, receiver)) = &self.task_channel {
6796            while let Ok(command) = receiver.try_recv() {
6797                queued.push(command);
6798            }
6799        }
6800
6801        for command in queued {
6802            match &command {
6803                TaskCommand::SetText { widget_id, text } => {
6804                    let result = self.set_text(*widget_id, text);
6805                    self.note_task_outcome(&command, result, &mut report);
6806                }
6807                TaskCommand::SetValue { widget_id, value } => {
6808                    let result = self.set_value(*widget_id, *value);
6809                    self.note_task_outcome(&command, result, &mut report);
6810                }
6811                TaskCommand::SetChecked { widget_id, checked } => {
6812                    let result = self.set_checked(*widget_id, *checked);
6813                    self.note_task_outcome(&command, result, &mut report);
6814                }
6815                TaskCommand::SetEnabled { widget_id, enabled } => {
6816                    let result = self.set_enabled(*widget_id, *enabled);
6817                    self.note_task_outcome(&command, result, &mut report);
6818                }
6819                TaskCommand::SetVisible { widget_id, visible } => {
6820                    let result = self.set_visible(*widget_id, *visible);
6821                    self.note_task_outcome(&command, result, &mut report);
6822                }
6823                TaskCommand::SetDataListItems { widget_id, items } => {
6824                    let result = self.set_data_list_items(*widget_id, items);
6825                    self.note_task_outcome(&command, result, &mut report);
6826                }
6827                TaskCommand::SetDataGridRows { widget_id, rows } => {
6828                    let result = self.set_data_grid_rows(*widget_id, rows);
6829                    self.note_task_outcome(&command, result, &mut report);
6830                }
6831                TaskCommand::Progress { task, value } => {
6832                    self.pending_events
6833                        .push_back(UiEvent::Task(TaskEvent::Progress {
6834                            task: *task,
6835                            value: *value,
6836                        }));
6837                    report.applied += 1;
6838                }
6839                TaskCommand::Finished { task } => {
6840                    self.pending_events
6841                        .push_back(UiEvent::Task(TaskEvent::Finished { task: *task }));
6842                    report.applied += 1;
6843                }
6844                TaskCommand::Failed { task, message } => {
6845                    self.pending_events
6846                        .push_back(UiEvent::Task(TaskEvent::Failed {
6847                            task: *task,
6848                            message: message.clone(),
6849                        }));
6850                    report.applied += 1;
6851                }
6852            }
6853        }
6854
6855        self.drain_task_callbacks();
6856
6857        report
6858    }
6859
6860    /// Drains and invokes any pending typed task completion callbacks.
6861    #[cfg(feature = "async")]
6862    pub fn drain_task_callbacks(&mut self) {
6863        let mut completed = Vec::new();
6864        if let Some((_, rx)) = &self.task_completions {
6865            while let Ok(item) = rx.try_recv() {
6866                completed.push(item);
6867            }
6868        }
6869
6870        for (task_id, payload) in completed {
6871            if let Some(handle) = self.task_handles.remove(&task_id) {
6872                handle.mark_finished();
6873            }
6874            if let Some(callback) = self.task_callbacks.remove(&task_id) {
6875                let _ = callback(self, payload);
6876            }
6877        }
6878    }
6879
6880    /// Spawns a background worker thread and delivers its typed return value to
6881    /// `callback` on the UI thread when complete.
6882    ///
6883    /// This pattern mimics Tauri's `invoke()`, eliminating manual `TaskId`
6884    /// maps and custom task events. If the task is cancelled via [`crate::async_ui::TaskHandle::cancel`],
6885    /// the completion callback is skipped.
6886    /// Attempts to spawn a background worker thread and deliver its typed return value
6887    /// to `callback` on the UI thread when complete.
6888    ///
6889    /// If thread creation fails (e.g. OS thread resource exhaustion), returns
6890    /// `GuiError::ResourceExhausted` and cleans up task bookkeeping.
6891    ///
6892    /// If `worker` panics, the panic is caught and isolated: `callback` is safely dropped
6893    /// without executing, the `TaskHandle` is marked finished, and `UiEvent::Task(TaskEvent::Failed)`
6894    /// is dispatched on the UI thread, preventing permanent callback or memory leaks.
6895    #[cfg(feature = "async")]
6896    pub fn try_spawn_task_with_callback<T, W, C>(
6897        &mut self,
6898        worker: W,
6899        callback: C,
6900    ) -> GuiResult<crate::async_ui::TaskHandle>
6901    where
6902        T: Send + 'static,
6903        W: FnOnce(crate::async_ui::TaskToken) -> T + Send + 'static,
6904        C: FnOnce(&mut Ui<B>, T) -> GuiResult<()> + 'static,
6905    {
6906        let token = self.task_proxy().start_task();
6907        let task_id = token.id();
6908
6909        if self.task_completions.is_none() {
6910            self.task_completions = Some(std::sync::mpsc::channel());
6911        }
6912        let sender = self.task_completions.as_ref().unwrap().0.clone();
6913        let wake = self.backend.wake_handle();
6914
6915        let token_for_worker = token.clone();
6916        let token_for_check = token.clone();
6917
6918        self.task_callbacks.insert(
6919            task_id,
6920            Box::new(
6921                move |ui: &mut Ui<B>, boxed: Box<dyn std::any::Any + Send>| {
6922                    if token_for_check.is_cancelled() {
6923                        return Ok(());
6924                    }
6925                    if let Ok(res) = boxed.downcast::<Result<T, String>>() {
6926                        match *res {
6927                            Ok(val) => callback(ui, val),
6928                            Err(panic_msg) => {
6929                                ui.pending_events.push_back(UiEvent::Task(
6930                                    crate::async_ui::TaskEvent::Failed {
6931                                        task: task_id,
6932                                        message: format!("worker panicked: {panic_msg}"),
6933                                    },
6934                                ));
6935                                Ok(())
6936                            }
6937                        }
6938                    } else {
6939                        Ok(())
6940                    }
6941                },
6942            ),
6943        );
6944
6945        let handle = crate::async_ui::TaskHandle::new(token);
6946        self.task_handles.insert(task_id, handle.clone());
6947
6948        let spawn_res = std::thread::Builder::new()
6949            .name(format!("task-{}", task_id.0))
6950            .spawn(move || {
6951                let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
6952                    worker(token_for_worker)
6953                }));
6954                let payload: Box<dyn std::any::Any + Send> = match outcome {
6955                    Ok(val) => Box::new(Ok::<T, String>(val)),
6956                    Err(panic_err) => {
6957                        let msg = if let Some(s) = panic_err.downcast_ref::<&str>() {
6958                            s.to_string()
6959                        } else if let Some(s) = panic_err.downcast_ref::<String>() {
6960                            s.clone()
6961                        } else {
6962                            "worker panicked with unknown payload".to_string()
6963                        };
6964                        Box::new(Err::<T, String>(msg))
6965                    }
6966                };
6967                let _ = sender.send((task_id, payload));
6968                if let Some(wake) = wake {
6969                    wake();
6970                }
6971            });
6972
6973        if let Err(_err) = spawn_res {
6974            self.task_callbacks.remove(&task_id);
6975            self.task_handles.remove(&task_id);
6976            return Err(GuiError::ResourceExhausted {
6977                operation: "spawn_task_with_callback thread creation",
6978                code: None,
6979            });
6980        }
6981
6982        Ok(handle)
6983    }
6984
6985    /// Spawns a background worker thread and delivers its typed return value to
6986    /// `callback` on the UI thread when complete.
6987    ///
6988    /// This pattern mimics Tauri's `invoke()`, eliminating manual `TaskId`
6989    /// maps and custom task events. If the task is cancelled via [`crate::async_ui::TaskHandle::cancel`],
6990    /// the completion callback is skipped.
6991    ///
6992    /// If the worker panics, the panic is caught and isolated: the callback is dropped without
6993    /// executing, the handle is marked finished, and a `TaskEvent::Failed` is dispatched.
6994    #[cfg(feature = "async")]
6995    pub fn spawn_task_with_callback<T, W, C>(
6996        &mut self,
6997        worker: W,
6998        callback: C,
6999    ) -> crate::async_ui::TaskHandle
7000    where
7001        T: Send + 'static,
7002        W: FnOnce(crate::async_ui::TaskToken) -> T + Send + 'static,
7003        C: FnOnce(&mut Ui<B>, T) -> GuiResult<()> + 'static,
7004    {
7005        self.try_spawn_task_with_callback(worker, callback)
7006            .expect("spawn_task_with_callback failed to spawn thread")
7007    }
7008
7009    /// Records one command's outcome, emitting the dead-letter event for
7010    /// widget commands that did not apply: counting them
7011    /// in `rejected` alone hid teardown races from applications.
7012    #[cfg(feature = "async")]
7013    fn note_task_outcome(
7014        &mut self,
7015        command: &TaskCommand,
7016        result: GuiResult<()>,
7017        report: &mut TaskDrainReport,
7018    ) {
7019        match result {
7020            Ok(()) => report.applied += 1,
7021            Err(error) => {
7022                report.rejected += 1;
7023                if let Some((widget_id, kind)) = command.widget_target() {
7024                    let reason = if self.widgets.contains_key(&widget_id) {
7025                        TaskAbortReason::Refused(error)
7026                    } else {
7027                        TaskAbortReason::WidgetRemoved
7028                    };
7029                    self.pending_events
7030                        .push_back(UiEvent::Task(TaskEvent::Aborted {
7031                            widget_id,
7032                            command: kind,
7033                            reason,
7034                        }));
7035                }
7036            }
7037        }
7038    }
7039
7040    /// Blocks until the next UI event arrives, without busy-looping.
7041    ///
7042    /// Queued background-task commands are applied first (FIFO); their
7043    /// lifecycle notifications are returned before backend events whenever
7044    /// both are ready. The internal `TasksPending` wake marker is consumed
7045    /// here and never surfaces to application code.
7046    pub fn wait_event(&mut self) -> GuiResult<UiEvent> {
7047        loop {
7048            #[cfg(feature = "async")]
7049            self.drain_task_commands();
7050            self.flush_layout_roots();
7051            if let Some(event) = self.pending_events.pop_front() {
7052                if let Some(event) = self.translate_motion_event(event)? {
7053                    let event = self.project_pointer(event);
7054                    self.pre_dispatch(&event);
7055                    return Ok(event);
7056                }
7057                continue;
7058            }
7059
7060            let event = self.backend.wait_event()?;
7061            if matches!(event, UiEvent::TasksPending) {
7062                continue;
7063            }
7064
7065            // Commands posted while we were blocked outrank the event we
7066            // just observed: return their notifications first and keep the
7067            // backend event queued for the next call.
7068            #[cfg(feature = "async")]
7069            self.drain_task_commands();
7070            if let Some(task_event) = self.pending_events.pop_front() {
7071                self.pending_events.push_back(event);
7072                let task_event = self.project_pointer(task_event);
7073                self.pre_dispatch(&task_event);
7074                return Ok(task_event);
7075            }
7076            if let Some(event) = self.translate_motion_event(event)? {
7077                let event = self.project_pointer(event);
7078                self.pre_dispatch(&event);
7079                return Ok(event);
7080            }
7081        }
7082    }
7083
7084    /// Polls one event, applying queued background-task commands first.
7085    ///
7086    /// Returns `None` when neither task notifications nor backend events are
7087    /// pending. The internal `TasksPending` wake marker is consumed here.
7088    pub fn poll_event(&mut self) -> GuiResult<Option<UiEvent>> {
7089        loop {
7090            #[cfg(feature = "async")]
7091            self.drain_task_commands();
7092            self.flush_layout_roots();
7093            if let Some(event) = self.pending_events.pop_front() {
7094                if let Some(event) = self.translate_motion_event(event)? {
7095                    let event = self.project_pointer(event);
7096                    self.pre_dispatch(&event);
7097                    return Ok(Some(event));
7098                }
7099                continue;
7100            }
7101
7102            match self.backend.poll_event()? {
7103                Some(UiEvent::TasksPending) => continue,
7104                Some(event) => {
7105                    if let Some(event) = self.translate_motion_event(event)? {
7106                        let event = self.project_pointer(event);
7107                        self.pre_dispatch(&event);
7108                        return Ok(Some(event));
7109                    }
7110                }
7111                None => return Ok(None),
7112            }
7113        }
7114    }
7115
7116    fn translate_motion_event(&mut self, event: UiEvent) -> GuiResult<Option<UiEvent>> {
7117        let UiEvent::TimerFired {
7118            timer,
7119            elapsed,
7120            missed,
7121        } = event
7122        else {
7123            return Ok(Some(event));
7124        };
7125        let Some(motion) = self.motion_timers.get(&timer).copied() else {
7126            return Ok(Some(UiEvent::TimerFired {
7127                timer,
7128                elapsed,
7129                missed,
7130            }));
7131        };
7132        let Some(active) = self.motions.get(&motion).copied() else {
7133            self.motion_timers.remove(&timer);
7134            return Ok(None);
7135        };
7136
7137        let finished = elapsed >= active.spec.duration;
7138        let progress = if finished {
7139            1.0
7140        } else {
7141            let ratio = elapsed.as_secs_f64() / active.spec.duration.as_secs_f64();
7142            (ratio as f32).min(f32::from_bits(1.0_f32.to_bits() - 1))
7143        };
7144
7145        if finished {
7146            self.backend.cancel_timer(timer)?;
7147            self.motions.remove(&motion);
7148            self.motion_timers.remove(&timer);
7149            self.pending_events.push_front(UiEvent::MotionFinished {
7150                motion,
7151                widget_id: active.widget_id,
7152            });
7153        }
7154
7155        Ok(Some(UiEvent::MotionTicked {
7156            motion,
7157            widget_id: active.widget_id,
7158            progress,
7159        }))
7160    }
7161
7162    fn purge_motion_events(&mut self, motion: MotionId, timer: TimerId) {
7163        self.pending_events.retain(|event| match event {
7164            UiEvent::TimerFired { timer: queued, .. } => *queued != timer,
7165            UiEvent::MotionTicked { motion: queued, .. }
7166            | UiEvent::MotionFinished { motion: queued, .. } => *queued != motion,
7167            _ => true,
7168        });
7169    }
7170
7171    fn remove_widget_motions(&mut self, widget_id: WidgetId) {
7172        let removed: Vec<_> = self
7173            .motions
7174            .iter()
7175            .filter_map(|(motion, active)| {
7176                (active.widget_id == widget_id).then_some((*motion, active.timer))
7177            })
7178            .collect();
7179        for (motion, timer) in &removed {
7180            self.motions.remove(motion);
7181            self.motion_timers.remove(timer);
7182        }
7183        self.pending_events.retain(|event| match event {
7184            UiEvent::TimerFired { timer, .. } => !removed.iter().any(|(_, queued)| queued == timer),
7185            UiEvent::MotionTicked {
7186                widget_id: queued, ..
7187            }
7188            | UiEvent::MotionFinished {
7189                widget_id: queued, ..
7190            } => *queued != widget_id,
7191            _ => true,
7192        });
7193    }
7194
7195    /// Projects a pointer event's coordinates onto the logical (96-DPI) space
7196    /// every app hit-tests against.
7197    ///
7198    /// Applied once per event, on the single path out of `Ui` — every
7199    /// `wait_event`/`poll_event` return and therefore every dispatch API and
7200    /// runner. Non-pointer events pass through untouched. See
7201    /// [`UiEvent::PointerDown`] for the contract and
7202    /// [`Self::logical_pointer_projection`] for the conversion itself.
7203    fn project_pointer(&mut self, mut event: UiEvent) -> UiEvent {
7204        if let UiEvent::PopupDismissed { widget_id, .. } = &event {
7205            self.hidden_widgets.insert(*widget_id);
7206        }
7207        match &mut event {
7208            UiEvent::PointerDown {
7209                widget_id, x, y, ..
7210            }
7211            | UiEvent::PointerMove { widget_id, x, y }
7212            | UiEvent::PointerUp {
7213                widget_id, x, y, ..
7214            } => self.project_axes(*widget_id, x, y),
7215            _ => {}
7216        }
7217        event
7218    }
7219
7220    /// Projects one pointer position onto the logical space.
7221    fn project_axes(&self, widget_id: WidgetId, x: &mut f32, y: &mut f32) {
7222        let (logical_x, logical_y) = self.logical_pointer_projection(widget_id, *x, *y);
7223        *x = logical_x;
7224        *y = logical_y;
7225    }
7226
7227    /// Drains queued events, running registered callbacks and invoking `handler`.
7228    ///
7229    /// Returns the number of dispatched events.
7230    pub fn dispatch_events<F>(&mut self, mut handler: F) -> GuiResult<usize>
7231    where
7232        F: FnMut(UiEvent),
7233    {
7234        let mut dispatched = 0;
7235        while let Some(event) = self.poll_event()? {
7236            self.dispatch_event(event, &mut handler);
7237            dispatched += 1;
7238        }
7239        Ok(dispatched)
7240    }
7241
7242    /// Drains queued events, running registered callbacks and invoking
7243    /// `handler` with `&mut Ui` so it can mutate widgets inline.
7244    ///
7245    /// Returns the number of dispatched events. Each event gets the same
7246    /// pre-handler treatment as [`Self::dispatch_events`] — layout-root
7247    /// recompute, focus bookkeeping, then the callbacks registered through
7248    /// `Ui::on_*` — and only then `handler` runs. Returning
7249    /// [`LoopFlow::Exit`] stops the drain early; events produced by the
7250    /// handler are queued, never dropped, and are delivered in the same
7251    /// drain (see [`Self::run_until_closed_with`] for the ordering and
7252    /// reentrancy rules).
7253    pub fn dispatch_events_with<F>(&mut self, mut handler: F) -> GuiResult<usize>
7254    where
7255        F: FnMut(&mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
7256    {
7257        let mut dispatched = 0;
7258        while let Some(event) = self.poll_event()? {
7259            dispatched += 1;
7260            if handler(self, event)? == LoopFlow::Exit {
7261                break;
7262            }
7263        }
7264        Ok(dispatched)
7265    }
7266
7267    /// Runs the application event loop until a `WindowClosed` event arrives.
7268    ///
7269    /// Blocks efficiently (no 16 ms sleep loop): `wait_event` parks the
7270    /// backend until an event is ready. Each event gets the same treatment
7271    /// as in [`Self::dispatch_events`] — layout-root recompute, registered
7272    /// callbacks, then `handler`.
7273    pub fn run_until_closed<F>(&mut self, mut handler: F) -> GuiResult<()>
7274    where
7275        F: FnMut(UiEvent),
7276    {
7277        loop {
7278            let event = self.wait_event()?;
7279            let closed = matches!(event, UiEvent::WindowClosed { .. });
7280            self.dispatch_event(event, &mut handler);
7281            if closed {
7282                return Ok(());
7283            }
7284        }
7285    }
7286
7287    /// Runs the application event loop until a `WindowClosed` event arrives,
7288    /// handing `handler` both the UI and the event so it can mutate widgets
7289    /// inline.
7290    ///
7291    /// Blocks efficiently (no poll loop): `wait_event` parks the backend
7292    /// until an event is ready. Each event gets the same pre-handler
7293    /// treatment as [`Self::dispatch_events`] — layout-root recompute, focus
7294    /// bookkeeping, then the callbacks registered through `Ui::on_*` — and
7295    /// only then `handler` runs with `&mut Ui`. Returning
7296    /// [`LoopFlow::Exit`] stops the loop early; `WindowClosed` always stops
7297    /// it after the handler has seen the event.
7298    ///
7299    /// # Reentrancy and ordering
7300    ///
7301    /// - A handler may call any `Ui` API; re-entering this runner or
7302    ///   [`Self::dispatch_events_with`] is prevented at compile time by the
7303    ///   `&mut Ui` borrow.
7304    /// - Registered callbacks run before the handler for the same event,
7305    ///   exactly like [`Self::dispatch_events`].
7306    /// - Events produced by a handler (for example `Ui::activate` on the
7307    ///   Mock backend) are queued, never dropped, and are delivered on
7308    ///   subsequent iterations; a handler that unconditionally produces
7309    ///   events keeps the loop busy, so guards belong in app code.
7310    pub fn run_until_closed_with<F>(&mut self, mut handler: F) -> GuiResult<()>
7311    where
7312        F: FnMut(&mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
7313    {
7314        loop {
7315            let event = self.wait_event()?;
7316            let closed = matches!(event, UiEvent::WindowClosed { .. });
7317            let flow = handler(self, event)?;
7318            if closed || flow == LoopFlow::Exit {
7319                return Ok(());
7320            }
7321        }
7322    }
7323
7324    /// Runs the application event loop until it closes, with an optional
7325    /// autoclose budget.
7326    ///
7327    /// `budget == None` is exactly [`Self::run_until_closed`]: the loop parks
7328    /// in `wait_event` with no polling and returns once a
7329    /// [`UiEvent::WindowClosed`] arrives. With `Some(budget)` the loop polls
7330    /// ([`Self::poll_event`] plus a [`crate::autoclose::BOUNDED_POLL_INTERVAL`]
7331    /// sleep) and returns as soon as one of three things happens: the window
7332    /// closed, the handler answered [`LoopFlow::Exit`], or the budget elapsed
7333    /// — see [`RunStop`] for which.
7334    ///
7335    /// This is the library half of the `NATIVE_GUI_<APP>_AUTOCLOSE_MS` contract the
7336    /// example-level hook established: an unattended capture run must
7337    /// end by itself, because the runner's `TERM` can only ever be reported as
7338    /// a hang. The budget itself is resolved by
7339    /// [`crate::autoclose::from_env`], which the `native-gui` facade's `app::run`
7340    /// calls for you.
7341    ///
7342    /// # Ordering
7343    ///
7344    /// The same pre-handler treatment as [`Self::dispatch_events`] applies
7345    /// (layout-root recompute, focus bookkeeping, then the callbacks
7346    /// registered through `Ui::on_*`), and events produced by the handler are
7347    /// queued rather than dropped — except that a stop leaves anything still
7348    /// queued undelivered, exactly like [`Self::run_until_closed`].
7349    pub fn run_bounded<F>(&mut self, budget: Option<Duration>, mut handler: F) -> GuiResult<RunStop>
7350    where
7351        F: FnMut(UiEvent),
7352    {
7353        self.run_bounded_with(budget, |_ui, event| {
7354            handler(event);
7355            Ok(LoopFlow::Continue)
7356        })
7357    }
7358
7359    /// [`Self::run_until_closed_with`], bounded by an optional autoclose
7360    /// budget.
7361    ///
7362    /// Drop-in for the `&mut Ui` runner: without a budget it forwards to
7363    /// [`Self::run_until_closed_with`] unchanged, so the blocking,
7364    /// callback-first semantics stay the library's. With a budget it drives
7365    /// the public [`Self::dispatch_events_with`] pump and stops on the first
7366    /// of a [`UiEvent::WindowClosed`], a [`LoopFlow::Exit`] from the handler,
7367    /// or the elapsed budget, reporting which through [`RunStop`].
7368    pub fn run_bounded_with<F>(
7369        &mut self,
7370        budget: Option<Duration>,
7371        mut handler: F,
7372    ) -> GuiResult<RunStop>
7373    where
7374        F: FnMut(&mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
7375    {
7376        let Some(budget) = budget else {
7377            self.run_until_closed_with(handler)?;
7378            return Ok(RunStop::WindowClosed);
7379        };
7380
7381        let started = Instant::now();
7382        loop {
7383            let mut stop = None;
7384            self.dispatch_events_with(|ui, event| {
7385                let closed = matches!(event, UiEvent::WindowClosed { .. });
7386                let flow = handler(ui, event)?;
7387                if closed {
7388                    stop = Some(RunStop::WindowClosed);
7389                } else if flow == LoopFlow::Exit {
7390                    stop = Some(RunStop::Exit);
7391                }
7392                if stop.is_some() {
7393                    return Ok(LoopFlow::Exit);
7394                }
7395                Ok(LoopFlow::Continue)
7396            })?;
7397
7398            if let Some(stop) = stop {
7399                return Ok(stop);
7400            }
7401            if started.elapsed() >= budget {
7402                return Ok(RunStop::TimedOut);
7403            }
7404            std::thread::sleep(crate::autoclose::BOUNDED_POLL_INTERVAL);
7405        }
7406    }
7407
7408    /// Runs the application event loop with typed message routing.
7409    ///
7410    /// Each event is translated through `routes` (ignore-by-default); when a
7411    /// route matches, `handler` receives the typed message with `&mut Ui`.
7412    /// Registered `Ui::on_*` callbacks still run first, exactly like
7413    /// [`Self::run_until_closed_with`]. The loop ends after the handler sees
7414    /// a `WindowClosed` event, or early when the handler returns
7415    /// [`LoopFlow::Exit`].
7416    #[cfg(feature = "routes")]
7417    pub fn run_routed<M, F>(&mut self, routes: &Routes<M>, mut handler: F) -> GuiResult<()>
7418    where
7419        M: Clone + 'static,
7420        F: FnMut(&mut Ui<B>, M) -> GuiResult<LoopFlow>,
7421    {
7422        self.run_until_closed_with(|ui, event| match routes.translate(&event) {
7423            Some(message) => handler(ui, message),
7424            None => Ok(LoopFlow::Continue),
7425        })
7426    }
7427
7428    /// Drains queued events with typed message routing.
7429    ///
7430    /// Like [`Self::dispatch_events_with`], but each event is translated
7431    /// through `routes` first. Returns the number of dispatched events
7432    /// (routed or ignored).
7433    #[cfg(feature = "routes")]
7434    pub fn dispatch_routed<M, F>(&mut self, routes: &Routes<M>, mut handler: F) -> GuiResult<usize>
7435    where
7436        M: Clone + 'static,
7437        F: FnMut(&mut Ui<B>, M) -> GuiResult<LoopFlow>,
7438    {
7439        self.dispatch_events_with(|ui, event| match routes.translate(&event) {
7440            Some(message) => handler(ui, message),
7441            None => Ok(LoopFlow::Continue),
7442        })
7443    }
7444
7445    fn dispatch_event<F>(&mut self, event: UiEvent, handler: &mut F)
7446    where
7447        F: FnMut(UiEvent),
7448    {
7449        handler(event);
7450    }
7451
7452    /// Work shared by every dispatch path: layout recompute for layout
7453    /// roots, focus bookkeeping, and registered callbacks.
7454    pub fn pre_dispatch(&mut self, event: &UiEvent) {
7455        if let UiEvent::WindowResized {
7456            widget_id,
7457            width,
7458            height,
7459        } = event
7460        {
7461            if self.layout_roots.contains(widget_id) {
7462                if let Some(compute) = self.auto_layout_fn {
7463                    let _ = compute(self, *widget_id, *width as f32, *height as f32);
7464                }
7465            }
7466        }
7467        if let UiEvent::FocusChanged { widget_id, focused } = event {
7468            if *focused {
7469                self.focused = Some(*widget_id);
7470            } else if self.focused == Some(*widget_id) {
7471                self.focused = None;
7472            }
7473        }
7474        #[cfg(feature = "widgets-pickers")]
7475        if let UiEvent::ColorSelected {
7476            widget_id,
7477            color: Some(color),
7478        } = event
7479        {
7480            if let Some(spec) = self.widgets.get_mut(widget_id) {
7481                if spec.kind == WidgetKind::ColorDialog {
7482                    spec.color_dialog_data
7483                        .get_or_insert_with(|| ColorDialogData::new(*color))
7484                        .remember_accepted(*color);
7485                }
7486            }
7487        }
7488        #[cfg(feature = "widgets-pickers")]
7489        if let UiEvent::FontSelected {
7490            widget_id,
7491            selection: Some((descriptor, effects)),
7492        } = event
7493        {
7494            if let Some(spec) = self.widgets.get_mut(widget_id) {
7495                if spec.kind == WidgetKind::FontDialog {
7496                    let data = spec
7497                        .font_dialog_data
7498                        .get_or_insert_with(|| FontDialogData::new(descriptor.clone()));
7499                    data.effects = *effects;
7500                    // The shared clamp keeps the stored preference inside the
7501                    // configured range even if a lane returns an unclamped
7502                    // descriptor.
7503                    let size = data.clamp_size(descriptor.size_pt);
7504                    data.initial = FontDescriptor {
7505                        size_pt: size,
7506                        ..descriptor.clone()
7507                    };
7508                }
7509            }
7510        }
7511        self.mirror_user_value(event);
7512        if let UiEvent::ToolToggled {
7513            widget_id,
7514            tool_id,
7515            checked,
7516        } = event
7517        {
7518            // User toggles arrive from the native control (or the Mock
7519            // injector); mirroring the reported state means the shared model
7520            // never fights the user's last action, so a later
7521            // `set_tool_state` only reports real differences.
7522            if let Some(spec) = self.widgets.get_mut(widget_id) {
7523                if spec.kind == WidgetKind::Toolbar {
7524                    if let Some(tool) = toolbar::find_tool_mut(&mut spec.toolbar_items, *tool_id) {
7525                        tool.checked = *checked;
7526                    }
7527                }
7528            }
7529        }
7530        #[cfg(feature = "property-grid")]
7531        self.observe_property_grid_event(event);
7532        #[cfg(feature = "styled-text")]
7533        self.observe_styled_text_event(event);
7534        #[cfg(feature = "webview")]
7535        self.observe_webview_event(event);
7536        self.dispatch_registered_callbacks(event);
7537    }
7538
7539    /// Queues an event produced by the shared layer; it is delivered before
7540    /// the next backend event.
7541    #[cfg(any(feature = "property-grid", feature = "styled-text"))]
7542    pub(crate) fn queue_event(&mut self, event: UiEvent) {
7543        self.pending_events.push_back(event);
7544    }
7545
7546    /// Observes an event for the UI's internal bookkeeping.
7547    pub fn observe_event(&mut self, event: &UiEvent) {
7548        self.pre_dispatch(event);
7549    }
7550
7551    /// Mirrors values the *user* changed into the shared spec, so the live
7552    /// getters ([`Self::text`], [`Self::is_checked`],
7553    /// [`Self::selected_index`], [`Self::value`], [`Self::date_value`]) report
7554    /// what the native control shows rather than the last programmatic write.
7555    fn mirror_user_value(&mut self, event: &UiEvent) {
7556        match event {
7557            UiEvent::TextChanged { widget_id, text }
7558            | UiEvent::TextSubmitted { widget_id, text } => {
7559                if let Some(spec) = self.widgets.get_mut(widget_id) {
7560                    #[cfg(feature = "widgets-text")]
7561                    let is_text_input = matches!(
7562                        spec.kind,
7563                        WidgetKind::TextInput | WidgetKind::TextArea | WidgetKind::RichText
7564                    );
7565                    #[cfg(not(feature = "widgets-text"))]
7566                    let is_text_input = false;
7567                    if is_text_input {
7568                        spec.text = Some(text.clone());
7569                    }
7570                }
7571            }
7572            UiEvent::Toggled { widget_id, checked } => {
7573                if let Some(spec) = self.widgets.get_mut(widget_id) {
7574                    if spec.ensure_property(WidgetProperty::Checked).is_ok() {
7575                        spec.checked = Some(*checked);
7576                    }
7577                }
7578            }
7579            UiEvent::SelectionChanged {
7580                widget_id, index, ..
7581            } => {
7582                let mirrored = match self.widgets.get_mut(widget_id) {
7583                    Some(spec) if spec.ensure_property(WidgetProperty::SelectedIndex).is_ok() => {
7584                        spec.selected_index = *index;
7585                        true
7586                    }
7587                    _ => false,
7588                };
7589                if mirrored {
7590                    if let Some(index) = index {
7591                        self.record_keyed_selection(*widget_id, &[*index]);
7592                    }
7593                }
7594            }
7595            UiEvent::MultiSelectionChanged { widget_id, indices } => {
7596                if let Some(spec) = self.widgets.get_mut(widget_id) {
7597                    if spec
7598                        .ensure_property(WidgetProperty::SelectedIndices)
7599                        .is_ok()
7600                    {
7601                        spec.selected_indices = indices.clone();
7602                    }
7603                }
7604            }
7605            UiEvent::ValueChanged { widget_id, value } => {
7606                if let Some(spec) = self.widgets.get_mut(widget_id) {
7607                    if spec.ensure_property(WidgetProperty::Value).is_ok() {
7608                        spec.value = Some(*value);
7609                    }
7610                }
7611            }
7612            UiEvent::DateChanged {
7613                widget_id,
7614                iso_date,
7615            } => {
7616                if let Some(spec) = self.widgets.get_mut(widget_id) {
7617                    spec.date_value = Some(iso_date.clone());
7618                }
7619            }
7620            _ => {}
7621        }
7622    }
7623
7624    /// The live text of a widget: the user's latest edit for text controls
7625    /// (mirrored from `TextChanged`/`TextSubmitted` during dispatch), else
7626    /// the last value written with [`Self::set_text`] or at creation.
7627    ///
7628    /// Returns `""` for a widget that never had text.
7629    pub fn text(&self, widget_id: WidgetId) -> GuiResult<&str> {
7630        let spec = self
7631            .widgets
7632            .get(&widget_id)
7633            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
7634        Ok(spec.text.as_deref().unwrap_or(""))
7635    }
7636
7637    /// The live checked state of a check-capable widget (`Checkbox`,
7638    /// `RadioButton`, …), kept in sync with user `Toggled` events.
7639    ///
7640    /// Returns `false` when the state was never set or reported.
7641    pub fn is_checked(&self, widget_id: WidgetId) -> GuiResult<bool> {
7642        let spec = self.widget_spec(widget_id)?;
7643        spec.ensure_property(WidgetProperty::Checked)?;
7644        Ok(spec.checked.unwrap_or(false))
7645    }
7646
7647    /// The live selected index of a selection widget (`ComboBox`,
7648    /// `ListView`, `DataList`, `Tabs`, …), kept in sync with user
7649    /// `SelectionChanged` events. `None` means nothing is selected.
7650    pub fn selected_index(&self, widget_id: WidgetId) -> GuiResult<Option<usize>> {
7651        let spec = self.widget_spec(widget_id)?;
7652        spec.ensure_property(WidgetProperty::SelectedIndex)?;
7653        Ok(spec.selected_index)
7654    }
7655
7656    /// The live selected indices of a multi-selection widget, kept in sync
7657    /// with user `MultiSelectionChanged` events.
7658    pub fn selected_indices(&self, widget_id: WidgetId) -> GuiResult<&[usize]> {
7659        let spec = self.widget_spec(widget_id)?;
7660        spec.ensure_property(WidgetProperty::SelectedIndices)?;
7661        Ok(&spec.selected_indices)
7662    }
7663
7664    /// The live numeric value of a range widget (`Slider`, `SpinBox`,
7665    /// `ProgressBar`), kept in sync with user `ValueChanged` events.
7666    pub fn value(&self, widget_id: WidgetId) -> GuiResult<Option<i32>> {
7667        let spec = self.widget_spec(widget_id)?;
7668        spec.ensure_property(WidgetProperty::Value)?;
7669        Ok(spec.value)
7670    }
7671
7672    /// The live ISO date of a date widget, kept in sync with user
7673    /// `DateChanged` events.
7674    pub fn date_value(&self, widget_id: WidgetId) -> GuiResult<Option<&str>> {
7675        let spec = self.widget_spec(widget_id)?;
7676        Ok(spec.date_value.as_deref())
7677    }
7678
7679    /// Registers a callback triggered when the given window closes.
7680    pub fn on_window_close<F>(&mut self, window_id: WidgetId, callback: F) -> GuiResult<()>
7681    where
7682        F: FnMut() + 'static,
7683    {
7684        self.ensure_window(window_id, WidgetProperty::WindowCallback)?;
7685        self.on_window_close
7686            .entry(window_id)
7687            .or_default()
7688            .push(Box::new(callback));
7689        Ok(())
7690    }
7691
7692    /// Registers a callback triggered when the given window is resized.
7693    pub fn on_window_resize<F>(&mut self, window_id: WidgetId, callback: F) -> GuiResult<()>
7694    where
7695        F: FnMut(i32, i32) + 'static,
7696    {
7697        self.ensure_window(window_id, WidgetProperty::WindowCallback)?;
7698        self.on_window_resize
7699            .entry(window_id)
7700            .or_default()
7701            .push(Box::new(callback));
7702        Ok(())
7703    }
7704
7705    /// Registers a window whose declarative layout is kept in sync with the
7706    /// native window automatically.
7707    ///
7708    /// Whenever `dispatch_events` sees a `UiEvent::WindowResized` for
7709    /// `window_id`, `compute_layout` runs with the new dimensions before
7710    /// user handlers. App code no longer needs manual resize plumbing to
7711    /// keep computed layouts correct.
7712    ///
7713    /// Multiple windows can be registered simultaneously. Calling
7714    /// `set_layout_root` adds `window_id` to the registered layout roots.
7715    pub fn set_layout_root(&mut self, window_id: WidgetId) -> GuiResult<()> {
7716        self.add_layout_root(window_id)
7717    }
7718
7719    /// Adds a window to the set of registered layout roots.
7720    ///
7721    /// Secondary windows and dialogs can be added so they also automatically
7722    /// recompute layout on resize without clobbering other windows.
7723    pub fn add_layout_root(&mut self, window_id: WidgetId) -> GuiResult<()> {
7724        self.ensure_window(window_id, WidgetProperty::LayoutRoot)?;
7725        self.enable_auto_layout();
7726        self.layout_roots.insert(window_id);
7727        if let Some((w, h)) = self.widgets.get(&window_id).and_then(|spec| spec.size) {
7728            self.layout_root_sizes
7729                .insert(window_id, (w as f32, h as f32));
7730            self.invalidate_layout(window_id);
7731        }
7732        Ok(())
7733    }
7734
7735    /// Returns whether any layout roots have pending layout invalidations.
7736    pub fn has_dirty_layout(&self) -> bool {
7737        !self.layout_dirty.is_empty()
7738    }
7739
7740    /// Returns whether `widget_id` is in the pending layout invalidation schedule.
7741    pub fn is_layout_dirty(&self, widget_id: WidgetId) -> bool {
7742        self.layout_dirty.contains(&widget_id)
7743    }
7744
7745    /// Re-runs layout for every layout root that has pending invalidations.
7746    ///
7747    /// Called before each event poll/wait, so widgets shown, hidden,
7748    /// re-sized or re-attached since the last pass - inside a handler or
7749    /// after `dispatch_events` returned - are laid out at the root's last
7750    /// known size instead of waiting for the next window resize. Free when
7751    /// nothing is scheduled; roots that were never laid out are skipped.
7752    pub fn flush_layout_roots(&mut self) {
7753        let Some(compute) = self.auto_layout_fn else {
7754            return;
7755        };
7756        if self.layout_dirty.is_empty() {
7757            return;
7758        }
7759        let pending: Vec<(WidgetId, (f32, f32))> = self
7760            .layout_root_sizes
7761            .iter()
7762            .filter(|(root, _)| self.layout_roots.contains(root))
7763            .filter(|(root, _)| {
7764                self.layout_dirty
7765                    .iter()
7766                    .any(|widget_id| self.chain_reaches_root(*widget_id, **root))
7767            })
7768            .map(|(root, size)| (*root, *size))
7769            .collect();
7770        for (root, (width, height)) in pending {
7771            let _ = compute(self, root, width, height);
7772        }
7773    }
7774
7775    /// Synchronously runs a layout pass on any layout roots with pending invalidations.
7776    ///
7777    /// Equivalent to [`Self::flush_layout_roots`].
7778    pub fn compute_layout_if_dirty(&mut self) {
7779        self.flush_layout_roots();
7780    }
7781
7782    /// Removes a window from the set of registered layout roots.
7783    /// Returns `true` if the window was registered.
7784    pub fn remove_layout_root(&mut self, window_id: WidgetId) -> bool {
7785        self.layout_roots.remove(&window_id)
7786    }
7787
7788    /// Returns `true` if the given window is currently a registered layout root.
7789    pub fn is_layout_root(&self, window_id: WidgetId) -> bool {
7790        self.layout_roots.contains(&window_id)
7791    }
7792
7793    /// Returns the set of currently registered layout roots.
7794    pub fn layout_roots(&self) -> &HashSet<WidgetId> {
7795        &self.layout_roots
7796    }
7797
7798    /// Registers a callback triggered when a menu item is selected.
7799    pub fn on_menu_item_selected<F>(&mut self, item_id: MenuItemId, callback: F) -> GuiResult<()>
7800    where
7801        F: FnMut() + 'static,
7802    {
7803        if !self.menu_item_to_menu.contains_key(&item_id) {
7804            return Err(GuiError::Backend(format!(
7805                "Menu item not found: {}",
7806                item_id.0
7807            )));
7808        }
7809
7810        self.on_menu_item_selected
7811            .entry(item_id)
7812            .or_default()
7813            .push(Box::new(callback));
7814        Ok(())
7815    }
7816
7817    /// Native string APIs truncate at the first NUL. Reject before the spec
7818    /// or a backend buffer is built so the stored text cannot diverge from
7819    /// the control.
7820    fn reject_embedded_nul(text: &str) -> GuiResult<()> {
7821        if text.contains('\0') {
7822            Err(GuiError::Backend(
7823                "text cannot contain an embedded NUL".to_owned(),
7824            ))
7825        } else {
7826            Ok(())
7827        }
7828    }
7829
7830    /// Looks up a widget by id, returning the shared typed error when missing.
7831    pub(crate) fn widget_spec(&self, widget_id: WidgetId) -> GuiResult<&WidgetSpec> {
7832        self.widgets
7833            .get(&widget_id)
7834            .ok_or(GuiError::WidgetNotFound(widget_id.0))
7835    }
7836
7837    /// Looks a widget up mutably and rejects `property` when its kind is
7838    /// outside the row's applicability.
7839    ///
7840    /// This is the shared entry point for every kind guard in `Ui`: the
7841    /// allowed kinds live in [`WidgetProperty::applicable_kinds`], never in
7842    /// the setter body.
7843    fn require_property(
7844        &mut self,
7845        widget_id: WidgetId,
7846        property: WidgetProperty,
7847    ) -> GuiResult<&mut WidgetSpec> {
7848        let spec = self
7849            .widgets
7850            .get_mut(&widget_id)
7851            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
7852        spec.ensure_property(property)?;
7853        Ok(spec)
7854    }
7855
7856    /// Validates that `widget_id` is a window.
7857    fn ensure_window(&self, widget_id: WidgetId, property: WidgetProperty) -> GuiResult<()> {
7858        self.widget_spec(widget_id)?.ensure_property(property)
7859    }
7860
7861    fn dispatch_registered_callbacks(&mut self, event: &UiEvent) {
7862        match event {
7863            UiEvent::WindowClosed { widget_id } => {
7864                if let Some(callbacks) = self.on_window_close.get_mut(widget_id) {
7865                    for callback in callbacks.iter_mut() {
7866                        callback();
7867                    }
7868                }
7869            }
7870            UiEvent::WindowResized {
7871                widget_id,
7872                width,
7873                height,
7874            } => {
7875                if let Some(callbacks) = self.on_window_resize.get_mut(widget_id) {
7876                    for callback in callbacks.iter_mut() {
7877                        callback(*width, *height);
7878                    }
7879                }
7880            }
7881            UiEvent::MenuItemSelected { item_id, .. } => {
7882                if let Some(callbacks) = self.on_menu_item_selected.get_mut(item_id) {
7883                    for callback in callbacks.iter_mut() {
7884                        callback();
7885                    }
7886                }
7887            }
7888            _ => {}
7889        }
7890    }
7891
7892    /// Returns a widget specification by identifier.
7893    pub fn widget(&self, widget_id: WidgetId) -> Option<&WidgetSpec> {
7894        self.widgets.get(&widget_id)
7895    }
7896
7897    #[doc(hidden)]
7898    pub fn e2e_widget_specs(&self) -> impl Iterator<Item = &WidgetSpec> {
7899        self.widgets.values()
7900    }
7901
7902    #[doc(hidden)]
7903    pub fn e2e_dispatch_one<F>(&mut self, handler: &mut F) -> GuiResult<Option<LoopFlow>>
7904    where
7905        F: FnMut(&mut Self, UiEvent) -> GuiResult<LoopFlow>,
7906    {
7907        #[cfg(feature = "async")]
7908        self.drain_task_commands();
7909        let event = match self.pending_events.pop_front() {
7910            Some(event) => Some(event),
7911            None => self.backend.e2e_poll_event()?,
7912        };
7913        let Some(event) = event else {
7914            return Ok(None);
7915        };
7916        let Some(event) = self.translate_motion_event(event)? else {
7917            return Ok(Some(LoopFlow::Continue));
7918        };
7919        let event = self.project_pointer(event);
7920        if matches!(event, UiEvent::TasksPending) {
7921            return Ok(Some(LoopFlow::Continue));
7922        }
7923        match &event {
7924            UiEvent::TextChanged { widget_id, text } => {
7925                if let Some(spec) = self.widgets.get_mut(widget_id) {
7926                    spec.text = Some(text.clone());
7927                }
7928            }
7929            UiEvent::Toggled { widget_id, checked } => {
7930                if let Some(spec) = self.widgets.get_mut(widget_id) {
7931                    spec.checked = Some(*checked);
7932                }
7933            }
7934            _ => {}
7935        }
7936        self.pre_dispatch(&event);
7937        handler(self, event).map(Some)
7938    }
7939
7940    /// Returns the number of known widgets.
7941    pub fn widget_count(&self) -> usize {
7942        self.widgets.len()
7943    }
7944}
7945
7946#[cfg(feature = "widgets-data")]
7947fn serialize_data_grid_rows(rows: &[Vec<String>]) -> String {
7948    rows.iter()
7949        .map(|row| row.join("\t"))
7950        .collect::<Vec<String>>()
7951        .join("\n")
7952}
7953
7954#[cfg(feature = "widgets-data")]
7955fn parse_data_list_items(content: &str) -> Vec<String> {
7956    content
7957        .lines()
7958        .map(str::trim)
7959        .filter(|line| !line.is_empty())
7960        .map(ToOwned::to_owned)
7961        .collect()
7962}
7963
7964#[cfg(feature = "widgets-data")]
7965fn parse_data_grid_rows(content: &str) -> Vec<Vec<String>> {
7966    content
7967        .lines()
7968        .filter(|line| !line.trim().is_empty())
7969        .map(|line| line.split('\t').map(ToOwned::to_owned).collect())
7970        .collect()
7971}
7972
7973#[cfg(test)]
7974mod tests {
7975    use crate::access::AccessibleRole;
7976    use crate::events::{AccessibleNotification, UiEvent};
7977    use crate::pickers::Rgba;
7978    use crate::test_support::MockBackend;
7979    use crate::theme::{Theme, ThemeMode, ThemeOverride};
7980
7981    use super::*;
7982
7983    #[test]
7984    fn backend_inventory_matches_declarations_and_group_totals() {
7985        let raw_source = include_str!("ui.rs");
7986        let source = raw_source.replace("\r\n", "\n");
7987        let body = |declaration| {
7988            source
7989                .split_once(declaration)
7990                .unwrap()
7991                .1
7992                .split_once("\n}\n")
7993                .unwrap()
7994                .0
7995        };
7996        let backend = body("\npub trait Backend: TextMeasure {");
7997        let methods = |body: &str| {
7998            body.lines()
7999                .filter(|line| line.starts_with("    fn ") || line.starts_with("    unsafe fn "))
8000                .count()
8001        };
8002        let declared = methods(backend);
8003        let associated = backend
8004            .lines()
8005            .filter(|line| line.starts_with("    type "))
8006            .count();
8007        let inherited = methods(body("\npub trait TextMeasure {"));
8008        let total = declared + associated + inherited;
8009        assert!(source.contains(&format!(
8010            "/// The trait carries {total} items: {declared} methods declared here"
8011        )));
8012        assert!(source.contains(&format!(
8013            "/// It must print `Backend {declared} fns + {associated} assoc type + {inherited} supertrait fn = {total}"
8014        )));
8015        let table = source
8016            .split_once("/// | Group | Items | Covers |")
8017            .unwrap()
8018            .1
8019            .split_once("/// # Maintenance")
8020            .unwrap()
8021            .0;
8022        let grouped: usize = table
8023            .lines()
8024            .filter_map(|line| line.split('|').nth(2)?.trim().parse::<usize>().ok())
8025            .sum();
8026        assert_eq!(grouped, total);
8027    }
8028
8029    #[test]
8030    fn create_attach_show_happy_path() {
8031        let backend = MockBackend::default();
8032        let mut ui = Ui::new(backend);
8033
8034        let window = ui
8035            .create(WidgetKind::Window, Some("Main"))
8036            .expect("window should be created");
8037        let button = ui
8038            .create(WidgetKind::Button, Some("Run"))
8039            .expect("button should be created");
8040
8041        ui.attach(window, button).expect("attach should succeed");
8042        ui.show(window).expect("window should show");
8043
8044        assert_eq!(ui.widget_count(), 2);
8045        assert_eq!(ui.widget(button).and_then(|s| s.parent), Some(window));
8046        assert_eq!(ui.backend().shown, vec![window]);
8047    }
8048
8049    #[test]
8050    fn set_text_for_unknown_widget_fails() {
8051        let backend = MockBackend::default();
8052        let mut ui = Ui::new(backend);
8053
8054        let err = ui
8055            .set_text(WidgetId(999), "Nope")
8056            .expect_err("unknown widget should return error");
8057
8058        assert_eq!(err, GuiError::WidgetNotFound(999));
8059    }
8060
8061    #[test]
8062    #[cfg(feature = "widgets-text")]
8063    fn set_text_updates_text_area() {
8064        let backend = MockBackend::default();
8065        let mut ui = Ui::new(backend);
8066
8067        let text_area = ui
8068            .create(WidgetKind::TextArea, Some("line 1"))
8069            .expect("text area should be created");
8070
8071        ui.set_text(text_area, "line 1\nline 2")
8072            .expect("set_text should update text area");
8073
8074        assert_eq!(
8075            ui.widget(text_area).and_then(|spec| spec.text.as_deref()),
8076            Some("line 1\nline 2")
8077        );
8078    }
8079
8080    #[test]
8081    #[cfg(feature = "widgets-text")]
8082    fn set_text_and_placeholder_reject_embedded_nul_without_mutating_spec() {
8083        let mut ui = Ui::new(MockBackend::default());
8084        let input = ui
8085            .create(WidgetKind::TextInput, Some("visible"))
8086            .expect("text input should be created");
8087        ui.set_placeholder_text(input, "hint")
8088            .expect("placeholder should be accepted");
8089
8090        let err = ui
8091            .set_text(input, "visible\0hidden")
8092            .expect_err("embedded NUL must be rejected");
8093        assert!(
8094            matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")),
8095            "unexpected error: {err:?}"
8096        );
8097        assert_eq!(
8098            ui.widget(input).and_then(|spec| spec.text.as_deref()),
8099            Some("visible"),
8100            "a rejected set_text must not store the truncated suffix"
8101        );
8102
8103        let err = ui
8104            .set_placeholder_text(input, "hint\0hidden")
8105            .expect_err("embedded NUL must be rejected");
8106        assert!(matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")));
8107        assert_eq!(
8108            ui.widget(input)
8109                .and_then(|spec| spec.placeholder_text.as_deref()),
8110            Some("hint")
8111        );
8112    }
8113
8114    #[test]
8115    fn comprehensive_embedded_nul_rejection_and_transactional_rollback() {
8116        let mut ui = Ui::new(MockBackend::default());
8117        // Creation text rejection
8118        let err = ui
8119            .create(WidgetKind::Label, Some("visible\0hidden"))
8120            .expect_err("embedded NUL in creation text must be rejected");
8121        assert!(matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")));
8122
8123        let label = ui
8124            .create(WidgetKind::Label, Some("status"))
8125            .expect("clean label");
8126        #[cfg(feature = "widgets-media")]
8127        let img = ui.create(WidgetKind::Image, None).expect("clean image");
8128        let tabs = ui.create(WidgetKind::Tabs, None).expect("clean tabs");
8129
8130        // Tooltip rejection
8131        let err = ui
8132            .set_tooltip(label, "info\0hidden")
8133            .expect_err("embedded NUL in tooltip must be rejected");
8134        assert!(matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")));
8135        assert_eq!(ui.widget(label).and_then(|s| s.tooltip.as_deref()), None);
8136
8137        // Image source rejection
8138        #[cfg(feature = "widgets-media")]
8139        {
8140            let err = ui
8141                .set_image_source(img, "art\0hidden.png")
8142                .expect_err("embedded NUL in image source must be rejected");
8143            assert!(matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")));
8144            assert_eq!(ui.widget(img).and_then(|s| s.image_source.as_deref()), None);
8145        }
8146
8147        // Tab items rejection
8148        let err = ui
8149            .set_tab_items(tabs, &["Tab 1".to_owned(), "Tab 2\0hidden".to_owned()])
8150            .expect_err("embedded NUL in tab items must be rejected");
8151        assert!(matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")));
8152        assert!(ui.widget(tabs).unwrap().tab_items.is_empty());
8153
8154        // Confirm dialog rejection
8155        let err = ui
8156            .show_confirm_dialog("Delete?\0hidden", "Are you sure?")
8157            .expect_err("embedded NUL in dialog title must be rejected");
8158        assert!(matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")));
8159
8160        // Menu rejection
8161        let menu = ui.create_menu().expect("menu");
8162        let err = ui
8163            .add_submenu(menu, "Sub\0hidden")
8164            .expect_err("embedded NUL in submenu must be rejected");
8165        assert!(matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")));
8166
8167        let err = ui
8168            .add_menu_item(menu, "Item\0hidden")
8169            .expect_err("embedded NUL in menu item must be rejected");
8170        assert!(matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")));
8171    }
8172
8173    #[test]
8174    fn unsupported_label_presentation_setters_are_transactional() {
8175        let mut ui = Ui::new(CustomMeasuringBackend::default());
8176        let label = ui
8177            .create(WidgetKind::Label, Some("status"))
8178            .expect("label should be created");
8179        let before = ui.widget(label).cloned().expect("label spec");
8180
8181        assert_eq!(
8182            ui.set_label_alignment(label, LabelAlignment::Center),
8183            Err(GuiError::UnsupportedCapability(
8184                "label_alignment".to_owned()
8185            ))
8186        );
8187        assert_eq!(
8188            ui.set_label_wrap(label, LabelWrap::Word),
8189            Err(GuiError::UnsupportedCapability("label_wrap".to_owned()))
8190        );
8191
8192        assert_eq!(ui.widget(label), Some(&before));
8193        assert_eq!(ui.backend().created.get(&label), Some(&before));
8194    }
8195
8196    #[test]
8197    #[cfg(feature = "widgets-canvas")]
8198    fn canvas_surface_round_trips_and_rejects_other_kinds() {
8199        let backend = MockBackend::default();
8200        let mut ui = Ui::new(backend);
8201
8202        let canvas = ui
8203            .create(WidgetKind::Canvas, None)
8204            .expect("canvas should be created");
8205        let button = ui
8206            .create(WidgetKind::Button, Some("button"))
8207            .expect("button should be created");
8208
8209        let mut pixels = vec![0u8; 4 * 4 * 4];
8210        for pixel in pixels.as_chunks_mut::<4>().0 {
8211            pixel[3] = 255;
8212        }
8213        let surface = crate::CanvasSurface::from_rgba(4, 4, pixels).expect("valid surface");
8214        assert_eq!(surface.width(), 4);
8215        assert_eq!(surface.height(), 4);
8216        assert_eq!(surface.pixels().len(), 64);
8217
8218        ui.set_canvas_surface(canvas, &surface)
8219            .expect("canvas accepts a surface");
8220        assert_eq!(
8221            ui.widget(canvas)
8222                .and_then(|spec| spec.canvas_surface.as_ref()),
8223            Some(&surface)
8224        );
8225        assert_eq!(ui.backend().last_canvas_surface(), Some(&surface));
8226
8227        let err = ui
8228            .set_canvas_surface(button, &surface)
8229            .expect_err("only canvases accept surfaces");
8230        assert_eq!(err, GuiError::UnsupportedWidget("set_canvas_surface"));
8231
8232        assert!(crate::CanvasSurface::from_rgba(4, 4, vec![0; 63]).is_err());
8233        assert!(crate::CanvasSurface::from_rgba(0, 4, Vec::new()).is_err());
8234    }
8235
8236    #[test]
8237    #[cfg(feature = "widgets-canvas")]
8238    fn canvas_scene_rejects_invalid_logical_size() {
8239        let backend = MockBackend::default();
8240        let mut ui = Ui::new(backend);
8241
8242        let canvas = ui
8243            .create(WidgetKind::Canvas, None)
8244            .expect("canvas should be created");
8245
8246        let invalid = crate::CanvasScene {
8247            logical_width: 0.0,
8248            logical_height: 10.0,
8249            primitives: vec![],
8250        };
8251
8252        let err = ui
8253            .set_canvas_scene(canvas, &invalid)
8254            .expect_err("canvas scenes must have positive finite logical dimensions");
8255
8256        assert_eq!(
8257            err,
8258            GuiError::Backend("Canvas scene logical size must be finite and positive".to_owned())
8259        );
8260    }
8261
8262    #[test]
8263    fn vulkan_canvas_handle_requires_vulkan_canvas_widget() {
8264        let backend = MockBackend::default();
8265        let mut ui = Ui::new(backend);
8266
8267        let button = ui
8268            .create(WidgetKind::Button, Some("button"))
8269            .expect("button should be created");
8270
8271        let err = ui
8272            .native_handle(button)
8273            .expect_err("non-vulkan widget should be rejected");
8274
8275        assert_eq!(err, GuiError::UnsupportedWidget("native_handle"));
8276    }
8277
8278    #[test]
8279    fn gpu_capabilities_are_queryable_and_unknown_names_are_false() {
8280        let ui = Ui::new(MockBackend::default());
8281        let capabilities = ui.gpu_surface_capabilities();
8282
8283        assert_eq!(capabilities, GpuSurfaceCapabilities::all());
8284        assert!(ui.supports_capability("vulkan_surface"));
8285        assert!(ui.supports_capability("gpu_surface"));
8286        assert!(ui.supports_capability("gpu_degradation_fallback"));
8287        assert!(!ui.supports_capability("unknown_gpu_capability"));
8288    }
8289
8290    #[test]
8291    #[cfg(feature = "widgets-canvas")]
8292    fn unavailable_vulkan_canvas_strictly_fails_with_typed_capability_error() {
8293        let mut backend = MockBackend::default();
8294        let mut capabilities = GpuSurfaceCapabilities::all();
8295        capabilities.vulkan_surface = false;
8296        backend.set_gpu_surface_capabilities(capabilities);
8297        let mut ui = Ui::new(backend);
8298
8299        assert_eq!(
8300            ui.create(WidgetKind::VulkanCanvas, None),
8301            Err(GuiError::UnsupportedCapability("vulkan_surface".to_owned()))
8302        );
8303        assert_eq!(ui.widget_count(), 0);
8304        assert!(!ui.is_gpu_degraded(WidgetId(1)));
8305    }
8306
8307    #[test]
8308    #[cfg(feature = "widgets-canvas")]
8309    fn gpu_diagnostic_placeholder_policy_is_deterministic_in_mock() {
8310        let mut backend = MockBackend::default();
8311        let mut capabilities = GpuSurfaceCapabilities::all();
8312        capabilities.vulkan_surface = false;
8313        backend.set_gpu_surface_capabilities(capabilities);
8314        let mut ui = Ui::new(backend);
8315        ui.set_gpu_degradation_policy(GpuDegradationPolicy::DiagnosticPlaceholder);
8316
8317        let canvas = ui
8318            .create(WidgetKind::VulkanCanvas, None)
8319            .expect("Mock should simulate a diagnostic placeholder");
8320        assert!(ui.is_gpu_degraded(canvas));
8321        assert_eq!(
8322            ui.backend().gpu_fallbacks.get(&canvas),
8323            Some(&GpuDegradationPolicy::DiagnosticPlaceholder)
8324        );
8325        assert_eq!(
8326            ui.vulkan_canvas_handle(canvas),
8327            Err(GuiError::UnsupportedCapability("vulkan_surface".to_owned()))
8328        );
8329        assert_eq!(
8330            ui.draw_demo_cube(canvas),
8331            Err(GuiError::UnsupportedCapability("vulkan_surface".to_owned()))
8332        );
8333        ui.remove(canvas).expect("remove degraded widget");
8334        assert!(!ui.is_gpu_degraded(canvas));
8335    }
8336
8337    #[test]
8338    #[cfg(feature = "widgets-canvas")]
8339    fn gpu_canvas_fallback_accepts_canvas_scenes_and_refuses_without_support() {
8340        let mut backend = MockBackend::default();
8341        let mut capabilities = GpuSurfaceCapabilities::all();
8342        capabilities.vulkan_surface = false;
8343        backend.set_gpu_surface_capabilities(capabilities);
8344        let mut ui = Ui::new(backend);
8345        ui.set_gpu_degradation_policy(GpuDegradationPolicy::Canvas2DFallback);
8346
8347        let canvas = ui
8348            .create(WidgetKind::VulkanCanvas, None)
8349            .expect("Mock should simulate the 2D fallback");
8350        let scene = crate::CanvasScene {
8351            logical_width: 80.0,
8352            logical_height: 60.0,
8353            primitives: Vec::new(),
8354        };
8355        ui.set_canvas_scene(canvas, &scene)
8356            .expect("the 2D fallback accepts a canvas scene");
8357        assert_eq!(ui.backend().last_canvas_scene(), Some(&scene));
8358
8359        let mut no_fallback = GpuSurfaceCapabilities::all();
8360        no_fallback.vulkan_surface = false;
8361        no_fallback.diagnostic_placeholder = false;
8362        no_fallback.headless_emulation = false;
8363        let mut backend = MockBackend::default();
8364        backend.set_gpu_surface_capabilities(no_fallback);
8365        let mut ui = Ui::new(backend);
8366        ui.set_gpu_degradation_policy(GpuDegradationPolicy::Canvas2DFallback);
8367        assert_eq!(
8368            ui.create(WidgetKind::VulkanCanvas, None),
8369            Err(GuiError::UnsupportedCapability(
8370                "gpu_degradation_fallback".to_owned()
8371            ))
8372        );
8373        assert_eq!(ui.widget_count(), 0);
8374    }
8375
8376    #[test]
8377    #[cfg(feature = "widgets-canvas")]
8378    fn vulkan_canvas_handle_returns_backend_handle() {
8379        let backend = MockBackend::default();
8380        let mut ui = Ui::new(backend);
8381
8382        let canvas = ui
8383            .create(WidgetKind::VulkanCanvas, None)
8384            .expect("vulkan canvas should be created");
8385
8386        let handle = ui
8387            .native_handle(canvas)
8388            .expect("native handle should be returned");
8389
8390        assert_eq!(handle, canvas.0 as usize);
8391    }
8392
8393    #[test]
8394    #[cfg(feature = "widgets-canvas")]
8395    fn draw_demo_cube_requires_vulkan_canvas_widget() {
8396        let backend = MockBackend::default();
8397        let mut ui = Ui::new(backend);
8398
8399        let label = ui
8400            .create(WidgetKind::Label, Some("label"))
8401            .expect("label should be created");
8402
8403        let err = ui
8404            .draw_demo_cube(label)
8405            .expect_err("non-vulkan widget should be rejected");
8406
8407        assert_eq!(err, GuiError::UnsupportedWidget("draw_demo_cube"));
8408    }
8409
8410    #[test]
8411    #[cfg(feature = "widgets-canvas")]
8412    fn draw_demo_cube_accepts_vulkan_canvas_widget() {
8413        let backend = MockBackend::default();
8414        let mut ui = Ui::new(backend);
8415
8416        let canvas = ui
8417            .create(WidgetKind::VulkanCanvas, None)
8418            .expect("vulkan canvas should be created");
8419
8420        ui.draw_demo_cube(canvas)
8421            .expect("draw demo cube should succeed for canvas");
8422    }
8423
8424    #[test]
8425    fn dispatch_events_processes_backend_queue() {
8426        let mut backend = MockBackend::default();
8427        backend.push_event(UiEvent::Clicked {
8428            widget_id: WidgetId(1),
8429        });
8430        backend.push_event(UiEvent::WindowClosed {
8431            widget_id: WidgetId(1),
8432        });
8433
8434        let mut ui = Ui::new(backend);
8435        let mut seen = Vec::new();
8436
8437        let count = ui
8438            .dispatch_events(|event| seen.push(event))
8439            .expect("dispatch should succeed");
8440
8441        assert_eq!(count, 2);
8442        assert_eq!(
8443            seen,
8444            vec![
8445                UiEvent::Clicked {
8446                    widget_id: WidgetId(1),
8447                },
8448                UiEvent::WindowClosed {
8449                    widget_id: WidgetId(1),
8450                },
8451            ]
8452        );
8453    }
8454
8455    #[test]
8456    fn dispatch_events_with_hands_ui_to_handler_and_preserves_order() {
8457        use std::cell::RefCell;
8458        use std::rc::Rc;
8459
8460        let backend = MockBackend::default();
8461        let mut ui = Ui::new(backend);
8462
8463        let window = ui
8464            .create(WidgetKind::Window, Some("Runner"))
8465            .expect("window should be created");
8466        let label = ui
8467            .create(WidgetKind::Label, Some("before"))
8468            .expect("label should be created");
8469        ui.attach(window, label).expect("attach label");
8470        ui.show(window).expect("show window");
8471
8472        // Registered callbacks must run before the handler for the same
8473        // event, exactly like `dispatch_events` does.
8474        let order = Rc::new(RefCell::new(Vec::new()));
8475        let callback_order = Rc::clone(&order);
8476        ui.on_window_close(window, move || {
8477            callback_order.borrow_mut().push("callback");
8478        })
8479        .expect("register close callback");
8480
8481        ui.backend_mut()
8482            .push_event(UiEvent::Clicked { widget_id: label });
8483        ui.backend_mut()
8484            .push_event(UiEvent::WindowClosed { widget_id: window });
8485
8486        let handler_order = Rc::clone(&order);
8487        let dispatched = ui
8488            .dispatch_events_with(|ui, event| {
8489                handler_order.borrow_mut().push(match &event {
8490                    UiEvent::Clicked { .. } => "click",
8491                    UiEvent::WindowClosed { .. } => "close",
8492                    _ => "other",
8493                });
8494                if matches!(event, UiEvent::Clicked { .. }) {
8495                    ui.set_text(label, "mutated")?;
8496                }
8497                Ok(LoopFlow::Continue)
8498            })
8499            .expect("dispatch should succeed");
8500
8501        assert_eq!(dispatched, 2);
8502        assert_eq!(
8503            ui.widget(label).and_then(|spec| spec.text.as_deref()),
8504            Some("mutated"),
8505            "the handler mutates widgets inline"
8506        );
8507        assert_eq!(&*order.borrow(), &["click", "callback", "close"]);
8508    }
8509
8510    #[test]
8511    fn run_until_closed_with_can_mutate_and_exit_early() {
8512        let backend = MockBackend::default();
8513        let mut ui = Ui::new(backend);
8514
8515        let window = ui
8516            .create(WidgetKind::Window, Some("Runner"))
8517            .expect("window should be created");
8518        let label = ui
8519            .create(WidgetKind::Label, Some("idle"))
8520            .expect("label should be created");
8521        ui.attach(window, label).expect("attach label");
8522        ui.show(window).expect("show window");
8523
8524        // No WindowClosed is queued: the loop must stop on `LoopFlow::Exit`
8525        // alone (and would otherwise block on `wait_event`).
8526        ui.backend_mut()
8527            .push_event(UiEvent::Clicked { widget_id: label });
8528        let mut seen = 0;
8529        ui.run_until_closed_with(|ui, event| {
8530            if matches!(event, UiEvent::Clicked { .. }) {
8531                seen += 1;
8532                ui.set_text(label, "clicked")?;
8533                return Ok(LoopFlow::Exit);
8534            }
8535            Ok(LoopFlow::Continue)
8536        })
8537        .expect("runner should stop on Exit");
8538
8539        assert_eq!(seen, 1);
8540        assert_eq!(
8541            ui.widget(label).and_then(|spec| spec.text.as_deref()),
8542            Some("clicked")
8543        );
8544    }
8545
8546    #[test]
8547    fn run_bounded_without_a_budget_matches_the_unbounded_runner() {
8548        let backend = MockBackend::default();
8549        let mut ui = Ui::new(backend);
8550
8551        let window = ui
8552            .create(WidgetKind::Window, Some("Bounded"))
8553            .expect("window should be created");
8554        ui.show(window).expect("show window");
8555        ui.backend_mut()
8556            .push_event(UiEvent::WindowClosed { widget_id: window });
8557
8558        let stop = ui
8559            .run_bounded_with(None, |_ui, _event| Ok(LoopFlow::Continue))
8560            .expect("runner should stop on the queued close");
8561
8562        assert_eq!(stop, RunStop::WindowClosed);
8563    }
8564
8565    #[test]
8566    fn run_bounded_with_stops_on_exit_and_on_the_budget() {
8567        let backend = MockBackend::default();
8568        let mut ui = Ui::new(backend);
8569
8570        let window = ui
8571            .create(WidgetKind::Window, Some("Bounded"))
8572            .expect("window should be created");
8573        ui.show(window).expect("show window");
8574        ui.backend_mut()
8575            .push_event(UiEvent::Clicked { widget_id: window });
8576
8577        let exit = ui
8578            .run_bounded_with(Some(Duration::from_secs(5)), |_ui, event| {
8579                Ok(if matches!(event, UiEvent::Clicked { .. }) {
8580                    LoopFlow::Exit
8581                } else {
8582                    LoopFlow::Continue
8583                })
8584            })
8585            .expect("runner should stop on Exit");
8586        assert_eq!(exit, RunStop::Exit, "an explicit exit beats the budget");
8587
8588        // Nothing is queued on the Mock backend, so only the budget can end
8589        // this run — the capture-host case the bound exists for.
8590        let started = Instant::now();
8591        let timed_out = ui
8592            .run_bounded_with(Some(Duration::from_millis(20)), |_ui, _event| {
8593                panic!("no event should arrive")
8594            })
8595            .expect("runner should return once the budget elapses");
8596        assert_eq!(timed_out, RunStop::TimedOut);
8597        assert!(
8598            started.elapsed() >= Duration::from_millis(20),
8599            "the budget, not an event, ended the run"
8600        );
8601    }
8602
8603    #[test]
8604    fn run_bounded_with_returns_immediately_on_a_zero_budget() {
8605        let backend = MockBackend::default();
8606        let mut ui = Ui::new(backend);
8607
8608        let window = ui
8609            .create(WidgetKind::Window, Some("Bounded"))
8610            .expect("window should be created");
8611        ui.show(window).expect("show window");
8612
8613        let started = Instant::now();
8614        let stop = ui
8615            .run_bounded_with(Some(Duration::ZERO), |_ui, _event| {
8616                panic!("no event should arrive")
8617            })
8618            .expect("runner should return at once");
8619        assert_eq!(stop, RunStop::TimedOut);
8620        assert!(
8621            started.elapsed() < Duration::from_secs(1),
8622            "a zero budget never sleeps through a poll interval"
8623        );
8624    }
8625
8626    #[test]
8627    fn run_bounded_dispatches_events_and_reports_the_timeout() {
8628        let backend = MockBackend::default();
8629        let mut ui = Ui::new(backend);
8630
8631        let window = ui
8632            .create(WidgetKind::Window, Some("Bounded"))
8633            .expect("window should be created");
8634        ui.show(window).expect("show window");
8635        ui.backend_mut()
8636            .push_event(UiEvent::Clicked { widget_id: window });
8637
8638        let mut seen = 0;
8639        let stop = ui
8640            .run_bounded(Some(Duration::from_millis(20)), |_event| seen += 1)
8641            .expect("runner should return once the budget elapses");
8642
8643        assert_eq!(stop, RunStop::TimedOut, "the queued click is not a close");
8644        assert_eq!(seen, 1, "queued events are still dispatched");
8645    }
8646
8647    #[test]
8648    fn pointer_events_are_projected_onto_the_logical_space() {
8649        use crate::displays::{DisplayInfo, DisplayRect};
8650
8651        let backend = MockBackend::default();
8652        let mut ui = Ui::new(backend);
8653
8654        let window = ui
8655            .create(WidgetKind::Window, Some("Pointer"))
8656            .expect("window should be created");
8657        let canvas = ui
8658            .create(WidgetKind::Button, Some("target"))
8659            .expect("target should be created");
8660        ui.attach(window, canvas).expect("attach canvas");
8661        ui.show(window).expect("show window");
8662
8663        // No display fixture: the lane reports the identity, so logical
8664        // coordinates arrive untouched.
8665        ui.backend_mut().push_event(UiEvent::PointerMove {
8666            widget_id: canvas,
8667            x: 100.0,
8668            y: 200.0,
8669        });
8670        assert_eq!(
8671            ui.poll_event().expect("poll should succeed"),
8672            Some(UiEvent::PointerMove {
8673                widget_id: canvas,
8674                x: 100.0,
8675                y: 200.0,
8676            })
8677        );
8678
8679        // A 125 % display fixture makes the Mock simulate a physical-pixel
8680        // lane: every pointer event is divided before the app sees it, so
8681        // hit-testing lines up with the logical layout targets.
8682        ui.backend_mut().set_displays(vec![DisplayInfo::new(
8683            1,
8684            "mock-primary",
8685            DisplayRect::new(0, 0, 1920, 1080),
8686            DisplayRect::new(0, 0, 1920, 1040),
8687            1.25,
8688            true,
8689        )]);
8690        for (physical, logical) in [
8691            (
8692                UiEvent::PointerDown {
8693                    widget_id: canvas,
8694                    x: 125.0,
8695                    y: 250.0,
8696                    button: 0,
8697                },
8698                (100.0, 200.0),
8699            ),
8700            (
8701                UiEvent::PointerMove {
8702                    widget_id: canvas,
8703                    x: 250.0,
8704                    y: 375.0,
8705                },
8706                (200.0, 300.0),
8707            ),
8708            (
8709                UiEvent::PointerUp {
8710                    widget_id: canvas,
8711                    x: 62.5,
8712                    y: 0.0,
8713                    button: 0,
8714                },
8715                (50.0, 0.0),
8716            ),
8717        ] {
8718            ui.backend_mut().push_event(physical);
8719            let delivered = ui
8720                .poll_event()
8721                .expect("poll should succeed")
8722                .expect("the pushed event should be delivered");
8723            let (x, y) = match delivered {
8724                UiEvent::PointerDown { x, y, .. }
8725                | UiEvent::PointerMove { x, y, .. }
8726                | UiEvent::PointerUp { x, y, .. } => (x, y),
8727                other => panic!("unexpected event: {other:?}"),
8728            };
8729            assert_eq!(
8730                (x, y),
8731                logical,
8732                "physical input maps onto the logical space"
8733            );
8734        }
8735
8736        // Non-pointer events are never touched, even with a scaled fixture.
8737        ui.backend_mut().push_event(UiEvent::WindowResized {
8738            widget_id: window,
8739            width: 800,
8740            height: 600,
8741        });
8742        assert_eq!(
8743            ui.poll_event().expect("poll should succeed"),
8744            Some(UiEvent::WindowResized {
8745                widget_id: window,
8746                width: 800,
8747                height: 600,
8748            })
8749        );
8750    }
8751
8752    #[test]
8753    fn pointer_projection_applies_once_per_event_on_every_delivery_path() {
8754        use crate::displays::{DisplayInfo, DisplayRect};
8755
8756        let backend = MockBackend::default();
8757        let mut ui = Ui::new(backend);
8758
8759        let window = ui
8760            .create(WidgetKind::Window, Some("Pointer"))
8761            .expect("window should be created");
8762        let canvas = ui
8763            .create(WidgetKind::Button, Some("target"))
8764            .expect("target should be created");
8765        ui.attach(window, canvas).expect("attach canvas");
8766        ui.show(window).expect("show window");
8767        ui.backend_mut().set_displays(vec![DisplayInfo::new(
8768            1,
8769            "mock-primary",
8770            DisplayRect::new(0, 0, 1920, 1080),
8771            DisplayRect::new(0, 0, 1920, 1040),
8772            2.0,
8773            true,
8774        )]);
8775
8776        ui.backend_mut().push_event(UiEvent::PointerMove {
8777            widget_id: canvas,
8778            x: 200.0,
8779            y: 100.0,
8780        });
8781
8782        let mut seen = Vec::new();
8783        let dispatched = ui
8784            .dispatch_events(|event| seen.push(event))
8785            .expect("dispatch should succeed");
8786
8787        assert_eq!(dispatched, 1);
8788        assert_eq!(
8789            seen,
8790            vec![UiEvent::PointerMove {
8791                widget_id: canvas,
8792                x: 100.0,
8793                y: 50.0,
8794            }],
8795            "a 200 % display divides exactly once"
8796        );
8797        assert_eq!(
8798            ui.logical_pointer_projection(canvas, 200.0, 100.0),
8799            (100.0, 50.0),
8800            "the event path and the explicit projection agree"
8801        );
8802    }
8803
8804    #[test]
8805    fn handler_produced_events_are_delivered_not_dropped() {
8806        let backend = MockBackend::default();
8807        let mut ui = Ui::new(backend);
8808
8809        let window = ui
8810            .create(WidgetKind::Window, Some("Runner"))
8811            .expect("window should be created");
8812        let button = ui
8813            .create(WidgetKind::Button, Some("Go"))
8814            .expect("button should be created");
8815        ui.attach(window, button).expect("attach button");
8816        ui.show(window).expect("show window");
8817
8818        ui.backend_mut()
8819            .push_event(UiEvent::Clicked { widget_id: button });
8820
8821        // `Ui::activate` queues a new `Clicked` event while the handler runs;
8822        // the drain must deliver it on a later iteration instead of losing
8823        // it, and must terminate once the queue empties.
8824        let mut produced = false;
8825        let mut clicks = 0;
8826        let dispatched = ui
8827            .dispatch_events_with(|ui, event| {
8828                if matches!(event, UiEvent::Clicked { .. }) {
8829                    clicks += 1;
8830                    if !produced {
8831                        produced = true;
8832                        ui.activate(button)?;
8833                    }
8834                }
8835                Ok(LoopFlow::Continue)
8836            })
8837            .expect("dispatch should succeed");
8838
8839        assert_eq!(clicks, 2, "the handler-produced click is delivered");
8840        assert_eq!(dispatched, 2);
8841    }
8842
8843    #[test]
8844    #[cfg(feature = "routes")]
8845    fn dispatch_routed_translates_messages_and_keeps_callback_order() {
8846        use std::cell::RefCell;
8847        use std::rc::Rc;
8848
8849        let backend = MockBackend::default();
8850        let mut ui = Ui::new(backend);
8851
8852        let window = ui
8853            .create(WidgetKind::Window, Some("Routed"))
8854            .expect("window should be created");
8855        let button = ui
8856            .create(WidgetKind::Button, Some("Go"))
8857            .expect("button should be created");
8858        let label = ui
8859            .create(WidgetKind::Label, Some("idle"))
8860            .expect("label should be created");
8861        ui.attach(window, button).expect("attach button");
8862        ui.attach(window, label).expect("attach label");
8863        ui.show(window).expect("show window");
8864
8865        // Registered callbacks run before the routed handler.
8866        let order = Rc::new(RefCell::new(Vec::new()));
8867        let callback_order = Rc::clone(&order);
8868        ui.on_window_close(window, move || {
8869            callback_order.borrow_mut().push("callback");
8870        })
8871        .expect("register close callback");
8872
8873        let mut routes = Routes::new();
8874        routes.on(button, "go");
8875        routes.on_event(window, |event| match event {
8876            UiEvent::WindowClosed { .. } => Some("closed"),
8877            _ => None,
8878        });
8879
8880        ui.backend_mut()
8881            .push_event(UiEvent::Clicked { widget_id: button });
8882        // Unrouted events never reach the handler.
8883        ui.backend_mut().push_event(UiEvent::Toggled {
8884            widget_id: label,
8885            checked: true,
8886        });
8887        ui.backend_mut()
8888            .push_event(UiEvent::WindowClosed { widget_id: window });
8889
8890        let handler_order = Rc::clone(&order);
8891        let dispatched = ui
8892            .dispatch_routed(&routes, |ui, message| {
8893                handler_order.borrow_mut().push(message);
8894                if message == "go" {
8895                    ui.set_text(label, "clicked")?;
8896                }
8897                Ok(LoopFlow::Continue)
8898            })
8899            .expect("routed dispatch should succeed");
8900
8901        assert_eq!(dispatched, 3, "every event is drained");
8902        assert_eq!(
8903            ui.widget(label).and_then(|spec| spec.text.as_deref()),
8904            Some("clicked"),
8905            "the routed handler updates widgets inline"
8906        );
8907        assert_eq!(&*order.borrow(), &["go", "callback", "closed"]);
8908    }
8909
8910    #[test]
8911    #[cfg(feature = "routes")]
8912    fn run_routed_hands_typed_messages_and_stops_on_exit() {
8913        let backend = MockBackend::default();
8914        let mut ui = Ui::new(backend);
8915
8916        let window = ui
8917            .create(WidgetKind::Window, Some("Routed"))
8918            .expect("window should be created");
8919        let button = ui
8920            .create(WidgetKind::Button, Some("Quit"))
8921            .expect("button should be created");
8922        ui.attach(window, button).expect("attach button");
8923        ui.show(window).expect("show window");
8924
8925        let mut routes = Routes::new();
8926        routes.on(button, "quit");
8927
8928        // No WindowClosed is queued: the loop must stop on `LoopFlow::Exit`
8929        // alone (and would otherwise block on `wait_event`).
8930        ui.backend_mut()
8931            .push_event(UiEvent::Clicked { widget_id: button });
8932        let mut messages = Vec::new();
8933        ui.run_routed(&routes, |_ui, message| {
8934            messages.push(message);
8935            Ok(LoopFlow::Exit)
8936        })
8937        .expect("routed runner should stop on Exit");
8938
8939        assert_eq!(messages, vec!["quit"]);
8940    }
8941
8942    #[test]
8943    fn register_window_callback_requires_window_widget() {
8944        let backend = MockBackend::default();
8945        let mut ui = Ui::new(backend);
8946
8947        let button = ui
8948            .create(WidgetKind::Button, Some("not a window"))
8949            .expect("button should be created");
8950
8951        let err = ui
8952            .on_window_close(button, || {})
8953            .expect_err("non-window should be rejected");
8954
8955        assert_eq!(err, GuiError::UnsupportedWidget("window_callback"));
8956    }
8957
8958    #[test]
8959    fn computed_layout_updates_apply_parent_frames_before_descendants() {
8960        let mut ui = Ui::new(MockBackend::default());
8961        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
8962        let root = ui.create(WidgetKind::Container, None).expect("root");
8963        let keypad = ui.create(WidgetKind::Container, None).expect("keypad");
8964        let row = ui.create(WidgetKind::Container, None).expect("row");
8965        let button = ui.create(WidgetKind::Button, Some("7")).expect("button");
8966        ui.attach(window, root).expect("attach root");
8967        ui.attach(root, keypad).expect("attach keypad");
8968        ui.attach(keypad, row).expect("attach row");
8969        ui.attach(row, button).expect("attach button");
8970
8971        let mut updates = vec![
8972            (button, Some((40, 30)), Some((0, 0))),
8973            (row, Some((200, 40)), Some((0, 0))),
8974            (keypad, Some((200, 160)), Some((0, 0))),
8975            (root, Some((300, 300)), Some((0, 0))),
8976        ];
8977        ui.sort_layout_updates_parent_first(&mut updates);
8978
8979        assert_eq!(
8980            updates.iter().map(|(id, _, _)| *id).collect::<Vec<_>>(),
8981            vec![root, keypad, row, button]
8982        );
8983
8984        ui.set_container_direction(root, ContainerDirection::Vertical)
8985            .expect("root direction");
8986        ui.set_container_padding(root, 16).expect("root padding");
8987        ui.set_container_direction(keypad, ContainerDirection::Vertical)
8988            .expect("keypad direction");
8989        ui.set_flex_grow(keypad, 1.0).expect("keypad grows");
8990        ui.set_container_direction(row, ContainerDirection::Horizontal)
8991            .expect("row direction");
8992        ui.set_flex_grow(row, 1.0).expect("row grows");
8993        ui.set_min_size(button, 28, 28).expect("button minimum");
8994        ui.set_flex_grow(button, 1.0).expect("button grows");
8995        ui.compute_layout(window, 318.0, 322.0)
8996            .expect("compute nested layout");
8997
8998        assert_eq!(ui.layout_rect(keypad).unwrap().x, 16.0);
8999        assert_eq!(ui.layout_rect(keypad).unwrap().y, 16.0);
9000        assert_eq!(ui.layout_rect(row).unwrap().x, 0.0);
9001        assert_eq!(ui.layout_rect(row).unwrap().y, 0.0);
9002        assert_eq!(ui.layout_rect(button).unwrap().x, 0.0);
9003        assert_eq!(ui.layout_rect(button).unwrap().y, 0.0);
9004    }
9005
9006    #[test]
9007    fn set_layout_root_recomputes_layout_on_window_resize() {
9008        use crate::layout::{Dimension, Size, Style};
9009
9010        let backend = MockBackend::default();
9011        let mut ui = Ui::new(backend);
9012
9013        let window = ui
9014            .create(WidgetKind::Window, Some("w"))
9015            .expect("window created");
9016        let button = ui
9017            .create(WidgetKind::Button, Some("b"))
9018            .expect("button created");
9019        ui.attach(window, button).expect("attached");
9020
9021        if let Some(&node) = ui.layout_nodes.get(&button) {
9022            let style = Style {
9023                size: Size {
9024                    width: Dimension::length(40.0),
9025                    height: Dimension::length(20.0),
9026                },
9027                ..Default::default()
9028            };
9029            let _ = ui.layout_tree.set_style(node, style);
9030        }
9031
9032        ui.set_layout_root(window).expect("layout root set");
9033
9034        ui.backend_mut().push_event(UiEvent::WindowResized {
9035            widget_id: window,
9036            width: 640,
9037            height: 480,
9038        });
9039        let count = ui.dispatch_events(|_| {}).expect("dispatch");
9040        assert_eq!(count, 1);
9041        assert_eq!(ui.widget(button).and_then(|spec| spec.size), Some((40, 20)));
9042    }
9043
9044    #[test]
9045    #[cfg(feature = "widgets-text")]
9046    fn computed_layout_expansion_tracks_percent_flex_and_stretch() {
9047        use crate::layout::{Dimension, Size};
9048
9049        let mut ui = Ui::new(MockBackend::default());
9050        let window = ui
9051            .create(WidgetKind::Window, Some("Notepad layout"))
9052            .expect("window created");
9053        let root = ui
9054            .create(WidgetKind::Container, None)
9055            .expect("root container created");
9056        let editor = ui
9057            .create(WidgetKind::TextArea, None)
9058            .expect("editor created");
9059        let status = ui.create(WidgetKind::Label, None).expect("status created");
9060        ui.attach(window, root).expect("attach root");
9061        ui.attach(root, editor).expect("attach editor");
9062        ui.attach(root, status).expect("attach status");
9063        ui.set_container_direction(root, ContainerDirection::Vertical)
9064            .expect("set vertical flow");
9065
9066        let root_node = ui.layout_nodes[&root];
9067        let mut root_style = ui.layout_tree.style(root_node).unwrap().clone();
9068        root_style.size = Size {
9069            width: Dimension::percent(1.0),
9070            height: Dimension::percent(1.0),
9071        };
9072        ui.layout_tree.set_style(root_node, root_style).unwrap();
9073
9074        let editor_node = ui.layout_nodes[&editor];
9075        let mut editor_style = ui.layout_tree.style(editor_node).unwrap().clone();
9076        editor_style.flex_grow = 1.0;
9077        ui.layout_tree.set_style(editor_node, editor_style).unwrap();
9078
9079        ui.compute_layout(window, 740.0, 850.0)
9080            .expect("compute Notepad layout");
9081
9082        assert_eq!(ui.computed_layout_expansion(root), (true, true));
9083        assert_eq!(
9084            ui.computed_layout_expansion(editor),
9085            (true, true),
9086            "the editor stretches across the column and grows vertically"
9087        );
9088        assert_eq!(
9089            ui.computed_layout_expansion(status),
9090            (true, false),
9091            "a status label stretches across the column without taking spare height"
9092        );
9093        assert_eq!(ui.widget(root).and_then(|spec| spec.size), Some((740, 850)));
9094    }
9095
9096    #[test]
9097    fn set_layout_root_rejects_non_window_widget() {
9098        let backend = MockBackend::default();
9099        let mut ui = Ui::new(backend);
9100
9101        let button = ui
9102            .create(WidgetKind::Button, Some("b"))
9103            .expect("button created");
9104        let err = ui.set_layout_root(button).expect_err("non-window rejected");
9105        assert_eq!(err, GuiError::UnsupportedWidget("set_layout_root"));
9106    }
9107
9108    #[test]
9109    fn set_flex_grow_lets_sized_panes_fill_a_resized_layout_root() {
9110        let mut ui = Ui::new(MockBackend::default());
9111        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
9112        let row = ui.create(WidgetKind::Container, None).expect("row");
9113        ui.set_container_direction(row, ContainerDirection::Horizontal)
9114            .expect("row direction");
9115        let sidebar = ui.create(WidgetKind::Container, None).expect("sidebar");
9116        let content = ui.create(WidgetKind::Container, None).expect("content");
9117        ui.attach(window, row).expect("attach row");
9118        ui.attach(row, sidebar).expect("attach sidebar");
9119        ui.attach(row, content).expect("attach content");
9120        ui.set_size(sidebar, 200, 100).expect("sidebar size");
9121        ui.set_size(content, 400, 100).expect("content size");
9122        ui.set_layout_root(window).expect("layout root");
9123
9124        ui.compute_layout(window, 600.0, 400.0)
9125            .expect("initial layout");
9126        assert_eq!(
9127            ui.widget(content).and_then(|spec| spec.size),
9128            Some((400, 100))
9129        );
9130
9131        // Without grow the pinned pane ignores the extra window width.
9132        ui.backend_mut().push_event(UiEvent::WindowResized {
9133            widget_id: window,
9134            width: 1000,
9135            height: 400,
9136        });
9137        ui.dispatch_events(|_| {}).expect("dispatch");
9138        assert_eq!(
9139            ui.widget(content).and_then(|spec| spec.size),
9140            Some((400, 100))
9141        );
9142
9143        ui.set_flex_grow(content, 1.0).expect("grow");
9144        assert_eq!(ui.flex_grow(content), Ok(1.0));
9145        ui.backend_mut().push_event(UiEvent::WindowResized {
9146            widget_id: window,
9147            width: 1200,
9148            height: 400,
9149        });
9150        ui.dispatch_events(|_| {}).expect("dispatch");
9151        assert_eq!(
9152            ui.widget(sidebar).and_then(|spec| spec.size),
9153            Some((200, 100))
9154        );
9155        assert_eq!(
9156            ui.widget(content).and_then(|spec| spec.size),
9157            Some((1000, 100))
9158        );
9159        assert_eq!(
9160            ui.widget(content).and_then(|spec| spec.position),
9161            Some((200, 0))
9162        );
9163
9164        assert!(ui.set_flex_grow(content, -1.0).is_err());
9165        assert!(ui.set_flex_grow(content, f32::NAN).is_err());
9166        assert_eq!(
9167            ui.set_flex_grow(WidgetId(9_999), 1.0),
9168            Err(GuiError::WidgetNotFound(9_999))
9169        );
9170    }
9171
9172    #[test]
9173    fn set_min_size_keeps_a_floor_while_panes_stretch_with_the_window() {
9174        let mut ui = Ui::new(MockBackend::default());
9175        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
9176        let column = ui.create(WidgetKind::Container, None).expect("column");
9177        let row = ui.create(WidgetKind::Container, None).expect("row");
9178        ui.set_container_direction(row, ContainerDirection::Horizontal)
9179            .expect("row direction");
9180        let sidebar = ui.create(WidgetKind::Container, None).expect("sidebar");
9181        let content = ui.create(WidgetKind::Container, None).expect("content");
9182        ui.attach(window, column).expect("attach column");
9183        ui.attach(column, row).expect("attach row");
9184        ui.attach(row, sidebar).expect("attach sidebar");
9185        ui.attach(row, content).expect("attach content");
9186        ui.set_min_size(sidebar, 180, 0).expect("sidebar min");
9187        ui.set_min_size(content, 300, 200).expect("content min");
9188        ui.set_flex_grow(row, 1.0).expect("row grows");
9189        ui.set_flex_grow(content, 1.0).expect("content grows");
9190        assert_eq!(ui.min_size(content), Ok((300, 200)));
9191        ui.set_layout_root(window).expect("layout root");
9192
9193        // No pin: the row stretches across the column and the content pane
9194        // takes the width the sidebar's floor leaves.
9195        ui.compute_layout(window, 900.0, 500.0).expect("layout");
9196        assert_eq!(
9197            ui.widget(sidebar).and_then(|spec| spec.size),
9198            Some((180, 500))
9199        );
9200        assert_eq!(
9201            ui.widget(content).and_then(|spec| spec.size),
9202            Some((720, 500))
9203        );
9204
9205        ui.backend_mut().push_event(UiEvent::WindowResized {
9206            widget_id: window,
9207            width: 1400,
9208            height: 800,
9209        });
9210        ui.dispatch_events(|_| {}).expect("dispatch");
9211        assert_eq!(
9212            ui.widget(content).and_then(|spec| spec.size),
9213            Some((1220, 800))
9214        );
9215
9216        // Shrinking below the floors keeps them instead of collapsing panes.
9217        ui.compute_layout(window, 300.0, 100.0).expect("shrunk");
9218        assert_eq!(
9219            ui.widget(sidebar).and_then(|spec| spec.size.map(|s| s.0)),
9220            Some(180)
9221        );
9222        assert_eq!(
9223            ui.widget(content).and_then(|spec| spec.size),
9224            Some((300, 200))
9225        );
9226
9227        ui.set_min_size(sidebar, 0, 0).expect("clear");
9228        assert_eq!(ui.min_size(sidebar), Ok((0, 0)));
9229        assert!(ui.set_min_size(sidebar, -1, 0).is_err());
9230        assert_eq!(
9231            ui.set_min_size(WidgetId(9_999), 1, 1),
9232            Err(GuiError::WidgetNotFound(9_999))
9233        );
9234    }
9235
9236    #[test]
9237    fn layout_roots_flush_pending_invalidations_before_the_next_event_wait() {
9238        let mut ui = Ui::new(MockBackend::default());
9239        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
9240        let column = ui.create(WidgetKind::Container, None).expect("column");
9241        let panel = ui.create(WidgetKind::Container, None).expect("panel");
9242        ui.attach(window, column).expect("attach column");
9243        ui.attach(column, panel).expect("attach panel");
9244        ui.set_flex_grow(panel, 1.0).expect("panel grows");
9245        ui.hide(panel).expect("hide panel");
9246        ui.set_layout_root(window).expect("layout root");
9247        ui.backend_mut().push_event(UiEvent::WindowResized {
9248            widget_id: window,
9249            width: 500,
9250            height: 300,
9251        });
9252        ui.dispatch_events(|_| {}).expect("dispatch");
9253        assert_eq!(ui.widget(panel).and_then(|spec| spec.size), Some((0, 0)));
9254
9255        // Revealing the panel outside any handler schedules a pass that the
9256        // next pump runs at the root's last size - no resize needed.
9257        ui.show(panel).expect("show panel");
9258        ui.dispatch_events(|_| {}).expect("dispatch");
9259        assert_eq!(
9260            ui.widget(panel).and_then(|spec| spec.size),
9261            Some((500, 300))
9262        );
9263
9264        // A window that is not a layout root keeps the opt-in behavior.
9265        ui.remove_layout_root(window);
9266        ui.hide(panel).expect("hide again");
9267        ui.dispatch_events(|_| {}).expect("dispatch");
9268        assert_eq!(
9269            ui.widget(panel).and_then(|spec| spec.size),
9270            Some((500, 300))
9271        );
9272    }
9273
9274    #[test]
9275    fn show_hide_schedules_layout_pass() {
9276        let mut ui = Ui::new(MockBackend::default());
9277        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
9278        let panel = ui.create(WidgetKind::Container, None).expect("panel");
9279        ui.attach(window, panel).expect("attach panel");
9280        ui.set_layout_root(window).expect("layout root");
9281        ui.compute_layout(window, 500.0, 300.0)
9282            .expect("initial layout");
9283        assert!(!ui.has_dirty_layout(), "layout clean after compute");
9284
9285        // Hiding the panel marks layout dirty
9286        ui.hide(panel).expect("hide panel");
9287        assert!(ui.is_layout_dirty(panel));
9288        assert!(ui.has_dirty_layout());
9289
9290        // Flushing recomputes and cleans dirty state
9291        ui.compute_layout_if_dirty();
9292        assert!(!ui.has_dirty_layout(), "layout clean after flush");
9293
9294        // Showing the panel marks layout dirty again
9295        ui.show(panel).expect("show panel");
9296        assert!(ui.is_layout_dirty(panel));
9297        assert!(ui.has_dirty_layout());
9298
9299        // Flushing recomputes and cleans dirty state
9300        ui.compute_layout_if_dirty();
9301        assert!(!ui.has_dirty_layout(), "layout clean after second flush");
9302    }
9303
9304    #[test]
9305    fn set_preferred_width_constrains_width_only() {
9306        let mut ui = Ui::new(MockBackend::default());
9307        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
9308        let root = ui.create(WidgetKind::Container, None).expect("root");
9309        ui.set_container_direction(root, ContainerDirection::Horizontal)
9310            .expect("row");
9311        let inspector = ui.create(WidgetKind::Container, None).expect("inspector");
9312        let content = ui.create(WidgetKind::Container, None).expect("content");
9313        ui.attach(window, root).expect("attach root");
9314        ui.attach(root, inspector).expect("attach inspector");
9315        ui.attach(root, content).expect("attach content");
9316        ui.set_flex_grow(content, 1.0).expect("content grows");
9317
9318        ui.set_preferred_width(inspector, 240)
9319            .expect("set preferred width");
9320        assert_eq!(ui.preferred_width(inspector), Ok(Some(240)));
9321
9322        ui.set_layout_root(window).expect("layout root");
9323        ui.compute_layout(window, 800.0, 600.0)
9324            .expect("compute layout");
9325
9326        let (inspector_w, inspector_h) = ui.widget(inspector).unwrap().size.unwrap();
9327        assert_eq!(inspector_w, 240);
9328        // Inspector height is not pinned; it stretches to the container height (600)
9329        assert_eq!(inspector_h, 600);
9330
9331        // Window resize re-runs layout; inspector width stays 240, height stretches to 700 without re-pinning
9332        ui.compute_layout(window, 1000.0, 700.0)
9333            .expect("recompute layout");
9334        let (inspector_w2, inspector_h2) = ui.widget(inspector).unwrap().size.unwrap();
9335        assert_eq!(inspector_w2, 240);
9336        assert_eq!(inspector_h2, 700);
9337
9338        // Clearing preferred width
9339        ui.set_preferred_width(inspector, 0)
9340            .expect("clear preferred width");
9341        assert_eq!(ui.preferred_width(inspector), Ok(None));
9342    }
9343
9344    #[test]
9345    fn window_min_size_and_resizable_api() {
9346        let mut ui = Ui::new(MockBackend::default());
9347        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
9348        let button = ui.create(WidgetKind::Button, Some("b")).expect("button");
9349
9350        // Reject non-window widgets
9351        let err = ui
9352            .set_window_min_size(button, 400, 300)
9353            .expect_err("non-window rejected");
9354        assert_eq!(err, GuiError::UnsupportedWidget("set_window_min_size"));
9355
9356        let err = ui.window_min_size(button).expect_err("non-window rejected");
9357        assert_eq!(err, GuiError::UnsupportedWidget("set_window_min_size"));
9358
9359        let err = ui
9360            .set_resizable(button, false)
9361            .expect_err("non-window rejected");
9362        assert_eq!(err, GuiError::UnsupportedWidget("set_resizable"));
9363
9364        let err = ui.is_resizable(button).expect_err("non-window rejected");
9365        assert_eq!(err, GuiError::UnsupportedWidget("set_resizable"));
9366
9367        // Default resizable is true
9368        assert_eq!(ui.is_resizable(window), Ok(true));
9369        assert_eq!(ui.resizable(window), Ok(true));
9370
9371        // MockBackend returns UnsupportedCapability default stubs for both APIs
9372        let res = ui.set_window_min_size(window, 400, 300);
9373        assert_eq!(
9374            res,
9375            Err(GuiError::UnsupportedCapability(
9376                "set_window_min_size".to_owned()
9377            ))
9378        );
9379        assert_eq!(ui.explicit_window_min_size(window), Ok(Some((400, 300))));
9380        assert_eq!(ui.window_min_size(window), Ok(Some((400, 300))));
9381
9382        let res = ui.set_resizable(window, false);
9383        assert_eq!(
9384            res,
9385            Err(GuiError::UnsupportedCapability("set_resizable".to_owned()))
9386        );
9387        assert_eq!(ui.is_resizable(window), Ok(false));
9388
9389        // Derived content min size from layout root child
9390        let window2 = ui.create(WidgetKind::Window, Some("w2")).expect("window 2");
9391        let child = ui.create(WidgetKind::Container, None).expect("child");
9392        ui.attach(window2, child).expect("attach child");
9393        ui.set_min_size(child, 320, 240).expect("child min");
9394        ui.set_layout_root(window2).expect("layout root");
9395        assert_eq!(ui.window_min_size(window2), Ok(Some((320, 240))));
9396    }
9397
9398    #[test]
9399    fn multiple_layout_roots_recompute_layout_independently_on_window_resize() {
9400        let backend = MockBackend::default();
9401        let mut ui = Ui::new(backend);
9402
9403        let window1 = ui
9404            .create(WidgetKind::Window, Some("w1"))
9405            .expect("window1 created");
9406        let btn1 = ui
9407            .create(WidgetKind::Button, Some("b1"))
9408            .expect("btn1 created");
9409        ui.attach(window1, btn1).expect("attached");
9410
9411        let window2 = ui
9412            .create(WidgetKind::Window, Some("w2"))
9413            .expect("window2 created");
9414        let btn2 = ui
9415            .create(WidgetKind::Button, Some("b2"))
9416            .expect("btn2 created");
9417        ui.attach(window2, btn2).expect("attached");
9418
9419        if let Some(&node) = ui.layout_nodes.get(&btn1) {
9420            let style = crate::layout::Style {
9421                size: crate::layout::Size {
9422                    width: crate::layout::Dimension::length(50.0),
9423                    height: crate::layout::Dimension::length(25.0),
9424                },
9425                ..Default::default()
9426            };
9427            let _ = ui.layout_tree.set_style(node, style);
9428        }
9429
9430        if let Some(&node) = ui.layout_nodes.get(&btn2) {
9431            let style = crate::layout::Style {
9432                size: crate::layout::Size {
9433                    width: crate::layout::Dimension::length(70.0),
9434                    height: crate::layout::Dimension::length(35.0),
9435                },
9436                ..Default::default()
9437            };
9438            let _ = ui.layout_tree.set_style(node, style);
9439        }
9440
9441        ui.set_layout_root(window1)
9442            .expect("window1 layout root set");
9443        ui.add_layout_root(window2)
9444            .expect("window2 layout root added");
9445
9446        assert!(ui.is_layout_root(window1));
9447        assert!(ui.is_layout_root(window2));
9448        assert_eq!(ui.layout_roots().len(), 2);
9449
9450        // Resize window1: only window1 layout is recomputed
9451        ui.backend_mut().push_event(UiEvent::WindowResized {
9452            widget_id: window1,
9453            width: 800,
9454            height: 600,
9455        });
9456        let count = ui.dispatch_events(|_| {}).expect("dispatch");
9457        assert_eq!(count, 1);
9458        assert_eq!(ui.widget(btn1).and_then(|spec| spec.size), Some((50, 25)));
9459        assert_eq!(ui.widget(btn2).and_then(|spec| spec.size), None);
9460
9461        // Resize window2: window2 layout is recomputed
9462        ui.backend_mut().push_event(UiEvent::WindowResized {
9463            widget_id: window2,
9464            width: 400,
9465            height: 300,
9466        });
9467        let count = ui.dispatch_events(|_| {}).expect("dispatch");
9468        assert_eq!(count, 1);
9469        assert_eq!(ui.widget(btn2).and_then(|spec| spec.size), Some((70, 35)));
9470
9471        // Remove window2 as layout root
9472        assert!(ui.remove_layout_root(window2));
9473        assert!(!ui.is_layout_root(window2));
9474        assert!(ui.is_layout_root(window1));
9475        assert_eq!(ui.layout_roots().len(), 1);
9476        assert!(!ui.remove_layout_root(window2));
9477
9478        // Removing the window widget cleans up layout_roots
9479        ui.remove(window1).expect("removed");
9480        assert!(!ui.is_layout_root(window1));
9481        assert!(ui.layout_roots().is_empty());
9482    }
9483
9484    #[test]
9485    fn add_layout_root_rejects_non_window_widget() {
9486        let backend = MockBackend::default();
9487        let mut ui = Ui::new(backend);
9488
9489        let button = ui
9490            .create(WidgetKind::Button, Some("b"))
9491            .expect("button created");
9492        let err = ui.add_layout_root(button).expect_err("non-window rejected");
9493        assert_eq!(err, GuiError::UnsupportedWidget("set_layout_root"));
9494    }
9495
9496    /// `(size writes, position writes)` recorded for one widget
9497    /// (layout-bound assertions).
9498    fn widget_write_counts(backend: &MockBackend, id: WidgetId) -> (usize, usize) {
9499        (
9500            backend.size_writes.get(&id).copied().unwrap_or(0),
9501            backend.position_writes.get(&id).copied().unwrap_or(0),
9502        )
9503    }
9504
9505    #[test]
9506    fn layout_pass_is_bounded_to_the_invalidated_branch() {
9507        let backend = MockBackend::default();
9508        let mut ui = Ui::new(backend);
9509
9510        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
9511        let left = ui
9512            .create(WidgetKind::Container, Some("left"))
9513            .expect("left");
9514        let right = ui
9515            .create(WidgetKind::Container, Some("right"))
9516            .expect("right");
9517        let l1 = ui.create(WidgetKind::Label, Some("l1")).expect("l1");
9518        let r1 = ui.create(WidgetKind::Label, Some("r1")).expect("r1");
9519        ui.attach(window, left).expect("attach left");
9520        ui.attach(window, right).expect("attach right");
9521        ui.attach(left, l1).expect("attach l1");
9522        ui.attach(right, r1).expect("attach r1");
9523
9524        ui.compute_layout(window, 400.0, 300.0).expect("first pass");
9525        assert!(ui.layout_dirty.is_empty(), "the pass consumes the schedule");
9526
9527        // Nothing scheduled: the pass measures nothing and writes nothing -
9528        // the invalidated branch was recomputed exactly once.
9529        let probes = ui
9530            .backend()
9531            .natural_size_probes
9532            .load(std::sync::atomic::Ordering::Relaxed);
9533        let r1_writes = widget_write_counts(ui.backend(), r1);
9534        ui.compute_layout(window, 400.0, 300.0)
9535            .expect("steady pass");
9536        assert_eq!(
9537            ui.backend()
9538                .natural_size_probes
9539                .load(std::sync::atomic::Ordering::Relaxed),
9540            probes,
9541            "an unchanged pass performs no backend measurements"
9542        );
9543        assert_eq!(widget_write_counts(ui.backend(), r1), r1_writes);
9544        assert!(ui.layout_dirty.is_empty());
9545
9546        // One new leaf under `left` measures exactly that leaf; the untouched
9547        // `right` branch keeps its geometry and is never measured.
9548        let l2 = ui.create(WidgetKind::Label, Some("l2")).expect("l2");
9549        ui.attach(left, l2).expect("attach l2");
9550        ui.compute_layout(window, 400.0, 300.0)
9551            .expect("branch pass");
9552        assert_eq!(
9553            ui.backend()
9554                .natural_size_probes
9555                .load(std::sync::atomic::Ordering::Relaxed),
9556            probes + 1,
9557            "only the invalidated leaf is measured"
9558        );
9559        assert_eq!(
9560            widget_write_counts(ui.backend(), r1),
9561            r1_writes,
9562            "the untouched branch is not rewritten"
9563        );
9564        let (l2_sizes, l2_positions) = widget_write_counts(ui.backend(), l2);
9565        assert!(
9566            l2_sizes + l2_positions > 0,
9567            "the new leaf receives its geometry"
9568        );
9569        assert!(ui.layout_dirty.is_empty());
9570    }
9571
9572    #[test]
9573    fn layout_schedule_is_topological_and_ancestor_free() {
9574        let backend = MockBackend::default();
9575        let mut ui = Ui::new(backend);
9576
9577        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
9578        let left = ui
9579            .create(WidgetKind::Container, Some("left"))
9580            .expect("left");
9581        let inner = ui
9582            .create(WidgetKind::Container, Some("inner"))
9583            .expect("inner");
9584        let l1 = ui.create(WidgetKind::Label, Some("l1")).expect("l1");
9585        let right = ui
9586            .create(WidgetKind::Container, Some("right"))
9587            .expect("right");
9588        let r1 = ui.create(WidgetKind::Label, Some("r1")).expect("r1");
9589        ui.attach(window, left).expect("attach left");
9590        ui.attach(window, right).expect("attach right");
9591        ui.attach(left, inner).expect("attach inner");
9592        ui.attach(inner, l1).expect("attach l1");
9593        ui.attach(right, r1).expect("attach r1");
9594        ui.compute_layout(window, 400.0, 300.0).expect("first pass");
9595        assert!(ui.layout_dirty.is_empty());
9596
9597        // Scheduling a container and then a descendant keeps the schedule
9598        // ancestor-free: the descendant is subsumed by the scheduled branch
9599        // (the O(D) short-circuit), so it never becomes a second walk root.
9600        ui.set_container_direction(left, ContainerDirection::Horizontal)
9601            .expect("direction");
9602        assert!(ui.layout_dirty.contains(&left));
9603        ui.set_container_direction(inner, ContainerDirection::Horizontal)
9604            .expect("inner direction");
9605        assert_eq!(
9606            ui.layout_dirty.len(),
9607            1,
9608            "descendant invalidations are subsumed by the scheduled branch"
9609        );
9610
9611        let dirty_nodes = |ui: &Ui<MockBackend>| -> usize {
9612            ui.layout_nodes
9613                .values()
9614                .filter(|node| ui.layout_tree.is_dirty(**node).unwrap_or(false))
9615                .count()
9616        };
9617        assert!(
9618            dirty_nodes(&ui) > 0,
9619            "the direction change dirtied layout nodes"
9620        );
9621
9622        ui.compute_layout(window, 400.0, 300.0).expect("pass");
9623        assert!(ui.layout_dirty.is_empty(), "the pass consumes the schedule");
9624        assert_eq!(
9625            dirty_nodes(&ui),
9626            0,
9627            "layout recomputes and clears every dirty node"
9628        );
9629    }
9630
9631    #[test]
9632    fn layout_passes_still_apply_resizes_and_write_only_changes() {
9633        let backend = MockBackend::default();
9634        let mut ui = Ui::new(backend);
9635
9636        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
9637        let left = ui
9638            .create(WidgetKind::Container, Some("left"))
9639            .expect("left");
9640        let right = ui
9641            .create(WidgetKind::Container, Some("right"))
9642            .expect("right");
9643        ui.attach(window, left).expect("attach left");
9644        ui.attach(window, right).expect("attach right");
9645        ui.compute_layout(window, 400.0, 300.0).expect("first pass");
9646
9647        let write_total = |ui: &Ui<MockBackend>| -> usize {
9648            ui.backend()
9649                .size_writes
9650                .values()
9651                .chain(ui.backend().position_writes.values())
9652                .sum()
9653        };
9654        let before = write_total(&ui);
9655        ui.compute_layout(window, 800.0, 300.0)
9656            .expect("resize pass");
9657        let after_resize = write_total(&ui);
9658        assert!(
9659            after_resize > before,
9660            "a resize still recomputes and applies changed geometry"
9661        );
9662        ui.compute_layout(window, 800.0, 300.0)
9663            .expect("repeat pass");
9664        assert_eq!(
9665            write_total(&ui),
9666            after_resize,
9667            "repeating the same pass writes nothing"
9668        );
9669    }
9670
9671    #[test]
9672    fn layout_schedule_drops_removed_widgets() {
9673        let backend = MockBackend::default();
9674        let mut ui = Ui::new(backend);
9675
9676        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
9677        ui.compute_layout(window, 100.0, 100.0).expect("pass");
9678        assert!(ui.layout_dirty.is_empty());
9679
9680        let label = ui.create(WidgetKind::Label, Some("l")).expect("label");
9681        ui.attach(window, label).expect("attach");
9682        assert!(ui.layout_dirty.contains(&label));
9683        ui.remove(label).expect("remove");
9684        assert!(
9685            ui.layout_dirty.is_empty(),
9686            "a removed widget leaves no schedule entry"
9687        );
9688    }
9689
9690    #[test]
9691    fn keyed_rows_preserve_selection_and_reanchor_by_key() {
9692        let backend = MockBackend::default();
9693        let mut ui = Ui::new(backend);
9694
9695        let list = ui.create(WidgetKind::DataList, Some("rows")).expect("list");
9696        let first = [
9697            RowSet::new(1, &["Backlog"]),
9698            RowSet::new(2, &["Doing"]),
9699            RowSet::new(3, &["Done"]),
9700        ];
9701        let delta = ui.set_rows_keyed(list, &first).expect("first apply");
9702        assert_eq!(
9703            delta,
9704            RowDelta {
9705                inserted: 3,
9706                updated: 0,
9707                removed: 0,
9708                moved: 0,
9709                unchanged: 0,
9710            }
9711        );
9712        assert_eq!(
9713            ui.widget(list).expect("spec").data_list_items,
9714            vec!["Backlog".to_owned(), "Doing".to_owned(), "Done".to_owned()]
9715        );
9716
9717        // Identical rows are free: empty delta with no row write.
9718        let writes = ui.backend().row_writes.get(&list).copied().unwrap_or(0);
9719        let delta = ui.set_rows_keyed(list, &first).expect("no-op apply");
9720        assert!(delta.is_noop());
9721        assert_eq!(
9722            ui.backend().row_writes.get(&list).copied().unwrap_or(0),
9723            writes,
9724            "a no-op keyed apply performs no backend write"
9725        );
9726
9727        // Select key 2 through the index path and pin the top visible row to
9728        // key 1; a reorder must follow both by identity.
9729        ui.set_selected_index(list, 1).expect("select");
9730        assert_eq!(ui.selected_row_key(list), Some(RowKey(2)));
9731        ui.backend_mut().scroll_anchors.insert(list, 0);
9732        let reordered = [
9733            RowSet::new(3, &["Done"]),
9734            RowSet::new(1, &["Backlog"]),
9735            RowSet::new(2, &["Doing"]),
9736        ];
9737        let delta = ui.set_rows_keyed(list, &reordered).expect("reorder");
9738        assert_eq!(
9739            delta,
9740            RowDelta {
9741                inserted: 0,
9742                updated: 0,
9743                removed: 0,
9744                moved: 3,
9745                unchanged: 0,
9746            }
9747        );
9748        assert_eq!(
9749            ui.widget(list).expect("spec").selected_index,
9750            Some(2),
9751            "the selection follows its key to the new index"
9752        );
9753        assert_eq!(ui.selected_row_key(list), Some(RowKey(2)));
9754        assert_eq!(
9755            ui.backend().scroll_requests,
9756            vec![(list, 1)],
9757            "the anchor key re-anchors at its new index"
9758        );
9759        let event = ui.poll_event().expect("poll").expect("selection event");
9760        assert_eq!(
9761            event,
9762            UiEvent::SelectionChanged {
9763                widget_id: list,
9764                selected: Some("Doing".to_owned()),
9765                index: Some(2),
9766            }
9767        );
9768        assert_eq!(ui.visible_anchor(list).expect("anchor"), Some(RowKey(1)));
9769
9770        // Removing the selected key clears it, emits the clear, and records
9771        // the lane's native clear.
9772        let without_doing = [RowSet::new(3, &["Done"]), RowSet::new(1, &["Backlog"])];
9773        let delta = ui
9774            .set_rows_keyed(list, &without_doing)
9775            .expect("remove selected");
9776        assert_eq!(delta.removed, 1);
9777        assert_eq!(ui.widget(list).expect("spec").selected_index, None);
9778        assert_eq!(ui.selected_row_key(list), None);
9779        assert_eq!(ui.backend().selection_clears, vec![list]);
9780        let event = ui.poll_event().expect("poll").expect("clear event");
9781        assert_eq!(
9782            event,
9783            UiEvent::SelectionChanged {
9784                widget_id: list,
9785                selected: None,
9786                index: None,
9787            }
9788        );
9789
9790        // Duplicate keys reject the apply without touching rows or selection.
9791        let before = ui.widget(list).cloned();
9792        assert_eq!(
9793            ui.set_rows_keyed(list, &[RowSet::new(5, &["x"]), RowSet::new(5, &["y"])]),
9794            Err(GuiError::Backend("duplicate row key".to_owned()))
9795        );
9796        assert_eq!(ui.widget(list), before.as_ref());
9797    }
9798
9799    #[test]
9800    fn keyed_rows_filter_multi_selection_by_key() {
9801        let backend = MockBackend::default();
9802        let mut ui = Ui::new(backend);
9803
9804        let list = ui.create(WidgetKind::ListView, Some("rows")).expect("list");
9805        let rows = [
9806            RowSet::new(1, &["a"]),
9807            RowSet::new(2, &["b"]),
9808            RowSet::new(3, &["c"]),
9809        ];
9810        ui.set_rows_keyed(list, &rows).expect("apply");
9811        ui.set_selected_indices(list, &[0, 2])
9812            .expect("multi select");
9813
9814        // Key 3 is dropped: key 1 survives at index 0, and the multi event
9815        // reports the filtered index set exactly once.
9816        let delta = ui
9817            .set_rows_keyed(list, &[RowSet::new(1, &["a"]), RowSet::new(2, &["b"])])
9818            .expect("apply");
9819        assert_eq!(delta.removed, 1);
9820        assert_eq!(ui.widget(list).expect("spec").selected_indices, vec![0]);
9821        let event = ui.poll_event().expect("poll").expect("multi event");
9822        assert_eq!(
9823            event,
9824            UiEvent::MultiSelectionChanged {
9825                widget_id: list,
9826                indices: vec![0],
9827            }
9828        );
9829
9830        // A direct clear empties the selection and emits the clear shape.
9831        ui.set_selected_index(list, 0).expect("select");
9832        ui.clear_selection(list).expect("clear");
9833        assert_eq!(ui.widget(list).expect("spec").selected_index, None);
9834        assert_eq!(
9835            ui.widget(list).expect("spec").selected_indices,
9836            Vec::<usize>::new()
9837        );
9838        assert_eq!(ui.selected_row_key(list), None);
9839        let event = ui.poll_event().expect("poll").expect("clear event");
9840        assert_eq!(
9841            event,
9842            UiEvent::SelectionChanged {
9843                widget_id: list,
9844                selected: None,
9845                index: None,
9846            }
9847        );
9848    }
9849
9850    #[test]
9851    fn keyed_rows_cover_grids_and_reject_other_kinds() {
9852        let backend = MockBackend::default();
9853        let mut ui = Ui::new(backend);
9854
9855        let grid = ui.create(WidgetKind::DataGrid, Some("grid")).expect("grid");
9856        let delta = ui
9857            .set_rows_keyed(grid, &[RowSet::new(1, &["r1c1", "r1c2"])])
9858            .expect("apply");
9859        assert_eq!(delta.inserted, 1);
9860        assert_eq!(
9861            ui.widget(grid)
9862                .expect("spec")
9863                .data_grid_rows
9864                .as_ref()
9865                .clone(),
9866            vec![vec!["r1c1".to_owned(), "r1c2".to_owned()]]
9867        );
9868        // A widget without keyed rows has no anchor to report, and nothing
9869        // is scrolled when no anchor is observable.
9870        assert_eq!(ui.visible_anchor(grid).expect("anchor"), None);
9871        assert!(ui.backend().scroll_requests.is_empty());
9872
9873        let button = ui.create(WidgetKind::Button, Some("b")).expect("button");
9874        assert_eq!(
9875            ui.set_rows_keyed(button, &[RowSet::new(1, &["x"])])
9876                .expect_err("button rejected"),
9877            GuiError::UnsupportedWidget("set_rows_keyed")
9878        );
9879        assert_eq!(
9880            ui.clear_selection(button).expect_err("button rejected"),
9881            GuiError::UnsupportedWidget("clear_selection")
9882        );
9883        assert_eq!(
9884            ui.visible_anchor(button).expect_err("button rejected"),
9885            GuiError::UnsupportedWidget("visible_anchor")
9886        );
9887        assert_eq!(
9888            ui.scroll_to_row(button, 0).expect_err("button rejected"),
9889            GuiError::UnsupportedWidget("visible_anchor")
9890        );
9891    }
9892
9893    #[test]
9894    fn scroll_to_row_moves_the_mock_anchor() {
9895        let backend = MockBackend::default();
9896        let mut ui = Ui::new(backend);
9897        let list = ui.create(WidgetKind::DataList, None).expect("list");
9898        ui.set_data_list_items(list, &["a".into(), "b".into(), "c".into()])
9899            .expect("items");
9900        ui.scroll_to_row(list, 2).expect("scroll");
9901        assert_eq!(
9902            ui.backend().scroll_requests,
9903            vec![(list, 2)],
9904            "Ui::scroll_to_row is recorded on the mock"
9905        );
9906        assert_eq!(
9907            ui.backend().visible_anchor_index(list).expect("anchor"),
9908            Some(2)
9909        );
9910    }
9911
9912    #[test]
9913    fn keyed_rows_feed_a_columned_list_view_through_list_rows() {
9914        let backend = MockBackend::default();
9915        let mut ui = Ui::new(backend);
9916
9917        let list = ui
9918            .create(WidgetKind::ListView, Some("Files"))
9919            .expect("list");
9920        ui.set_list_columns(list, &[ColumnSpec::new("Name"), ColumnSpec::new("Size")])
9921            .expect("columns");
9922
9923        let delta = ui
9924            .set_rows_keyed(
9925                list,
9926                &[
9927                    RowSet::new(1, &["a.txt", "12 KB"]),
9928                    RowSet::new(2, &["b.txt", "8 KB"]),
9929                ],
9930            )
9931            .expect("keyed rows");
9932        assert_eq!(delta.inserted, 2);
9933
9934        // The columned lane renders `list_rows`; the single-column model must
9935        // not be the one updated behind its back.
9936        let spec = ui.widget(list).expect("spec");
9937        assert_eq!(
9938            spec.list_rows,
9939            vec![
9940                vec!["a.txt".to_owned(), "12 KB".to_owned()],
9941                vec!["b.txt".to_owned(), "8 KB".to_owned()],
9942            ]
9943        );
9944        assert!(spec.data_list_items.is_empty());
9945
9946        // Selection follows the keyed rows as usual.
9947        ui.set_selected_index(list, 1).expect("select");
9948        assert_eq!(ui.selected_row_key(list), Some(RowKey(2)));
9949
9950        // A no-column ListView keeps the single-column contract.
9951        let plain = ui
9952            .create(WidgetKind::ListView, Some("Plain"))
9953            .expect("plain list");
9954        ui.set_rows_keyed(plain, &[RowSet::new(7, &["only"])])
9955            .expect("plain keyed rows");
9956        assert_eq!(
9957            ui.widget(plain).expect("spec").data_list_items,
9958            vec!["only".to_owned()]
9959        );
9960        assert!(ui.widget(plain).expect("spec").list_rows.is_empty());
9961    }
9962
9963    #[test]
9964    fn list_columns_and_rows_update_spec_and_mock_record() {
9965        let backend = MockBackend::default();
9966        let mut ui = Ui::new(backend);
9967
9968        let list = ui
9969            .create(WidgetKind::ListView, Some("Files"))
9970            .expect("list");
9971        let columns = [
9972            ColumnSpec::new("Name"),
9973            ColumnSpec::new("Size").with_width(80),
9974        ];
9975        ui.set_list_columns(list, &columns).expect("columns");
9976        ui.set_list_rows(list, &[vec!["a.txt".to_owned(), "12 KB".to_owned()]])
9977            .expect("rows");
9978
9979        let spec = ui.widget(list).expect("spec");
9980        assert_eq!(spec.list_columns, columns);
9981        assert_eq!(
9982            spec.list_rows,
9983            vec![vec!["a.txt".to_owned(), "12 KB".to_owned()]]
9984        );
9985        let native = ui.backend().created.get(&list).expect("native record");
9986        assert_eq!(native.list_columns, columns);
9987
9988        // The columned contract is ListView-only; other kinds keep the
9989        // typed guard and leave the model untouched.
9990        let button = ui.create(WidgetKind::Button, Some("b")).expect("button");
9991        assert_eq!(
9992            ui.set_list_columns(button, &columns)
9993                .expect_err("button rejected"),
9994            GuiError::UnsupportedWidget("set_list_columns")
9995        );
9996        assert_eq!(
9997            ui.set_list_rows(button, &[]).expect_err("button rejected"),
9998            GuiError::UnsupportedWidget("set_list_rows")
9999        );
10000        assert!(ui.widget(button).expect("spec").list_columns.is_empty());
10001    }
10002
10003    #[test]
10004    fn menu_item_callback_requires_existing_item() {
10005        let backend = MockBackend::default();
10006        let mut ui = Ui::new(backend);
10007
10008        let err = ui
10009            .on_menu_item_selected(MenuItemId(999), || {})
10010            .expect_err("unknown menu item should be rejected");
10011
10012        assert_eq!(
10013            err,
10014            GuiError::Backend("Menu item not found: 999".to_owned())
10015        );
10016    }
10017
10018    #[test]
10019    fn add_menu_item_with_shortcut_registers_backend_shortcut() {
10020        let backend = MockBackend::default();
10021        let mut ui = Ui::new(backend);
10022
10023        let menu = ui.create_menu().expect("menu should be created");
10024        let item = ui
10025            .add_menu_item_with_shortcut(menu, "Quit", Some("Ctrl+Q"))
10026            .expect("menu item should be created");
10027
10028        assert_eq!(
10029            ui.backend().menu_shortcuts.get(&item).cloned(),
10030            Some("Ctrl+Q".to_owned())
10031        );
10032    }
10033
10034    #[test]
10035    fn set_selected_indices_supports_multi_select_lists() {
10036        let backend = MockBackend::default();
10037        let mut ui = Ui::new(backend);
10038
10039        let list = ui.create(WidgetKind::ListView, None).expect("list created");
10040        ui.set_selected_indices(list, &[0, 2])
10041            .expect("multi select set");
10042        assert_eq!(ui.widget(list).unwrap().selected_indices, vec![0, 2]);
10043
10044        let button = ui
10045            .create(WidgetKind::Button, Some("b"))
10046            .expect("button created");
10047        let err = ui
10048            .set_selected_indices(button, &[0])
10049            .expect_err("button rejected");
10050        assert_eq!(err, GuiError::UnsupportedWidget("set_selected_indices"));
10051    }
10052
10053    #[test]
10054    fn set_tree_items_populates_tree_view_and_rejects_others() {
10055        let backend = MockBackend::default();
10056        let mut ui = Ui::new(backend);
10057
10058        let tree = ui.create(WidgetKind::TreeView, None).expect("tree created");
10059        let items = vec![
10060            TreeItem::new("Documents").with_child(TreeItem::new("Archive")),
10061            TreeItem::new("Downloads"),
10062        ];
10063        ui.set_tree_items(tree, &items).expect("tree items set");
10064        assert_eq!(ui.widget(tree).unwrap().tree_items, items);
10065        assert_eq!(
10066            items[0].indented_rows(),
10067            vec!["Documents".to_owned(), "  Archive".to_owned()]
10068        );
10069
10070        let button = ui
10071            .create(WidgetKind::Button, Some("b"))
10072            .expect("button created");
10073        let err = ui
10074            .set_tree_items(button, &items)
10075            .expect_err("button rejected");
10076        assert_eq!(err, GuiError::UnsupportedWidget("set_tree_items"));
10077    }
10078
10079    #[test]
10080    fn set_container_direction_rejects_non_container() {
10081        let backend = MockBackend::default();
10082        let mut ui = Ui::new(backend);
10083
10084        let button = ui
10085            .create(WidgetKind::Button, Some("button"))
10086            .expect("button should be created");
10087
10088        let err = ui
10089            .set_container_direction(button, ContainerDirection::Horizontal)
10090            .expect_err("non-container should be rejected");
10091
10092        assert_eq!(err, GuiError::UnsupportedWidget("set_container_direction"));
10093    }
10094
10095    #[test]
10096    fn set_container_scroll_rejects_non_container() {
10097        let backend = MockBackend::default();
10098        let mut ui = Ui::new(backend);
10099
10100        let button = ui
10101            .create(WidgetKind::Button, Some("button"))
10102            .expect("button should be created");
10103
10104        let err = ui
10105            .set_container_scroll(button, true, false)
10106            .expect_err("non-container should be rejected");
10107
10108        assert_eq!(err, GuiError::UnsupportedWidget("set_container_scroll"));
10109    }
10110
10111    #[test]
10112    fn set_container_gap_and_padding_update_spec_and_layout() {
10113        let backend = MockBackend::default();
10114        let mut ui = Ui::new(backend);
10115
10116        let container = ui
10117            .create(WidgetKind::Container, None)
10118            .expect("container should be created");
10119
10120        ui.set_container_gap(container, 6).expect("set gap");
10121        ui.set_container_padding(container, 10)
10122            .expect("set padding");
10123        assert_eq!(
10124            ui.widget(container).and_then(|spec| spec.container_gap),
10125            Some(6)
10126        );
10127        assert_eq!(
10128            ui.widget(container).and_then(|spec| spec.container_padding),
10129            Some(10)
10130        );
10131
10132        // The layout tree stays in sync for `compute_layout` (parity
10133        // with `set_container_direction`).
10134        let node = ui
10135            .layout_nodes
10136            .get(&container)
10137            .copied()
10138            .expect("layout node");
10139        let style = ui.layout_tree.style(node).expect("layout style").clone();
10140        assert_eq!(
10141            style.gap.width,
10142            crate::layout::LengthPercentage::length(6.0)
10143        );
10144        assert_eq!(
10145            style.gap.height,
10146            crate::layout::LengthPercentage::length(6.0)
10147        );
10148        assert_eq!(
10149            style.padding.left,
10150            crate::layout::LengthPercentage::length(10.0)
10151        );
10152        assert_eq!(
10153            style.padding.bottom,
10154            crate::layout::LengthPercentage::length(10.0)
10155        );
10156
10157        // Negative values clamp to zero instead of erroring.
10158        ui.set_container_gap(container, -4).expect("clamped gap");
10159        ui.set_container_padding(container, -9)
10160            .expect("clamped padding");
10161        assert_eq!(
10162            ui.widget(container).and_then(|spec| spec.container_gap),
10163            Some(0)
10164        );
10165        assert_eq!(
10166            ui.widget(container).and_then(|spec| spec.container_padding),
10167            Some(0)
10168        );
10169        let style = ui.layout_tree.style(node).expect("layout style").clone();
10170        assert_eq!(
10171            style.gap.width,
10172            crate::layout::LengthPercentage::length(0.0)
10173        );
10174        assert_eq!(
10175            style.padding.top,
10176            crate::layout::LengthPercentage::length(0.0)
10177        );
10178    }
10179
10180    #[test]
10181    fn set_container_gap_and_padding_reject_non_container() {
10182        let backend = MockBackend::default();
10183        let mut ui = Ui::new(backend);
10184
10185        let button = ui
10186            .create(WidgetKind::Button, Some("button"))
10187            .expect("button should be created");
10188
10189        assert!(matches!(
10190            ui.set_container_gap(button, 4),
10191            Err(GuiError::UnsupportedWidget("set_container_gap"))
10192        ));
10193        assert!(matches!(
10194            ui.set_container_padding(button, 4),
10195            Err(GuiError::UnsupportedWidget("set_container_padding"))
10196        ));
10197
10198        #[cfg(feature = "widgets-containers")]
10199        {
10200            // SplitPane keeps its ratio semantics and stays outside the row.
10201            let split = ui
10202                .create(WidgetKind::SplitPane, None)
10203                .expect("split pane should be created");
10204            assert!(matches!(
10205                ui.set_container_gap(split, 4),
10206                Err(GuiError::UnsupportedWidget("set_container_gap"))
10207            ));
10208        }
10209    }
10210
10211    #[test]
10212    fn set_container_scroll_updates_widget_spec() {
10213        let backend = MockBackend::default();
10214        let mut ui = Ui::new(backend);
10215
10216        let container = ui
10217            .create(WidgetKind::Container, None)
10218            .expect("container should be created");
10219
10220        ui.set_container_scroll(container, true, true)
10221            .expect("set container scroll should succeed");
10222
10223        let Some(spec) = ui.widget(container) else {
10224            panic!("container spec should exist");
10225        };
10226        assert!(spec.container_scroll_vertical);
10227        assert!(spec.container_scroll_horizontal);
10228    }
10229
10230    #[test]
10231    fn set_size_accepts_non_button_widget() {
10232        let backend = MockBackend::default();
10233        let mut ui = Ui::new(backend);
10234
10235        let label = ui
10236            .create(WidgetKind::Label, Some("label"))
10237            .expect("label should be created");
10238
10239        ui.set_size(label, 120, 40)
10240            .expect("set size should support non-button widgets");
10241        assert_eq!(ui.widget(label).and_then(|spec| spec.size), Some((120, 40)));
10242    }
10243
10244    #[test]
10245    fn set_size_updates_widget_spec() {
10246        let backend = MockBackend::default();
10247        let mut ui = Ui::new(backend);
10248
10249        let button = ui
10250            .create(WidgetKind::Button, Some("Run"))
10251            .expect("button should be created");
10252
10253        ui.set_size(button, 140, 44)
10254            .expect("set size should succeed");
10255
10256        assert_eq!(
10257            ui.widget(button).and_then(|spec| spec.size),
10258            Some((140, 44))
10259        );
10260        assert_eq!(
10261            ui.backend().created.get(&button).and_then(|spec| spec.size),
10262            Some((140, 44))
10263        );
10264    }
10265
10266    #[test]
10267    fn set_size_rejects_non_positive_dimensions() {
10268        let backend = MockBackend::default();
10269        let mut ui = Ui::new(backend);
10270
10271        let button = ui
10272            .create(WidgetKind::Button, Some("Run"))
10273            .expect("button should be created");
10274
10275        let err = ui
10276            .set_size(button, 0, 44)
10277            .expect_err("non-positive size should be rejected");
10278
10279        assert_eq!(
10280            err,
10281            GuiError::Backend("Widget size must be positive".to_owned())
10282        );
10283    }
10284
10285    /// An app-requested size must survive a `compute_layout`
10286    /// pass instead of losing to layout's computed value (the
10287    /// `gui_photo_gallery` tile overwrite). The column parent stretches
10288    /// auto-sized children on the cross axis, so without the layout sync the
10289    /// request would be recomputed away.
10290    #[test]
10291    fn set_size_survives_a_compute_layout_pass() {
10292        let backend = MockBackend::default();
10293        let mut ui = Ui::new(backend);
10294
10295        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
10296        let column = ui
10297            .create(WidgetKind::Container, Some("column"))
10298            .expect("column");
10299        ui.set_container_direction(column, ContainerDirection::Vertical)
10300            .expect("column direction");
10301        let tile = ui.create(WidgetKind::Label, Some("tile")).expect("tile");
10302        ui.attach(window, column).expect("attach column");
10303        ui.attach(column, tile).expect("attach tile");
10304
10305        ui.set_size(tile, 160, 120).expect("tile size");
10306        ui.compute_layout(window, 800.0, 600.0).expect("pass");
10307
10308        assert_eq!(
10309            ui.widget(tile).and_then(|spec| spec.size),
10310            Some((160, 120)),
10311            "the spec keeps the requested size through the pass"
10312        );
10313        assert_eq!(
10314            ui.backend().created.get(&tile).and_then(|spec| spec.size),
10315            Some((160, 120)),
10316            "the backend receives the requested size, not a rewrite"
10317        );
10318        let node = *ui.layout_nodes.get(&tile).expect("layout node");
10319        let layout = ui.layout_tree.layout(node).expect("layout");
10320        assert_eq!(
10321            (layout.width, layout.height),
10322            (160.0, 120.0),
10323            "layout computes the requested size, so later passes agree"
10324        );
10325    }
10326
10327    /// Imperative `set_size`, spec-based `create_with` and
10328    /// declarative `Node::size` authoring must produce the same result.
10329    #[test]
10330    #[cfg(all(feature = "declarative", feature = "widgets-media"))]
10331    fn size_authoring_paths_lay_out_alike() {
10332        use crate::declarative::{DeclarativeUi, Image as NodeImage, Window as NodeWindow};
10333
10334        // Imperative and spec-based authoring side by side.
10335        let backend = MockBackend::default();
10336        let mut ui = Ui::new(backend);
10337
10338        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
10339        let column = ui
10340            .create(WidgetKind::Container, Some("column"))
10341            .expect("column");
10342        ui.set_container_direction(column, ContainerDirection::Vertical)
10343            .expect("column direction");
10344        ui.attach(window, column).expect("attach column");
10345
10346        let imperative = ui.create(WidgetKind::Image, None).expect("imperative");
10347        ui.attach(column, imperative).expect("attach imperative");
10348        ui.set_size(imperative, 160, 120).expect("imperative size");
10349
10350        let spec_based = ui
10351            .create_with(WidgetKind::Image, |spec| spec.size = Some((160, 120)))
10352            .expect("spec-based");
10353        ui.attach(column, spec_based).expect("attach spec-based");
10354
10355        // Declarative authoring writes the layout style directly.
10356        let mut node_ui = Ui::new(MockBackend::default());
10357        let mut declarative = WidgetId(0);
10358        let mut tree = NodeWindow::new("w").child(
10359            crate::declarative::Container::vertical().child(
10360                NodeImage::new()
10361                    .size(160.0, 120.0)
10362                    .bind_id(&mut declarative),
10363            ),
10364        );
10365        let node_root = node_ui.render(&mut tree).expect("render");
10366        drop(tree);
10367
10368        ui.compute_layout(window, 800.0, 600.0)
10369            .expect("imperative pass");
10370        node_ui
10371            .compute_layout(node_root, 800.0, 600.0)
10372            .expect("declarative pass");
10373
10374        let layout_size = |ui: &Ui<MockBackend>, id: WidgetId| {
10375            let node = *ui.layout_nodes.get(&id).expect("layout node");
10376            let layout = ui.layout_tree.layout(node).expect("layout");
10377            (layout.width, layout.height)
10378        };
10379
10380        for id in [imperative, spec_based] {
10381            assert_eq!(
10382                ui.widget(id).and_then(|spec| spec.size),
10383                Some((160, 120)),
10384                "imperative and spec-based requests keep their size"
10385            );
10386            assert_eq!(layout_size(&ui, id), (160.0, 120.0));
10387        }
10388        assert_eq!(
10389            node_ui.widget(declarative).and_then(|spec| spec.size),
10390            Some((160, 120)),
10391            "the declarative leaf lands on the same spec size"
10392        );
10393        assert_eq!(
10394            layout_size(&node_ui, declarative),
10395            (160.0, 120.0),
10396            "the declarative leaf lands on the same layout geometry"
10397        );
10398    }
10399
10400    /// Computed geometry is pass output, not an app request - an
10401    /// auto-sized leaf must keep recomputing with the window instead of
10402    /// having the last pass's size pinned into its layout style.
10403    #[test]
10404    fn computed_sizes_do_not_pin_auto_axes_into_layout() {
10405        let backend = MockBackend::default();
10406        let mut ui = Ui::new(backend);
10407
10408        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
10409        let label = ui
10410            .create(WidgetKind::Label, Some("stretch"))
10411            .expect("label");
10412        ui.attach(window, label).expect("attach");
10413
10414        ui.compute_layout(window, 800.0, 600.0).expect("first pass");
10415        let node = *ui.layout_nodes.get(&label).expect("layout node");
10416        let first = ui.layout_tree.layout(node).expect("layout");
10417        assert_eq!((first.width, first.height), (800.0, 600.0));
10418
10419        ui.compute_layout(window, 800.0, 300.0)
10420            .expect("shorter pass");
10421        let second = ui.layout_tree.layout(node).expect("layout");
10422        assert_eq!(
10423            second.height, 300.0,
10424            "the auto leaf follows the window on the next pass"
10425        );
10426    }
10427
10428    #[test]
10429    fn set_position_updates_widget_spec() {
10430        let backend = MockBackend::default();
10431        let mut ui = Ui::new(backend);
10432
10433        let button = ui
10434            .create(WidgetKind::Button, Some("Move"))
10435            .expect("button should be created");
10436
10437        ui.set_position(button, 18, 26)
10438            .expect("set position should succeed");
10439
10440        assert_eq!(
10441            ui.widget(button).and_then(|spec| spec.position),
10442            Some((18, 26))
10443        );
10444        assert_eq!(
10445            ui.backend()
10446                .created
10447                .get(&button)
10448                .and_then(|spec| spec.position),
10449            Some((18, 26))
10450        );
10451    }
10452
10453    #[test]
10454    fn set_background_color_updates_widget_spec() {
10455        let backend = MockBackend::default();
10456        let mut ui = Ui::new(backend);
10457
10458        let label = ui
10459            .create(WidgetKind::Label, Some("label"))
10460            .expect("label should be created");
10461        let color = Color::rgb(12, 34, 56);
10462
10463        ui.set_background_color(label, color)
10464            .expect("set background color should succeed");
10465
10466        assert_eq!(
10467            ui.widget(label).and_then(|spec| spec.background_color),
10468            Some(color)
10469        );
10470        assert_eq!(
10471            ui.backend()
10472                .created
10473                .get(&label)
10474                .and_then(|spec| spec.background_color),
10475            Some(color)
10476        );
10477    }
10478
10479    #[test]
10480    #[cfg(feature = "widgets-containers")]
10481    fn set_alert_level_rejects_non_alert_dialog() {
10482        let backend = MockBackend::default();
10483        let mut ui = Ui::new(backend);
10484
10485        let label = ui
10486            .create(WidgetKind::Label, Some("label"))
10487            .expect("label should be created");
10488
10489        let err = ui
10490            .set_alert_level(label, AlertLevel::Warning)
10491            .expect_err("non-alert widget should be rejected");
10492
10493        assert_eq!(err, GuiError::UnsupportedWidget("set_alert_level"));
10494    }
10495
10496    #[test]
10497    #[cfg(feature = "widgets-containers")]
10498    fn set_alert_level_updates_widget_spec() {
10499        let backend = MockBackend::default();
10500        let mut ui = Ui::new(backend);
10501
10502        let alert = ui
10503            .create(WidgetKind::AlertDialog, Some("Something happened"))
10504            .expect("alert should be created");
10505
10506        ui.set_alert_level(alert, AlertLevel::Error)
10507            .expect("set alert level should succeed");
10508
10509        assert_eq!(
10510            ui.widget(alert).and_then(|spec| spec.alert_level),
10511            Some(AlertLevel::Error)
10512        );
10513        assert_eq!(
10514            ui.backend()
10515                .created
10516                .get(&alert)
10517                .and_then(|spec| spec.alert_level),
10518            Some(AlertLevel::Error)
10519        );
10520    }
10521
10522    #[test]
10523    #[cfg(feature = "widgets-data")]
10524    fn set_data_list_items_updates_widget_spec() {
10525        let backend = MockBackend::default();
10526        let mut ui = Ui::new(backend);
10527
10528        let data_list = ui
10529            .create(WidgetKind::DataList, None)
10530            .expect("data list should be created");
10531        let items = vec!["Alpha".to_owned(), "Beta".to_owned()];
10532
10533        ui.set_data_list_items(data_list, &items)
10534            .expect("set data list items should succeed");
10535
10536        assert_eq!(
10537            ui.widget(data_list)
10538                .map(|spec| spec.data_list_items.clone())
10539                .unwrap_or_default(),
10540            items
10541        );
10542    }
10543
10544    #[test]
10545    #[cfg(feature = "widgets-containers")]
10546    fn set_tab_items_updates_widget_spec() {
10547        let backend = MockBackend::default();
10548        let mut ui = Ui::new(backend);
10549
10550        let tabs = ui
10551            .create(WidgetKind::Tabs, None)
10552            .expect("tabs should be created");
10553        let labels = vec!["General".to_owned(), "Editor".to_owned()];
10554
10555        ui.set_tab_items(tabs, &labels)
10556            .expect("set tab items should succeed");
10557
10558        assert_eq!(
10559            ui.widget(tabs)
10560                .map(|spec| spec.tab_items.clone())
10561                .unwrap_or_default(),
10562            labels
10563        );
10564        assert_eq!(
10565            ui.backend()
10566                .created
10567                .get(&tabs)
10568                .map(|spec| spec.tab_items.clone())
10569                .unwrap_or_default(),
10570            labels
10571        );
10572    }
10573
10574    #[test]
10575    fn set_tab_items_rejects_unsupported_kind() {
10576        let backend = MockBackend::default();
10577        let mut ui = Ui::new(backend);
10578
10579        let label = ui
10580            .create(WidgetKind::Label, Some("Not tabs"))
10581            .expect("label should be created");
10582
10583        assert!(matches!(
10584            ui.set_tab_items(label, &["Nope".to_owned()]),
10585            Err(GuiError::UnsupportedWidget("set_tab_items"))
10586        ));
10587    }
10588
10589    #[test]
10590    #[cfg(feature = "widgets-containers")]
10591    fn test_containers_widgets_and_setters_contract() {
10592        let backend = MockBackend::default();
10593        let mut ui = Ui::new(backend);
10594
10595        let sep = ui.create(WidgetKind::Separator, None).expect("separator");
10596        assert_eq!(ui.widget(sep).map(|s| s.kind), Some(WidgetKind::Separator));
10597
10598        let group = ui
10599            .create(WidgetKind::GroupBox, Some("Options"))
10600            .expect("group");
10601        assert_eq!(ui.widget(group).map(|s| s.kind), Some(WidgetKind::GroupBox));
10602
10603        let tabs = ui.create(WidgetKind::Tabs, None).expect("tabs");
10604        assert_eq!(ui.widget(tabs).map(|s| s.kind), Some(WidgetKind::Tabs));
10605        ui.set_tab_items(tabs, &["Tab A".to_string(), "Tab B".to_string()])
10606            .expect("tab items");
10607        assert_eq!(
10608            ui.widget(tabs).unwrap().tab_items,
10609            vec!["Tab A".to_string(), "Tab B".to_string()]
10610        );
10611        ui.set_selected_index(tabs, 1).expect("selected index");
10612        assert_eq!(ui.widget(tabs).unwrap().selected_index, Some(1));
10613
10614        let split = ui
10615            .create_with(WidgetKind::SplitPane, |s| {
10616                s.split_ratio = Some(70);
10617                s.container_direction = Some(ContainerDirection::Horizontal);
10618            })
10619            .expect("split pane");
10620        assert_eq!(
10621            ui.widget(split).map(|s| s.kind),
10622            Some(WidgetKind::SplitPane)
10623        );
10624        assert_eq!(ui.widget(split).and_then(|s| s.split_ratio), Some(70));
10625
10626        let alert = ui
10627            .create(WidgetKind::AlertDialog, Some("Caution"))
10628            .expect("alert");
10629        assert_eq!(
10630            ui.widget(alert).map(|s| s.kind),
10631            Some(WidgetKind::AlertDialog)
10632        );
10633        ui.set_alert_level(alert, AlertLevel::Warning)
10634            .expect("alert level");
10635        assert_eq!(
10636            ui.widget(alert).and_then(|s| s.alert_level),
10637            Some(AlertLevel::Warning)
10638        );
10639    }
10640
10641    #[test]
10642    #[cfg(feature = "widgets-data")]
10643    fn data_grid_clipboard_round_trip() {
10644        let backend = MockBackend::default();
10645        let mut ui = Ui::new(backend);
10646
10647        let source = ui
10648            .create(WidgetKind::DataGrid, None)
10649            .expect("source grid should be created");
10650        let target = ui
10651            .create(WidgetKind::DataGrid, None)
10652            .expect("target grid should be created");
10653
10654        let rows = vec![
10655            vec!["A1".to_owned(), "B1".to_owned()],
10656            vec!["A2".to_owned(), "B2".to_owned()],
10657        ];
10658        ui.set_data_grid_rows(source, &rows)
10659            .expect("source rows should be set");
10660
10661        ui.copy_to_clipboard(source).expect("copy should succeed");
10662        ui.paste_from_clipboard(target)
10663            .expect("paste should succeed");
10664
10665        assert_eq!(
10666            ui.widget(target)
10667                .map(|spec| spec.data_grid_rows.as_ref().clone())
10668                .unwrap_or_default(),
10669            rows
10670        );
10671    }
10672
10673    #[test]
10674    fn clipboard_rejects_unsupported_widgets() {
10675        let backend = MockBackend::default();
10676        let mut ui = Ui::new(backend);
10677
10678        let button = ui
10679            .create(WidgetKind::Button, Some("nope"))
10680            .expect("button should be created");
10681
10682        let err = ui
10683            .copy_to_clipboard(button)
10684            .expect_err("non-clipboard widget should be rejected");
10685        assert_eq!(err, GuiError::UnsupportedWidget("copy_to_clipboard"));
10686    }
10687
10688    #[test]
10689    #[cfg(feature = "widgets-text")]
10690    fn clipboard_round_trips_text_widgets_and_labels() {
10691        let backend = MockBackend::default();
10692        let mut ui = Ui::new(backend);
10693
10694        let label = ui
10695            .create(WidgetKind::Label, Some("0"))
10696            .expect("label should be created");
10697        let input = ui
10698            .create(WidgetKind::TextInput, None)
10699            .expect("input should be created");
10700
10701        ui.set_text(label, "42 + 7").expect("label text");
10702
10703        ui.copy_to_clipboard(label).expect("copy should succeed");
10704        ui.paste_from_clipboard(input)
10705            .expect("paste should succeed");
10706        assert_eq!(
10707            ui.widget(input).and_then(|spec| spec.text.clone()),
10708            Some("42 + 7".to_owned())
10709        );
10710
10711        // Pasting back into a label replaces its text (calculator use case).
10712        ui.set_text(input, "clear").expect("input text");
10713        ui.copy_to_clipboard(input).expect("copy from input");
10714        ui.paste_from_clipboard(label).expect("paste into label");
10715        assert_eq!(
10716            ui.widget(label).and_then(|spec| spec.text.clone()),
10717            Some("clear".to_owned())
10718        );
10719    }
10720
10721    #[test]
10722    fn create_all_tier_widget_kinds_on_mock_backend() {
10723        let backend = MockBackend::default();
10724        let mut ui = Ui::new(backend);
10725
10726        let kinds = [
10727            #[cfg(feature = "widgets-choice")]
10728            WidgetKind::RadioButton,
10729            #[cfg(feature = "widgets-range")]
10730            WidgetKind::Slider,
10731            #[cfg(feature = "widgets-range")]
10732            WidgetKind::SpinBox,
10733            #[cfg(feature = "widgets-containers")]
10734            WidgetKind::Separator,
10735            #[cfg(feature = "widgets-containers")]
10736            WidgetKind::GroupBox,
10737            #[cfg(feature = "widgets-containers")]
10738            WidgetKind::Tabs,
10739            #[cfg(feature = "widgets-media")]
10740            WidgetKind::Image,
10741            #[cfg(feature = "widgets-pickers")]
10742            WidgetKind::DatePicker,
10743            #[cfg(feature = "widgets-text")]
10744            WidgetKind::LinkLabel,
10745            #[cfg(feature = "widgets-data")]
10746            WidgetKind::ListView,
10747            #[cfg(feature = "widgets-data")]
10748            WidgetKind::TreeView,
10749            #[cfg(feature = "widgets-containers")]
10750            WidgetKind::SplitPane,
10751            #[cfg(feature = "widgets-containers")]
10752            WidgetKind::AlertDialog,
10753        ];
10754
10755        for kind in kinds {
10756            let id = ui
10757                .create(kind, Some("demo"))
10758                .expect("new widget kind should be creatable");
10759            assert_eq!(ui.widget(id).map(|spec| spec.kind), Some(kind));
10760        }
10761    }
10762
10763    /// `create_with` carries a full creation-time spec to the backend
10764    /// and keeps the `Ui`-allocated id authoritative.
10765    #[test]
10766    fn create_with_applies_creation_time_spec_and_keeps_the_allocated_id() {
10767        let backend = MockBackend::default();
10768        let mut ui = Ui::new(backend);
10769
10770        let id = ui
10771            .create_with(WidgetKind::Toolbar, |spec| {
10772                // The allocated id is authoritative, so a stray write is ignored.
10773                spec.id = WidgetId(9_999);
10774                spec.text = Some("Strip".to_owned());
10775                spec.toolbar_orientation = ToolbarOrientation::Vertical;
10776                spec.toolbar_items = vec![ToolbarItem::tool(ToolId(1), "New")];
10777                spec.background_color = Some(Color::rgb(10, 20, 30));
10778                spec.selected_index = Some(2);
10779            })
10780            .expect("spec-based creation succeeds on Mock");
10781
10782        assert_ne!(id, WidgetId(9_999), "the Ui allocates the id");
10783        let spec = ui.widget(id).expect("the spec is stored");
10784        assert_eq!(spec.text.as_deref(), Some("Strip"));
10785        assert_eq!(spec.toolbar_orientation, ToolbarOrientation::Vertical);
10786        assert_eq!(spec.toolbar_items.len(), 1);
10787        assert_eq!(spec.background_color, Some(Color::rgb(10, 20, 30)));
10788        assert_eq!(spec.selected_index, Some(2));
10789
10790        // The backend receives the same configured spec at creation time.
10791        let recorded = ui
10792            .backend()
10793            .created
10794            .get(&id)
10795            .expect("the Mock backend records the created spec");
10796        assert_eq!(recorded.toolbar_orientation, ToolbarOrientation::Vertical);
10797        assert_eq!(recorded.toolbar_items.len(), 1);
10798        assert_eq!(recorded.background_color, Some(Color::rgb(10, 20, 30)));
10799    }
10800
10801    /// Text selection is mirrored in the spec and forwarded to the
10802    /// backend, and non-text kinds are rejected with the operation name.
10803    #[test]
10804    #[cfg(feature = "widgets-text")]
10805    fn set_text_selection_records_on_text_controls_only() {
10806        let backend = MockBackend::default();
10807        let mut ui = Ui::new(backend);
10808
10809        let input = ui
10810            .create(WidgetKind::TextInput, Some("report.txt"))
10811            .expect("input");
10812        let area = ui.create(WidgetKind::TextArea, None).expect("area");
10813        let button = ui.create(WidgetKind::Button, Some("OK")).expect("button");
10814        let rich = ui
10815            .create(WidgetKind::RichText, Some("🦀 alpha"))
10816            .expect("rich");
10817        ui.set_text_selection(rich, 2, 7)
10818            .expect("RichText supports selection jumps");
10819        assert_eq!(ui.widget(rich).unwrap().text_selection, Some((2, 7)));
10820        assert!(matches!(
10821            ui.text_selection(rich),
10822            Err(GuiError::UnsupportedCapability(_))
10823        ));
10824        assert!(matches!(
10825            ui.text_selection(button),
10826            Err(GuiError::UnsupportedWidget(_))
10827        ));
10828        assert_eq!(
10829            ui.text_selection(WidgetId(u64::MAX)),
10830            Err(GuiError::WidgetNotFound(u64::MAX))
10831        );
10832        ui.set_spell_check(rich, true)
10833            .expect("native checking flag forwarded");
10834        assert_eq!(ui.backend().spell_check.get(&rich), Some(&true));
10835        assert!(matches!(
10836            ui.set_spell_check(button, true),
10837            Err(GuiError::UnsupportedWidget(_))
10838        ));
10839
10840        ui.set_text_selection(input, 0, 6)
10841            .expect("selection applies to text inputs");
10842        ui.set_text_selection(area, 2, 4)
10843            .expect("selection applies to text areas");
10844
10845        assert_eq!(
10846            ui.widget(input).and_then(|spec| spec.text_selection),
10847            Some((0, 6))
10848        );
10849        assert_eq!(
10850            ui.widget(area).and_then(|spec| spec.text_selection),
10851            Some((2, 4))
10852        );
10853        // The Mock backend records the same range on its created spec.
10854        assert_eq!(
10855            ui.backend()
10856                .created
10857                .get(&input)
10858                .and_then(|spec| spec.text_selection),
10859            Some((0, 6))
10860        );
10861
10862        let err = ui
10863            .set_text_selection(button, 0, 1)
10864            .expect_err("buttons have no text selection");
10865        assert_eq!(err, GuiError::UnsupportedWidget("set_text_selection"));
10866
10867        let err = ui
10868            .set_text_selection(input, 4, 2)
10869            .expect_err("reversed ranges are rejected");
10870        assert_eq!(
10871            err,
10872            GuiError::Backend("Text selection start must be <= end".to_owned())
10873        );
10874    }
10875
10876    /// The icon role is mirrored in the spec and
10877    /// forwarded to the backend for button-capable kinds, cleared by `None`,
10878    /// and non-button kinds are rejected with the operation name.
10879    #[test]
10880    fn set_font_validates_and_records_on_supported_widgets() {
10881        let backend = MockBackend::default();
10882        let mut ui = Ui::new(backend);
10883
10884        let label = ui
10885            .create(WidgetKind::Label, Some("Preview"))
10886            .expect("label");
10887        let window = ui.create(WidgetKind::Window, Some("Win")).expect("window");
10888        let font = FontDescriptor::new("Helvetica", 16.0);
10889
10890        ui.set_font(label, Some(&font)).expect("set font");
10891        assert_eq!(ui.widget(label).unwrap().font.as_ref(), Some(&font));
10892
10893        ui.set_font(label, None).expect("clear font");
10894        assert_eq!(ui.widget(label).unwrap().font, None);
10895
10896        let invalid = FontDescriptor::new("", 12.0);
10897        assert!(ui.set_font(label, Some(&invalid)).is_err());
10898        assert_eq!(
10899            ui.set_font(window, Some(&font)),
10900            Err(GuiError::UnsupportedWidget("set_font"))
10901        );
10902    }
10903
10904    #[cfg(feature = "widgets-data")]
10905    #[test]
10906    fn set_row_icons_records_on_list_widgets_only() {
10907        let backend = MockBackend::default();
10908        let mut ui = Ui::new(backend);
10909
10910        let list = ui.create(WidgetKind::DataList, None).expect("list");
10911        let view = ui.create(WidgetKind::ListView, None).expect("view");
10912        let label = ui.create(WidgetKind::Label, Some("Text")).expect("label");
10913        let icons = vec![Some(IconRole::Folder), Some(IconRole::File), None];
10914
10915        ui.set_row_icons(list, &icons).expect("datalist icons");
10916        ui.set_row_icons(view, &icons).expect("listview icons");
10917        assert_eq!(ui.widget(list).unwrap().row_icons, icons);
10918        assert_eq!(ui.widget(view).unwrap().row_icons, icons);
10919        assert_eq!(
10920            ui.set_row_icons(label, &icons),
10921            Err(GuiError::UnsupportedWidget("set_row_icons"))
10922        );
10923    }
10924
10925    #[test]
10926    fn set_icon_records_on_button_capable_widgets_only() {
10927        let backend = MockBackend::default();
10928        let mut ui = Ui::new(backend);
10929
10930        let button = ui.create(WidgetKind::Button, Some("Save")).expect("button");
10931        #[cfg(feature = "widgets-pickers")]
10932        let chooser = ui
10933            .create(WidgetKind::FileChooserDialog, Some("Open File..."))
10934            .expect("chooser");
10935        let label = ui.create(WidgetKind::Label, Some("status")).expect("label");
10936
10937        ui.set_icon(button, Some(IconRole::Save))
10938            .expect("buttons accept a role");
10939        #[cfg(feature = "widgets-pickers")]
10940        ui.set_icon(chooser, Some(IconRole::Open))
10941            .expect("file chooser buttons accept a role");
10942
10943        assert_eq!(
10944            ui.widget(button).and_then(|spec| spec.icon),
10945            Some(IconRole::Save)
10946        );
10947        #[cfg(feature = "widgets-pickers")]
10948        assert_eq!(
10949            ui.widget(chooser).and_then(|spec| spec.icon),
10950            Some(IconRole::Open)
10951        );
10952        // The Mock backend records the same role on its created spec.
10953        assert_eq!(
10954            ui.backend().created.get(&button).and_then(|spec| spec.icon),
10955            Some(IconRole::Save)
10956        );
10957
10958        ui.set_icon(button, None).expect("None clears the role");
10959        assert_eq!(ui.widget(button).and_then(|spec| spec.icon), None);
10960        assert_eq!(
10961            ui.backend().created.get(&button).and_then(|spec| spec.icon),
10962            None
10963        );
10964
10965        let err = ui
10966            .set_icon(label, Some(IconRole::Save))
10967            .expect_err("labels have no button art");
10968        assert_eq!(err, GuiError::UnsupportedWidget("set_icon"));
10969    }
10970
10971    #[test]
10972    fn data_grid_metric_overrides_record_and_reject_non_grids() {
10973        let backend = MockBackend::default();
10974        let mut ui = Ui::new(backend);
10975        let window = ui.create(WidgetKind::Window, None).expect("window");
10976        let grid = ui.create(WidgetKind::DataGrid, None).expect("grid");
10977
10978        ui.set_data_grid_col_width(grid, 0, 220)
10979            .expect("width records");
10980        ui.set_data_grid_row_height(grid, 1, 40)
10981            .expect("height records");
10982        assert_eq!(
10983            ui.backend().data_grid_col_widths.get(&(grid, 0)),
10984            Some(&220)
10985        );
10986        assert_eq!(
10987            ui.backend().data_grid_row_heights.get(&(grid, 1)),
10988            Some(&40)
10989        );
10990
10991        // Non-positive values clear the override.
10992        ui.set_data_grid_col_width(grid, 0, 0)
10993            .expect("width clears");
10994        assert_eq!(ui.backend().data_grid_col_widths.get(&(grid, 0)), None);
10995
10996        // The kind guard mirrors the other grid setters.
10997        assert!(matches!(
10998            ui.set_data_grid_col_width(window, 0, 100),
10999            Err(GuiError::UnsupportedWidget("set_data_grid_col_width"))
11000        ));
11001        assert!(matches!(
11002            ui.set_data_grid_row_height(window, 0, 30),
11003            Err(GuiError::UnsupportedWidget("set_data_grid_row_height"))
11004        ));
11005    }
11006
11007    #[test]
11008    fn display_metrics_fixture_records_capabilities_and_change_events() {
11009        let backend = MockBackend::default();
11010        let mut ui = Ui::new(backend);
11011
11012        // Safe default: no capabilities, no fabricated geometry.
11013        assert_eq!(ui.display_capabilities(), DisplayCapabilities::none());
11014        assert!(matches!(
11015            ui.displays(),
11016            Err(GuiError::UnsupportedCapability(ref capability)) if capability == "display_metrics"
11017        ));
11018
11019        let primary = DisplayInfo::new(
11020            1,
11021            "mock-primary",
11022            crate::DisplayRect::new(0, 0, 1920, 1080),
11023            crate::DisplayRect::new(0, 0, 1920, 1040),
11024            1.0,
11025            true,
11026        );
11027        let secondary = DisplayInfo::new(
11028            2,
11029            "mock-secondary",
11030            crate::DisplayRect::new(1920, 0, 1280, 1024),
11031            crate::DisplayRect::new(1920, 0, 1280, 984),
11032            1.25,
11033            false,
11034        );
11035        ui.backend_mut()
11036            .set_displays(vec![primary.clone(), secondary.clone()]);
11037        assert!(ui.display_capabilities().enumeration);
11038        assert_eq!(
11039            ui.displays().expect("fixture enumerates"),
11040            vec![primary.clone(), secondary.clone()]
11041        );
11042        assert_eq!(
11043            ui.primary_display().expect("primary query"),
11044            Some(primary.clone())
11045        );
11046
11047        // Injection advertises the event support and queues the typed event.
11048        ui.backend_mut().inject_display_change(secondary.clone());
11049        assert!(ui.display_capabilities().dpi_change_events);
11050        assert_eq!(
11051            ui.poll_event().expect("poll"),
11052            Some(UiEvent::DisplayChanged {
11053                display: secondary.clone()
11054            })
11055        );
11056
11057        // Explicit capability control stays available for hostile fixtures.
11058        ui.backend_mut()
11059            .set_display_capabilities(DisplayCapabilities::none());
11060        assert_eq!(ui.display_capabilities(), DisplayCapabilities::none());
11061        assert_eq!(
11062            ui.displays().expect("fixture still enumerates"),
11063            vec![primary, secondary]
11064        );
11065    }
11066
11067    #[test]
11068    fn numeric_and_metadata_setters_update_widget_spec() {
11069        let backend = MockBackend::default();
11070        let mut ui = Ui::new(backend);
11071
11072        #[cfg(feature = "widgets-range")]
11073        let slider = {
11074            let s = ui
11075                .create(WidgetKind::Slider, Some("slider"))
11076                .expect("slider should be created");
11077            ui.set_range(s, 0, 200).expect("range set");
11078            ui.set_step(s, 5).expect("step set");
11079            ui.set_value(s, 55).expect("value set");
11080            s
11081        };
11082
11083        #[cfg(feature = "widgets-containers")]
11084        let tabs = {
11085            let tabs = ui
11086                .create(WidgetKind::Tabs, Some("tabs"))
11087                .expect("tabs should be created");
11088            ui.set_selected_index(tabs, 0).expect("selected index set");
11089            tabs
11090        };
11091
11092        #[cfg(feature = "widgets-media")]
11093        let image = {
11094            let img = ui
11095                .create(WidgetKind::Image, None)
11096                .expect("image should be created");
11097            ui.set_image_source(img, "./assets/icon.png")
11098                .expect("image source set");
11099            img
11100        };
11101
11102        #[cfg(feature = "widgets-pickers")]
11103        let date = ui
11104            .create(WidgetKind::DatePicker, None)
11105            .expect("date picker should be created");
11106        #[cfg(feature = "widgets-pickers")]
11107        ui.set_date_value(date, "2026-03-06")
11108            .expect("date value set");
11109
11110        #[cfg(feature = "widgets-text")]
11111        let link = ui
11112            .create(WidgetKind::LinkLabel, Some("Open docs"))
11113            .expect("link label should be created");
11114        #[cfg(feature = "widgets-text")]
11115        ui.set_link_url(link, "https://example.com")
11116            .expect("link url set");
11117
11118        #[cfg(feature = "widgets-range")]
11119        {
11120            assert_eq!(
11121                ui.widget(slider).and_then(|spec| spec.range),
11122                Some((0, 200))
11123            );
11124            assert_eq!(ui.widget(slider).and_then(|spec| spec.step), Some(5));
11125            assert_eq!(ui.widget(slider).and_then(|spec| spec.value), Some(55));
11126        }
11127        #[cfg(feature = "widgets-containers")]
11128        assert_eq!(
11129            ui.widget(tabs).and_then(|spec| spec.selected_index),
11130            Some(0)
11131        );
11132        #[cfg(feature = "widgets-media")]
11133        assert_eq!(
11134            ui.widget(image)
11135                .and_then(|spec| spec.image_source.as_deref()),
11136            Some("./assets/icon.png")
11137        );
11138        #[cfg(feature = "widgets-pickers")]
11139        assert_eq!(
11140            ui.widget(date).and_then(|spec| spec.date_value.as_deref()),
11141            Some("2026-03-06")
11142        );
11143        #[cfg(feature = "widgets-text")]
11144        assert_eq!(
11145            ui.widget(link).and_then(|spec| spec.link_url.as_deref()),
11146            Some("https://example.com")
11147        );
11148    }
11149
11150    #[test]
11151    #[cfg(feature = "widgets-choice")]
11152    fn set_checked_updates_spec() {
11153        let backend = MockBackend::default();
11154        let mut ui = Ui::new(backend);
11155
11156        let checkbox = ui
11157            .create(WidgetKind::Checkbox, Some("I agree"))
11158            .expect("checkbox should be created");
11159
11160        ui.set_checked(checkbox, true)
11161            .expect("set_checked should succeed");
11162
11163        assert_eq!(
11164            ui.widget(checkbox).and_then(|spec| spec.checked),
11165            Some(true)
11166        );
11167    }
11168
11169    #[test]
11170    fn set_value_rejects_unsupported_kind() {
11171        let backend = MockBackend::default();
11172        let mut ui = Ui::new(backend);
11173
11174        let label = ui
11175            .create(WidgetKind::Label, Some("label"))
11176            .expect("label should be created");
11177
11178        let err = ui
11179            .set_value(label, 5)
11180            .expect_err("non-value widget should be rejected");
11181        assert_eq!(err, GuiError::UnsupportedWidget("set_value"));
11182    }
11183
11184    #[test]
11185    #[cfg(feature = "widgets-range")]
11186    fn set_value_updates_spec() {
11187        let backend = MockBackend::default();
11188        let mut ui = Ui::new(backend);
11189
11190        let progress = ui
11191            .create(WidgetKind::ProgressBar, None)
11192            .expect("progress bar should be created");
11193
11194        ui.set_value(progress, 42)
11195            .expect("set_value should succeed");
11196
11197        assert_eq!(ui.widget(progress).and_then(|spec| spec.value), Some(42));
11198    }
11199
11200    #[test]
11201    #[cfg(feature = "widgets-range")]
11202    fn set_range_rejects_inverted_bounds() {
11203        let backend = MockBackend::default();
11204        let mut ui = Ui::new(backend);
11205
11206        let slider = ui
11207            .create(WidgetKind::Slider, None)
11208            .expect("slider should be created");
11209
11210        let err = ui
11211            .set_range(slider, 10, 5)
11212            .expect_err("inverted range should be rejected");
11213        assert_eq!(
11214            err,
11215            GuiError::Backend("Widget range min must be <= max".to_owned())
11216        );
11217    }
11218
11219    #[test]
11220    #[cfg(feature = "widgets-range")]
11221    fn set_step_rejects_non_positive_value() {
11222        let backend = MockBackend::default();
11223        let mut ui = Ui::new(backend);
11224
11225        let slider = ui
11226            .create(WidgetKind::Slider, None)
11227            .expect("slider should be created");
11228
11229        let err = ui
11230            .set_step(slider, 0)
11231            .expect_err("non-positive step should be rejected");
11232        assert_eq!(
11233            err,
11234            GuiError::Backend("Widget step must be positive".to_owned())
11235        );
11236    }
11237
11238    #[test]
11239    fn set_selected_index_rejects_unsupported_kind() {
11240        let backend = MockBackend::default();
11241        let mut ui = Ui::new(backend);
11242
11243        let label = ui
11244            .create(WidgetKind::Label, Some("label"))
11245            .expect("label should be created");
11246
11247        let err = ui
11248            .set_selected_index(label, 0)
11249            .expect_err("non-selection widget should be rejected");
11250        assert_eq!(err, GuiError::UnsupportedWidget("set_selected_index"));
11251    }
11252
11253    #[test]
11254    fn set_data_grid_rows_rejects_non_grid() {
11255        let backend = MockBackend::default();
11256        let mut ui = Ui::new(backend);
11257
11258        let label = ui
11259            .create(WidgetKind::Label, Some("label"))
11260            .expect("label should be created");
11261
11262        let err = ui
11263            .set_data_grid_rows(label, &[vec!["x".to_owned()]])
11264            .expect_err("non-grid widget should be rejected");
11265        assert_eq!(err, GuiError::UnsupportedWidget("set_data_grid_rows"));
11266    }
11267
11268    #[test]
11269    fn set_data_grid_rows_updates_spec() {
11270        let backend = MockBackend::default();
11271        let mut ui = Ui::new(backend);
11272
11273        let grid = ui
11274            .create(WidgetKind::DataGrid, None)
11275            .expect("grid should be created");
11276
11277        let rows = vec![vec!["A".to_owned(), "B".to_owned()]];
11278        ui.set_data_grid_rows(grid, &rows)
11279            .expect("set_data_grid_rows should succeed");
11280
11281        assert_eq!(
11282            ui.widget(grid)
11283                .map(|spec| spec.data_grid_rows.as_ref().clone())
11284                .unwrap_or_default(),
11285            rows
11286        );
11287    }
11288
11289    #[test]
11290    #[cfg(feature = "widgets-media")]
11291    fn set_image_source_rejects_non_image() {
11292        let backend = MockBackend::default();
11293        let mut ui = Ui::new(backend);
11294
11295        let label = ui
11296            .create(WidgetKind::Label, Some("label"))
11297            .expect("label should be created");
11298
11299        let err = ui
11300            .set_image_source(label, "./icon.png")
11301            .expect_err("non-image widget should be rejected");
11302        assert_eq!(err, GuiError::UnsupportedWidget("set_image_source"));
11303    }
11304
11305    #[test]
11306    #[cfg(not(feature = "widgets-media"))]
11307    fn image_setters_return_unsupported_when_media_is_compiled_out() {
11308        let mut ui = Ui::new(MockBackend::default());
11309        let label = ui
11310            .create(WidgetKind::Label, Some("label"))
11311            .expect("label should be created");
11312
11313        assert_eq!(
11314            ui.set_image_source(label, "./icon.png"),
11315            Err(GuiError::UnsupportedWidget("set_image_source"))
11316        );
11317        assert_eq!(
11318            ui.set_image_fit(label, ImageFit::Contain),
11319            Err(GuiError::UnsupportedWidget("set_image_fit"))
11320        );
11321    }
11322
11323    #[test]
11324    #[cfg(feature = "widgets-media")]
11325    fn set_image_fit_round_trips_and_rejects_non_image() {
11326        let backend = MockBackend::default();
11327        let mut ui = Ui::new(backend);
11328
11329        let image = ui
11330            .create(WidgetKind::Image, None)
11331            .expect("image should be created");
11332        assert_eq!(
11333            ui.widget(image).map(|spec| spec.image_fit),
11334            Some(ImageFit::Contain),
11335            "the default preserves the existing letterbox behavior"
11336        );
11337
11338        ui.set_image_fit(image, ImageFit::Cover)
11339            .expect("set_image_fit should succeed");
11340        assert_eq!(
11341            ui.widget(image).map(|spec| spec.image_fit),
11342            Some(ImageFit::Cover)
11343        );
11344        assert_eq!(
11345            ui.backend().created.get(&image).map(|spec| spec.image_fit),
11346            Some(ImageFit::Cover),
11347            "the backend records the mode too"
11348        );
11349
11350        let label = ui
11351            .create(WidgetKind::Label, Some("label"))
11352            .expect("label should be created");
11353        let err = ui
11354            .set_image_fit(label, ImageFit::Fill)
11355            .expect_err("non-image widget should be rejected");
11356        assert_eq!(err, GuiError::UnsupportedWidget("set_image_fit"));
11357    }
11358
11359    #[test]
11360    #[cfg(feature = "widgets-pickers")]
11361    fn set_file_chooser_mode_round_trips_and_rejects_non_chooser() {
11362        let backend = MockBackend::default();
11363        let mut ui = Ui::new(backend);
11364
11365        let chooser = ui
11366            .create(WidgetKind::FileChooserDialog, Some("Open Folder…"))
11367            .expect("chooser should be created");
11368        assert_eq!(
11369            ui.widget(chooser).map(|spec| spec.file_chooser_mode),
11370            Some(FileChooserMode::OpenFile),
11371            "the default keeps the open-file dialog"
11372        );
11373
11374        ui.set_file_chooser_mode(chooser, FileChooserMode::PickFolder)
11375            .expect("set_file_chooser_mode should succeed");
11376        assert_eq!(
11377            ui.widget(chooser).map(|spec| spec.file_chooser_mode),
11378            Some(FileChooserMode::PickFolder)
11379        );
11380        assert_eq!(
11381            ui.backend()
11382                .created
11383                .get(&chooser)
11384                .map(|spec| spec.file_chooser_mode),
11385            Some(FileChooserMode::PickFolder),
11386            "the backend records the mode too"
11387        );
11388
11389        let label = ui
11390            .create(WidgetKind::Label, Some("label"))
11391            .expect("label should be created");
11392        assert_eq!(
11393            ui.set_file_chooser_mode(label, FileChooserMode::PickFolder)
11394                .unwrap_err(),
11395            GuiError::UnsupportedWidget("set_file_chooser_mode")
11396        );
11397    }
11398
11399    #[test]
11400    #[cfg(feature = "widgets-pickers")]
11401    fn set_color_dialog_data_round_trips_and_rejects_non_dialogs() {
11402        let backend = MockBackend::default();
11403        let mut ui = Ui::new(backend);
11404
11405        let dialog = ui
11406            .create(WidgetKind::ColorDialog, Some("Pick colour…"))
11407            .expect("colour dialog should be created");
11408        assert_eq!(
11409            ui.widget(dialog)
11410                .and_then(|spec| spec.color_dialog_data.as_ref()),
11411            None,
11412            "a fresh dialog carries no preferences"
11413        );
11414
11415        let mut data = ColorDialogData::new(Rgba::new(4, 5, 6, 255));
11416        data.push_custom(Rgba::new(7, 8, 9, 255)).unwrap();
11417        ui.set_color_dialog_data(dialog, data.clone())
11418            .expect("set_color_dialog_data should succeed");
11419        assert_eq!(
11420            ui.widget(dialog)
11421                .and_then(|spec| spec.color_dialog_data.as_ref()),
11422            Some(&data)
11423        );
11424        assert_eq!(
11425            ui.backend()
11426                .created
11427                .get(&dialog)
11428                .and_then(|spec| spec.color_dialog_data.as_ref()),
11429            Some(&data),
11430            "the backend records the preferences too"
11431        );
11432
11433        // The shared palette cap is enforced before anything is recorded.
11434        let mut oversized = data.clone();
11435        for index in 0..=crate::MAX_CUSTOM_COLORS {
11436            oversized.custom.push(Rgba::new(index as u8, 0, 0, 255));
11437        }
11438        let error = ui.set_color_dialog_data(dialog, oversized).unwrap_err();
11439        assert!(
11440            matches!(error, GuiError::Backend(ref message) if message.contains("at most 16 are supported")),
11441            "unexpected error: {error:?}"
11442        );
11443        assert_eq!(
11444            ui.widget(dialog)
11445                .and_then(|spec| spec.color_dialog_data.as_ref()),
11446            Some(&data),
11447            "a rejected update leaves the stored preferences untouched"
11448        );
11449
11450        let label = ui
11451            .create(WidgetKind::Label, Some("label"))
11452            .expect("label should be created");
11453        assert_eq!(
11454            ui.set_color_dialog_data(label, ColorDialogData::default())
11455                .unwrap_err(),
11456            GuiError::UnsupportedWidget("set_color_dialog_data")
11457        );
11458    }
11459
11460    #[test]
11461    #[cfg(feature = "widgets-pickers")]
11462    fn set_font_dialog_data_round_trips_and_rejects_non_dialogs() {
11463        let backend = MockBackend::default();
11464        let mut ui = Ui::new(backend);
11465
11466        let dialog = ui
11467            .create(WidgetKind::FontDialog, Some("Pick font…"))
11468            .expect("font dialog should be created");
11469        assert_eq!(
11470            ui.widget(dialog)
11471                .and_then(|spec| spec.font_dialog_data.as_ref()),
11472            None,
11473            "a fresh dialog carries no preferences"
11474        );
11475
11476        let mut data = FontDialogData::new(FontDescriptor::new("Inter", 12.0));
11477        data.min_size_pt = Some(9.0);
11478        data.max_size_pt = Some(24.0);
11479        ui.set_font_dialog_data(dialog, data.clone())
11480            .expect("set_font_dialog_data should succeed");
11481        assert_eq!(
11482            ui.widget(dialog)
11483                .and_then(|spec| spec.font_dialog_data.as_ref()),
11484            Some(&data)
11485        );
11486        assert_eq!(
11487            ui.backend()
11488                .created
11489                .get(&dialog)
11490                .and_then(|spec| spec.font_dialog_data.as_ref()),
11491            Some(&data),
11492            "the backend records the preferences too"
11493        );
11494
11495        // The shared range validation runs before anything is recorded.
11496        let mut inverted = data.clone();
11497        inverted.min_size_pt = Some(30.0);
11498        inverted.max_size_pt = Some(20.0);
11499        let error = ui.set_font_dialog_data(dialog, inverted).unwrap_err();
11500        assert!(
11501            matches!(error, GuiError::Backend(ref message) if message.contains("inverted")),
11502            "unexpected error: {error:?}"
11503        );
11504        assert_eq!(
11505            ui.widget(dialog)
11506                .and_then(|spec| spec.font_dialog_data.as_ref()),
11507            Some(&data),
11508            "a rejected update leaves the stored preferences untouched"
11509        );
11510
11511        let label = ui
11512            .create(WidgetKind::Label, Some("label"))
11513            .expect("label should be created");
11514        assert_eq!(
11515            ui.set_font_dialog_data(
11516                label,
11517                FontDialogData::new(FontDescriptor::new("Inter", 12.0))
11518            )
11519            .unwrap_err(),
11520            GuiError::UnsupportedWidget("set_font_dialog_data")
11521        );
11522    }
11523
11524    #[test]
11525    fn toolbar_setters_round_trip_and_reject_other_kinds() {
11526        use crate::toolbar::ToolSpec;
11527
11528        let backend = MockBackend::default();
11529        let mut ui = Ui::new(backend);
11530
11531        let toolbar = ui
11532            .create(WidgetKind::Toolbar, Some("Main"))
11533            .expect("toolbar should be created");
11534        assert!(ui.widget(toolbar).unwrap().toolbar_items.is_empty());
11535        assert_eq!(
11536            ui.widget(toolbar).unwrap().toolbar_orientation,
11537            ToolbarOrientation::Horizontal
11538        );
11539
11540        let items = vec![
11541            ToolbarItem::Tool(ToolSpec::new(ToolId(1), "New")),
11542            ToolbarItem::Separator,
11543            ToolbarItem::Tool(ToolSpec::new(ToolId(2), "Bold").with_checkable()),
11544        ];
11545        ui.set_toolbar_items(toolbar, items.clone())
11546            .expect("set_toolbar_items should succeed");
11547        assert_eq!(ui.widget(toolbar).unwrap().toolbar_items, items);
11548        assert_eq!(
11549            ui.backend()
11550                .created
11551                .get(&toolbar)
11552                .map(|spec| spec.toolbar_items.clone()),
11553            Some(items.clone()),
11554            "the backend records the rows too"
11555        );
11556
11557        ui.set_toolbar_orientation(toolbar, ToolbarOrientation::Vertical)
11558            .expect("set_toolbar_orientation should succeed");
11559        assert_eq!(
11560            ui.widget(toolbar).unwrap().toolbar_orientation,
11561            ToolbarOrientation::Vertical
11562        );
11563
11564        // Model rules run before anything is recorded, and the programmatic
11565        // state change reports the changed tools without emitting events.
11566        let dangling = vec![ToolbarItem::Tool(
11567            ToolSpec::new(ToolId(3), "Center").with_radio_group(ToolId(9)),
11568        )];
11569        let error = ui.set_toolbar_items(toolbar, dangling).unwrap_err();
11570        assert!(
11571            matches!(error, GuiError::Backend(ref message) if message.contains("radio group")),
11572            "unexpected error: {error:?}"
11573        );
11574        assert_eq!(ui.widget(toolbar).unwrap().toolbar_items, items);
11575        assert_eq!(
11576            ui.set_tool_state(toolbar, ToolId(1), true).unwrap_err(),
11577            GuiError::Backend(crate::toolbar::ToolbarError::NotCheckable(ToolId(1)).to_string())
11578        );
11579        assert_eq!(
11580            ui.set_tool_state(toolbar, ToolId(2), true).unwrap(),
11581            vec![(ToolId(2), true)]
11582        );
11583        ui.update_tool(toolbar, ToolId(1), ToolUpdate::new().with_label("New file"))
11584            .unwrap();
11585        assert_eq!(
11586            crate::toolbar::find_tool(&ui.widget(toolbar).unwrap().toolbar_items, ToolId(1))
11587                .map(|tool| tool.label.clone()),
11588            Some("New file".to_owned())
11589        );
11590        assert!(
11591            ui.poll_event().expect("poll_event").is_none(),
11592            "no events were emitted"
11593        );
11594
11595        let label = ui
11596            .create(WidgetKind::Label, Some("label"))
11597            .expect("label should be created");
11598        assert_eq!(
11599            ui.set_toolbar_items(label, items.clone()).unwrap_err(),
11600            GuiError::UnsupportedWidget("set_toolbar_items")
11601        );
11602        assert_eq!(
11603            ui.set_toolbar_orientation(label, ToolbarOrientation::Horizontal)
11604                .unwrap_err(),
11605            GuiError::UnsupportedWidget("set_toolbar_orientation")
11606        );
11607        assert_eq!(
11608            ui.update_tool(label, ToolId(1), ToolUpdate::new()),
11609            Err(GuiError::UnsupportedWidget("set_toolbar_items"))
11610        );
11611    }
11612
11613    #[test]
11614    fn set_date_value_rejects_non_date_picker() {
11615        let backend = MockBackend::default();
11616        let mut ui = Ui::new(backend);
11617
11618        let label = ui
11619            .create(WidgetKind::Label, Some("label"))
11620            .expect("label should be created");
11621
11622        let err = ui
11623            .set_date_value(label, "2026-09-07")
11624            .expect_err("non-date widget should be rejected");
11625        assert_eq!(err, GuiError::UnsupportedWidget("set_date_value"));
11626    }
11627
11628    #[test]
11629    fn set_link_url_rejects_non_link_label() {
11630        let backend = MockBackend::default();
11631        let mut ui = Ui::new(backend);
11632
11633        let label = ui
11634            .create(WidgetKind::Label, Some("label"))
11635            .expect("label should be created");
11636
11637        let err = ui
11638            .set_link_url(label, "https://example.com")
11639            .expect_err("non-link widget should be rejected");
11640        assert_eq!(err, GuiError::UnsupportedWidget("set_link_url"));
11641    }
11642
11643    #[test]
11644    fn set_container_direction_updates_spec() {
11645        let backend = MockBackend::default();
11646        let mut ui = Ui::new(backend);
11647
11648        let container = ui
11649            .create(WidgetKind::Container, None)
11650            .expect("container should be created");
11651
11652        ui.set_container_direction(container, ContainerDirection::Horizontal)
11653            .expect("set_container_direction should succeed");
11654
11655        assert_eq!(
11656            ui.widget(container)
11657                .and_then(|spec| spec.container_direction),
11658            Some(ContainerDirection::Horizontal)
11659        );
11660        // The layout tree follows the imperative API so a later
11661        // `compute_layout` cannot silently stack the container.
11662        let node = *ui.layout_nodes.get(&container).expect("layout node");
11663        let style = ui.layout_tree.style(node).expect("style");
11664        assert_eq!(style.flex_direction, crate::layout::FlexDirection::Row);
11665
11666        ui.set_container_direction(container, ContainerDirection::Vertical)
11667            .expect("set_container_direction should succeed");
11668        let style = ui.layout_tree.style(node).expect("style");
11669        assert_eq!(style.flex_direction, crate::layout::FlexDirection::Column);
11670    }
11671
11672    #[test]
11673    fn unset_container_direction_stacks_vertically_like_native_backends() {
11674        // Figure 12.2 regression: Win32 and Cocoa apply `compute_layout`
11675        // geometry, so a Container with no explicit direction must stack its
11676        // children the way GTK/Win32/Cocoa/Web/TUI do natively, not as a row.
11677        let backend = MockBackend::default();
11678        let mut ui = Ui::new(backend);
11679        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
11680        let container = ui.create(WidgetKind::Container, None).expect("container");
11681        let first = ui.create(WidgetKind::Button, Some("first")).expect("first");
11682        let second = ui
11683            .create(WidgetKind::Button, Some("second"))
11684            .expect("second");
11685        ui.attach(window, container).expect("attach container");
11686        ui.attach(container, first).expect("attach first");
11687        ui.attach(container, second).expect("attach second");
11688        for widget in [
11689            container,
11690            ui.create(WidgetKind::GroupBox, Some("g")).expect("group"),
11691        ] {
11692            let node = *ui.layout_nodes.get(&widget).expect("layout node");
11693            let style = ui.layout_tree.style(node).expect("style");
11694            assert_eq!(style.flex_direction, crate::layout::FlexDirection::Column);
11695        }
11696        let split = ui.create(WidgetKind::SplitPane, None).expect("split");
11697        let node = *ui.layout_nodes.get(&split).expect("layout node");
11698        let style = ui.layout_tree.style(node).expect("style");
11699        assert_eq!(style.flex_direction, crate::layout::FlexDirection::Row);
11700
11701        ui.compute_layout(window, 420.0, 380.0).expect("layout");
11702        let a = ui.layout_rect(first).expect("first rect");
11703        let b = ui.layout_rect(second).expect("second rect");
11704        assert!(
11705            b.y >= a.y + a.height,
11706            "children of an unset-direction container overlap or share a row: {a:?} vs {b:?}"
11707        );
11708    }
11709
11710    #[test]
11711    fn set_tooltip_updates_spec_and_backend() {
11712        let backend = MockBackend::default();
11713        let mut ui = Ui::new(backend);
11714
11715        let button = ui
11716            .create(WidgetKind::Button, Some("Run"))
11717            .expect("button should be created");
11718
11719        ui.set_tooltip(button, "Run the build")
11720            .expect("set_tooltip should succeed");
11721
11722        assert_eq!(
11723            ui.widget(button).and_then(|spec| spec.tooltip.as_deref()),
11724            Some("Run the build")
11725        );
11726        assert_eq!(
11727            ui.backend()
11728                .created
11729                .get(&button)
11730                .and_then(|spec| spec.tooltip.as_deref()),
11731            Some("Run the build")
11732        );
11733    }
11734
11735    #[test]
11736    #[cfg(feature = "widgets-canvas")]
11737    fn set_accessible_metadata_updates_spec_and_backend() {
11738        let backend = MockBackend::default();
11739        let mut ui = Ui::new(backend);
11740
11741        let canvas = ui
11742            .create(WidgetKind::Canvas, None)
11743            .expect("canvas should be created");
11744
11745        assert_eq!(
11746            ui.accessibility(canvas).map(|spec| spec.role),
11747            Some(AccessibleRole::Canvas)
11748        );
11749
11750        ui.set_accessible_name(canvas, "Live chart")
11751            .expect("set_accessible_name should succeed");
11752        ui.set_accessible_description(canvas, "Renders throughput over time")
11753            .expect("set_accessible_description should succeed");
11754
11755        let spec = ui.widget(canvas).expect("widget spec");
11756        assert_eq!(spec.accessibility.name.as_deref(), Some("Live chart"));
11757        assert_eq!(
11758            spec.accessibility.description.as_deref(),
11759            Some("Renders throughput over time")
11760        );
11761
11762        let mock_spec = ui.backend().created.get(&canvas).expect("mock spec");
11763        assert_eq!(mock_spec.accessibility.name.as_deref(), Some("Live chart"));
11764        assert_eq!(
11765            mock_spec.accessibility.description.as_deref(),
11766            Some("Renders throughput over time")
11767        );
11768
11769        let err = ui
11770            .set_accessible_name(WidgetId(9999), "missing")
11771            .expect_err("missing widget should fail");
11772        assert_eq!(err, GuiError::WidgetNotFound(9999));
11773    }
11774
11775    #[test]
11776    #[cfg(all(feature = "widgets-containers", feature = "widgets-text"))]
11777    fn dynamic_accessible_updates_are_forwarded_to_the_backend() {
11778        let mut ui = Ui::new(MockBackend::default());
11779        let window = ui
11780            .create(WidgetKind::Window, Some("Notifications"))
11781            .expect("window");
11782        let input = ui
11783            .create(WidgetKind::TextInput, Some("Initial"))
11784            .expect("text input");
11785        #[cfg(feature = "widgets-range")]
11786        let slider = ui.create(WidgetKind::Slider, None).expect("slider");
11787        let alert = ui
11788            .create(WidgetKind::AlertDialog, Some("Saved"))
11789            .expect("alert dialog");
11790        ui.attach(window, input).expect("attach input");
11791        #[cfg(feature = "widgets-range")]
11792        ui.attach(window, slider).expect("attach slider");
11793        ui.attach(window, alert).expect("attach alert");
11794
11795        ui.set_text(input, "Updated").expect("update text");
11796        #[cfg(feature = "widgets-range")]
11797        ui.set_value(slider, 42).expect("update value");
11798        ui.focus(input).expect("move focus");
11799        ui.show(alert).expect("show alert widget");
11800        ui.show_confirm_dialog("Continue?", "Save first?")
11801            .expect("show confirm dialog");
11802
11803        #[cfg(feature = "widgets-range")]
11804        let expected_notifications = vec![
11805            (input, AccessibleNotification::TextChanged),
11806            (slider, AccessibleNotification::ValueChanged),
11807            (input, AccessibleNotification::FocusChanged),
11808            (
11809                alert,
11810                AccessibleNotification::Announcement("Saved".to_owned()),
11811            ),
11812            (
11813                input,
11814                AccessibleNotification::Announcement("Continue?. Save first?".to_owned()),
11815            ),
11816        ];
11817        #[cfg(not(feature = "widgets-range"))]
11818        let expected_notifications = vec![
11819            (input, AccessibleNotification::TextChanged),
11820            (input, AccessibleNotification::FocusChanged),
11821            (
11822                alert,
11823                AccessibleNotification::Announcement("Saved".to_owned()),
11824            ),
11825            (
11826                input,
11827                AccessibleNotification::Announcement("Continue?. Save first?".to_owned()),
11828            ),
11829        ];
11830        assert_eq!(
11831            ui.backend().posted_accessible_notifications,
11832            expected_notifications,
11833        );
11834
11835        let err = ui
11836            .set_text(WidgetId(9999), "missing")
11837            .expect_err("unknown widget is rejected");
11838        assert_eq!(err, GuiError::WidgetNotFound(9999));
11839        #[cfg(feature = "widgets-range")]
11840        assert_eq!(ui.backend().posted_accessible_notifications.len(), 5);
11841        #[cfg(not(feature = "widgets-range"))]
11842        assert_eq!(ui.backend().posted_accessible_notifications.len(), 4);
11843    }
11844
11845    #[test]
11846    #[cfg(feature = "widgets-text")]
11847    fn focus_traversal_visits_focusable_widgets_in_creation_order() {
11848        let backend = MockBackend::default();
11849        let mut ui = Ui::new(backend);
11850
11851        let window = ui.create(WidgetKind::Window, Some("Form")).expect("window");
11852        let container = ui.create(WidgetKind::Container, None).expect("container");
11853        let label = ui.create(WidgetKind::Label, Some("Name")).expect("label");
11854        let name = ui.create(WidgetKind::TextInput, None).expect("text input");
11855        let save = ui.create(WidgetKind::Button, Some("Save")).expect("button");
11856        ui.attach(window, container).expect("attach container");
11857        ui.attach(container, label).expect("attach label");
11858        ui.attach(container, name).expect("attach input");
11859        ui.attach(container, save).expect("attach button");
11860
11861        assert_eq!(ui.focused(), None);
11862        assert_eq!(ui.focus_next().expect("focus"), Some(name));
11863        assert_eq!(ui.focused(), Some(name));
11864        assert_eq!(ui.focus_next().expect("focus"), Some(save));
11865        assert_eq!(
11866            ui.focus_next().expect("focus"),
11867            Some(name),
11868            "traversal wraps to the start"
11869        );
11870        assert_eq!(
11871            ui.focus_previous().expect("focus"),
11872            Some(save),
11873            "backwards traversal wraps too"
11874        );
11875    }
11876
11877    #[test]
11878    #[cfg(feature = "widgets-text")]
11879    fn focus_traversal_skips_disabled_widgets_and_their_children() {
11880        let backend = MockBackend::default();
11881        let mut ui = Ui::new(backend);
11882
11883        let window = ui.create(WidgetKind::Window, None).expect("window");
11884        let first = ui
11885            .create(WidgetKind::Button, Some("First"))
11886            .expect("button");
11887        let group = ui.create(WidgetKind::Container, None).expect("container");
11888        let nested = ui
11889            .create(WidgetKind::TextInput, Some("Nested"))
11890            .expect("text_input");
11891        let last = ui.create(WidgetKind::Button, Some("Last")).expect("button");
11892        ui.attach(window, first).expect("attach first");
11893        ui.attach(window, group).expect("attach group");
11894        ui.attach(group, nested).expect("attach nested");
11895        ui.attach(window, last).expect("attach last");
11896
11897        assert_eq!(ui.focus_next().expect("focus"), Some(first));
11898        assert_eq!(ui.focus_next().expect("focus"), Some(nested));
11899        assert_eq!(ui.focus_next().expect("focus"), Some(last));
11900
11901        ui.set_enabled(group, false).expect("disable group");
11902        ui.focus(first).expect("focus first");
11903        assert_eq!(
11904            ui.focus_next().expect("focus"),
11905            Some(last),
11906            "disabled subtree is skipped"
11907        );
11908
11909        ui.set_enabled(group, true).expect("enable group");
11910        ui.focus(first).expect("focus first");
11911        assert_eq!(ui.focus_next().expect("focus"), Some(nested));
11912    }
11913
11914    #[test]
11915    fn set_focusable_updates_spec_and_backend_and_validates() {
11916        let backend = MockBackend::default();
11917        let mut ui = Ui::new(backend);
11918
11919        let window = ui.create(WidgetKind::Window, None).expect("window");
11920        let label = ui.create(WidgetKind::Label, Some("Static")).expect("label");
11921        assert_eq!(ui.is_focusable(label), Some(false));
11922
11923        ui.set_focusable(label, true)
11924            .expect("label becomes focusable");
11925        assert_eq!(ui.is_focusable(label), Some(true));
11926        assert_eq!(ui.widget(label).and_then(|spec| spec.focusable), Some(true));
11927        assert_eq!(
11928            ui.backend()
11929                .created
11930                .get(&label)
11931                .and_then(|spec| spec.focusable),
11932            Some(true)
11933        );
11934
11935        let order = ui.focus_order();
11936        assert!(order.contains(&label), "override joins the traversal order");
11937        assert!(!order.contains(&window), "window stays out of the order");
11938
11939        let err = ui
11940            .set_focusable(WidgetId(9999), true)
11941            .expect_err("unknown widget rejected");
11942        assert_eq!(err, GuiError::WidgetNotFound(9999));
11943    }
11944
11945    #[test]
11946    fn focus_reports_changes_and_clears_on_remove() {
11947        let backend = MockBackend::default();
11948        let mut ui = Ui::new(backend);
11949
11950        let window = ui.create(WidgetKind::Window, None).expect("window");
11951        let first = ui
11952            .create(WidgetKind::Button, Some("First"))
11953            .expect("button");
11954        let second = ui
11955            .create(WidgetKind::Button, Some("Second"))
11956            .expect("button");
11957        ui.attach(window, first).expect("attach first");
11958        ui.attach(window, second).expect("attach second");
11959
11960        ui.focus(first).expect("focus first");
11961        assert_eq!(ui.backend().focused, Some(first));
11962        ui.focus(second).expect("focus second");
11963        assert_eq!(ui.backend().focused, Some(second));
11964
11965        let mut events = Vec::new();
11966        ui.dispatch_events(|event| events.push(event))
11967            .expect("dispatch");
11968        let reported: Vec<(WidgetId, bool)> = events
11969            .iter()
11970            .filter_map(|event| match event {
11971                UiEvent::FocusChanged { widget_id, focused } => Some((*widget_id, *focused)),
11972                _ => None,
11973            })
11974            .collect();
11975        assert_eq!(
11976            reported,
11977            vec![(first, true), (first, false), (second, true)]
11978        );
11979        assert_eq!(
11980            ui.focused(),
11981            Some(second),
11982            "dispatch keeps the Ui record in sync"
11983        );
11984
11985        ui.remove(second).expect("remove focused widget");
11986        assert_eq!(
11987            ui.focused(),
11988            None,
11989            "removing the focused widget clears focus"
11990        );
11991
11992        let err = ui
11993            .focus(WidgetId(4242))
11994            .expect_err("unknown widget rejected");
11995        assert_eq!(err, GuiError::WidgetNotFound(4242));
11996    }
11997
11998    #[test]
11999    fn focus_next_without_candidates_reports_none() {
12000        let backend = MockBackend::default();
12001        let mut ui = Ui::new(backend);
12002        ui.create(WidgetKind::Window, None).expect("window");
12003        assert_eq!(ui.focus_next().expect("focus"), None);
12004        assert_eq!(ui.focused(), None);
12005    }
12006
12007    #[test]
12008    fn set_theme_and_mode_update_record_and_backend() {
12009        let backend = MockBackend::default();
12010        let mut ui = Ui::new(backend);
12011
12012        assert_eq!(ui.theme_mode(), ThemeMode::Light);
12013        assert_eq!(ui.backend().theme, None);
12014
12015        ui.set_theme_mode(ThemeMode::Dark)
12016            .expect("theme mode should apply");
12017        assert_eq!(ui.theme_mode(), ThemeMode::Dark);
12018        assert_eq!(
12019            ui.backend().theme.as_ref().map(|theme| theme.mode),
12020            Some(ThemeMode::Dark)
12021        );
12022
12023        let custom = Theme::light();
12024        ui.set_theme(custom.clone()).expect("theme should apply");
12025        assert_eq!(ui.theme(), &custom);
12026        assert_eq!(ui.backend().theme.as_ref(), Some(&custom));
12027    }
12028
12029    #[test]
12030    fn theme_overrides_round_trip_and_clear() {
12031        let backend = MockBackend::default();
12032        let mut ui = Ui::new(backend);
12033
12034        let button = ui.create(WidgetKind::Button, Some("Go")).expect("button");
12035        assert!(ui.theme_overrides(button).is_empty());
12036
12037        ui.set_theme_override(button, ThemeOverride::Padding(12))
12038            .expect("padding override should apply");
12039        ui.set_theme_override(button, ThemeOverride::FontSize(15.0))
12040            .expect("font override should apply");
12041        assert_eq!(
12042            ui.theme_overrides(button),
12043            [ThemeOverride::Padding(12), ThemeOverride::FontSize(15.0)]
12044        );
12045        assert_eq!(
12046            ui.backend().theme_overrides.get(&button).map(Vec::len),
12047            Some(2)
12048        );
12049
12050        ui.clear_theme_overrides(button).expect("clear should work");
12051        assert!(ui.theme_overrides(button).is_empty());
12052        assert!(!ui.backend().theme_overrides.contains_key(&button));
12053
12054        let err = ui
12055            .set_theme_override(WidgetId(9999), ThemeOverride::Padding(1))
12056            .expect_err("unknown widget rejected");
12057        assert_eq!(err, GuiError::WidgetNotFound(9999));
12058    }
12059
12060    #[test]
12061    fn stock_icon_resolution_follows_theme_mode_and_dpi_scale() {
12062        use crate::artprov::IconSource;
12063
12064        let backend = MockBackend::default();
12065        let mut ui = Ui::new(backend);
12066
12067        let light_small = ui.stock_icon(IconRole::Warning, IconSize::Small);
12068        assert_eq!(light_small.mode, ThemeMode::Light);
12069        assert_eq!(light_small.size, IconSize::Small);
12070        assert_eq!((light_small.width, light_small.height), (16, 16));
12071        assert_eq!(light_small.source, IconSource::Portable);
12072        assert!(light_small.has_visible_pixels());
12073
12074        let light_large_2x = ui.stock_icon_at_scale(IconRole::Warning, IconSize::Large, 2);
12075        assert_eq!((light_large_2x.width, light_large_2x.height), (64, 64));
12076        assert_eq!(light_large_2x.scale, 2);
12077
12078        ui.set_theme_mode(ThemeMode::Dark)
12079            .expect("theme mode should apply");
12080        let dark_small = ui.stock_icon(IconRole::Warning, IconSize::Small);
12081        assert_eq!(dark_small.mode, ThemeMode::Dark);
12082        assert_ne!(
12083            dark_small.pixels, light_small.pixels,
12084            "theme mode must change the resolved pixels"
12085        );
12086    }
12087
12088    #[test]
12089    fn native_stock_icon_is_a_typed_capability_error_on_mock() {
12090        let backend = MockBackend::default();
12091        let ui = Ui::new(backend);
12092
12093        assert_eq!(ui.art_capabilities(), ArtCapabilities::none());
12094        let err = ui
12095            .native_stock_icon(IconRole::Information, IconSize::Large)
12096            .expect_err("mock has no native stock art");
12097        match err {
12098            GuiError::UnsupportedCapability(message) => {
12099                assert!(message.contains("information"), "message: {message}");
12100                assert!(message.contains("large"), "message: {message}");
12101            }
12102            other => panic!("expected UnsupportedCapability, got {other:?}"),
12103        }
12104    }
12105
12106    #[test]
12107    fn attach_context_menu_binds_menu_to_widget_and_validates() {
12108        let backend = MockBackend::default();
12109        let mut ui = Ui::new(backend);
12110
12111        let list = ui
12112            .create(WidgetKind::DataList, Some("Files"))
12113            .expect("list should be created");
12114        let menu = ui.create_menu().expect("menu should be created");
12115        let item = ui
12116            .add_menu_item(menu, "Open")
12117            .expect("item should be created");
12118
12119        ui.attach_context_menu(list, menu)
12120            .expect("attach should succeed");
12121        assert_eq!(ui.backend().context_menus.get(&list), Some(&menu));
12122        assert_eq!(ui.backend().menus.get(&menu), Some(&vec![item]));
12123
12124        // Unknown widget and unknown menu are rejected cleanly.
12125        assert_eq!(
12126            ui.attach_context_menu(WidgetId(9999), menu).unwrap_err(),
12127            GuiError::WidgetNotFound(9999)
12128        );
12129        assert!(matches!(
12130            ui.attach_context_menu(list, MenuId(9999)),
12131            Err(GuiError::Backend(_))
12132        ));
12133    }
12134
12135    #[test]
12136    fn set_row_drag_updates_spec_and_backend_and_validates() {
12137        let backend = MockBackend::default();
12138        let mut ui = Ui::new(backend);
12139
12140        let list = ui
12141            .create(WidgetKind::ListView, Some("Files"))
12142            .expect("list should be created");
12143
12144        ui.set_row_drag(list, true, true)
12145            .expect("set_row_drag should succeed");
12146
12147        assert!(ui.widget(list).unwrap().row_drag_source);
12148        assert!(ui.widget(list).unwrap().row_drop_target);
12149        assert!(ui.backend().created.get(&list).unwrap().row_drag_source);
12150        assert!(ui.backend().created.get(&list).unwrap().row_drop_target);
12151
12152        ui.set_row_drag(list, false, false)
12153            .expect("disable should succeed");
12154        assert!(!ui.widget(list).unwrap().row_drag_source);
12155        assert!(!ui.widget(list).unwrap().row_drop_target);
12156
12157        let button = ui
12158            .create(WidgetKind::Button, Some("nope"))
12159            .expect("button should be created");
12160        let err = ui
12161            .set_row_drag(button, true, false)
12162            .expect_err("button rejected");
12163        assert_eq!(err, GuiError::UnsupportedWidget("set_row_drag"));
12164    }
12165
12166    #[test]
12167    fn show_confirm_dialog_returns_token_and_records_request() {
12168        let backend = MockBackend::default();
12169        let mut ui = Ui::new(backend);
12170
12171        let token1 = ui
12172            .show_confirm_dialog("Delete?", "Move to trash?")
12173            .expect("first dialog");
12174        let token2 = ui
12175            .show_confirm_dialog("Exit?", "Really quit?")
12176            .expect("second dialog");
12177        assert!(token2 > token1);
12178
12179        assert_eq!(
12180            ui.backend().confirm_requests,
12181            vec![
12182                (token1, "Delete?".to_owned(), "Move to trash?".to_owned()),
12183                (token2, "Exit?".to_owned(), "Really quit?".to_owned()),
12184            ]
12185        );
12186
12187        // The answer arrives as an event carrying the same token.
12188        ui.backend_mut().push_event(UiEvent::DialogResponse {
12189            token: token1,
12190            confirmed: true,
12191        });
12192        assert_eq!(
12193            ui.poll_event().unwrap(),
12194            Some(UiEvent::DialogResponse {
12195                token: token1,
12196                confirmed: true
12197            })
12198        );
12199    }
12200
12201    #[test]
12202    fn close_guard_records_per_window_and_rejects_other_kinds() {
12203        let backend = MockBackend::default();
12204        let mut ui = Ui::new(backend);
12205
12206        let window = ui
12207            .create(WidgetKind::Window, Some("Guard"))
12208            .expect("window should be created");
12209        ui.set_close_guard(window, true).expect("guard on");
12210        assert_eq!(ui.backend().close_guards.get(&window), Some(&true));
12211        ui.set_close_guard(window, false).expect("guard off");
12212        assert_eq!(ui.backend().close_guards.get(&window), Some(&false));
12213
12214        let label = ui
12215            .create(WidgetKind::Label, Some("not a window"))
12216            .expect("label should be created");
12217        let err = ui
12218            .set_close_guard(label, true)
12219            .expect_err("labels cannot be guarded");
12220        assert_eq!(err, GuiError::UnsupportedWidget("set_close_guard"));
12221    }
12222
12223    #[test]
12224    fn menu_item_enable_state_records_on_mock_and_validates_the_item() {
12225        let mut ui = Ui::new(MockBackend::default());
12226
12227        let menu = ui.create_menu().expect("menu should be created");
12228        let item = ui.add_menu_item(menu, "Undo").expect("menu item");
12229
12230        ui.set_menu_item_enabled(item, false).expect("disable");
12231        assert_eq!(ui.backend().menu_item_enabled.get(&item), Some(&false));
12232        ui.set_menu_item_enabled(item, true).expect("enable");
12233        assert_eq!(ui.backend().menu_item_enabled.get(&item), Some(&true));
12234
12235        let err = ui
12236            .set_menu_item_enabled(MenuItemId(9_999), true)
12237            .expect_err("unknown items are rejected");
12238        assert!(
12239            matches!(&err, GuiError::Backend(message) if message.contains("Menu item not found")),
12240            "{err:?}"
12241        );
12242    }
12243
12244    #[test]
12245    fn dynamic_menu_items_relabel_insert_remove_and_detach_submenus() {
12246        let mut ui = Ui::new(MockBackend::default());
12247
12248        let menu = ui.create_menu().expect("menu should be created");
12249        let recent = ui.add_submenu(menu, "Open Recent").expect("submenu");
12250        let recent_slot = *ui
12251            .submenu_slots
12252            .get(&recent)
12253            .expect("the submenu row slot is recorded");
12254        assert_eq!(
12255            ui.backend().menus.get(&menu).cloned(),
12256            Some(vec![recent_slot]),
12257            "a submenu holds its slot in the parent's ordered list"
12258        );
12259
12260        let first = ui
12261            .insert_menu_item(menu, 0, "New")
12262            .expect("insert at a valid position should succeed");
12263        assert_eq!(
12264            ui.backend().menus.get(&menu).cloned(),
12265            Some(vec![first, recent_slot])
12266        );
12267
12268        // Relabel in place: the recorded label changes, the order does not.
12269        ui.set_menu_item_text(first, "New Document")
12270            .expect("relabel should succeed");
12271        assert_eq!(
12272            ui.backend().menu_item_text.get(&first).map(String::as_str),
12273            Some("New Document")
12274        );
12275
12276        // Insert-at-index, then a clamped append past the end.
12277        let second = ui
12278            .insert_menu_item_with_shortcut(menu, 1, "Open", Some("Ctrl+O"))
12279            .expect("insert with shortcut");
12280        let tail = ui
12281            .insert_menu_item(menu, 99, "Quit")
12282            .expect("an index past the end appends");
12283        assert_eq!(
12284            ui.backend().menus.get(&menu).cloned(),
12285            Some(vec![first, second, recent_slot, tail]),
12286            "bookkeeping and the recorded lane order agree"
12287        );
12288        assert_eq!(
12289            ui.backend().menu_shortcuts.get(&second).map(String::as_str),
12290            Some("Ctrl+O")
12291        );
12292
12293        // Removal drops the row, its label, and its callback everywhere.
12294        ui.on_menu_item_selected(second, || {}).expect("callback");
12295        assert!(ui.on_menu_item_selected.contains_key(&second));
12296        ui.remove_menu_item(second).expect("remove should succeed");
12297        assert_eq!(
12298            ui.backend().menus.get(&menu).cloned(),
12299            Some(vec![first, recent_slot, tail])
12300        );
12301        assert!(!ui.backend().menu_item_text.contains_key(&second));
12302        assert!(!ui.on_menu_item_selected.contains_key(&second));
12303
12304        // Detaching a submenu drops its slot and orphaned rows.
12305        let recent_item = ui
12306            .add_menu_item(MenuId(recent.0), "notes.txt")
12307            .expect("submenu item");
12308        ui.remove_submenu(recent).expect("remove submenu");
12309        assert_eq!(
12310            ui.backend().menus.get(&menu).cloned(),
12311            Some(vec![first, tail]),
12312            "the parent loses the submenu slot"
12313        );
12314        assert!(!ui.backend().menus.contains_key(&MenuId(recent.0)));
12315        assert!(!ui.backend().menu_item_text.contains_key(&recent_item));
12316        assert!(!ui.menu_parents.contains_key(&recent));
12317
12318        // Validation: unknown ids and root menus are typed errors.
12319        assert!(ui.set_menu_item_text(MenuItemId(9_999), "x").is_err());
12320        assert!(ui.remove_menu_item(MenuItemId(9_999)).is_err());
12321        assert!(ui.insert_menu_item(MenuId(9_999), 0, "x").is_err());
12322        let err = ui
12323            .remove_submenu(menu)
12324            .expect_err("a root menu has no parent to detach from");
12325        assert!(
12326            matches!(&err, GuiError::Backend(message) if message.contains("Submenu not found")),
12327            "{err:?}"
12328        );
12329    }
12330
12331    #[test]
12332    fn wait_event_returns_pushed_events_in_order() {
12333        let backend = MockBackend::default();
12334        let mut ui = Ui::new(backend);
12335
12336        let window = ui
12337            .create(WidgetKind::Window, Some("Main"))
12338            .expect("window should be created");
12339
12340        ui.backend_mut()
12341            .push_event(UiEvent::Clicked { widget_id: window });
12342
12343        assert_eq!(
12344            ui.wait_event().expect("wait should succeed"),
12345            UiEvent::Clicked { widget_id: window }
12346        );
12347        // The mock backend blocks until an event is pushed; pushing a second
12348        // event and waiting for it must return exactly that event.
12349        ui.backend_mut()
12350            .push_event(UiEvent::WindowClosed { widget_id: window });
12351        assert_eq!(
12352            ui.wait_event().expect("wait should succeed"),
12353            UiEvent::WindowClosed { widget_id: window }
12354        );
12355    }
12356
12357    #[test]
12358    fn activated_event_dispatches_to_handler_with_index() {
12359        let backend = MockBackend::default();
12360        let mut ui = Ui::new(backend);
12361
12362        let window = ui
12363            .create(WidgetKind::Window, Some("Main"))
12364            .expect("window should be created");
12365
12366        let mut seen: Vec<UiEvent> = Vec::new();
12367        ui.backend_mut().push_event(UiEvent::Activated {
12368            widget_id: window,
12369            index: Some(2),
12370        });
12371        ui.dispatch_events(|event| seen.push(event))
12372            .expect("event dispatch should succeed");
12373        assert_eq!(
12374            seen,
12375            vec![UiEvent::Activated {
12376                widget_id: window,
12377                index: Some(2),
12378            }]
12379        );
12380    }
12381
12382    #[test]
12383    #[cfg(all(feature = "async", feature = "widgets-range"))]
12384    fn task_proxy_applies_queued_mutations_in_fifo_order() {
12385        use crate::async_ui::TaskDrainReport;
12386
12387        let backend = MockBackend::default();
12388        let mut ui = Ui::new(backend);
12389
12390        let label = ui
12391            .create(WidgetKind::Label, Some("start"))
12392            .expect("label should be created");
12393        let progress = ui
12394            .create(WidgetKind::ProgressBar, None)
12395            .expect("progress bar should be created");
12396        let data_list = ui
12397            .create(WidgetKind::DataList, None)
12398            .expect("data list should be created");
12399        let grid = ui
12400            .create(WidgetKind::DataGrid, None)
12401            .expect("data grid should be created");
12402        let proxy = ui.task_proxy();
12403
12404        let token = proxy.start_task();
12405        proxy.set_text(label, "first").expect("post");
12406        proxy.set_value(progress, 25).expect("post");
12407        proxy
12408            .set_data_list_items(data_list, ["Alpha".to_owned(), "Beta".to_owned()])
12409            .expect("post");
12410        proxy
12411            .set_data_grid_rows(grid, [vec!["A1".to_owned(), "A2".to_owned()]])
12412            .expect("post");
12413        proxy.set_text(label, "second").expect("post");
12414        proxy.progress(&token, 25.0).expect("post");
12415
12416        // Nothing is applied until the UI thread drains.
12417        assert_eq!(
12418            ui.widget(label).and_then(|spec| spec.text.as_deref()),
12419            Some("start")
12420        );
12421        assert_eq!(ui.widget(progress).and_then(|spec| spec.value), None);
12422        assert!(ui
12423            .widget(data_list)
12424            .map(|spec| spec.data_list_items.clone())
12425            .unwrap_or_default()
12426            .is_empty());
12427        assert!(ui
12428            .widget(grid)
12429            .map(|spec| spec.data_grid_rows.clone())
12430            .unwrap_or_default()
12431            .is_empty());
12432
12433        let report = ui.drain_task_commands();
12434        assert_eq!(
12435            report,
12436            TaskDrainReport {
12437                applied: 6,
12438                rejected: 0,
12439            }
12440        );
12441        // FIFO: the later SetText wins.
12442        assert_eq!(
12443            ui.widget(label).and_then(|spec| spec.text.as_deref()),
12444            Some("second")
12445        );
12446        assert_eq!(ui.widget(progress).and_then(|spec| spec.value), Some(25));
12447        assert_eq!(
12448            ui.widget(data_list)
12449                .map(|spec| spec.data_list_items.clone())
12450                .unwrap_or_default(),
12451            vec!["Alpha".to_owned(), "Beta".to_owned()]
12452        );
12453        assert_eq!(
12454            ui.widget(grid)
12455                .map(|spec| spec.data_grid_rows.as_ref().clone())
12456                .unwrap_or_default(),
12457            vec![vec!["A1".to_owned(), "A2".to_owned()]]
12458        );
12459
12460        let event = ui.poll_event().expect("poll").expect("task event");
12461        assert_eq!(
12462            event,
12463            UiEvent::Task(TaskEvent::Progress {
12464                task: token.id(),
12465                value: 25.0,
12466            })
12467        );
12468        assert!(ui.poll_event().expect("poll").is_none());
12469    }
12470
12471    #[test]
12472    #[cfg(feature = "async")]
12473    fn wait_event_applies_commands_and_wakes_on_a_worker_post() {
12474        let backend = MockBackend::default();
12475        let mut ui = Ui::new(backend);
12476
12477        let label = ui
12478            .create(WidgetKind::Label, Some("idle"))
12479            .expect("label should be created");
12480        let proxy = ui.task_proxy();
12481        let token = proxy.start_task();
12482
12483        let worker_proxy = proxy.clone();
12484        let worker_token = token.clone();
12485        let worker = std::thread::spawn(move || {
12486            std::thread::sleep(std::time::Duration::from_millis(30));
12487            worker_proxy.set_text(label, "from worker").expect("post");
12488            worker_proxy.finish(&worker_token).expect("post");
12489        });
12490
12491        // Blocks first (nothing queued yet), then wakes on the worker post
12492        // without leaking the internal wake marker.
12493        let event = ui.wait_event().expect("wait");
12494        assert_eq!(
12495            event,
12496            UiEvent::Task(TaskEvent::Finished { task: token.id() })
12497        );
12498        assert_eq!(
12499            ui.widget(label).and_then(|spec| spec.text.as_deref()),
12500            Some("from worker")
12501        );
12502        worker.join().expect("worker should join");
12503    }
12504
12505    #[test]
12506    #[cfg(feature = "async")]
12507    fn wake_marker_never_reaches_dispatch_handlers() {
12508        let backend = MockBackend::default();
12509        let mut ui = Ui::new(backend);
12510
12511        let window = ui
12512            .create(WidgetKind::Window, Some("Main"))
12513            .expect("window should be created");
12514        let proxy = ui.task_proxy();
12515        let token = proxy.start_task();
12516        proxy.finish(&token).expect("post");
12517        ui.backend_mut()
12518            .push_event(UiEvent::Clicked { widget_id: window });
12519
12520        let mut seen = Vec::new();
12521        let count = ui
12522            .dispatch_events(|event| seen.push(event))
12523            .expect("dispatch should succeed");
12524
12525        assert_eq!(count, 2);
12526        assert_eq!(
12527            seen,
12528            vec![
12529                UiEvent::Task(TaskEvent::Finished { task: token.id() }),
12530                UiEvent::Clicked { widget_id: window },
12531            ]
12532        );
12533    }
12534
12535    #[test]
12536    #[cfg(feature = "async")]
12537    fn drain_rejects_commands_for_removed_widgets() {
12538        use crate::async_ui::{TaskAbortReason, TaskCommandKind, TaskDrainReport};
12539
12540        let backend = MockBackend::default();
12541        let mut ui = Ui::new(backend);
12542
12543        let label = ui
12544            .create(WidgetKind::Label, Some("alive"))
12545            .expect("label should be created");
12546        let doomed = ui
12547            .create(WidgetKind::Label, Some("doomed"))
12548            .expect("label should be created");
12549        let proxy = ui.task_proxy();
12550
12551        ui.remove(doomed).expect("remove should succeed");
12552        proxy.set_text(doomed, "ghost").expect("post");
12553        proxy.set_text(label, "kept").expect("post");
12554
12555        let report = ui.drain_task_commands();
12556        assert_eq!(
12557            report,
12558            TaskDrainReport {
12559                applied: 1,
12560                rejected: 1,
12561            }
12562        );
12563        assert_eq!(
12564            ui.widget(label).and_then(|spec| spec.text.as_deref()),
12565            Some("kept")
12566        );
12567        assert!(ui.widget(doomed).is_none());
12568
12569        // The rejection is never silent - the aborted
12570        // command surfaces as a dead-letter event instead.
12571        let event = ui.poll_event().expect("poll").expect("abort event");
12572        assert_eq!(
12573            event,
12574            UiEvent::Task(TaskEvent::Aborted {
12575                widget_id: doomed,
12576                command: TaskCommandKind::SetText,
12577                reason: TaskAbortReason::WidgetRemoved,
12578            })
12579        );
12580        assert!(
12581            ui.poll_event().expect("poll").is_none(),
12582            "exactly one dead-letter event per aborted command"
12583        );
12584    }
12585
12586    #[test]
12587    #[cfg(feature = "async")]
12588    fn drain_reports_live_refusals_and_keeps_aborts_in_post_order() {
12589        use crate::async_ui::{TaskAbortReason, TaskCommandKind, TaskDrainReport};
12590
12591        let backend = MockBackend::default();
12592        let mut ui = Ui::new(backend);
12593
12594        let label = ui
12595            .create(WidgetKind::Label, Some("plain"))
12596            .expect("label should be created");
12597        let doomed = ui
12598            .create(WidgetKind::Label, Some("doomed"))
12599            .expect("label should be created");
12600        let proxy = ui.task_proxy();
12601        let token = proxy.start_task();
12602
12603        // A live target refuses `set_checked` on a Label; a tombstoned target
12604        // refuses the final commit; the completion token follows both.
12605        proxy.set_checked(label, true).expect("post");
12606        ui.remove(doomed).expect("remove should succeed");
12607        proxy.set_text(doomed, "final").expect("post");
12608        proxy
12609            .finish_lossless(&token, std::time::Duration::from_secs(1))
12610            .expect("post");
12611
12612        let report = ui.drain_task_commands();
12613        assert_eq!(
12614            report,
12615            TaskDrainReport {
12616                applied: 1,
12617                rejected: 2,
12618            }
12619        );
12620        assert_eq!(ui.widget(label).and_then(|spec| spec.checked), None);
12621
12622        // Post order: live refusal, tombstone, lifecycle token - nothing is
12623        // dropped or reordered.
12624        let events: Vec<UiEvent> = std::iter::from_fn(|| ui.poll_event().expect("poll")).collect();
12625        assert_eq!(
12626            events,
12627            vec![
12628                UiEvent::Task(TaskEvent::Aborted {
12629                    widget_id: label,
12630                    command: TaskCommandKind::SetChecked,
12631                    reason: TaskAbortReason::Refused(GuiError::UnsupportedWidget("set_checked")),
12632                }),
12633                UiEvent::Task(TaskEvent::Aborted {
12634                    widget_id: doomed,
12635                    command: TaskCommandKind::SetText,
12636                    reason: TaskAbortReason::WidgetRemoved,
12637                }),
12638                UiEvent::Task(TaskEvent::Finished { task: token.id() }),
12639            ]
12640        );
12641    }
12642
12643    #[test]
12644    #[cfg(feature = "async")]
12645    fn overflowing_task_queue_is_reported_and_recovers() {
12646        use crate::async_ui::TaskSendError;
12647
12648        let backend = MockBackend::default();
12649        let mut ui = Ui::new(backend);
12650
12651        let label = ui
12652            .create(WidgetKind::Label, Some("x"))
12653            .expect("label should be created");
12654        let proxy = ui.task_proxy();
12655        assert_eq!(proxy.capacity(), DEFAULT_TASK_QUEUE_CAPACITY);
12656
12657        for _ in 0..DEFAULT_TASK_QUEUE_CAPACITY {
12658            proxy.set_text(label, "queued").expect("post within bound");
12659        }
12660        assert_eq!(proxy.set_text(label, "overflow"), Err(TaskSendError::Full));
12661
12662        let report = ui.drain_task_commands();
12663        assert_eq!(report.applied, DEFAULT_TASK_QUEUE_CAPACITY);
12664        assert_eq!(report.rejected, 0);
12665
12666        proxy
12667            .set_text(label, "after drain")
12668            .expect("post after drain");
12669        assert_eq!(ui.drain_task_commands().applied, 1);
12670    }
12671
12672    #[test]
12673    #[cfg(feature = "async")]
12674    fn posts_fail_closed_after_the_ui_is_dropped() {
12675        use crate::async_ui::TaskSendError;
12676
12677        let proxy = {
12678            let backend = MockBackend::default();
12679            let mut ui = Ui::new(backend);
12680            ui.create(WidgetKind::Label, None).expect("label");
12681            ui.task_proxy()
12682        };
12683
12684        assert_eq!(
12685            proxy.set_text(WidgetId(1), "late"),
12686            Err(TaskSendError::Closed)
12687        );
12688    }
12689
12690    #[test]
12691    fn set_file_drop_target_updates_spec_and_backend() {
12692        let backend = MockBackend::default();
12693        let mut ui = Ui::new(backend);
12694
12695        let window = ui.create(WidgetKind::Window, Some("DropWindow")).unwrap();
12696        assert!(!ui.widget(window).unwrap().file_drop_target);
12697        assert!(!ui.backend().created.get(&window).unwrap().file_drop_target);
12698
12699        ui.set_file_drop_target(window, true).unwrap();
12700        assert!(ui.widget(window).unwrap().file_drop_target);
12701        assert!(ui.backend().created.get(&window).unwrap().file_drop_target);
12702
12703        ui.set_file_drop_target(window, false).unwrap();
12704        assert!(!ui.widget(window).unwrap().file_drop_target);
12705        assert!(!ui.backend().created.get(&window).unwrap().file_drop_target);
12706
12707        let err = ui.set_file_drop_target(WidgetId(9999), true).unwrap_err();
12708        assert_eq!(err, GuiError::WidgetNotFound(9999));
12709    }
12710
12711    #[test]
12712    fn set_file_drop_target_refusal_preserves_spec_and_backend_state() {
12713        let backend = CustomMeasuringBackend {
12714            reject_file_drop: true,
12715            ..CustomMeasuringBackend::default()
12716        };
12717        let mut ui = Ui::new(backend);
12718        let window = ui.create(WidgetKind::Window, Some("DropWindow")).unwrap();
12719
12720        assert_eq!(
12721            ui.set_file_drop_target(window, true),
12722            Err(GuiError::UnsupportedCapability("drag_file_drop".to_owned()))
12723        );
12724        assert!(!ui.widget(window).unwrap().file_drop_target);
12725        assert!(!ui.backend().created.get(&window).unwrap().file_drop_target);
12726
12727        ui.backend_mut().reject_file_drop = false;
12728        ui.set_file_drop_target(window, true).unwrap();
12729        assert!(ui.widget(window).unwrap().file_drop_target);
12730        assert!(ui.backend().created.get(&window).unwrap().file_drop_target);
12731    }
12732
12733    #[test]
12734    fn files_dropped_event_dispatches_paths() {
12735        let backend = MockBackend::default();
12736        let mut ui = Ui::new(backend);
12737
12738        let window = ui.create(WidgetKind::Window, Some("Main")).unwrap();
12739        let mut seen = Vec::new();
12740        let paths = vec![
12741            "/home/user/doc.txt".to_string(),
12742            "/home/user/img.png".to_string(),
12743        ];
12744
12745        ui.backend_mut().push_event(UiEvent::FilesDropped {
12746            widget_id: window,
12747            paths: paths.clone(),
12748        });
12749
12750        ui.dispatch_events(|event| seen.push(event)).unwrap();
12751        assert_eq!(
12752            seen,
12753            vec![UiEvent::FilesDropped {
12754                widget_id: window,
12755                paths,
12756            }]
12757        );
12758    }
12759
12760    /// helper: every parent link points at a live widget, no
12761    /// link is self-referential, and walking a parent chain always terminates
12762    /// inside the live set (strict acyclic forest, single parentage).
12763    fn assert_acyclic_parentage(ui: &Ui<MockBackend>) {
12764        for (id, spec) in &ui.widgets {
12765            let Some(parent) = spec.parent else {
12766                continue;
12767            };
12768            assert_ne!(parent, *id, "widget {id:?} is its own parent");
12769            assert!(
12770                ui.widgets.contains_key(&parent),
12771                "widget {id:?} points at removed parent {parent:?}"
12772            );
12773            let mut hops = 0usize;
12774            let mut cursor = Some(parent);
12775            while let Some(current) = cursor {
12776                hops += 1;
12777                assert!(
12778                    hops <= ui.widgets.len(),
12779                    "parent chain from {id:?} does not terminate (cycle)"
12780                );
12781                cursor = ui.widgets.get(&current).and_then(|spec| spec.parent);
12782            }
12783        }
12784    }
12785
12786    /// Helper: the adjacency index is exactly the parent-link view -
12787    /// one entry per parented widget, no duplicates, no stale ids, no empty
12788    /// parent keys.
12789    fn assert_children_index_matches_links(ui: &Ui<MockBackend>) {
12790        use std::collections::BTreeMap;
12791
12792        let total: usize = ui.children_index.values().map(Vec::len).sum();
12793        let parented = ui
12794            .widgets
12795            .values()
12796            .filter(|spec| spec.parent.is_some())
12797            .count();
12798        assert_eq!(
12799            total, parented,
12800            "the index must hold exactly one entry per parented widget"
12801        );
12802
12803        let mut from_links: BTreeMap<u64, Vec<u64>> = BTreeMap::new();
12804        for (id, spec) in &ui.widgets {
12805            if let Some(parent) = spec.parent {
12806                from_links.entry(parent.0).or_default().push(id.0);
12807            }
12808        }
12809        for children in from_links.values_mut() {
12810            children.sort_unstable();
12811        }
12812
12813        let mut from_index: BTreeMap<u64, Vec<u64>> = BTreeMap::new();
12814        for (parent, children) in &ui.children_index {
12815            assert!(
12816                !children.is_empty(),
12817                "parent key {parent:?} left in the index with no children"
12818            );
12819            let mut ids = Vec::with_capacity(children.len());
12820            for child in children {
12821                assert!(
12822                    ui.widgets.contains_key(child),
12823                    "stale {child:?} under {parent:?} in the index"
12824                );
12825                assert_eq!(
12826                    ui.widgets.get(child).and_then(|spec| spec.parent),
12827                    Some(*parent),
12828                    "index edge {parent:?} -> {child:?} contradicts the parent link"
12829                );
12830                ids.push(child.0);
12831            }
12832            ids.sort_unstable();
12833            ids.dedup();
12834            assert_eq!(
12835                ids.len(),
12836                children.len(),
12837                "duplicate child entries under {parent:?}"
12838            );
12839            from_index.insert(parent.0, ids);
12840        }
12841
12842        assert_eq!(
12843            from_index, from_links,
12844            "children_index disagrees with the parent-link view"
12845        );
12846    }
12847
12848    /// helper: the shared map and the Mock's native record
12849    /// describe the same widget set, and every spec compares equal to its
12850    /// native record (the Mock lane's spec-native coherence invariant).
12851    fn assert_mock_mirror_is_exact(ui: &Ui<MockBackend>) {
12852        assert_eq!(
12853            ui.widgets.len(),
12854            ui.backend().created.len(),
12855            "shared and native widget sets diverged"
12856        );
12857        for (id, spec) in &ui.widgets {
12858            let native = ui
12859                .backend()
12860                .created
12861                .get(id)
12862                .unwrap_or_else(|| panic!("no native record for {id:?}"));
12863            assert_eq!(
12864                spec, native,
12865                "shared spec and native record differ for {id:?}"
12866            );
12867        }
12868    }
12869
12870    #[test]
12871    fn attach_and_reparent_reject_self_and_cycles_without_mutation() {
12872        let backend = MockBackend::default();
12873        let mut ui = Ui::new(backend);
12874
12875        let window = ui.create(WidgetKind::Window, Some("Root")).unwrap();
12876        let container = ui.create(WidgetKind::Container, None).unwrap();
12877        let label = ui.create(WidgetKind::Label, Some("Leaf")).unwrap();
12878        ui.attach(window, container).unwrap();
12879        ui.attach(container, label).unwrap();
12880        assert_mock_mirror_is_exact(&ui);
12881
12882        // Self-parentage is a one-node cycle and must be refused.
12883        assert!(ui.attach(window, window).is_err(), "self-attach refused");
12884        assert!(
12885            ui.reparent(window, window).is_err(),
12886            "self-reparent refused"
12887        );
12888
12889        // Attaching an ancestor beneath a descendant closes a cycle.
12890        assert!(
12891            ui.attach(label, container).is_err(),
12892            "upward attach refused"
12893        );
12894        assert!(
12895            ui.attach(container, window).is_err(),
12896            "upward attach refused"
12897        );
12898        assert!(
12899            ui.reparent(window, label).is_err(),
12900            "cycle reparent refused"
12901        );
12902
12903        // Refusals are transactional: the previous edges are untouched.
12904        assert_eq!(ui.widget(window).unwrap().parent, None);
12905        assert_eq!(ui.widget(container).unwrap().parent, Some(window));
12906        assert_eq!(ui.widget(label).unwrap().parent, Some(container));
12907
12908        // Unknown ids fail before any mutation as well.
12909        assert_eq!(
12910            ui.attach(WidgetId(9001), label),
12911            Err(GuiError::WidgetNotFound(9001))
12912        );
12913        assert_eq!(
12914            ui.attach(window, WidgetId(9001)),
12915            Err(GuiError::WidgetNotFound(9001))
12916        );
12917
12918        // A legal cross-branch move still works after all the refusals.
12919        let other = ui.create(WidgetKind::Container, None).unwrap();
12920        ui.attach(window, other).unwrap();
12921        ui.reparent(label, other).expect("legal reparent");
12922        assert_eq!(ui.widget(label).unwrap().parent, Some(other));
12923
12924        assert_acyclic_parentage(&ui);
12925        assert_mock_mirror_is_exact(&ui);
12926    }
12927
12928    #[test]
12929    fn remove_cascades_the_subtree_and_never_reuses_ids() {
12930        let backend = MockBackend::default();
12931        let mut ui = Ui::new(backend);
12932
12933        let window = ui.create(WidgetKind::Window, Some("Root")).unwrap();
12934        let left = ui.create(WidgetKind::Container, None).unwrap();
12935        let right = ui.create(WidgetKind::Container, None).unwrap();
12936        let leaf_a = ui.create(WidgetKind::Label, Some("A")).unwrap();
12937        let leaf_b = ui.create(WidgetKind::Label, Some("B")).unwrap();
12938        let leaf_c = ui.create(WidgetKind::Label, Some("C")).unwrap();
12939        ui.attach(window, left).unwrap();
12940        ui.attach(window, right).unwrap();
12941        ui.attach(left, leaf_a).unwrap();
12942        ui.attach(left, leaf_b).unwrap();
12943        ui.attach(right, leaf_c).unwrap();
12944        ui.show(left).unwrap();
12945
12946        ui.remove(left).expect("cascade removal");
12947        for gone in [left, leaf_a, leaf_b] {
12948            assert!(ui.widget(gone).is_none(), "{gone:?} must be removed");
12949            assert!(
12950                !ui.backend().created.contains_key(&gone),
12951                "{gone:?} must leave the native record"
12952            );
12953            assert_eq!(ui.remove(gone), Err(GuiError::WidgetNotFound(gone.0)));
12954        }
12955        for survivor in [window, right, leaf_c] {
12956            assert!(ui.widget(survivor).is_some(), "{survivor:?} must survive");
12957        }
12958        assert_eq!(ui.widget_count(), 3);
12959        assert!(!ui.backend().shown.contains(&left), "show record cleaned");
12960
12961        // Ids are monotonic and a removed id is never handed out again.
12962        let next = ui.create(WidgetKind::Label, Some("D")).unwrap();
12963        assert!(
12964            next.0 > leaf_c.0,
12965            "new ids must be monotonic ({next:?} after {leaf_c:?})"
12966        );
12967        for old in [left, leaf_a, leaf_b] {
12968            assert_ne!(next, old, "removed id {old:?} was reused");
12969        }
12970
12971        assert_acyclic_parentage(&ui);
12972        assert_mock_mirror_is_exact(&ui);
12973        assert_children_index_matches_links(&ui);
12974    }
12975
12976    #[test]
12977    fn children_index_tracks_attach_reparent_and_remove() {
12978        let backend = MockBackend::default();
12979        let mut ui = Ui::new(backend);
12980
12981        let window = ui.create(WidgetKind::Window, Some("Root")).unwrap();
12982        let left = ui.create(WidgetKind::Container, None).unwrap();
12983        let right = ui.create(WidgetKind::Container, None).unwrap();
12984        let branch = ui.create(WidgetKind::Container, None).unwrap();
12985        let leaf = ui.create(WidgetKind::Label, Some("Leaf")).unwrap();
12986
12987        ui.attach(window, left).unwrap();
12988        ui.attach(window, right).unwrap();
12989        ui.attach(left, branch).unwrap();
12990        ui.attach(branch, leaf).unwrap();
12991        assert_children_index_matches_links(&ui);
12992
12993        // Re-attaching the same pair is idempotent: one edge, no duplicate.
12994        ui.attach(left, branch).unwrap();
12995        assert_children_index_matches_links(&ui);
12996        assert_eq!(ui.children_index.get(&left), Some(&vec![branch]));
12997
12998        // Reparenting moves the edge (with its subtree) off the old parent.
12999        ui.reparent(branch, right).unwrap();
13000        assert_children_index_matches_links(&ui);
13001        assert_eq!(
13002            ui.children_index.get(&left),
13003            None,
13004            "the old parent's empty key must be dropped"
13005        );
13006
13007        // The old branch no longer cascades; the moved subtree survives it.
13008        ui.remove(left).expect("left has no children left");
13009        assert!(ui.widget(branch).is_some(), "moved branch survives");
13010        assert!(ui.widget(leaf).is_some(), "moved leaf survives");
13011        assert_children_index_matches_links(&ui);
13012
13013        // The new branch cascades the whole moved subtree, root last.
13014        ui.remove(right).expect("cascade through the new parent");
13015        for gone in [branch, leaf, right] {
13016            assert!(ui.widget(gone).is_none(), "{gone:?} must be removed");
13017            assert!(
13018                !ui.backend().created.contains_key(&gone),
13019                "{gone:?} must leave the native record"
13020            );
13021        }
13022        assert!(ui.widget(window).is_some(), "the window survives");
13023        assert_children_index_matches_links(&ui);
13024        assert_acyclic_parentage(&ui);
13025        assert_mock_mirror_is_exact(&ui);
13026    }
13027
13028    #[test]
13029    fn create_with_a_configured_parent_joins_the_children_index() {
13030        let backend = MockBackend::default();
13031        let mut ui = Ui::new(backend);
13032
13033        let window = ui.create(WidgetKind::Window, Some("Root")).unwrap();
13034        let declarative = ui
13035            .create_with(WidgetKind::Label, |spec| {
13036                spec.text = Some("configured".to_owned());
13037                spec.parent = Some(window);
13038            })
13039            .expect("create with a configured parent");
13040
13041        assert_children_index_matches_links(&ui);
13042        assert_eq!(ui.children_index.get(&window), Some(&vec![declarative]));
13043
13044        // The configured edge participates in cascades like an attach.
13045        ui.remove(window)
13046            .expect("cascade through the configured edge");
13047        assert!(ui.widget(declarative).is_none());
13048        assert_eq!(ui.widget_count(), 0);
13049        assert_children_index_matches_links(&ui);
13050        assert_mock_mirror_is_exact(&ui);
13051    }
13052
13053    #[test]
13054    fn teardown_walks_each_node_once_even_at_scale() {
13055        // Regression guard for the O(N^2) whole-graph scan: a wide
13056        // star plus a deep chain must tear down in one indexed pass with no
13057        // stale edges left behind.
13058        let backend = MockBackend::default();
13059        let mut ui = Ui::new(backend);
13060
13061        let root = ui.create(WidgetKind::Window, Some("Root")).unwrap();
13062        let stem = ui.create(WidgetKind::Container, None).unwrap();
13063        ui.attach(root, stem).unwrap();
13064        let mut cursor = stem;
13065        for _ in 0..100 {
13066            let next = ui.create(WidgetKind::Container, None).unwrap();
13067            ui.attach(cursor, next).unwrap();
13068            cursor = next;
13069        }
13070        for _ in 0..2000 {
13071            let leaf = ui.create(WidgetKind::Label, Some("leaf")).unwrap();
13072            ui.attach(root, leaf).unwrap();
13073        }
13074        assert_children_index_matches_links(&ui);
13075
13076        ui.remove(root).expect("single-pass teardown");
13077        assert_eq!(ui.widget_count(), 0);
13078        assert!(ui.backend().created.is_empty());
13079        assert!(ui.children_index.is_empty(), "index fully drained");
13080    }
13081
13082    #[test]
13083    #[cfg(feature = "widgets-range")]
13084    fn refused_setters_leave_the_spec_and_the_native_record_untouched() {
13085        let backend = MockBackend::default();
13086        let mut ui = Ui::new(backend);
13087
13088        let label = ui.create(WidgetKind::Label, Some("text")).unwrap();
13089        let slider = ui.create(WidgetKind::Slider, None).unwrap();
13090
13091        type Refusal = Box<dyn Fn(&mut Ui<MockBackend>) -> GuiResult<()>>;
13092        let cases: Vec<(&str, GuiError, Refusal)> = vec![
13093            (
13094                "set_checked on a Label",
13095                GuiError::UnsupportedWidget("set_checked"),
13096                Box::new(move |ui| ui.set_checked(label, true)),
13097            ),
13098            (
13099                "set_value on a Label",
13100                GuiError::UnsupportedWidget("set_value"),
13101                Box::new(move |ui| ui.set_value(label, 7)),
13102            ),
13103            (
13104                "set_range with inverted bounds",
13105                GuiError::Backend("Widget range min must be <= max".to_owned()),
13106                Box::new(move |ui| ui.set_range(slider, 10, 0)),
13107            ),
13108            (
13109                "set_step with a non-positive step",
13110                GuiError::Backend("Widget step must be positive".to_owned()),
13111                Box::new(move |ui| ui.set_step(slider, 0)),
13112            ),
13113            (
13114                "set_size with a zero dimension",
13115                GuiError::Backend("Widget size must be positive".to_owned()),
13116                Box::new(move |ui| ui.set_size(label, 0, 0)),
13117            ),
13118            (
13119                "set_text_selection with start > end",
13120                GuiError::Backend("Text selection start must be <= end".to_owned()),
13121                Box::new(move |ui| ui.set_text_selection(label, 3, 1)),
13122            ),
13123            (
13124                "set_text on an unknown id",
13125                GuiError::WidgetNotFound(4242),
13126                Box::new(move |ui| ui.set_text(WidgetId(4242), "nope")),
13127            ),
13128            (
13129                "set_checked on an unknown id",
13130                GuiError::WidgetNotFound(4242),
13131                Box::new(move |ui| ui.set_checked(WidgetId(4242), true)),
13132            ),
13133            (
13134                "focus on an unknown id",
13135                GuiError::WidgetNotFound(4242),
13136                Box::new(move |ui| ui.focus(WidgetId(4242))),
13137            ),
13138            (
13139                "remove on an unknown id",
13140                GuiError::WidgetNotFound(4242),
13141                Box::new(move |ui| ui.remove(WidgetId(4242))),
13142            ),
13143            (
13144                "attach with an unknown parent",
13145                GuiError::WidgetNotFound(4242),
13146                Box::new(move |ui| ui.attach(WidgetId(4242), label)),
13147            ),
13148        ];
13149
13150        for (name, expected, call) in cases {
13151            let before_count = ui.widget_count();
13152            let before_label = ui.widget(label).cloned();
13153            let before_slider = ui.widget(slider).cloned();
13154            let before_native_label = ui.backend().created.get(&label).cloned();
13155            let before_native_slider = ui.backend().created.get(&slider).cloned();
13156
13157            let error = call(&mut ui).expect_err(name);
13158            assert_eq!(error, expected, "{name}: typed error");
13159
13160            assert_eq!(ui.widget_count(), before_count, "{name}: widget count");
13161            assert_eq!(
13162                ui.widget(label).cloned(),
13163                before_label,
13164                "{name}: label spec"
13165            );
13166            assert_eq!(
13167                ui.widget(slider).cloned(),
13168                before_slider,
13169                "{name}: slider spec"
13170            );
13171            assert_eq!(
13172                ui.backend().created.get(&label).cloned(),
13173                before_native_label,
13174                "{name}: label native record"
13175            );
13176            assert_eq!(
13177                ui.backend().created.get(&slider).cloned(),
13178                before_native_slider,
13179                "{name}: slider native record"
13180            );
13181        }
13182
13183        assert_acyclic_parentage(&ui);
13184        assert_mock_mirror_is_exact(&ui);
13185    }
13186
13187    #[test]
13188    #[cfg(not(feature = "widgets-range"))]
13189    fn range_setters_return_unsupported_when_range_is_compiled_out() {
13190        let backend = MockBackend::default();
13191        let mut ui = Ui::new(backend);
13192        let label = ui.create(WidgetKind::Label, Some("test")).unwrap();
13193        assert_eq!(
13194            ui.set_value(label, 10).unwrap_err(),
13195            GuiError::UnsupportedWidget("set_value")
13196        );
13197        assert_eq!(
13198            ui.set_range(label, 0, 10).unwrap_err(),
13199            GuiError::UnsupportedWidget("set_range")
13200        );
13201        assert_eq!(
13202            ui.set_step(label, 1).unwrap_err(),
13203            GuiError::UnsupportedWidget("set_step")
13204        );
13205    }
13206
13207    #[test]
13208    #[cfg(not(feature = "widgets-choice"))]
13209    fn choice_setters_return_unsupported_when_choice_is_compiled_out() {
13210        let backend = MockBackend::default();
13211        let mut ui = Ui::new(backend);
13212        let label = ui.create(WidgetKind::Label, Some("test")).unwrap();
13213        assert_eq!(
13214            ui.set_checked(label, true).unwrap_err(),
13215            GuiError::UnsupportedWidget("set_checked")
13216        );
13217    }
13218
13219    #[test]
13220    #[cfg(not(feature = "widgets-containers"))]
13221    fn containers_setters_return_unsupported_when_containers_is_compiled_out() {
13222        let backend = MockBackend::default();
13223        let mut ui = Ui::new(backend);
13224        let label = ui.create(WidgetKind::Label, Some("test")).unwrap();
13225        assert_eq!(
13226            ui.set_tab_items(label, &["Tab 1".to_string()]).unwrap_err(),
13227            GuiError::UnsupportedWidget("set_tab_items")
13228        );
13229        assert_eq!(
13230            ui.set_alert_level(label, AlertLevel::Info).unwrap_err(),
13231            GuiError::UnsupportedWidget("set_alert_level")
13232        );
13233    }
13234
13235    #[test]
13236    #[cfg(not(feature = "widgets-pickers"))]
13237    fn pickers_setters_return_unsupported_when_pickers_is_compiled_out() {
13238        let backend = MockBackend::default();
13239        let mut ui = Ui::new(backend);
13240        let label = ui.create(WidgetKind::Label, Some("test")).unwrap();
13241        assert_eq!(
13242            ui.set_date_value(label, "2026-09-07").unwrap_err(),
13243            GuiError::UnsupportedWidget("set_date_value")
13244        );
13245        assert_eq!(
13246            ui.set_file_chooser_mode(label, FileChooserMode::PickFolder)
13247                .unwrap_err(),
13248            GuiError::UnsupportedWidget("set_file_chooser_mode")
13249        );
13250        assert_eq!(
13251            ui.set_color_dialog_data(label, ColorDialogData::default())
13252                .unwrap_err(),
13253            GuiError::UnsupportedWidget("set_color_dialog_data")
13254        );
13255        assert_eq!(
13256            ui.set_font_dialog_data(
13257                label,
13258                FontDialogData::new(FontDescriptor::new("Inter", 12.0))
13259            )
13260            .unwrap_err(),
13261            GuiError::UnsupportedWidget("set_font_dialog_data")
13262        );
13263        assert_eq!(
13264            ui.set_calendar_selected_dates(label, &[]).unwrap_err(),
13265            GuiError::UnsupportedWidget("set_calendar_selected_dates")
13266        );
13267        assert_eq!(
13268            ui.set_calendar_bounds(label, None, None).unwrap_err(),
13269            GuiError::UnsupportedWidget("set_calendar_bounds")
13270        );
13271        assert_eq!(
13272            ui.set_calendar_first_day_of_week(label, CalendarFirstDayOfWeek::Monday)
13273                .unwrap_err(),
13274            GuiError::UnsupportedWidget("set_calendar_first_day_of_week")
13275        );
13276        assert_eq!(
13277            ui.set_calendar_selection_mode(label, CalendarSelectionMode::Single)
13278                .unwrap_err(),
13279            GuiError::UnsupportedWidget("set_calendar_selection_mode")
13280        );
13281    }
13282
13283    #[test]
13284    #[cfg(not(feature = "widgets-text"))]
13285    fn text_setters_return_unsupported_when_text_is_compiled_out() {
13286        let backend = MockBackend::default();
13287        let mut ui = Ui::new(backend);
13288        let label = ui.create(WidgetKind::Label, Some("test")).unwrap();
13289        assert_eq!(
13290            ui.set_link_url(label, "https://example.com").unwrap_err(),
13291            GuiError::UnsupportedWidget("set_link_url")
13292        );
13293        assert_eq!(
13294            ui.set_placeholder_text(label, "placeholder").unwrap_err(),
13295            GuiError::UnsupportedWidget("set_placeholder_text")
13296        );
13297        assert_eq!(
13298            ui.set_text_selection(label, 0, 5).unwrap_err(),
13299            GuiError::UnsupportedWidget("set_text_selection")
13300        );
13301        assert_eq!(
13302            ui.set_text_completion_items(label, &["one".to_string()])
13303                .unwrap_err(),
13304            GuiError::UnsupportedWidget("set_text_completion_items")
13305        );
13306        assert_eq!(
13307            ui.set_spell_check(label, true).unwrap_err(),
13308            GuiError::UnsupportedWidget("set_spell_check")
13309        );
13310        assert_eq!(
13311            ui.set_rich_text_runs(label, &[]).unwrap_err(),
13312            GuiError::UnsupportedWidget("set_rich_text_runs")
13313        );
13314        assert_eq!(
13315            ui.set_rich_text_images(label, &[]).unwrap_err(),
13316            GuiError::UnsupportedWidget("set_rich_text_images")
13317        );
13318    }
13319
13320    #[test]
13321    #[cfg(feature = "async")]
13322    fn concurrent_task_posts_are_applied_exactly_once_and_in_order() {
13323        use crate::async_ui::TaskSendError;
13324        use std::sync::atomic::{AtomicUsize, Ordering};
13325        use std::sync::Arc;
13326        use std::thread;
13327
13328        let backend = MockBackend::default();
13329        let mut ui = Ui::new(backend);
13330        let label = ui.create(WidgetKind::Label, Some("idle")).unwrap();
13331        let proxy = ui.task_proxy();
13332
13333        const TOTAL: usize = 512;
13334        let posted = Arc::new(AtomicUsize::new(0));
13335        let worker_proxy = proxy.clone();
13336        let worker_posted = Arc::clone(&posted);
13337
13338        let worker = thread::spawn(move || {
13339            for index in 0..TOTAL {
13340                let text = format!("tick-{index}");
13341                loop {
13342                    match worker_proxy.set_text(label, text.clone()) {
13343                        Ok(()) => break,
13344                        Err(TaskSendError::Full) => thread::yield_now(),
13345                        Err(TaskSendError::Closed) => panic!("channel closed early"),
13346                    }
13347                }
13348                worker_posted.fetch_add(1, Ordering::SeqCst);
13349            }
13350        });
13351
13352        // Drain while the worker posts: the queue saturates and recovers, and
13353        // no command may be lost, duplicated, or applied re-entrantly
13354        // (commands posted while a drain is in flight are applied by the
13355        // next drain, never inside the current one).
13356        let mut applied = 0usize;
13357        while applied < TOTAL {
13358            let report = ui.drain_task_commands();
13359            assert_eq!(report.rejected, 0, "every command targets a live label");
13360            applied += report.applied;
13361            thread::yield_now();
13362        }
13363        worker.join().expect("worker thread");
13364
13365        assert_eq!(posted.load(Ordering::SeqCst), TOTAL);
13366        assert_eq!(applied, TOTAL, "exactly-once delivery");
13367        assert_eq!(ui.drain_task_commands().total(), 0, "queue drained");
13368        assert_eq!(
13369            ui.widget(label).and_then(|spec| spec.text.clone()),
13370            Some(format!("tick-{}", TOTAL - 1)),
13371            "single producer is FIFO, so the last post wins"
13372        );
13373
13374        assert_acyclic_parentage(&ui);
13375        assert_mock_mirror_is_exact(&ui);
13376    }
13377
13378    /// Lifecycle completion tokens survive a saturated
13379    /// bounded queue, the way the lossy/lossless taxonomy promises.
13380    ///
13381    /// The worker provably saturates the 256-slot queue first (the 257th
13382    /// lossy telemetry post reports `Full`), then runs 500 tasks whose
13383    /// `Finished` tokens all travel through `send_lossless` while the UI
13384    /// thread drains. Every token must arrive exactly once, in task order,
13385    /// and telemetry may drop without ever stranding the state machine.
13386    #[test]
13387    #[cfg(feature = "async")]
13388    fn lifecycle_tokens_survive_a_saturated_task_queue() {
13389        use crate::async_ui::{TaskId, TaskSendError};
13390        use std::sync::mpsc::channel;
13391        use std::time::{Duration, Instant};
13392
13393        let backend = MockBackend::default();
13394        let mut ui = Ui::new(backend);
13395        let proxy = ui.task_proxy();
13396        let capacity = proxy.capacity();
13397
13398        const TASKS: usize = 500;
13399        const SAMPLES_PER_TASK: usize = 3;
13400
13401        let (saturated_tx, saturated_rx) = channel();
13402        let worker_proxy = proxy.clone();
13403        let worker = std::thread::spawn(move || {
13404            // Phase 1: deterministic saturation. Filling within capacity must
13405            // succeed; the next lossy sample must report Full.
13406            let filler = worker_proxy.start_task();
13407            for index in 0..capacity {
13408                worker_proxy
13409                    .progress(&filler, index as f64)
13410                    .expect("filling within capacity");
13411            }
13412            assert_eq!(
13413                worker_proxy.progress(&filler, f64::MAX),
13414                Err(TaskSendError::Full),
13415                "the queue must be saturated here"
13416            );
13417            saturated_tx.send(()).expect("signal saturation");
13418
13419            // The filler's own completion is sent while the queue is still
13420            // saturated: the lossless path waits for the UI thread to drain.
13421            worker_proxy
13422                .finish_lossless(&filler, Duration::from_secs(10))
13423                .expect("the filler task completes losslessly too");
13424
13425            // Phase 2: 500 task lifecycles. Telemetry may be skipped under
13426            // pressure; every completion token is sent losslessly.
13427            let mut dropped_samples = 0usize;
13428            for _ in 0..TASKS {
13429                let token = worker_proxy.start_task();
13430                for _ in 0..SAMPLES_PER_TASK {
13431                    if worker_proxy.progress(&token, 1.0).is_err() {
13432                        dropped_samples += 1;
13433                    }
13434                }
13435                worker_proxy
13436                    .finish_lossless(&token, Duration::from_secs(10))
13437                    .expect("lifecycle token must survive queue saturation");
13438            }
13439            dropped_samples
13440        });
13441
13442        saturated_rx.recv().expect("worker saturated the queue");
13443
13444        // Drain everything; the deadline turns a missed token into a clear
13445        // failure instead of a hanging test.
13446        let deadline = Instant::now() + Duration::from_secs(20);
13447        let mut finished = Vec::new();
13448        while finished.len() < TASKS + 1 {
13449            while let Some(event) = ui.poll_event().expect("poll") {
13450                if let UiEvent::Task(TaskEvent::Finished { task }) = event {
13451                    finished.push(task);
13452                }
13453            }
13454            assert!(
13455                Instant::now() < deadline,
13456                "only {} of {} completion tokens arrived before the deadline",
13457                finished.len(),
13458                TASKS + 1
13459            );
13460            std::thread::yield_now();
13461        }
13462        let _dropped_samples = worker.join().expect("worker thread");
13463
13464        // Every completion token arrived exactly once, in per-producer order
13465        // (task ids are minted 1..=TASKS+1 by this single worker).
13466        let expected: Vec<TaskId> = (1..=TASKS as u64 + 1).map(TaskId).collect();
13467        assert_eq!(
13468            finished, expected,
13469            "completion tokens must arrive exactly once, in order"
13470        );
13471        assert_eq!(ui.drain_task_commands().total(), 0, "queue drained");
13472    }
13473
13474    #[test]
13475    #[cfg(feature = "widgets-text")]
13476    fn set_text_completion_items_records_on_text_inputs_only() {
13477        let backend = MockBackend::default();
13478        let mut ui = Ui::new(backend);
13479
13480        let input = ui.create(WidgetKind::TextInput, Some("alp")).unwrap();
13481        let area = ui.create(WidgetKind::TextArea, Some("alp")).unwrap();
13482        let label = ui.create(WidgetKind::Label, Some("plain")).unwrap();
13483
13484        ui.set_text_completion_items(input, &["alpha".to_owned()])
13485            .expect("TextInput accepts completion items");
13486        assert_eq!(
13487            ui.widget(input).unwrap().completion_items,
13488            vec!["alpha".to_owned()]
13489        );
13490        assert_eq!(
13491            ui.backend().created.get(&input).unwrap().completion_items,
13492            vec!["alpha".to_owned()],
13493            "the shared spec and the Mock record agree"
13494        );
13495
13496        // TextArea and Label stay outside the applicability row, and the
13497        // refusal is transactional on both sides.
13498        for widget in [area, label] {
13499            let before = ui.widget(widget).cloned();
13500            let error = ui
13501                .set_text_completion_items(widget, &["nope".to_owned()])
13502                .expect_err("completion is TextInput-only");
13503            assert_eq!(
13504                error,
13505                GuiError::UnsupportedWidget("set_text_completion_items")
13506            );
13507            assert_eq!(ui.widget(widget).cloned(), before);
13508            assert!(ui.widget(widget).unwrap().completion_items.is_empty());
13509        }
13510    }
13511
13512    #[test]
13513    fn hidden_widget_in_container_does_not_take_layout_space_and_has_zero_dimension() {
13514        let backend = MockBackend::default();
13515        let mut ui = Ui::new(backend);
13516
13517        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
13518        let column = ui
13519            .create(WidgetKind::Container, Some("col"))
13520            .expect("column");
13521        ui.set_container_direction(column, ContainerDirection::Vertical)
13522            .expect("vertical");
13523
13524        let item1 = ui.create(WidgetKind::Label, Some("item1")).expect("item1");
13525        ui.set_size(item1, 200, 30).expect("item1 size");
13526
13527        #[cfg(feature = "widgets-pickers")]
13528        let chooser = ui
13529            .create(WidgetKind::FileChooserDialog, Some("hidden_chooser"))
13530            .expect("chooser");
13531        #[cfg(not(feature = "widgets-pickers"))]
13532        let chooser = ui
13533            .create(WidgetKind::Button, Some("hidden_chooser"))
13534            .expect("chooser");
13535        ui.set_size(chooser, 200, 40).expect("chooser size");
13536
13537        let item2 = ui.create(WidgetKind::Label, Some("item2")).expect("item2");
13538        ui.set_size(item2, 200, 30).expect("item2 size");
13539
13540        ui.attach(window, column).expect("attach column");
13541        ui.attach(column, item1).expect("attach item1");
13542        ui.attach(column, chooser).expect("attach chooser");
13543        ui.attach(column, item2).expect("attach item2");
13544
13545        // Hide chooser before computing layout
13546        ui.hide(chooser).expect("hide chooser");
13547        assert!(!ui.is_visible(chooser));
13548        assert!(ui.is_visible(item1));
13549        assert!(ui.is_visible(item2));
13550
13551        ui.compute_layout(window, 400.0, 300.0)
13552            .expect("layout pass");
13553
13554        // Hidden chooser must have zero dimension
13555        assert_eq!(
13556            ui.widget(chooser).and_then(|spec| spec.size),
13557            Some((0, 0)),
13558            "hidden widget must report zero dimension in computed size"
13559        );
13560        let chooser_node = *ui.layout_nodes.get(&chooser).expect("layout node");
13561        let chooser_layout = ui.layout_tree.layout(chooser_node).expect("layout");
13562        assert_eq!(chooser_layout.width, 0.0);
13563        assert_eq!(chooser_layout.height, 0.0);
13564
13565        // item2 must not be displaced by the hidden chooser
13566        let item1_y = ui
13567            .widget(item1)
13568            .and_then(|spec| spec.position)
13569            .map(|pos| pos.1)
13570            .unwrap_or(0);
13571        let item2_y = ui
13572            .widget(item2)
13573            .and_then(|spec| spec.position)
13574            .map(|pos| pos.1)
13575            .unwrap_or(0);
13576        assert_eq!(item1_y, 0);
13577        assert_eq!(
13578            item2_y, 30,
13579            "item2 must follow immediately after item1 without space taken by hidden chooser"
13580        );
13581
13582        // Re-showing the chooser restores its layout participation
13583        ui.show(chooser).expect("show chooser");
13584        assert!(ui.is_visible(chooser));
13585        ui.compute_layout(window, 400.0, 300.0)
13586            .expect("layout pass");
13587
13588        assert_eq!(
13589            ui.widget(chooser).and_then(|spec| spec.size),
13590            Some((200, 40)),
13591            "visible chooser restores its size"
13592        );
13593        let item2_y_after = ui
13594            .widget(item2)
13595            .and_then(|spec| spec.position)
13596            .map(|pos| pos.1)
13597            .unwrap_or(0);
13598        assert_eq!(
13599            item2_y_after, 70,
13600            "item2 must now be placed after item1 (30) + chooser (40)"
13601        );
13602    }
13603
13604    #[test]
13605    fn warm_layout_pass_restores_flow_geometry_after_set_position() {
13606        let backend = MockBackend::default();
13607        let mut ui = Ui::new(backend);
13608        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
13609        let column = ui.create(WidgetKind::Container, None).expect("column");
13610        ui.set_container_direction(column, ContainerDirection::Vertical)
13611            .expect("vertical");
13612        ui.attach(window, column).expect("column");
13613        let label = ui.create(WidgetKind::Label, Some("row")).expect("label");
13614        ui.attach(column, label).expect("label");
13615
13616        ui.compute_layout(window, 640.0, 480.0).expect("cold pass");
13617        let computed = ui.widget(label).and_then(|spec| spec.position);
13618        ui.set_position(label, 123, 45)
13619            .expect("imperative position");
13620        assert_eq!(
13621            ui.widget(label).and_then(|spec| spec.position),
13622            Some((123, 45))
13623        );
13624
13625        // Skipping the write-back on a warm pass must not let an
13626        // imperative position outlive the flow pass that owns it.
13627        ui.compute_layout(window, 640.0, 480.0).expect("warm pass");
13628        assert_eq!(
13629            ui.widget(label).and_then(|spec| spec.position),
13630            computed,
13631            "a layout pass restores computed flow geometry"
13632        );
13633    }
13634
13635    /// Lays out eight 24 px labels and a row of buttons in a window far too
13636    /// short for them, with or without a backend compression floor.
13637    /// Label rects and button rects as `(y, height)` / `(x, width)` pairs.
13638    type ColumnRects = (Vec<(i32, i32)>, Vec<(i32, i32)>);
13639
13640    fn compressed_column(floor: Option<(i32, i32)>) -> ColumnRects {
13641        let mut ui = Ui::new(CustomMeasuringBackend {
13642            inner: MockBackend::with_natural_sizes(),
13643            compressed_floor: floor,
13644            ..CustomMeasuringBackend::default()
13645        });
13646        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
13647        let column = ui.create(WidgetKind::Container, None).expect("column");
13648        ui.set_container_direction(column, ContainerDirection::Vertical)
13649            .expect("column direction");
13650        ui.attach(window, column).expect("attach column");
13651        let mut labels = Vec::new();
13652        for index in 0..8 {
13653            let label = ui
13654                .create(WidgetKind::Label, Some(&format!("Row {index}")))
13655                .expect("label");
13656            ui.attach(column, label).expect("attach label");
13657            labels.push(label);
13658        }
13659        let row = ui.create(WidgetKind::Container, None).expect("row");
13660        ui.set_container_direction(row, ContainerDirection::Horizontal)
13661            .expect("row direction");
13662        ui.attach(column, row).expect("attach row");
13663        let mut buttons = Vec::new();
13664        for text in ["New", "Save", "Undo", "Redo", "Clear"] {
13665            let button = ui.create(WidgetKind::Button, Some(text)).expect("button");
13666            ui.attach(row, button).expect("attach button");
13667            buttons.push(button);
13668        }
13669        ui.compute_layout(window, 120.0, 64.0).expect("layout");
13670        let rows = labels
13671            .iter()
13672            .map(|id| {
13673                let spec = ui.widget(*id).expect("label spec");
13674                (
13675                    spec.position.unwrap_or((0, 0)).1,
13676                    spec.size.unwrap_or((0, 0)).1,
13677                )
13678            })
13679            .collect();
13680        let cols = buttons
13681            .iter()
13682            .map(|id| {
13683                let spec = ui.widget(*id).expect("button spec");
13684                (
13685                    spec.position.unwrap_or((0, 0)).0,
13686                    spec.size.unwrap_or((0, 0)).0,
13687                )
13688            })
13689            .collect();
13690        (rows, cols)
13691    }
13692
13693    #[test]
13694    fn compression_floor_keeps_quantized_leaves_from_overlapping() {
13695        // Without a floor the shared pass compresses leaves to fit (desktop
13696        // behaviour): eight labels share 64 px, so each is far below 16 px.
13697        let (rows, _) = compressed_column(None);
13698        assert!(
13699            rows.iter().any(|(_, h)| *h < 16),
13700            "default lanes still compress: {rows:?}"
13701        );
13702
13703        // A lane that declares a 16 px floor (TUI: one cell row) never gets
13704        // a leaf shorter than the floor or a sibling that starts above the
13705        // previous one's bottom edge, and row leaves keep their floor width.
13706        let (rows, cols) = compressed_column(Some((40, 16)));
13707        let mut bottom = i32::MIN;
13708        for (y, h) in &rows {
13709            assert!(*h >= 16, "leaf compressed below the floor: {rows:?}");
13710            assert!(*y >= bottom, "siblings overlap: {rows:?}");
13711            bottom = y + h;
13712        }
13713        let mut right = i32::MIN;
13714        for (x, w) in &cols {
13715            assert!(*w >= 40, "row leaf compressed below the floor: {cols:?}");
13716            assert!(*x >= right, "row siblings overlap: {cols:?}");
13717            right = x + w;
13718        }
13719    }
13720
13721    #[test]
13722    fn creation_time_parent_attaches_through_the_backend() {
13723        let mut ui = Ui::new(CustomMeasuringBackend::default());
13724        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
13725        let child = ui
13726            .create_with(WidgetKind::Label, |spec| {
13727                spec.text = Some("child".to_owned());
13728                spec.parent = Some(window);
13729            })
13730            .expect("create with parent");
13731
13732        // GTK and Cocoa build the native control unparented, so the shared
13733        // model may only record the edge after the lane accepted it.
13734        assert_eq!(ui.backend().add_child_calls, 1);
13735        assert_eq!(ui.widget(child).and_then(|spec| spec.parent), Some(window));
13736        assert_eq!(
13737            ui.children_index.get(&window),
13738            Some(&vec![child]),
13739            "exactly one edge is recorded"
13740        );
13741        assert_eq!(ui.layout_nodes.len(), ui.widget_count());
13742    }
13743
13744    #[test]
13745    fn creation_time_parent_must_exist_before_any_widget_is_created() {
13746        let mut ui = Ui::new(CustomMeasuringBackend::default());
13747        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
13748        let before = ui.widget_count();
13749
13750        let error = ui
13751            .create_with(WidgetKind::Label, |spec| {
13752                spec.parent = Some(WidgetId(999));
13753            })
13754            .expect_err("a missing parent is refused like attach does");
13755        assert_eq!(error, GuiError::WidgetNotFound(999));
13756        assert_eq!(ui.widget_count(), before, "no orphan widget is created");
13757        assert_eq!(ui.layout_nodes.len(), before, "no orphan layout node");
13758        assert!(
13759            !ui.children_index.contains_key(&WidgetId(999)),
13760            "a refused creation records no edge"
13761        );
13762        assert_eq!(
13763            ui.backend().created.len(),
13764            before,
13765            "nothing reached the lane"
13766        );
13767
13768        // The valid parent still works afterwards.
13769        let child = ui
13770            .create_with(WidgetKind::Label, |spec| spec.parent = Some(window))
13771            .expect("valid creation-time parent");
13772        assert_eq!(ui.widget(child).and_then(|spec| spec.parent), Some(window));
13773    }
13774
13775    #[test]
13776    fn refused_creation_time_attachment_rolls_the_widget_back() {
13777        let backend = CustomMeasuringBackend {
13778            reject_add_child: true,
13779            ..CustomMeasuringBackend::default()
13780        };
13781        let mut ui = Ui::new(backend);
13782        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
13783        let before = ui.widget_count();
13784
13785        let error = ui
13786            .create_with(WidgetKind::Label, |spec| spec.parent = Some(window))
13787            .expect_err("the lane refuses the attachment");
13788        assert!(matches!(error, GuiError::Backend(_)));
13789        assert_eq!(ui.widget_count(), before, "the widget is rolled back");
13790        assert_eq!(ui.layout_nodes.len(), before);
13791        assert_eq!(
13792            ui.backend().created.len(),
13793            before,
13794            "the refused native widget is removed"
13795        );
13796        assert!(!ui.children_index.contains_key(&window) || ui.children_index[&window].is_empty());
13797    }
13798
13799    #[test]
13800    fn refused_attach_and_reparent_leave_the_previous_edge_in_place() {
13801        let backend = CustomMeasuringBackend {
13802            reject_add_child: true,
13803            ..CustomMeasuringBackend::default()
13804        };
13805        let mut ui = Ui::new(backend);
13806        // Attach the fixture first; the rejection is switched on only for
13807        // the calls under test.
13808        ui.backend_mut().reject_add_child = false;
13809        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
13810        let first = ui
13811            .create(WidgetKind::Container, Some("first"))
13812            .expect("first");
13813        let second = ui
13814            .create(WidgetKind::Container, Some("second"))
13815            .expect("second");
13816        let child = ui.create(WidgetKind::Label, Some("child")).expect("child");
13817        ui.attach(window, first).expect("window -> first");
13818        ui.attach(window, second).expect("window -> second");
13819        ui.backend_mut().reject_add_child = true;
13820
13821        let error = ui.attach(first, child).expect_err("attach is refused");
13822        assert!(matches!(error, GuiError::Backend(_)));
13823        assert_eq!(
13824            ui.widget(child).and_then(|spec| spec.parent),
13825            None,
13826            "a refused attach must not claim a parent"
13827        );
13828        assert!(
13829            !ui.children_index
13830                .get(&first)
13831                .is_some_and(|children| children.contains(&child)),
13832            "a refused attach must not record an index edge"
13833        );
13834
13835        // The same rollback holds for a reparent.
13836        ui.backend_mut().reject_add_child = false;
13837        ui.attach(second, child).expect("seed the old edge");
13838        ui.backend_mut().reject_add_child = true;
13839        let error = ui.reparent(child, first).expect_err("reparent is refused");
13840        assert!(matches!(error, GuiError::Backend(_)));
13841        assert_eq!(
13842            ui.widget(child).and_then(|spec| spec.parent),
13843            Some(second),
13844            "the previous parent edge survives a refused reparent"
13845        );
13846        assert!(ui.children_index[&second].contains(&child));
13847        assert!(!ui
13848            .children_index
13849            .get(&first)
13850            .is_some_and(|children| children.contains(&child)));
13851    }
13852
13853    #[test]
13854    fn refused_row_writes_leave_the_spec_rows_untouched() {
13855        let backend = CustomMeasuringBackend {
13856            reject_row_writes: true,
13857            ..CustomMeasuringBackend::default()
13858        };
13859        let mut ui = Ui::new(backend);
13860        let list = ui.create(WidgetKind::DataList, Some("list")).expect("list");
13861        ui.set_data_list_items(list, &["seed".to_owned()])
13862            .expect_err("the lane refuses row writes");
13863        assert!(
13864            ui.widget(list).expect("spec").data_list_items.is_empty(),
13865            "a refused list write stores nothing"
13866        );
13867
13868        let grid = ui.create(WidgetKind::DataGrid, None).expect("grid");
13869        let error = ui
13870            .set_data_grid_rows(grid, &[vec!["a".to_owned()]])
13871            .expect_err("the lane refuses grid rows");
13872        assert!(matches!(error, GuiError::Backend(_)));
13873        assert!(
13874            ui.widget(grid).expect("spec").data_grid_rows.is_empty(),
13875            "a refused grid write stores nothing"
13876        );
13877
13878        // Acceptance stores the value in both places.
13879        ui.backend_mut().reject_row_writes = false;
13880        ui.set_data_list_items(list, &["seed".to_owned()])
13881            .expect("accepted");
13882        assert_eq!(
13883            ui.widget(list).expect("spec").data_list_items,
13884            vec!["seed".to_owned()]
13885        );
13886    }
13887
13888    #[test]
13889    fn refused_keyed_row_writes_leave_spec_selection_and_baseline_untouched() {
13890        let backend = CustomMeasuringBackend {
13891            reject_row_writes: false,
13892            ..CustomMeasuringBackend::default()
13893        };
13894        let mut ui = Ui::new(backend);
13895        let list = ui.create(WidgetKind::DataList, Some("list")).expect("list");
13896        let initial_rows = vec![RowSet::new(1, &["row1"]), RowSet::new(2, &["row2"])];
13897        ui.set_rows_keyed(list, &initial_rows).expect("initial set");
13898        ui.set_selected_index(list, 0).expect("select first");
13899        assert_eq!(ui.widget(list).expect("spec").selected_index, Some(0));
13900        assert_eq!(ui.selected_row_key(list), Some(RowKey(1)));
13901
13902        // Refused row write: attempting to update to rows where RowKey(1) is removed.
13903        // Previously this cleared the selection before failing the row write.
13904        ui.backend_mut().reject_row_writes = true;
13905        let new_rows = vec![RowSet::new(2, &["row2_updated"]), RowSet::new(3, &["row3"])];
13906        let err = ui
13907            .set_rows_keyed(list, &new_rows)
13908            .expect_err("refused row write");
13909        assert!(matches!(err, GuiError::Backend(_)));
13910
13911        // Selection, rows, and keyed baseline must all be untouched!
13912        assert_eq!(
13913            ui.widget(list).expect("spec").selected_index,
13914            Some(0),
13915            "selection index remains intact"
13916        );
13917        assert_eq!(
13918            ui.selected_row_key(list),
13919            Some(RowKey(1)),
13920            "selected row key remains intact"
13921        );
13922        assert_eq!(
13923            ui.widget(list).expect("spec").data_list_items,
13924            vec!["row1".to_string(), "row2".to_string()],
13925            "data_list_items remains untouched"
13926        );
13927    }
13928
13929    #[test]
13930    fn remove_drops_window_callbacks_and_theme_overrides() {
13931        let backend = MockBackend::default();
13932        let mut ui = Ui::new(backend);
13933        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
13934        ui.on_window_close(window, || {}).expect("close callback");
13935        ui.on_window_resize(window, |_, _| {})
13936            .expect("resize callback");
13937        let _ = ui.set_theme_override(window, ThemeOverride::Padding(4));
13938
13939        ui.remove(window).expect("remove");
13940        assert!(!ui.on_window_close.contains_key(&window));
13941        assert!(!ui.on_window_resize.contains_key(&window));
13942        assert!(!ui.theme_overrides.contains_key(&window));
13943        assert!(ui.widgets.is_empty());
13944    }
13945
13946    #[test]
13947    fn unchanged_window_layout_pass_reuses_the_cached_root() {
13948        let backend = MockBackend::default();
13949        let mut ui = Ui::new(backend);
13950        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
13951        let column = ui.create(WidgetKind::Container, None).expect("column");
13952        ui.set_container_direction(column, ContainerDirection::Vertical)
13953            .expect("vertical");
13954        ui.attach(window, column).expect("attach column");
13955        for _ in 0..8 {
13956            let label = ui.create(WidgetKind::Label, Some("row")).expect("label");
13957            ui.attach(column, label).expect("attach label");
13958        }
13959
13960        ui.compute_layout(window, 640.0, 480.0)
13961            .expect("initial pass");
13962        let hits = ui.layout_tree.metrics().cache_hits;
13963        let misses = ui.layout_tree.metrics().cache_misses;
13964        let solves = ui.layout_tree.metrics().solves;
13965        let style_updates = ui.layout_tree.metrics().style_updates;
13966        let geometry: Vec<Option<(i32, i32)>> =
13967            ui.widgets.values().map(|spec| spec.position).collect();
13968
13969        // Neither the Window normalization nor the child
13970        // normalization may rewrite an unchanged style, and the write-back
13971        // scan is skipped entirely on a root cache hit.
13972        ui.compute_layout(window, 640.0, 480.0)
13973            .expect("second pass");
13974        let metrics = ui.layout_tree.metrics();
13975        assert_eq!(metrics.cache_hits, hits + 1, "the second pass is a hit");
13976        assert_eq!(metrics.cache_misses, misses, "no solve on the second pass");
13977        assert_eq!(metrics.solves, solves + 1);
13978        assert_eq!(
13979            metrics.style_updates, style_updates,
13980            "an unchanged pass must not rewrite layout styles"
13981        );
13982        let geometry_after: Vec<Option<(i32, i32)>> =
13983            ui.widgets.values().map(|spec| spec.position).collect();
13984        assert_eq!(geometry_after, geometry, "cached geometry is unchanged");
13985
13986        // A real resize still has to solve.
13987        ui.compute_layout(window, 641.0, 480.0)
13988            .expect("resize pass");
13989        assert_eq!(
13990            ui.layout_tree.metrics().cache_misses,
13991            misses + 1,
13992            "a size change is a cache miss"
13993        );
13994    }
13995
13996    #[test]
13997    #[cfg(feature = "widgets-containers")]
13998    fn empty_or_childless_tabs_preserves_minimum_height_in_compute_layout() {
13999        let backend = MockBackend::default();
14000        let mut ui = Ui::new(backend);
14001
14002        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
14003        let column = ui
14004            .create(WidgetKind::Container, Some("col"))
14005            .expect("column");
14006        ui.set_container_direction(column, ContainerDirection::Vertical)
14007            .expect("vertical");
14008
14009        // 1. Childless Tabs widget
14010        let tabs = ui.create(WidgetKind::Tabs, None).expect("tabs");
14011        let following = ui.create(WidgetKind::Label, Some("below")).expect("label");
14012        ui.set_size(following, 200, 20).expect("following size");
14013
14014        ui.attach(window, column).expect("attach column");
14015        ui.attach(column, tabs).expect("attach tabs");
14016        ui.attach(column, following).expect("attach following");
14017
14018        ui.compute_layout(window, 500.0, 400.0)
14019            .expect("layout pass");
14020
14021        let tabs_size = ui
14022            .widget(tabs)
14023            .and_then(|spec| spec.size)
14024            .expect("tabs size");
14025        assert!(
14026            tabs_size.1 >= MIN_TABS_HEIGHT as i32,
14027            "childless tabs must preserve minimum height ({}), got {}",
14028            MIN_TABS_HEIGHT,
14029            tabs_size.1
14030        );
14031        let tabs_node = *ui.layout_nodes.get(&tabs).expect("layout node");
14032        let tabs_layout = ui.layout_tree.layout(tabs_node).expect("layout");
14033        assert!(
14034            tabs_layout.height >= MIN_TABS_HEIGHT,
14035            "childless tabs layout height must be >= {}, got {}",
14036            MIN_TABS_HEIGHT,
14037            tabs_layout.height
14038        );
14039        let following_y = ui
14040            .widget(following)
14041            .and_then(|spec| spec.position)
14042            .map(|p| p.1)
14043            .unwrap_or(0);
14044        assert!(
14045            following_y >= MIN_TABS_HEIGHT as i32,
14046            "following widget y offset must be >= tabs minimum height, got {}",
14047            following_y
14048        );
14049
14050        // 2. Tabs widget with empty container pages (WYSIWYG editor pattern)
14051        let page1 = ui.create(WidgetKind::Container, None).expect("page1");
14052        let page2 = ui.create(WidgetKind::Container, None).expect("page2");
14053        ui.attach(tabs, page1).expect("attach page1");
14054        ui.attach(tabs, page2).expect("attach page2");
14055
14056        ui.compute_layout(window, 500.0, 400.0)
14057            .expect("layout pass with empty pages");
14058
14059        let tabs_size_pages = ui
14060            .widget(tabs)
14061            .and_then(|spec| spec.size)
14062            .expect("tabs size with pages");
14063        assert!(
14064            tabs_size_pages.1 >= MIN_TABS_HEIGHT as i32,
14065            "tabs with empty container pages must preserve minimum height ({}), got {}",
14066            MIN_TABS_HEIGHT,
14067            tabs_size_pages.1
14068        );
14069        let following_y_pages = ui
14070            .widget(following)
14071            .and_then(|spec| spec.position)
14072            .map(|p| p.1)
14073            .unwrap_or(0);
14074        assert!(
14075            following_y_pages >= MIN_TABS_HEIGHT as i32,
14076            "following widget y offset must remain >= tabs minimum height with empty pages, got {}",
14077            following_y_pages
14078        );
14079    }
14080
14081    /// Every `Tabs` page gets the whole `Tabs` box, so a page's
14082    /// vertical stack keeps each control on its own row instead of the pages
14083    /// splitting the width and shrinking their children to the strip height
14084    /// (the TUI / Win32 Preferences "Restore last session" and "Check for
14085    /// updates" overprint).
14086    #[test]
14087    #[cfg(all(feature = "widgets-containers", feature = "widgets-choice"))]
14088    fn tabs_pages_fill_the_tabs_box_and_keep_their_rows_apart() {
14089        for with_min in [true, false] {
14090            let mut ui = Ui::new(MockBackend::with_natural_sizes());
14091            let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
14092            let root = ui.create(WidgetKind::Container, None).expect("root");
14093            ui.set_container_direction(root, ContainerDirection::Vertical)
14094                .expect("vertical");
14095            ui.attach(window, root).expect("attach root");
14096            let tabs = ui.create(WidgetKind::Tabs, None).expect("tabs");
14097            ui.attach(root, tabs).expect("attach tabs");
14098            if with_min {
14099                ui.set_min_size(tabs, 600, 300).expect("tabs min");
14100            }
14101            let mut pages = Vec::new();
14102            let mut rows = Vec::new();
14103            for _ in 0..3 {
14104                let page = ui.create(WidgetKind::Container, None).expect("page");
14105                ui.set_container_direction(page, ContainerDirection::Vertical)
14106                    .expect("page vertical");
14107                ui.set_container_gap(page, 10).expect("page gap");
14108                ui.attach(tabs, page).expect("attach page");
14109                for text in ["Restore last session", "Check for updates", "Theme"] {
14110                    let check = ui
14111                        .create(WidgetKind::Checkbox, Some(text))
14112                        .expect("checkbox");
14113                    ui.attach(page, check).expect("attach checkbox");
14114                    rows.push((page, check));
14115                }
14116                pages.push(page);
14117            }
14118            ui.compute_layout(window, 640.0, 480.0).expect("layout");
14119            let (tabs_w, tabs_h) = ui
14120                .widget(tabs)
14121                .and_then(|spec| spec.size)
14122                .expect("tabs size");
14123            let first = ui
14124                .widget(pages[0])
14125                .and_then(|spec| spec.size)
14126                .expect("page size");
14127            for &page in &pages {
14128                let (w, h) = ui
14129                    .widget(page)
14130                    .and_then(|spec| spec.size)
14131                    .expect("page size");
14132                assert_eq!(
14133                    (w, h),
14134                    first,
14135                    "every page gets the same box (min={with_min})"
14136                );
14137                assert_eq!(h, tabs_h, "page fills the Tabs height (min={with_min})");
14138                // Pages never split the Tabs width between them.
14139                assert!(
14140                    w * 2 > tabs_w && w <= tabs_w,
14141                    "page width {w} vs Tabs {tabs_w} (min={with_min})"
14142                );
14143            }
14144            for page in pages {
14145                let mut bottom = 0;
14146                for &(_, check) in rows.iter().filter(|(owner, _)| *owner == page) {
14147                    let spec = ui.widget(check).expect("checkbox spec");
14148                    let (_, y) = spec.position.expect("checkbox position");
14149                    let (_, h) = spec.size.expect("checkbox size");
14150                    assert!(h >= 24, "checkbox keeps its natural height, got {h}");
14151                    assert!(
14152                        y >= bottom,
14153                        "checkbox rows overlap: y={y} < previous bottom {bottom}"
14154                    );
14155                    bottom = y + h;
14156                }
14157            }
14158        }
14159    }
14160
14161    #[derive(Debug, Default)]
14162    struct CustomMeasuringBackend {
14163        inner: MockBackend,
14164        tabs_natural_height: Option<i32>,
14165        compressed_floor: Option<(i32, i32)>,
14166        reject_file_drop: bool,
14167        reject_add_child: bool,
14168        reject_row_writes: bool,
14169        reject_theme: bool,
14170        reject_theme_override: bool,
14171        add_child_calls: usize,
14172    }
14173
14174    impl std::ops::Deref for CustomMeasuringBackend {
14175        type Target = MockBackend;
14176        fn deref(&self) -> &Self::Target {
14177            &self.inner
14178        }
14179    }
14180
14181    impl std::ops::DerefMut for CustomMeasuringBackend {
14182        fn deref_mut(&mut self) -> &mut Self::Target {
14183            &mut self.inner
14184        }
14185    }
14186
14187    impl TextMeasure for CustomMeasuringBackend {
14188        fn measure_text(
14189            &self,
14190            widget_id: crate::widgets::WidgetId,
14191            known_dimensions: crate::layout::Size<Option<f32>>,
14192            available_space: crate::layout::Size<crate::layout::AvailableSpace>,
14193        ) -> Option<crate::layout::Size<f32>> {
14194            self.inner
14195                .measure_text(widget_id, known_dimensions, available_space)
14196        }
14197    }
14198
14199    impl Backend for CustomMeasuringBackend {
14200        type NativeHandle = <MockBackend as Backend>::NativeHandle;
14201
14202        fn natural_size(&self, widget_id: WidgetId) -> Option<(i32, i32)> {
14203            #[cfg(feature = "widgets-containers")]
14204            if let Some(h) = self.tabs_natural_height {
14205                if self.inner.created.get(&widget_id).map(|s| s.kind) == Some(WidgetKind::Tabs) {
14206                    return Some((200, h));
14207                }
14208            }
14209            self.inner.natural_size(widget_id)
14210        }
14211
14212        fn min_compressed_size(&self, _widget_id: WidgetId) -> Option<(i32, i32)> {
14213            self.compressed_floor
14214        }
14215
14216        fn create_widget(&mut self, spec: &WidgetSpec) -> GuiResult<()> {
14217            self.inner.create_widget(spec)
14218        }
14219        fn create_menu(&mut self, menu_id: MenuId) -> GuiResult<()> {
14220            self.inner.create_menu(menu_id)
14221        }
14222        fn add_submenu(
14223            &mut self,
14224            parent_id: MenuId,
14225            submenu_id: MenuId,
14226            slot_id: MenuItemId,
14227            text: &str,
14228        ) -> GuiResult<()> {
14229            self.inner.add_submenu(parent_id, submenu_id, slot_id, text)
14230        }
14231        fn create_menu_item(
14232            &mut self,
14233            menu_id: MenuId,
14234            item_id: MenuItemId,
14235            text: &str,
14236            shortcut: Option<&str>,
14237        ) -> GuiResult<()> {
14238            self.inner
14239                .create_menu_item(menu_id, item_id, text, shortcut)
14240        }
14241        fn attach_menu_to_window(&mut self, window_id: WidgetId, menu_id: MenuId) -> GuiResult<()> {
14242            self.inner.attach_menu_to_window(window_id, menu_id)
14243        }
14244        fn attach_context_menu(&mut self, widget_id: WidgetId, menu_id: MenuId) -> GuiResult<()> {
14245            self.inner.attach_context_menu(widget_id, menu_id)
14246        }
14247        fn set_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
14248            self.inner.set_text(widget_id, text)
14249        }
14250        fn set_checked(&mut self, widget_id: WidgetId, checked: bool) -> GuiResult<()> {
14251            self.inner.set_checked(widget_id, checked)
14252        }
14253        fn set_value(&mut self, widget_id: WidgetId, value: i32) -> GuiResult<()> {
14254            self.inner.set_value(widget_id, value)
14255        }
14256        fn set_range(&mut self, widget_id: WidgetId, min: i32, max: i32) -> GuiResult<()> {
14257            self.inner.set_range(widget_id, min, max)
14258        }
14259        fn set_step(&mut self, widget_id: WidgetId, step: i32) -> GuiResult<()> {
14260            self.inner.set_step(widget_id, step)
14261        }
14262        fn set_selected_index(&mut self, widget_id: WidgetId, index: usize) -> GuiResult<()> {
14263            self.inner.set_selected_index(widget_id, index)
14264        }
14265        fn set_tab_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()> {
14266            self.inner.set_tab_items(widget_id, items)
14267        }
14268        fn set_selected_indices(
14269            &mut self,
14270            widget_id: WidgetId,
14271            indices: &[usize],
14272        ) -> GuiResult<()> {
14273            self.inner.set_selected_indices(widget_id, indices)
14274        }
14275        fn set_row_drag(
14276            &mut self,
14277            widget_id: WidgetId,
14278            source: bool,
14279            target: bool,
14280        ) -> GuiResult<()> {
14281            self.inner.set_row_drag(widget_id, source, target)
14282        }
14283        fn set_file_drop_target(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
14284            if self.reject_file_drop && enabled {
14285                return Err(GuiError::UnsupportedCapability("drag_file_drop".to_owned()));
14286            }
14287            self.inner.set_file_drop_target(widget_id, enabled)
14288        }
14289        fn set_size(&mut self, widget_id: WidgetId, width: i32, height: i32) -> GuiResult<()> {
14290            self.inner.set_size(widget_id, width, height)
14291        }
14292        fn set_min_size(&mut self, widget_id: WidgetId, width: i32, height: i32) -> GuiResult<()> {
14293            self.inner.set_min_size(widget_id, width, height)
14294        }
14295        fn set_data_list_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()> {
14296            if self.reject_row_writes {
14297                return Err(GuiError::Backend("row write refused".to_owned()));
14298            }
14299            self.inner.set_data_list_items(widget_id, items)
14300        }
14301        fn apply_row_delta(
14302            &mut self,
14303            widget_id: WidgetId,
14304            ops: &[crate::widgets::RowOp],
14305        ) -> GuiResult<()> {
14306            if self.reject_row_writes {
14307                return Err(GuiError::Backend("row write refused".to_owned()));
14308            }
14309            self.inner.apply_row_delta(widget_id, ops)
14310        }
14311        fn set_data_grid_rows(
14312            &mut self,
14313            widget_id: WidgetId,
14314            rows: Arc<Vec<Vec<String>>>,
14315        ) -> GuiResult<()> {
14316            if self.reject_row_writes {
14317                return Err(GuiError::Backend("row write refused".to_owned()));
14318            }
14319            self.inner.set_data_grid_rows(widget_id, rows)
14320        }
14321        fn set_data_grid_model(
14322            &mut self,
14323            widget_id: WidgetId,
14324            model: Box<dyn crate::widgets::DataGridModel>,
14325        ) -> GuiResult<()> {
14326            self.inner.set_data_grid_model(widget_id, model)
14327        }
14328        fn set_data_grid_row_height(
14329            &mut self,
14330            widget_id: WidgetId,
14331            row: usize,
14332            height: i32,
14333        ) -> GuiResult<()> {
14334            self.inner.set_data_grid_row_height(widget_id, row, height)
14335        }
14336        fn set_data_grid_col_width(
14337            &mut self,
14338            widget_id: WidgetId,
14339            col: usize,
14340            width: i32,
14341        ) -> GuiResult<()> {
14342            self.inner.set_data_grid_col_width(widget_id, col, width)
14343        }
14344        fn set_data_grid_frozen_panes(
14345            &mut self,
14346            widget_id: WidgetId,
14347            rows: usize,
14348            cols: usize,
14349        ) -> GuiResult<()> {
14350            self.inner.set_data_grid_frozen_panes(widget_id, rows, cols)
14351        }
14352        fn set_data_grid_selection(
14353            &mut self,
14354            widget_id: WidgetId,
14355            selection: &[(usize, usize)],
14356        ) -> GuiResult<()> {
14357            self.inner.set_data_grid_selection(widget_id, selection)
14358        }
14359        fn set_tree_items(&mut self, widget_id: WidgetId, items: &[TreeItem]) -> GuiResult<()> {
14360            self.inner.set_tree_items(widget_id, items)
14361        }
14362        fn set_position(&mut self, widget_id: WidgetId, x: i32, y: i32) -> GuiResult<()> {
14363            self.inner.set_position(widget_id, x, y)
14364        }
14365        fn set_background_color(&mut self, widget_id: WidgetId, color: Color) -> GuiResult<()> {
14366            self.inner.set_background_color(widget_id, color)
14367        }
14368        fn set_alert_level(&mut self, widget_id: WidgetId, level: AlertLevel) -> GuiResult<()> {
14369            self.inner.set_alert_level(widget_id, level)
14370        }
14371        fn set_image_source(&mut self, widget_id: WidgetId, source: &str) -> GuiResult<()> {
14372            self.inner.set_image_source(widget_id, source)
14373        }
14374        fn set_date_value(&mut self, widget_id: WidgetId, iso_date: &str) -> GuiResult<()> {
14375            self.inner.set_date_value(widget_id, iso_date)
14376        }
14377        fn set_link_url(&mut self, widget_id: WidgetId, url: &str) -> GuiResult<()> {
14378            self.inner.set_link_url(widget_id, url)
14379        }
14380        fn set_container_direction(
14381            &mut self,
14382            widget_id: WidgetId,
14383            direction: ContainerDirection,
14384        ) -> GuiResult<()> {
14385            self.inner.set_container_direction(widget_id, direction)
14386        }
14387        fn set_container_scroll(
14388            &mut self,
14389            widget_id: WidgetId,
14390            vertical: bool,
14391            horizontal: bool,
14392        ) -> GuiResult<()> {
14393            self.inner
14394                .set_container_scroll(widget_id, vertical, horizontal)
14395        }
14396        fn set_container_gap(&mut self, widget_id: WidgetId, gap: i32) -> GuiResult<()> {
14397            self.inner.set_container_gap(widget_id, gap)
14398        }
14399        fn set_container_padding(&mut self, widget_id: WidgetId, padding: i32) -> GuiResult<()> {
14400            self.inner.set_container_padding(widget_id, padding)
14401        }
14402        fn draw_demo_cube(&mut self, widget_id: WidgetId) -> GuiResult<()> {
14403            self.inner.draw_demo_cube(widget_id)
14404        }
14405        fn create_gpu_fallback(
14406            &mut self,
14407            spec: &WidgetSpec,
14408            policy: GpuDegradationPolicy,
14409        ) -> GuiResult<()> {
14410            self.inner.create_gpu_fallback(spec, policy)
14411        }
14412        fn gpu_surface_capabilities(&self) -> GpuSurfaceCapabilities {
14413            self.inner.gpu_surface_capabilities()
14414        }
14415        fn set_canvas_scene(
14416            &mut self,
14417            widget_id: WidgetId,
14418            scene: &crate::CanvasScene,
14419        ) -> GuiResult<()> {
14420            self.inner.set_canvas_scene(widget_id, scene)
14421        }
14422        fn native_handle(&self, widget_id: WidgetId) -> GuiResult<Self::NativeHandle> {
14423            self.inner.native_handle(widget_id)
14424        }
14425        fn metal_canvas_handle(&self, widget_id: WidgetId) -> GuiResult<MetalCanvasHandle> {
14426            self.inner.metal_canvas_handle(widget_id)
14427        }
14428        fn add_child(&mut self, parent: WidgetId, child: WidgetId) -> GuiResult<()> {
14429            self.add_child_calls += 1;
14430            if self.reject_add_child {
14431                return Err(GuiError::Backend("attach refused".to_owned()));
14432            }
14433            self.inner.add_child(parent, child)
14434        }
14435        fn show(&mut self, widget_id: WidgetId) -> GuiResult<()> {
14436            self.inner.show(widget_id)
14437        }
14438        fn hide(&mut self, widget_id: WidgetId) -> GuiResult<()> {
14439            self.inner.hide(widget_id)
14440        }
14441        fn remove(&mut self, widget_id: WidgetId) -> GuiResult<()> {
14442            self.inner.remove(widget_id)
14443        }
14444        fn set_enabled(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
14445            self.inner.set_enabled(widget_id, enabled)
14446        }
14447        fn activate(&mut self, widget_id: WidgetId) -> GuiResult<()> {
14448            self.inner.activate(widget_id)
14449        }
14450        fn data_dir(&self) -> GuiResult<PathBuf> {
14451            self.inner.data_dir()
14452        }
14453        fn set_tooltip(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
14454            self.inner.set_tooltip(widget_id, text)
14455        }
14456        fn poll_event(&mut self) -> GuiResult<Option<UiEvent>> {
14457            self.inner.poll_event()
14458        }
14459        fn wait_event(&mut self) -> GuiResult<UiEvent> {
14460            self.inner.wait_event()
14461        }
14462        fn show_confirm_dialog(&mut self, token: u64, title: &str, message: &str) -> GuiResult<()> {
14463            self.inner.show_confirm_dialog(token, title, message)
14464        }
14465        fn set_theme(&mut self, theme: &Theme) -> GuiResult<()> {
14466            if self.reject_theme {
14467                return Err(GuiError::Backend("theme rejected".to_owned()));
14468            }
14469            self.inner.set_theme(theme)
14470        }
14471        fn set_theme_override(
14472            &mut self,
14473            widget_id: WidgetId,
14474            theme_override: ThemeOverride,
14475        ) -> GuiResult<()> {
14476            if self.reject_theme_override {
14477                return Err(GuiError::Backend("theme override rejected".to_owned()));
14478            }
14479            self.inner.set_theme_override(widget_id, theme_override)
14480        }
14481        fn clear_theme_overrides(&mut self, widget_id: WidgetId) -> GuiResult<()> {
14482            if self.reject_theme_override {
14483                return Err(GuiError::Backend(
14484                    "clear theme override rejected".to_owned(),
14485                ));
14486            }
14487            self.inner.clear_theme_overrides(widget_id)
14488        }
14489    }
14490
14491    #[test]
14492    fn tray_default_stubs_return_unsupported_capability() {
14493        let mut ui = Ui::new(CustomMeasuringBackend::default());
14494        assert_eq!(
14495            ui.create_tray_icon("Test"),
14496            Err(GuiError::UnsupportedCapability("tray_icon".to_string()))
14497        );
14498        assert_eq!(
14499            ui.destroy_tray_icon(TrayIconId(1)),
14500            Err(GuiError::UnsupportedCapability("tray_icon".to_string()))
14501        );
14502        assert_eq!(
14503            ui.set_tray_icon_tooltip(TrayIconId(1), "Tip"),
14504            Err(GuiError::UnsupportedCapability("tray_icon".to_string()))
14505        );
14506        assert_eq!(
14507            ui.set_tray_icon_menu(TrayIconId(1), None),
14508            Err(GuiError::UnsupportedCapability("tray_icon".to_string()))
14509        );
14510        assert_eq!(
14511            ui.set_tray_icon_visible(TrayIconId(1), true),
14512            Err(GuiError::UnsupportedCapability("tray_icon".to_string()))
14513        );
14514        assert_eq!(
14515            ui.create_tray_icon_with_icon("Test", vec![1, 2, 3, 4]),
14516            Err(GuiError::UnsupportedCapability("tray_icon".to_string()))
14517        );
14518        assert_eq!(
14519            ui.set_tray_icon_icon(TrayIconId(1), Some(vec![1, 2, 3, 4])),
14520            Err(GuiError::UnsupportedCapability("tray_icon".to_string()))
14521        );
14522    }
14523
14524    #[test]
14525    #[cfg(feature = "widgets-containers")]
14526    fn tabs_strip_respects_dynamic_natural_height_from_backend() {
14527        // 1. Natural height 44px (e.g. touch/large typography floor)
14528        let backend = CustomMeasuringBackend {
14529            inner: MockBackend::default(),
14530            tabs_natural_height: Some(44),
14531            reject_file_drop: false,
14532            ..CustomMeasuringBackend::default()
14533        };
14534        let mut ui = Ui::new(backend);
14535
14536        let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
14537        let column = ui
14538            .create(WidgetKind::Container, Some("col"))
14539            .expect("column");
14540        ui.set_container_direction(column, ContainerDirection::Vertical)
14541            .expect("vertical");
14542
14543        let tabs = ui.create(WidgetKind::Tabs, None).expect("tabs");
14544        let following = ui.create(WidgetKind::Label, Some("below")).expect("label");
14545        ui.set_size(following, 200, 20).expect("following size");
14546
14547        ui.attach(window, column).expect("attach column");
14548        ui.attach(column, tabs).expect("attach tabs");
14549        ui.attach(column, following).expect("attach following");
14550
14551        // Verify min_tabs_height and tabs_min_height return 44.0
14552        assert_eq!(ui.min_tabs_height(tabs), 44.0);
14553        assert_eq!(ui.tabs_min_height(tabs), 44.0);
14554
14555        ui.compute_layout(window, 500.0, 400.0)
14556            .expect("layout pass");
14557
14558        let tabs_size = ui
14559            .widget(tabs)
14560            .and_then(|spec| spec.size)
14561            .expect("tabs size");
14562        assert!(
14563            tabs_size.1 >= 44,
14564            "tabs with natural height 44px must preserve dynamic floor (got {})",
14565            tabs_size.1
14566        );
14567        let tabs_node = *ui.layout_nodes.get(&tabs).expect("layout node");
14568        let tabs_layout = ui.layout_tree.layout(tabs_node).expect("layout");
14569        assert!(
14570            tabs_layout.height >= 44.0,
14571            "layout height must respect 44.0 floor instead of clamping to 30.0 (got {})",
14572            tabs_layout.height
14573        );
14574        let following_y = ui
14575            .widget(following)
14576            .and_then(|spec| spec.position)
14577            .map(|p| p.1)
14578            .unwrap_or(0);
14579        assert!(
14580            following_y >= 44,
14581            "following widget y offset must be >= 44 (got {})",
14582            following_y
14583        );
14584
14585        // 2. Tabs with empty container pages and 36px natural height
14586        let backend36 = CustomMeasuringBackend {
14587            inner: MockBackend::default(),
14588            tabs_natural_height: Some(36),
14589            reject_file_drop: false,
14590            ..CustomMeasuringBackend::default()
14591        };
14592        let mut ui36 = Ui::new(backend36);
14593        let window36 = ui36.create(WidgetKind::Window, Some("w")).expect("window");
14594        let column36 = ui36
14595            .create(WidgetKind::Container, Some("col"))
14596            .expect("column");
14597        ui36.set_container_direction(column36, ContainerDirection::Vertical)
14598            .expect("vertical");
14599
14600        let tabs36 = ui36.create(WidgetKind::Tabs, None).expect("tabs");
14601        let page1 = ui36.create(WidgetKind::Container, None).expect("page1");
14602        let page2 = ui36.create(WidgetKind::Container, None).expect("page2");
14603        ui36.attach(tabs36, page1).expect("attach page1");
14604        ui36.attach(tabs36, page2).expect("attach page2");
14605
14606        let following36 = ui36
14607            .create(WidgetKind::Label, Some("below"))
14608            .expect("label");
14609        ui36.set_size(following36, 200, 20).expect("following size");
14610
14611        ui36.attach(window36, column36).expect("attach column");
14612        ui36.attach(column36, tabs36).expect("attach tabs");
14613        ui36.attach(column36, following36)
14614            .expect("attach following");
14615
14616        assert_eq!(ui36.min_tabs_height(tabs36), 36.0);
14617        ui36.compute_layout(window36, 500.0, 400.0)
14618            .expect("layout pass 36");
14619
14620        let tabs36_size = ui36
14621            .widget(tabs36)
14622            .and_then(|spec| spec.size)
14623            .expect("tabs size");
14624        assert!(
14625            tabs36_size.1 >= 36,
14626            "tabs with empty pages and 36px natural height must preserve 36px floor (got {})",
14627            tabs36_size.1
14628        );
14629        let following36_y = ui36
14630            .widget(following36)
14631            .and_then(|spec| spec.position)
14632            .map(|p| p.1)
14633            .unwrap_or(0);
14634        assert!(
14635            following36_y >= 36,
14636            "following widget y offset must be >= 36 (got {})",
14637            following36_y
14638        );
14639
14640        // 3. Fallback when natural size is None or <= 0
14641        let backend_none = CustomMeasuringBackend {
14642            inner: MockBackend::default(),
14643            tabs_natural_height: None,
14644            reject_file_drop: false,
14645            ..CustomMeasuringBackend::default()
14646        };
14647        let ui_none = Ui::new(backend_none);
14648        let tabs_none = WidgetId(42);
14649        assert_eq!(ui_none.min_tabs_height(tabs_none), MIN_TABS_HEIGHT);
14650
14651        let backend_zero = CustomMeasuringBackend {
14652            inner: MockBackend::default(),
14653            tabs_natural_height: Some(0),
14654            reject_file_drop: false,
14655            ..CustomMeasuringBackend::default()
14656        };
14657        let ui_zero = Ui::new(backend_zero);
14658        assert_eq!(ui_zero.min_tabs_height(tabs_none), MIN_TABS_HEIGHT);
14659    }
14660
14661    #[test]
14662    fn perf_010_subtree_teardown_scales_linearly_below_3x_ratio() {
14663        let n1 = 1500;
14664        let n2 = 3000;
14665
14666        let mut ui1 = Ui::new(MockBackend::default());
14667        let parent1 = ui1.create(WidgetKind::Container, None).expect("container");
14668        for i in 0..n1 {
14669            let child = ui1
14670                .create_with(WidgetKind::Label, |spec| {
14671                    spec.text = Some(format!("c{}", i));
14672                    spec.parent = Some(parent1);
14673                })
14674                .expect("child");
14675            let _ = child;
14676        }
14677
14678        let mut ui2 = Ui::new(MockBackend::default());
14679        let parent2 = ui2.create(WidgetKind::Container, None).expect("container");
14680        for i in 0..n2 {
14681            let child = ui2
14682                .create_with(WidgetKind::Label, |spec| {
14683                    spec.text = Some(format!("c{}", i));
14684                    spec.parent = Some(parent2);
14685                })
14686                .expect("child");
14687            let _ = child;
14688        }
14689
14690        let start1 = std::time::Instant::now();
14691        ui1.remove(parent1).expect("remove parent1");
14692        let dur1 = start1.elapsed().as_nanos().max(1);
14693
14694        let start2 = std::time::Instant::now();
14695        ui2.remove(parent2).expect("remove parent2");
14696        let dur2 = start2.elapsed().as_nanos().max(1);
14697
14698        let ratio = (dur2 as f64) / (dur1 as f64);
14699        let limit = crate::test_budget::teardown_ratio_limit();
14700        assert!(
14701            ratio < limit,
14702            "Teardown ratio for 2N vs N must scale linearly (< {limit}x vs 4x+ quadratic), got {ratio:.2}x (dur1={dur1}ns, dur2={dur2}ns)"
14703        );
14704        assert!(ui1.widgets.is_empty());
14705        assert!(ui2.widgets.is_empty());
14706    }
14707
14708    #[test]
14709    fn perf_014_leaf_attachment_short_circuits_cycle_check_and_detects_genuine_cycle() {
14710        let mut ui = Ui::new(MockBackend::default());
14711        let root = ui.create(WidgetKind::Window, None).expect("window");
14712        let mut current_parent = root;
14713
14714        // Build a chain of 100 containers
14715        for _ in 0..100 {
14716            let next = ui.create(WidgetKind::Container, None).expect("container");
14717            ui.attach(current_parent, next)
14718                .expect("attach next to parent");
14719            current_parent = next;
14720        }
14721
14722        // Attaching a newly created leaf child to the bottom of the 100-node chain is O(1)
14723        let leaf = ui.create(WidgetKind::Label, None).expect("label");
14724        let start = std::time::Instant::now();
14725        ui.attach(current_parent, leaf).expect("attach leaf");
14726        let elapsed = start.elapsed();
14727        // O(1) leaf check should take well under 100 microseconds locally
14728        // (typically under 5 us). CI gets the shared duration multiplier.
14729        let limit = crate::test_budget::duration_budget(std::time::Duration::from_micros(500));
14730        assert!(
14731            elapsed < limit,
14732            "Leaf attach took too long: {elapsed:?} (limit {limit:?})"
14733        );
14734
14735        // However, attempting to close a cycle (making root a child of current_parent) is rejected
14736        let cycle_err = ui.attach(current_parent, root);
14737        assert!(cycle_err.is_err(), "Cycle attachment must be rejected");
14738    }
14739
14740    #[test]
14741    fn perf_015_set_text_replaces_without_cloning_and_rolls_back_on_error() {
14742        let mut ui = Ui::new(MockBackend::default());
14743        let label = ui
14744            .create_with(WidgetKind::Label, |spec| {
14745                spec.text = Some("Initial".to_string());
14746            })
14747            .expect("label");
14748
14749        // Happy path: text is updated
14750        ui.set_text(label, "Updated").expect("set_text");
14751        assert_eq!(ui.widget(label).unwrap().text.as_deref(), Some("Updated"));
14752
14753        // Rollback on invalid NUL character
14754        let err = ui.set_text(label, "Bad\0String");
14755        assert!(err.is_err());
14756        assert_eq!(ui.widget(label).unwrap().text.as_deref(), Some("Updated"));
14757    }
14758
14759    #[test]
14760    fn bug_007_refusing_backend_preserves_theme_and_overrides() {
14761        let backend = CustomMeasuringBackend {
14762            reject_theme: true,
14763            reject_theme_override: true,
14764            ..CustomMeasuringBackend::default()
14765        };
14766        let mut ui = Ui::new(backend);
14767        let button = ui.create(WidgetKind::Button, Some("Test")).expect("button");
14768
14769        // Initial theme is Light
14770        assert_eq!(ui.theme_mode(), ThemeMode::Light);
14771
14772        // Attempting to change theme when backend refuses must not alter ui.theme
14773        let err = ui.set_theme_mode(ThemeMode::Dark);
14774        assert!(err.is_err(), "refusing backend must error");
14775        assert_eq!(
14776            ui.theme_mode(),
14777            ThemeMode::Light,
14778            "theme must remain Light on error"
14779        );
14780
14781        // Attempting to set theme override when backend refuses must not alter theme_overrides
14782        let override_spec = ThemeOverride::Background(crate::Color::rgb(255, 0, 0));
14783        let err = ui.set_theme_override(button, override_spec);
14784        assert!(
14785            err.is_err(),
14786            "refusing backend must error on theme override"
14787        );
14788        assert!(
14789            ui.theme_overrides(button).is_empty(),
14790            "theme overrides must remain empty when backend rejects"
14791        );
14792    }
14793
14794    #[test]
14795    fn bug_005_max_layout_depth_boundary_test() {
14796        let mut ui = Ui::new(MockBackend::default());
14797        let root = ui.create(WidgetKind::Window, None).unwrap();
14798        let mut current = root;
14799
14800        // Chain up to depth 128 (root is level 1, child 1 is level 2, ..., child 127 is level 128)
14801        for _ in 1..crate::layout::box_sizing::MAX_LAYOUT_DEPTH {
14802            let next = ui.create(WidgetKind::Container, None).unwrap();
14803            ui.attach(current, next).expect("depth <= 128 accepted");
14804            current = next;
14805        }
14806
14807        // Current is at depth 127 (128 total nodes in path from root).
14808        // Adding one more node (child 128, level 129) must be refused!
14809        let extra = ui.create(WidgetKind::Container, None).unwrap();
14810        let err = ui.attach(current, extra);
14811        assert!(
14812            err.is_err(),
14813            "attaching beyond MAX_LAYOUT_DEPTH (128) must be refused"
14814        );
14815        match err {
14816            Err(GuiError::Backend(msg)) => {
14817                assert!(msg.contains("maximum layout recursion depth exceeded"));
14818            }
14819            other => panic!("expected GuiError::Backend, got {:?}", other),
14820        }
14821
14822        // Also test create_with with configured_parent at depth 127
14823        let extra_create = ui.create_with(WidgetKind::Container, |spec| {
14824            spec.parent = Some(current);
14825        });
14826        assert!(
14827            extra_create.is_err(),
14828            "create_with beyond MAX_LAYOUT_DEPTH must be refused"
14829        );
14830    }
14831
14832    #[test]
14833    #[cfg(feature = "widgets-text")]
14834    fn test_b1453_poll_and_wait_event_mirror_user_text_into_spec() {
14835        let backend = MockBackend::default();
14836        let mut ui = Ui::new(backend);
14837
14838        let input = ui
14839            .create(WidgetKind::TextInput, Some("initial"))
14840            .expect("create input");
14841        assert_eq!(ui.text(input).unwrap(), "initial");
14842
14843        // Test poll_event bookkeeping
14844        ui.backend_mut().push_event(UiEvent::TextChanged {
14845            widget_id: input,
14846            text: "edited_via_poll".to_string(),
14847        });
14848
14849        let event = ui.poll_event().expect("poll event").expect("event exists");
14850        assert!(matches!(event, UiEvent::TextChanged { .. }));
14851        assert_eq!(
14852            ui.text(input).unwrap(),
14853            "edited_via_poll",
14854            "poll_event must run pre_dispatch to mirror text"
14855        );
14856        assert_eq!(
14857            ui.widget(input).unwrap().text.as_deref(),
14858            Some("edited_via_poll")
14859        );
14860
14861        // Test wait_event bookkeeping
14862        ui.backend_mut().push_event(UiEvent::TextChanged {
14863            widget_id: input,
14864            text: "edited_via_wait".to_string(),
14865        });
14866
14867        let event = ui.wait_event().expect("wait event");
14868        assert!(matches!(event, UiEvent::TextChanged { .. }));
14869        assert_eq!(
14870            ui.text(input).unwrap(),
14871            "edited_via_wait",
14872            "wait_event must run pre_dispatch to mirror text"
14873        );
14874    }
14875
14876    #[test]
14877    fn test_b1453_poll_event_recomputes_layout_on_window_resized() {
14878        let backend = MockBackend::default();
14879        let mut ui = Ui::new(backend);
14880
14881        let window = ui
14882            .create(WidgetKind::Window, Some("Root"))
14883            .expect("create window");
14884        let btn = ui
14885            .create(WidgetKind::Button, Some("Action"))
14886            .expect("create btn");
14887        ui.attach(window, btn).expect("attach");
14888
14889        if let Some(&node) = ui.layout_nodes.get(&btn) {
14890            let style = crate::layout::Style {
14891                size: crate::layout::Size {
14892                    width: crate::layout::Dimension::length(50.0),
14893                    height: crate::layout::Dimension::length(25.0),
14894                },
14895                ..Default::default()
14896            };
14897            let _ = ui.layout_tree.set_style(node, style);
14898        }
14899
14900        ui.add_layout_root(window).expect("add layout root");
14901        assert_eq!(ui.widget(btn).and_then(|spec| spec.size), None);
14902
14903        ui.backend_mut().push_event(UiEvent::WindowResized {
14904            widget_id: window,
14905            width: 1024,
14906            height: 768,
14907        });
14908
14909        let event = ui.poll_event().expect("poll event").expect("event exists");
14910        assert!(matches!(event, UiEvent::WindowResized { .. }));
14911        assert_eq!(
14912            ui.widget(btn).and_then(|spec| spec.size),
14913            Some((50, 25)),
14914            "poll_event must run pre_dispatch to recompute layout root"
14915        );
14916    }
14917
14918    #[test]
14919    fn test_b1460_secondary_window_show_registers_layout_root_and_preserves_primary() {
14920        let backend = MockBackend::default();
14921        let mut ui = Ui::new(backend);
14922
14923        let window1 = ui.create(WidgetKind::Window, Some("Primary")).unwrap();
14924        let btn1 = ui.create(WidgetKind::Button, Some("Btn1")).unwrap();
14925        ui.attach(window1, btn1).unwrap();
14926        ui.set_size(window1, 800, 600).unwrap();
14927        ui.show(window1).unwrap();
14928
14929        assert!(ui.is_layout_root(window1));
14930
14931        let window2 = ui.create(WidgetKind::Window, Some("Secondary")).unwrap();
14932        let btn2 = ui.create(WidgetKind::Button, Some("Btn2")).unwrap();
14933        ui.attach(window2, btn2).unwrap();
14934        ui.set_size(window2, 400, 300).unwrap();
14935
14936        ui.show(window2).unwrap();
14937        assert!(ui.is_layout_root(window2));
14938        assert!(ui.is_layout_root(window1));
14939
14940        assert!(ui.layout_root_sizes.contains_key(&window1));
14941        assert!(ui.layout_root_sizes.contains_key(&window2));
14942    }
14943
14944    #[test]
14945    fn text_changed_updates_spec_text() {
14946        let backend = MockBackend::default();
14947        let mut ui = Ui::new(backend);
14948
14949        let input = ui
14950            .create(WidgetKind::TextInput, None)
14951            .expect("input should be created");
14952
14953        ui.backend_mut().push_event(UiEvent::TextChanged {
14954            widget_id: input,
14955            text: "new text".to_string(),
14956        });
14957
14958        ui.poll_event().expect("poll should succeed");
14959
14960        assert_eq!(
14961            ui.widgets.get(&input).expect("input spec exists").text,
14962            Some("new text".to_string())
14963        );
14964    }
14965
14966    #[test]
14967    fn window_resized_recomputes_layout_on_poll() {
14968        let backend = MockBackend::default();
14969        let mut ui = Ui::new(backend);
14970
14971        let window = ui
14972            .create(WidgetKind::Window, None)
14973            .expect("window should be created");
14974        ui.add_layout_root(window).expect("add layout root");
14975
14976        ui.backend_mut().push_event(UiEvent::WindowResized {
14977            widget_id: window,
14978            width: 800,
14979            height: 600,
14980        });
14981
14982        ui.poll_event().expect("poll should succeed");
14983
14984        // Assuming recompute_layout updates something we can check.
14985        // Looking at pre_dispatch: it calls compute_layout which updates layout_root_sizes.
14986        assert!(ui.layout_root_sizes.contains_key(&window));
14987    }
14988}