Skip to main content

xrack_runtime/
lib.rs

1//! Renderer-independent scene snapshots produced by generated components.
2
3/// Compatibility level expected by the Rust code emitted by xrackc.
4#[doc(hidden)]
5pub const CODEGEN_ABI_VERSION: u32 = 2;
6
7mod animation;
8mod arithmetic;
9mod button_group;
10mod calendar;
11mod callback;
12mod child_window;
13mod color_picker;
14mod combo;
15mod controls;
16mod delegate;
17mod double_spin;
18mod drag;
19mod event_loop;
20#[doc(hidden)]
21pub use event_loop::EventLoopRegistration;
22pub use event_loop::{EventLoopError, WeakComponent, invoke_from_event_loop};
23mod focus;
24mod font_picker;
25mod geometry;
26mod hover;
27mod image_animation;
28mod image_asset;
29mod keyboard;
30mod list;
31mod localization;
32mod model;
33mod native_dialog;
34mod picker;
35mod pointer;
36mod property;
37mod range;
38mod record;
39pub use record::{RecordList, RecordRowValidator, RecordValue};
40mod repeat;
41mod row_heights;
42mod scale_rotate;
43mod scene_plan;
44mod split;
45mod stack;
46mod styled_text;
47mod swipe_gesture;
48mod table_clipboard;
49mod table_history;
50mod table_rows;
51mod table_selection;
52mod text_input;
53mod time_picker;
54mod timer;
55mod tree;
56mod tumbler;
57mod viewport;
58mod window_status;
59pub use animation::{Animation, Easing, SceneTransition, StateTiming};
60#[doc(hidden)]
61pub use arithmetic::{int_divide, int_remainder, try_int_divide, try_int_remainder};
62#[doc(hidden)]
63pub use button_group::{
64    ButtonGroup, ButtonGroupMembership, ButtonGroupSelection, RadioMembership, bind_button_group,
65    bind_check_group, bind_dynamic_button_group, prepare_radio_selection, radio_value,
66    summarize_checks, try_prepare_radio_selection, try_summarize_checks,
67};
68pub use calendar::{CalendarAction, CalendarState, Date, is_calendar_control};
69#[doc(hidden)]
70pub use calendar::{
71    CalendarCell, CalendarCells, CalendarUpdate, DateBounds, DatePopupState, apply_calendar_action,
72    calendar_input_is_current, try_apply_calendar_action, try_calendar_input_is_current,
73};
74#[doc(hidden)]
75pub use callback::{CallbackAlreadyRunning, CallbackSlot, EffectfulCallback};
76#[doc(hidden)]
77pub use child_window::{SecondaryWindowCommand, SecondaryWindowRegistration, SecondaryWindowSlot};
78#[doc(hidden)]
79pub use color_picker::ColorPopupState;
80pub use combo::{
81    ChoiceIdentity, choice_enabled, choice_identity, combo_count, combo_find_enabled_label,
82    combo_find_label, combo_index, combo_label, combo_labels, combo_row_index, combo_row_key,
83    combo_text,
84};
85#[doc(hidden)]
86pub use combo::{
87    ComboEditor, ComboInput, ComboItems, ComboModel, ComboSelection, ComboSubmission, ComboUpdate,
88    combo_model_is_current, combo_submission, combo_value, prepare_combo_input,
89    try_prepare_combo_input,
90};
91pub use controls::{
92    ActionKey, ControlAction, DialogCommand, DialogRole, PopupPlacement, SpinAction, SpinRange,
93    StandardButtonKind, SwipeSide, TableColumnOrder, TableHeader, TableSort, button_text,
94    combo_editable, delay_millis, dialog_button_action, group_index, group_item, is_button,
95    is_modal_overlay, is_pane, is_spin_box, is_window_overlay, page_indicator_count,
96    page_indicator_index, resizable_table_column, resolve_swipe_index, search_suggestion,
97    search_suggestions, spin_editable, spin_text, spin_value_after, text_input_value,
98};
99#[doc(hidden)]
100pub use controls::{DialogEvent, set_overlay_open, try_resolve_swipe_index, try_set_overlay_open};
101#[doc(hidden)]
102pub use controls::{
103    SPIN_VIEW_PROPERTIES, prepare_spin_view, spin_view_is_current, try_prepare_spin_view,
104    try_spin_view_is_current,
105};
106#[doc(hidden)]
107pub use controls::{
108    delay_button_transition_is_current, group_selection_item, prepare_action_activation,
109    prepare_action_view, prepare_group_box_toggle, prepare_group_selection,
110    prepare_index_selection, prepare_row_toggle, prepare_source_selection, resize_table_column,
111    table_drag_available, try_delay_button_transition_is_current, try_prepare_action_activation,
112    try_prepare_action_view, try_prepare_group_box_toggle, try_prepare_group_selection,
113    try_prepare_index_selection, try_prepare_row_toggle, try_prepare_source_selection,
114    try_table_drag_available,
115};
116#[doc(hidden)]
117pub use delegate::{ComponentRepeater, RowContext};
118pub use double_spin::{
119    DecimalSpinRange, SpinDecimal, decimal_separator, decimal_spin_value_after, spin_text_is_valid,
120};
121pub use drag::{DragAction, DragEvent, is_drag_area};
122pub use focus::{
123    FocusAction, FocusContext, FocusEvent, FocusHandle, FocusReason, FocusRequest, FocusRequests,
124    TextCommand,
125};
126#[doc(hidden)]
127pub use focus::{FocusCommandMethod, is_focus_handler};
128pub use font_picker::Font;
129#[doc(hidden)]
130pub use font_picker::{FontPopupState, is_font_family_choice, set_font_family_choices};
131#[doc(hidden)]
132pub use geometry::{GeometryHandle, GeometryMetric};
133pub use hover::{CursorShape, HoverHandle};
134pub use image_animation::{ImageAnimation, ImageAnimationFrame};
135#[doc(hidden)]
136pub use image_animation::{ImagePlaybackQueue, ImagePlaybackRegistration, ImagePlaybackSlot};
137pub use image_asset::{ImageAsset, ImageIdentity, ImagePixels, LoadedAnimation, LoadedImage};
138pub use keyboard::{EventResult, KeyEvent, KeyModifiers, KeyPhase, WheelEvent};
139#[doc(hidden)]
140pub use list::ViewIndex;
141pub use list::{ListMetrics, RowKey};
142#[doc(hidden)]
143pub use list::{
144    ListModel, ListRowLocator, ListRowRenderer, RowLifetime, TableCellEditor, TableColumnWindow,
145    project_standard_table_rows, standard_list_rows, standard_list_rows_in_view,
146    standard_table_rows, standard_table_rows_in_order, standard_table_rows_with_editors_in_order,
147    standard_table_rows_with_header, try_project_standard_table_rows,
148};
149pub use localization::LocaleContext;
150#[doc(hidden)]
151pub use localization::{LocaleBinding, LocaleId, TranslationCatalog, TranslationValue};
152pub use model::VecModel;
153pub use native_dialog::{
154    FileDialogMode, FileDialogOptions, FileDialogSelection, MessageButtons, MessageDialogOptions,
155    MessageLevel,
156};
157#[doc(hidden)]
158pub use native_dialog::{
159    NativeDialogEvent, NativeDialogOptions, NativeDialogPresentation, NativeDialogQueue,
160    NativeDialogRegistration, NativeDialogResult, NativeDialogSlot,
161};
162pub use pointer::{
163    PointerButton, PointerButtons, PointerEvent, PointerEventKind, PointerHandle, TouchPoint,
164    TouchPoints,
165};
166#[doc(hidden)]
167pub use property::ComponentLifetime;
168pub use property::{ChangeSignal, InputProperty, Property};
169pub use range::{
170    DialInputMode, IndicatorState, RangeAction, ScrollBarRange, ScrollSnapMode, SliderInterval,
171    SliderRange, indicator_state, progress_value,
172};
173#[doc(hidden)]
174pub use range::{
175    RANGE_VIEW_PROPERTIES, prepare_range_view, range_view_properties, try_prepare_range_view,
176};
177#[doc(hidden)]
178pub use repeat::{Repeater, repeat_scene, static_repeat_scene};
179#[doc(hidden)]
180pub use row_heights::{RowHeightOverrides, RowHeightProjection, RowHeights};
181pub use scale_rotate::{ScaleRotateHandle, ScaleRotateSample};
182#[doc(hidden)]
183pub use scene_plan::{
184    GridCellPosition, GridCellSlot, GridPlanner, GridTrackInput, LoadedVectorPath, ScenePlanSlice,
185    StaticVectorPath, VectorSegment,
186};
187#[doc(hidden)]
188pub use split::{
189    SplitHandleInput, SplitResizeHandle, decode_split_sizes, decode_split_state,
190    encode_split_sizes, encode_split_state,
191};
192#[doc(hidden)]
193pub use stack::{StackChange, StackEvent, StackNavigationArgument, StackNavigationMethod};
194pub use stack::{StackNavigation, StackSnapshot, StackState};
195use std::{collections::BTreeMap, rc::Rc, sync::Arc};
196pub use styled_text::{StyledLink, StyledRun, StyledText, StyledTextError, TextStyle};
197pub use swipe_gesture::{SwipeHandle, SwipeSample};
198#[doc(hidden)]
199pub use table_clipboard::{
200    TablePaste, TablePasteInput, paste_table_text, table_paste_bool, table_paste_check_state,
201    table_paste_number, try_table_paste_number,
202};
203#[doc(hidden)]
204pub use table_history::{TableEditHistory, TablePasteHistory, TableRowPatch};
205pub use table_rows::{
206    TableCellEditTarget, TableEditPosition, TableRowOrder, TableRowPositions, TableRows,
207    next_table_edit_cell, next_table_edit_cell_in_view, next_table_edit_cell_in_view_if,
208    next_table_edit_cell_while_current, table_cell_edit_target, table_cell_edit_target_if,
209    try_history_replay_source, try_next_table_edit_cell, try_next_table_edit_cell_in_view,
210    try_next_table_edit_cell_while_current, try_prepare_history_replay, try_table_cell_edit_target,
211};
212pub use table_selection::{
213    RowSelection, SelectionTarget, TableSelection, TableSelectionAction, TableSelectionSnapshot,
214};
215#[doc(hidden)]
216pub use table_selection::{
217    TableSelectionChange, TableSelectionCommand, TableSelectionEvent, TableSelectionMethod,
218    TableSelectionOptions,
219};
220pub use table_selection::{
221    copy_table_text, copy_table_text_in_order, copy_table_text_in_view, copy_table_text_in_view_if,
222    copy_table_text_while_current, try_copy_table_text_in_order, try_copy_table_text_in_view,
223    try_copy_table_text_while_current,
224};
225pub use text_input::InputType;
226#[doc(hidden)]
227pub use text_input::{
228    SearchInput, SearchUpdate, text_submission_is_valid, try_text_submission_is_valid,
229};
230pub use time_picker::Time;
231#[doc(hidden)]
232pub use time_picker::{TimePickerOptions, TimePopupState};
233#[doc(hidden)]
234pub use timer::{
235    TimerCommand, TimerConfig, TimerDelivery, TimerQueue, TimerRegistration, TimerSlot, TimerTick,
236};
237pub use tree::{TreeAction, TreeCommand, TreeItem, TreeSelectionAction, TreeSnapshot, TreeState};
238#[doc(hidden)]
239pub use tree::{
240    TreeCommandMethod, TreeControlChange, TreeControlEvent, TreeExpansionChange,
241    TreeSelectionChange,
242};
243pub use tumbler::{Tumbler, TumblerItems};
244pub use viewport::{
245    ScrollAction, ScrollAlignment, ScrollContext, ScrollRequest, ScrollRequests, ViewportHandle,
246    ViewportMotion,
247};
248#[doc(hidden)]
249pub use viewport::{ScrollCommand, ScrollCommandMethod, SourceScroll};
250pub use window_status::{WindowCommand, WindowStatus};
251#[doc(hidden)]
252pub use window_status::{WindowCommandMethod, WindowLifecycle, WindowMetric, WindowStatusBinding};
253
254/// The backend-independent interface implemented by generated UI components.
255pub trait Component {
256    fn render(&self) -> Node;
257
258    /// Supply the language shared by the desktop hosting this component.
259    #[doc(hidden)]
260    fn set_locale_context(&self, _context: LocaleContext) {}
261
262    /// Return the current scene. Reactive components may reuse a clean snapshot.
263    fn render_shared(&self) -> Rc<Node> {
264        Rc::new(self.render())
265    }
266
267    /// Report invalidation caused by a shared reactive dependency.
268    fn scene_dirty(&self) -> bool {
269        false
270    }
271
272    /// Decide whether the host may close this window.
273    fn close_requested(&mut self) -> bool {
274        true
275    }
276
277    /// Consume a close command emitted by the component.
278    fn take_window_close_request(&mut self) -> bool {
279        false
280    }
281
282    /// Consume presentation commands in the order emitted by the component.
283    fn take_window_commands(&mut self) -> Vec<WindowCommand> {
284        Vec::new()
285    }
286
287    #[doc(hidden)]
288    fn has_window_commands(&self) -> bool {
289        false
290    }
291
292    /// Publish native state after reading it from the window backend.
293    fn publish_window_status(&self, _status: WindowStatus) {}
294
295    /// Native child windows currently requested by this component.
296    #[doc(hidden)]
297    fn secondary_windows(&self) -> Option<Rc<[SecondaryWindowRegistration]>> {
298        None
299    }
300
301    /// Render the requested model rows of a virtual view in the current base scene.
302    fn list_rows(&self, _path: &[usize], _rows: std::ops::Range<usize>) -> Vec<Node> {
303        Vec::new()
304    }
305
306    #[doc(hidden)]
307    fn next_table_edit_cell(
308        &self,
309        _scene: &Node,
310        _path: &[usize],
311        _origin: TableEditPosition,
312        _columns: &[usize],
313        _backward: bool,
314    ) -> Option<TableEditPosition> {
315        None
316    }
317
318    #[doc(hidden)]
319    fn copy_table_at(&self, _scene: &Node, _path: &[usize], _columns: &[usize]) -> Option<String> {
320        None
321    }
322
323    #[doc(hidden)]
324    fn route_table_query(
325        &self,
326        scene: &Node,
327        path: &[usize],
328        input: InputRoute<'_>,
329    ) -> Option<TableQueryResult> {
330        let RoutedEvent::QueryTable(query) = *input.event() else {
331            return None;
332        };
333        match query {
334            TableQuery::Copy(columns) => self
335                .copy_table_at(scene, path, columns)
336                .map(TableQueryResult::Text),
337            TableQuery::NextEdit(query) => self
338                .next_table_edit_cell(scene, path, query.origin, query.columns, query.backward)
339                .map(TableQueryResult::Position),
340        }
341    }
342
343    #[doc(hidden)]
344    fn prepare_table_paste(
345        &self,
346        _scene: &Node,
347        _path: &[usize],
348        _row: usize,
349        _columns: Vec<usize>,
350    ) -> Option<TablePaste> {
351        None
352    }
353
354    #[doc(hidden)]
355    fn table_paste_stamp(&self, _scene: &Node, _path: &[usize]) -> Option<(u64, u64)> {
356        None
357    }
358
359    #[doc(hidden)]
360    fn replay_table_paste_at(&self, _scene: &Node, _path: &[usize], _redo: bool) -> bool {
361        false
362    }
363
364    #[doc(hidden)]
365    fn replay_table_edit_at(&self, scene: &Node, path: &[usize], redo: bool) -> bool {
366        self.replay_table_paste_at(scene, path, redo)
367    }
368
369    fn dispatch(&mut self, element_id: &str, event: &str) -> bool;
370
371    /// Commit the complete value of an editable text item after input validation.
372    fn edit_at(&mut self, _scene: &Node, _path: &[usize], _text: String) -> bool {
373        false
374    }
375
376    /// Commit a TableCell or TreeCell draft only if its model row and original value still match.
377    fn commit_table_cell(
378        &mut self,
379        _scene: &Node,
380        _path: &[usize],
381        _original: &str,
382        _text: String,
383    ) -> bool {
384        false
385    }
386
387    /// Apply a range control action through the same path used by pointer and keyboard input.
388    fn adjust_range_at(&mut self, _scene: &Node, _path: &[usize], _action: RangeAction) -> bool {
389        false
390    }
391
392    fn control_at(&mut self, _scene: &Node, _path: &[usize], _action: ControlAction) -> bool {
393        false
394    }
395
396    #[doc(hidden)]
397    fn drag_event_at(&mut self, _scene: &Node, _path: &[usize], _event: &DragEvent) -> bool {
398        false
399    }
400
401    #[doc(hidden)]
402    fn key_event_at(
403        &mut self,
404        _scene: &Node,
405        _path: &[usize],
406        _phase: KeyPhase,
407        _event: &KeyEvent,
408    ) -> EventResult {
409        EventResult::Reject
410    }
411
412    #[doc(hidden)]
413    fn focus_event_at(&mut self, _scene: &Node, _path: &[usize], _event: FocusEvent) -> bool {
414        false
415    }
416
417    #[doc(hidden)]
418    fn wheel_event_at(
419        &mut self,
420        _scene: &Node,
421        _path: &[usize],
422        _event: &WheelEvent,
423    ) -> EventResult {
424        EventResult::Reject
425    }
426
427    #[doc(hidden)]
428    fn pointer_event_at(&mut self, _scene: &Node, _path: &[usize], _event: &PointerEvent) -> bool {
429        false
430    }
431
432    #[doc(hidden)]
433    fn route_input(&mut self, scene: &Node, path: &[usize], input: InputRoute<'_>) -> bool {
434        input.event().apply(self, scene, path)
435    }
436
437    fn resize_split_at(
438        &mut self,
439        _scene: &Node,
440        _path: &[usize],
441        _weights: &[(usize, f32)],
442    ) -> bool {
443        false
444    }
445
446    fn resize_split_sizes_at(
447        &mut self,
448        _scene: &Node,
449        _path: &[usize],
450        _sizes: &[(usize, f32)],
451    ) -> bool {
452        false
453    }
454
455    /// Dispatch to the node hit by the backend. IDs may repeat in component instances.
456    fn dispatch_at(&mut self, scene: &Node, path: &[usize], event: &str) -> bool {
457        scene
458            .at_path(path)
459            .and_then(Node::element_id)
460            .is_some_and(|id| self.dispatch(id, event))
461    }
462}
463
464impl<T: Component + ?Sized> Component for Box<T> {
465    fn route_input(&mut self, scene: &Node, path: &[usize], input: InputRoute<'_>) -> bool {
466        (**self).route_input(scene, path, input)
467    }
468
469    fn render(&self) -> Node {
470        (**self).render()
471    }
472    fn set_locale_context(&self, context: LocaleContext) {
473        (**self).set_locale_context(context);
474    }
475    fn focus_event_at(&mut self, scene: &Node, path: &[usize], event: FocusEvent) -> bool {
476        (**self).focus_event_at(scene, path, event)
477    }
478    fn drag_event_at(&mut self, scene: &Node, path: &[usize], event: &DragEvent) -> bool {
479        (**self).drag_event_at(scene, path, event)
480    }
481    fn key_event_at(
482        &mut self,
483        scene: &Node,
484        path: &[usize],
485        phase: KeyPhase,
486        event: &KeyEvent,
487    ) -> EventResult {
488        (**self).key_event_at(scene, path, phase, event)
489    }
490    fn render_shared(&self) -> Rc<Node> {
491        (**self).render_shared()
492    }
493    fn scene_dirty(&self) -> bool {
494        (**self).scene_dirty()
495    }
496    fn close_requested(&mut self) -> bool {
497        (**self).close_requested()
498    }
499    fn take_window_close_request(&mut self) -> bool {
500        (**self).take_window_close_request()
501    }
502    fn take_window_commands(&mut self) -> Vec<WindowCommand> {
503        (**self).take_window_commands()
504    }
505    fn has_window_commands(&self) -> bool {
506        (**self).has_window_commands()
507    }
508    fn publish_window_status(&self, status: WindowStatus) {
509        (**self).publish_window_status(status);
510    }
511    fn secondary_windows(&self) -> Option<Rc<[SecondaryWindowRegistration]>> {
512        (**self).secondary_windows()
513    }
514
515    fn list_rows(&self, path: &[usize], rows: std::ops::Range<usize>) -> Vec<Node> {
516        (**self).list_rows(path, rows)
517    }
518
519    fn next_table_edit_cell(
520        &self,
521        scene: &Node,
522        path: &[usize],
523        origin: TableEditPosition,
524        columns: &[usize],
525        backward: bool,
526    ) -> Option<TableEditPosition> {
527        (**self).next_table_edit_cell(scene, path, origin, columns, backward)
528    }
529
530    fn copy_table_at(&self, scene: &Node, path: &[usize], columns: &[usize]) -> Option<String> {
531        (**self).copy_table_at(scene, path, columns)
532    }
533
534    fn route_table_query(
535        &self,
536        scene: &Node,
537        path: &[usize],
538        input: InputRoute<'_>,
539    ) -> Option<TableQueryResult> {
540        (**self).route_table_query(scene, path, input)
541    }
542
543    fn prepare_table_paste(
544        &self,
545        scene: &Node,
546        path: &[usize],
547        row: usize,
548        columns: Vec<usize>,
549    ) -> Option<TablePaste> {
550        (**self).prepare_table_paste(scene, path, row, columns)
551    }
552
553    fn table_paste_stamp(&self, scene: &Node, path: &[usize]) -> Option<(u64, u64)> {
554        (**self).table_paste_stamp(scene, path)
555    }
556
557    fn replay_table_paste_at(&self, scene: &Node, path: &[usize], redo: bool) -> bool {
558        (**self).replay_table_paste_at(scene, path, redo)
559    }
560
561    fn replay_table_edit_at(&self, scene: &Node, path: &[usize], redo: bool) -> bool {
562        (**self).replay_table_edit_at(scene, path, redo)
563    }
564
565    fn dispatch(&mut self, element_id: &str, event: &str) -> bool {
566        (**self).dispatch(element_id, event)
567    }
568
569    fn edit_at(&mut self, scene: &Node, path: &[usize], text: String) -> bool {
570        (**self).edit_at(scene, path, text)
571    }
572
573    fn commit_table_cell(
574        &mut self,
575        scene: &Node,
576        path: &[usize],
577        original: &str,
578        text: String,
579    ) -> bool {
580        (**self).commit_table_cell(scene, path, original, text)
581    }
582
583    fn adjust_range_at(&mut self, scene: &Node, path: &[usize], action: RangeAction) -> bool {
584        (**self).adjust_range_at(scene, path, action)
585    }
586
587    fn control_at(&mut self, scene: &Node, path: &[usize], action: ControlAction) -> bool {
588        (**self).control_at(scene, path, action)
589    }
590
591    fn resize_split_at(&mut self, scene: &Node, path: &[usize], weights: &[(usize, f32)]) -> bool {
592        (**self).resize_split_at(scene, path, weights)
593    }
594    fn resize_split_sizes_at(
595        &mut self,
596        scene: &Node,
597        path: &[usize],
598        sizes: &[(usize, f32)],
599    ) -> bool {
600        (**self).resize_split_sizes_at(scene, path, sizes)
601    }
602
603    fn dispatch_at(&mut self, scene: &Node, path: &[usize], event: &str) -> bool {
604        (**self).dispatch_at(scene, path, event)
605    }
606
607    fn wheel_event_at(&mut self, scene: &Node, path: &[usize], event: &WheelEvent) -> EventResult {
608        (**self).wheel_event_at(scene, path, event)
609    }
610
611    fn pointer_event_at(&mut self, scene: &Node, path: &[usize], event: &PointerEvent) -> bool {
612        (**self).pointer_event_at(scene, path, event)
613    }
614}
615
616#[doc(hidden)]
617#[derive(Clone, Copy)]
618pub struct TableEditNavigation<'a> {
619    pub origin: TableEditPosition,
620    pub columns: &'a [usize],
621    pub backward: bool,
622}
623
624#[doc(hidden)]
625#[derive(Clone, Copy)]
626pub enum TableQuery<'a> {
627    Copy(&'a [usize]),
628    NextEdit(TableEditNavigation<'a>),
629}
630
631impl TableQuery<'_> {
632    pub fn run(
633        self,
634        ui: &(impl Component + ?Sized),
635        scene: &Node,
636        path: &[usize],
637    ) -> Option<TableQueryResult> {
638        RoutedEvent::QueryTable(self)
639            .with_input(scene, path, |input| {
640                ui.route_table_query(scene, path, input)
641            })
642            .flatten()
643    }
644}
645
646#[doc(hidden)]
647pub enum TableQueryResult {
648    Text(String),
649    Position(TableEditPosition),
650}
651
652impl TableQueryResult {
653    pub fn text(self) -> Option<String> {
654        match self {
655            Self::Text(text) => Some(text),
656            Self::Position(_) => None,
657        }
658    }
659
660    pub fn position(self) -> Option<TableEditPosition> {
661        match self {
662            Self::Position(position) => Some(position),
663            Self::Text(_) => None,
664        }
665    }
666}
667
668#[doc(hidden)]
669pub enum RoutedEvent<'a> {
670    Dispatch(&'a str),
671    Edit(&'a str),
672    CommitCell { original: &'a str, text: &'a str },
673    PasteTable(TablePasteInput<'a>),
674    ReplayTable { redo: bool },
675    QueryTable(TableQuery<'a>),
676    Range(RangeAction),
677    Control(ControlAction),
678    Drag(&'a DragEvent),
679    Key(KeyPhase, &'a KeyEvent),
680    Wheel(&'a WheelEvent),
681    Pointer(&'a PointerEvent),
682    Focus(FocusEvent),
683    ResizeSplit(&'a [(usize, f32)]),
684    ResizeSplitSizes(&'a [(usize, f32)]),
685}
686
687/// Carries one availability check through all component instances on an input path.
688#[doc(hidden)]
689#[derive(Clone, Copy)]
690pub struct InputRoute<'a> {
691    event: &'a RoutedEvent<'a>,
692    reads: Option<&'a property::ReadWatch>,
693    root_visibility_overridden: bool,
694}
695
696impl<'a> InputRoute<'a> {
697    pub fn event(self) -> &'a RoutedEvent<'a> {
698        self.event
699    }
700
701    pub fn checks_availability(self) -> bool {
702        self.reads.is_some()
703    }
704
705    pub fn root_visibility_overridden(self) -> bool {
706        self.root_visibility_overridden
707    }
708
709    pub fn with_root_visibility_override(mut self, overridden: bool) -> Self {
710        self.root_visibility_overridden = overridden;
711        self
712    }
713
714    pub fn is_current(self) -> bool {
715        self.reads.is_none_or(|reads| !reads.changed())
716    }
717
718    pub fn can_open_drawer(self, node: &Node, is_target: bool) -> bool {
719        is_target
720            && node.kind == "Drawer"
721            && matches!(
722                self.event,
723                RoutedEvent::Control(ControlAction::Drawer(true))
724            )
725    }
726
727    pub fn try_available<E>(self, available: impl FnOnce() -> Result<bool, E>) -> Result<bool, E> {
728        match self.reads {
729            Some(reads) => Ok(!reads.changed() && available()? && !reads.changed()),
730            None => Ok(true),
731        }
732    }
733
734    pub fn available(self, available: impl FnOnce() -> bool) -> bool {
735        self.try_available(|| Ok::<_, std::convert::Infallible>(available()))
736            .unwrap_or_else(|error| match error {})
737    }
738
739    /// Only run preparation after availability checks pass and discard its result if input changes.
740    pub fn try_prepare<T, E>(
741        self,
742        available: impl FnOnce() -> Result<bool, E>,
743        prepare: impl FnOnce() -> Result<Option<T>, E>,
744    ) -> Result<Option<T>, E> {
745        if !self.try_available(available)? {
746            return Ok(None);
747        }
748        Ok(prepare()?.filter(|_| self.is_current()))
749    }
750
751    pub fn prepare<T>(
752        self,
753        available: impl FnOnce() -> bool,
754        prepare: impl FnOnce() -> Option<T>,
755    ) -> Option<T> {
756        self.try_prepare(
757            || Ok::<_, std::convert::Infallible>(available()),
758            || Ok(prepare()),
759        )
760        .unwrap_or_else(|error| match error {})
761    }
762}
763
764impl RoutedEvent<'_> {
765    fn is_input_cleanup(&self) -> bool {
766        match self {
767            Self::Focus(event) => event.is_loss(),
768            Self::Pointer(event) => event.kind == PointerEventKind::Cancel,
769            Self::Drag(event) => event.is_terminal(),
770            _ => false,
771        }
772    }
773
774    /// Cleanup events can follow an existing delegate to a new position.
775    pub fn follows_row(&self, scene: &Node, path: &[usize]) -> bool {
776        match self {
777            Self::Dispatch(event) => scene
778                .at_path(path)
779                .is_some_and(|node| node.terminal_dispatch(event)),
780            _ => self.is_input_cleanup(),
781        }
782    }
783
784    /// Resolve input against the scene that produced it.
785    pub fn input_target<'a>(&self, scene: &'a Node, path: &[usize]) -> Option<&'a Node> {
786        let target = || {
787            if self.is_input_cleanup() {
788                scene.at_path(path)
789            } else {
790                scene.interactive_at_path(path)
791            }
792        };
793        match self {
794            Self::Dispatch(event) => scene.dispatch_target(path, event),
795            Self::Control(action) => scene.control_target(path, *action),
796            Self::Range(_) => scene.range_target(path),
797            Self::CommitCell { original, .. } => scene.table_cell_commit_target(path, original),
798            Self::PasteTable(_) => scene
799                .interactive_at_path(path)
800                .filter(|node| node.kind == "TableView" && node.boolean("pasteable", false)),
801            Self::ReplayTable { .. } => {
802                scene.table_edit_history_model(path)?;
803                scene.at_path(path)
804            }
805            Self::QueryTable(query) => scene.interactive_at_path(path).filter(|node| {
806                node.kind == "TableView"
807                    && node.boolean(
808                        match query {
809                            TableQuery::Copy(_) => "copyable",
810                            TableQuery::NextEdit(_) => "edit-on-tab",
811                        },
812                        false,
813                    )
814            }),
815            Self::ResizeSplit(_) | Self::ResizeSplitSizes(_) => scene
816                .interactive_at_path(path)
817                .filter(|node| node.kind == "SplitView"),
818            Self::Edit(text) => scene
819                .interactive_at_path(path)
820                .filter(|node| node.accepts_editor_update(text)),
821            Self::Focus(event) => scene.focus_event_target(path, *event),
822            Self::Key(phase, _) => scene.key_event_target(path, *phase),
823            Self::Wheel(_) => scene
824                .interactive_at_path(path)
825                .filter(|node| node.handles_wheel()),
826            Self::Pointer(_) => target().filter(|node| node.pointer_handle.is_some()),
827            Self::Drag(event) => target().filter(|node| node.kind == event.target_kind()),
828        }
829    }
830
831    pub fn with_input<T>(
832        &self,
833        scene: &Node,
834        path: &[usize],
835        route: impl FnOnce(InputRoute<'_>) -> T,
836    ) -> Option<T> {
837        self.input_target(scene, path)?;
838        let input = InputRoute {
839            event: self,
840            reads: None,
841            root_visibility_overridden: false,
842        };
843        if self.follows_row(scene, path) {
844            Some(route(input))
845        } else {
846            Some(property::watch_reads(|reads| {
847                route(InputRoute {
848                    reads: Some(reads),
849                    ..input
850                })
851            }))
852        }
853    }
854
855    pub fn deliver_input(
856        &self,
857        ui: &mut (impl Component + ?Sized),
858        scene: &Node,
859        path: &[usize],
860    ) -> bool {
861        self.with_input(scene, path, |input| ui.route_input(scene, path, input))
862            .unwrap_or(false)
863    }
864
865    pub fn apply(&self, ui: &mut (impl Component + ?Sized), scene: &Node, path: &[usize]) -> bool {
866        match self {
867            Self::Dispatch(event) => ui.dispatch_at(scene, path, event),
868            Self::Edit(text) => ui.edit_at(scene, path, (*text).into()),
869            Self::CommitCell { original, text } => {
870                ui.commit_table_cell(scene, path, original, (*text).into())
871            }
872            Self::PasteTable(_) => false,
873            Self::ReplayTable { redo } => ui.replay_table_edit_at(scene, path, *redo),
874            Self::QueryTable(_) => false,
875            Self::Range(action) => ui.adjust_range_at(scene, path, *action),
876            Self::Control(action) => ui.control_at(scene, path, *action),
877            Self::Drag(event) => ui.drag_event_at(scene, path, event),
878            Self::Key(phase, event) => {
879                ui.key_event_at(scene, path, *phase, event) == EventResult::Accept
880            }
881            Self::Wheel(event) => ui.wheel_event_at(scene, path, event) == EventResult::Accept,
882            Self::Pointer(event) => ui.pointer_event_at(scene, path, event),
883            Self::Focus(event) => ui.focus_event_at(scene, path, *event),
884            Self::ResizeSplit(weights) => ui.resize_split_at(scene, path, weights),
885            Self::ResizeSplitSizes(sizes) => ui.resize_split_sizes_at(scene, path, sizes),
886        }
887    }
888}
889
890#[derive(Clone, Copy, Debug, Default, PartialEq)]
891pub struct Length(pub f64);
892
893#[derive(Clone, Copy, Debug, PartialEq)]
894pub struct Percent(pub f64);
895
896#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
897pub struct Color(pub u32);
898
899impl Color {
900    /// Decode the RGB and RGBA spellings accepted by the XR dialect.
901    #[doc(hidden)]
902    pub fn parse_hex_literal(spelling: &str) -> Option<Self> {
903        let digits = spelling.strip_prefix('#')?;
904        if !matches!(digits.len(), 3 | 4 | 6 | 8)
905            || !digits.bytes().all(|digit| digit.is_ascii_hexdigit())
906        {
907            return None;
908        }
909        let value = u32::from_str_radix(digits, 16).ok()?;
910        let rgba = match digits.len() {
911            3 | 4 => {
912                let expanded = (0..digits.len()).rev().fold(0, |rgba, index| {
913                    let digit = (value >> (index * 4)) & 0xf;
914                    (rgba << 8) | (digit * 17)
915                });
916                if digits.len() == 3 {
917                    (expanded << 8) | 0xff
918                } else {
919                    expanded
920                }
921            }
922            6 => (value << 8) | 0xff,
923            _ => value,
924        };
925        Some(Self(rgba))
926    }
927}
928
929#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
930pub enum ColorScheme {
931    #[default]
932    System,
933    Light,
934    Dark,
935}
936
937#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
938pub enum ImageFormat {
939    Png,
940    Svg,
941}
942
943#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
944pub enum Image {
945    #[default]
946    Empty,
947    Embedded {
948        format: ImageFormat,
949        bytes: &'static [u8],
950        size: [u32; 2],
951    },
952    Animated(&'static ImageAnimation),
953    NineSliced {
954        format: ImageFormat,
955        bytes: &'static [u8],
956        size: [u32; 2],
957        edges: NineSlice,
958    },
959}
960
961/// Source edge widths in pixels, clockwise from the top.
962#[derive(Clone, Copy, Debug, PartialEq, Eq)]
963pub struct NineSlice {
964    pub top: u32,
965    pub right: u32,
966    pub bottom: u32,
967    pub left: u32,
968}
969
970impl NineSlice {
971    pub fn fits(self, [width, height]: [u32; 2]) -> bool {
972        self.left.saturating_add(self.right) < width
973            && self.top.saturating_add(self.bottom) < height
974    }
975}
976
977#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
978#[error("nine-slice edges must leave a nonempty center in the source image")]
979pub struct InvalidNineSlice;
980
981impl Image {
982    pub fn size(self) -> [u32; 2] {
983        match self {
984            Self::Empty => [0, 0],
985            Self::Animated(animation) => animation.size(),
986            Self::Embedded { size, .. } | Self::NineSliced { size, .. } => size,
987        }
988    }
989
990    pub fn frame_count(self) -> usize {
991        match self {
992            Self::Empty => 0,
993            Self::Animated(animation) => animation.frame_count(),
994            _ => 1,
995        }
996    }
997
998    pub fn frame(self, index: usize) -> Self {
999        match self {
1000            Self::Animated(animation) => animation.frame(index),
1001            _ => self,
1002        }
1003    }
1004
1005    pub fn with_nine_slice(self, edges: NineSlice) -> Result<Self, InvalidNineSlice> {
1006        match self {
1007            Self::Embedded {
1008                format,
1009                bytes,
1010                size,
1011            }
1012            | Self::NineSliced {
1013                format,
1014                bytes,
1015                size,
1016                ..
1017            } if edges.fits(size) => Ok(Self::NineSliced {
1018                format,
1019                bytes,
1020                size,
1021                edges,
1022            }),
1023            _ => Err(InvalidNineSlice),
1024        }
1025    }
1026}
1027
1028/// Immutable font data shared by scenes from the same generated UI library.
1029pub struct EmbeddedFonts(&'static [&'static [u8]]);
1030
1031impl EmbeddedFonts {
1032    pub const fn new(fonts: &'static [&'static [u8]]) -> Self {
1033        Self(fonts)
1034    }
1035
1036    pub fn sources(&self) -> &'static [&'static [u8]] {
1037        self.0
1038    }
1039}
1040
1041impl PartialEq for EmbeddedFonts {
1042    fn eq(&self, other: &Self) -> bool {
1043        std::ptr::eq(self, other)
1044    }
1045}
1046
1047impl std::fmt::Debug for EmbeddedFonts {
1048    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1049        f.debug_struct("EmbeddedFonts")
1050            .field("count", &self.0.len())
1051            .finish()
1052    }
1053}
1054
1055/// Owned font data shared by the roots of an interpreted UI.
1056#[derive(Clone)]
1057pub struct LoadedFonts(Arc<Vec<Arc<Vec<u8>>>>);
1058
1059impl LoadedFonts {
1060    pub fn new(fonts: Vec<Vec<u8>>) -> Self {
1061        Self(Arc::new(fonts.into_iter().map(Arc::new).collect()))
1062    }
1063
1064    pub fn sources(&self) -> &[Arc<Vec<u8>>] {
1065        &self.0
1066    }
1067}
1068
1069impl std::fmt::Debug for LoadedFonts {
1070    fn fmt(&self, output: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1071        output
1072            .debug_struct("LoadedFonts")
1073            .field("count", &self.0.len())
1074            .finish()
1075    }
1076}
1077
1078impl PartialEq for LoadedFonts {
1079    fn eq(&self, other: &Self) -> bool {
1080        Arc::ptr_eq(&self.0, &other.0)
1081    }
1082}
1083
1084#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1085pub enum ImageFit {
1086    Fill,
1087    #[default]
1088    Contain,
1089    Cover,
1090    Preserve,
1091}
1092
1093#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1094pub enum ImageTileMode {
1095    #[default]
1096    Stretch,
1097    Repeat,
1098    Round,
1099}
1100
1101#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1102pub enum ImageHorizontalAlignment {
1103    Left,
1104    #[default]
1105    Center,
1106    Right,
1107}
1108
1109#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1110pub enum ImageVerticalAlignment {
1111    Top,
1112    #[default]
1113    Center,
1114    Bottom,
1115}
1116
1117#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1118pub enum ImageRendering {
1119    #[default]
1120    Smooth,
1121    Pixelated,
1122}
1123
1124#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1125pub enum LayoutAlignment {
1126    #[default]
1127    Stretch,
1128    Center,
1129    Start,
1130    End,
1131    SpaceBetween,
1132    SpaceAround,
1133    SpaceEvenly,
1134}
1135
1136#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1137pub enum CrossAxisAlignment {
1138    #[default]
1139    Auto,
1140    Stretch,
1141    Start,
1142    End,
1143    Center,
1144}
1145
1146#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1147pub enum Orientation {
1148    #[default]
1149    Horizontal,
1150    Vertical,
1151}
1152
1153#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1154pub enum FlickDirection {
1155    #[default]
1156    Both,
1157    Horizontal,
1158    Vertical,
1159}
1160
1161#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1162pub enum FlickBoundsBehavior {
1163    #[default]
1164    StopAtBounds,
1165    DragOverBounds,
1166    OvershootBounds,
1167    DragAndOvershootBounds,
1168}
1169
1170impl FlickBoundsBehavior {
1171    pub fn allows_overshoot(self, flick: bool) -> bool {
1172        matches!(
1173            (self, flick),
1174            (Self::DragAndOvershootBounds, _)
1175                | (Self::DragOverBounds, false)
1176                | (Self::OvershootBounds, true)
1177        )
1178    }
1179}
1180
1181#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1182pub enum FlickBoundsMovement {
1183    #[default]
1184    FollowBoundsBehavior,
1185    StopAtBounds,
1186}
1187
1188impl FlickDirection {
1189    pub fn allows(self, axis: Orientation) -> bool {
1190        matches!(
1191            (self, axis),
1192            (Self::Both, _)
1193                | (Self::Horizontal, Orientation::Horizontal)
1194                | (Self::Vertical, Orientation::Vertical)
1195        )
1196    }
1197}
1198
1199#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1200pub enum FlexboxLayoutDirection {
1201    #[default]
1202    Row,
1203    RowReverse,
1204    Column,
1205    ColumnReverse,
1206}
1207
1208#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1209pub enum FlexboxLayoutWrap {
1210    #[default]
1211    Wrap,
1212    NoWrap,
1213    WrapReverse,
1214}
1215
1216#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1217pub enum DrawerEdge {
1218    #[default]
1219    Left,
1220    Right,
1221    Top,
1222    Bottom,
1223}
1224
1225#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1226pub enum ScrollBarPolicy {
1227    #[default]
1228    AsNeeded,
1229    AlwaysOn,
1230    AlwaysOff,
1231}
1232
1233#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1234pub enum TextWrap {
1235    #[default]
1236    WordWrap,
1237    NoWrap,
1238    CharWrap,
1239}
1240
1241#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1242pub enum TextHorizontalAlignment {
1243    #[default]
1244    Start,
1245    End,
1246    Left,
1247    Center,
1248    Right,
1249}
1250
1251#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1252pub enum TextVerticalAlignment {
1253    #[default]
1254    Top,
1255    Center,
1256    Bottom,
1257}
1258
1259#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1260pub enum TextOverflow {
1261    #[default]
1262    Clip,
1263    Elide,
1264}
1265
1266#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1267pub enum CheckState {
1268    #[default]
1269    Unchecked,
1270    PartiallyChecked,
1271    Checked,
1272}
1273
1274impl From<bool> for CheckState {
1275    fn from(checked: bool) -> Self {
1276        if checked {
1277            Self::Checked
1278        } else {
1279            Self::Unchecked
1280        }
1281    }
1282}
1283
1284impl CheckState {
1285    pub fn next(self, tristate: bool) -> Self {
1286        match self {
1287            Self::Checked => Self::Unchecked,
1288            Self::Unchecked if tristate => Self::PartiallyChecked,
1289            _ => Self::Checked,
1290        }
1291    }
1292}
1293
1294#[derive(Clone, Copy, Debug, PartialEq)]
1295pub struct GradientStop {
1296    pub color: Color,
1297    /// Position along the gradient in the range 0.0 to 1.0.
1298    pub offset: f64,
1299}
1300
1301#[derive(Clone, Debug, PartialEq)]
1302pub enum Brush {
1303    Solid(Color),
1304    Linear {
1305        angle_degrees: f64,
1306        stops: Arc<[GradientStop]>,
1307    },
1308    Radial {
1309        stops: Arc<[GradientStop]>,
1310    },
1311}
1312
1313impl Default for Brush {
1314    fn default() -> Self {
1315        Self::Solid(Color::default())
1316    }
1317}
1318
1319#[derive(Clone, Debug, PartialEq)]
1320pub enum Value {
1321    EventResult(EventResult),
1322    FocusReason(FocusReason),
1323    KeyEvent(KeyEvent),
1324    WheelEvent(WheelEvent),
1325    PointerEvent(PointerEvent),
1326    TouchPoint(TouchPoint),
1327    TouchPoints(TouchPoints),
1328    KeyModifiers(KeyModifiers),
1329    Int(i64),
1330    Float(f64),
1331    Bool(bool),
1332    String(String),
1333    StyledText(StyledText),
1334    StringList(Vec<String>),
1335    /// A live string list whose row identities are shared by its bindings.
1336    StringModel(VecModel<String>),
1337    Record(RecordValue),
1338    RecordList(RecordList),
1339    ComboModel(ComboModel),
1340    Length(Length),
1341    Percent(Percent),
1342    Color(Color),
1343    Brush(Brush),
1344    Image(Image),
1345    ImageAsset(ImageAsset),
1346    ImageFit(ImageFit),
1347    ImageTileMode(ImageTileMode),
1348    ImageHorizontalAlignment(ImageHorizontalAlignment),
1349    ImageVerticalAlignment(ImageVerticalAlignment),
1350    ImageRendering(ImageRendering),
1351    LayoutAlignment(LayoutAlignment),
1352    CrossAxisAlignment(CrossAxisAlignment),
1353    Orientation(Orientation),
1354    FlickDirection(FlickDirection),
1355    FlickBoundsBehavior(FlickBoundsBehavior),
1356    FlickBoundsMovement(FlickBoundsMovement),
1357    FlexboxLayoutDirection(FlexboxLayoutDirection),
1358    FlexboxLayoutWrap(FlexboxLayoutWrap),
1359    DialInputMode(DialInputMode),
1360    ScrollBarPolicy(ScrollBarPolicy),
1361    ScrollSnapMode(ScrollSnapMode),
1362    ScrollAlignment(ScrollAlignment),
1363    TextWrap(TextWrap),
1364    TextHorizontalAlignment(TextHorizontalAlignment),
1365    TextVerticalAlignment(TextVerticalAlignment),
1366    TextOverflow(TextOverflow),
1367    InputType(InputType),
1368    CursorShape(CursorShape),
1369    PointerEventKind(PointerEventKind),
1370    PointerButton(PointerButton),
1371    PointerButtons(PointerButtons),
1372    ColorScheme(ColorScheme),
1373    FileDialogMode(FileDialogMode),
1374    MessageLevel(MessageLevel),
1375    MessageButtons(MessageButtons),
1376    CheckState(CheckState),
1377    DialogRole(DialogRole),
1378    StandardButtonKind(StandardButtonKind),
1379    SwipeSide(SwipeSide),
1380    DragAction(DragAction),
1381    DrawerEdge(DrawerEdge),
1382    PopupPlacement(PopupPlacement),
1383    SelectionTarget(SelectionTarget),
1384    Date(Date),
1385    Time(Time),
1386    Font(Font),
1387}
1388
1389impl Value {
1390    /// Compare a host image and an image asset using their shared image semantics.
1391    #[doc(hidden)]
1392    pub fn eq_with_image_assets(&self, other: &Self) -> bool {
1393        match (self, other) {
1394            (Self::Image(embedded), Self::ImageAsset(asset))
1395            | (Self::ImageAsset(asset), Self::Image(embedded)) => {
1396                ImageAsset::from(*embedded) == *asset
1397            }
1398            _ => self == other,
1399        }
1400    }
1401}
1402
1403macro_rules! value_from {
1404    ($ty:ty, $variant:ident) => {
1405        impl From<$ty> for Value {
1406            fn from(value: $ty) -> Self {
1407                Self::$variant(value)
1408            }
1409        }
1410    };
1411}
1412value_from!(i64, Int);
1413value_from!(f64, Float);
1414value_from!(bool, Bool);
1415value_from!(String, String);
1416value_from!(StyledText, StyledText);
1417value_from!(Vec<String>, StringList);
1418
1419impl From<VecModel<String>> for Value {
1420    fn from(model: VecModel<String>) -> Self {
1421        Self::StringList(model.into_snapshot())
1422    }
1423}
1424value_from!(Length, Length);
1425value_from!(Percent, Percent);
1426value_from!(Color, Color);
1427value_from!(Image, Image);
1428value_from!(ImageFit, ImageFit);
1429value_from!(ImageTileMode, ImageTileMode);
1430value_from!(ImageHorizontalAlignment, ImageHorizontalAlignment);
1431value_from!(ImageVerticalAlignment, ImageVerticalAlignment);
1432value_from!(ImageRendering, ImageRendering);
1433value_from!(LayoutAlignment, LayoutAlignment);
1434value_from!(CrossAxisAlignment, CrossAxisAlignment);
1435value_from!(Orientation, Orientation);
1436value_from!(FlickDirection, FlickDirection);
1437value_from!(FlickBoundsBehavior, FlickBoundsBehavior);
1438value_from!(FlickBoundsMovement, FlickBoundsMovement);
1439value_from!(FlexboxLayoutDirection, FlexboxLayoutDirection);
1440value_from!(FlexboxLayoutWrap, FlexboxLayoutWrap);
1441value_from!(DialInputMode, DialInputMode);
1442value_from!(ScrollBarPolicy, ScrollBarPolicy);
1443value_from!(ScrollSnapMode, ScrollSnapMode);
1444value_from!(ScrollAlignment, ScrollAlignment);
1445value_from!(TextWrap, TextWrap);
1446value_from!(TextHorizontalAlignment, TextHorizontalAlignment);
1447value_from!(TextVerticalAlignment, TextVerticalAlignment);
1448value_from!(TextOverflow, TextOverflow);
1449value_from!(InputType, InputType);
1450value_from!(CursorShape, CursorShape);
1451value_from!(PointerEventKind, PointerEventKind);
1452value_from!(PointerButton, PointerButton);
1453value_from!(PointerButtons, PointerButtons);
1454value_from!(ColorScheme, ColorScheme);
1455value_from!(FileDialogMode, FileDialogMode);
1456value_from!(MessageLevel, MessageLevel);
1457value_from!(MessageButtons, MessageButtons);
1458value_from!(CheckState, CheckState);
1459value_from!(DialogRole, DialogRole);
1460value_from!(StandardButtonKind, StandardButtonKind);
1461value_from!(SwipeSide, SwipeSide);
1462value_from!(DragAction, DragAction);
1463value_from!(DrawerEdge, DrawerEdge);
1464value_from!(PopupPlacement, PopupPlacement);
1465value_from!(SelectionTarget, SelectionTarget);
1466value_from!(Date, Date);
1467value_from!(Time, Time);
1468value_from!(Font, Font);
1469
1470impl From<Brush> for Value {
1471    fn from(value: Brush) -> Self {
1472        match value {
1473            Brush::Solid(color) => Self::Color(color),
1474            gradient => Self::Brush(gradient),
1475        }
1476    }
1477}
1478
1479#[derive(Clone, Debug)]
1480pub struct Node(NodeStorage);
1481
1482#[derive(Clone, Debug)]
1483#[allow(clippy::large_enum_variant)] // Keep ordinary dynamic nodes inline.
1484enum NodeStorage {
1485    Inline(NodeData),
1486    Shared(Arc<NodeData>),
1487}
1488
1489/// Scene data shared by clones of a node. Mutating a node detaches its data.
1490#[doc(hidden)]
1491#[derive(Clone, Debug, PartialEq)]
1492pub struct NodeData {
1493    pub kind: &'static str,
1494    #[doc(hidden)]
1495    pub application_window: bool,
1496    pub id: Option<&'static str>,
1497    owned_id: Option<Arc<str>>,
1498    pub properties: BTreeMap<&'static str, Value>,
1499    #[doc(hidden)]
1500    pub fonts: Option<&'static EmbeddedFonts>,
1501    #[doc(hidden)]
1502    pub loaded_fonts: Option<LoadedFonts>,
1503    pub tumbler_items: Option<TumblerItems>,
1504    pub children: Vec<Node>,
1505    #[doc(hidden)]
1506    pub table_column_window: TableColumnWindow,
1507    #[doc(hidden)]
1508    pub timers: Vec<TimerRegistration>,
1509    #[doc(hidden)]
1510    pub image_playback: Option<Rc<ImagePlaybackRegistration>>,
1511    #[doc(hidden)]
1512    pub native_dialogs: Vec<NativeDialogRegistration>,
1513    pub animations: BTreeMap<&'static str, Animation>,
1514    #[doc(hidden)]
1515    pub state_timings: Option<Box<BTreeMap<&'static str, StateTiming>>>,
1516    #[doc(hidden)]
1517    pub focus_handle: Option<FocusHandle>,
1518    #[doc(hidden)]
1519    pub scale_rotate_handle: Option<ScaleRotateHandle>,
1520    #[doc(hidden)]
1521    pub swipe_handle: Option<SwipeHandle>,
1522    #[doc(hidden)]
1523    pub hover_handle: Option<HoverHandle>,
1524    #[doc(hidden)]
1525    pub pointer_handle: Option<PointerHandle>,
1526    #[doc(hidden)]
1527    pub scroll_event_handler: bool,
1528    #[doc(hidden)]
1529    pub press_and_hold_handler: bool,
1530    #[doc(hidden)]
1531    pub viewport_handle: Option<ViewportHandle>,
1532    #[doc(hidden)]
1533    pub scroll_target: Option<ViewportHandle>,
1534    #[doc(hidden)]
1535    pub geometry_handle: Option<GeometryHandle>,
1536    #[doc(hidden)]
1537    pub instance_geometry_handle: Option<GeometryHandle>,
1538    #[doc(hidden)]
1539    pub initial_focus: Option<FocusHandle>,
1540    #[doc(hidden)]
1541    pub key_handlers: u8,
1542    pub list: Option<ListMetrics>,
1543    #[doc(hidden)]
1544    pub row_locator: Option<ListRowLocator>,
1545    #[doc(hidden)]
1546    pub list_row_renderer: Option<ListRowRenderer>,
1547    #[doc(hidden)]
1548    pub row_heights: Option<Arc<RowHeights>>,
1549    /// Selection snapshot for model-backed views. Retains the generated field name.
1550    #[doc(hidden)]
1551    pub standard_list_stamp: Option<(u64, u64)>,
1552    pub table_header: Option<Box<TableHeader>>,
1553    #[doc(hidden)]
1554    pub table_column_order: TableColumnOrder,
1555    pub table_selection: Option<Box<TableSelectionSnapshot>>,
1556    #[doc(hidden)]
1557    pub table_cell_editor: Option<TableCellEditor>,
1558    pub tree: Option<Arc<TreeSnapshot>>,
1559    pub stack: Option<Arc<StackSnapshot>>,
1560    pub action: Option<ActionKey>,
1561    #[doc(hidden)]
1562    pub button_group: Option<ButtonGroupMembership>,
1563    /// Selected TreeView business keys and model row identities, including folded descendants.
1564    pub tree_selection: Option<Arc<BTreeMap<i64, RowKey>>>,
1565    pub split_weights: Option<Arc<[Option<f32>]>>,
1566    #[doc(hidden)]
1567    pub split_fill_pane: Option<&'static str>,
1568    #[doc(hidden)]
1569    pub split_fill_index: Option<usize>,
1570    #[doc(hidden)]
1571    pub split_sizes: Option<Arc<[Option<f32>]>>,
1572    #[doc(hidden)]
1573    pub split_resize_handle: Option<SplitResizeHandle>,
1574    pub row_key: Option<RowKey>,
1575    #[doc(hidden)]
1576    pub row_scope: u64,
1577    paint_only: u8,
1578    static_paint_order: Option<ScenePlanSlice<usize>>,
1579    precompiled_path: Option<&'static StaticVectorPath>,
1580    loaded_path: Option<LoadedVectorPath>,
1581    static_grid: Option<ScenePlanSlice<GridCellSlot>>,
1582}
1583
1584impl std::ops::Deref for Node {
1585    type Target = NodeData;
1586
1587    fn deref(&self) -> &Self::Target {
1588        match &self.0 {
1589            NodeStorage::Inline(data) => data,
1590            NodeStorage::Shared(data) => data,
1591        }
1592    }
1593}
1594
1595impl std::ops::DerefMut for Node {
1596    fn deref_mut(&mut self) -> &mut Self::Target {
1597        let data = self.data_mut();
1598        // Public edits can change grid tracks, visibility or child order.
1599        data.static_grid = None;
1600        data.static_paint_order = None;
1601        data
1602    }
1603}
1604
1605impl PartialEq for Node {
1606    fn eq(&self, other: &Self) -> bool {
1607        **self == **other
1608    }
1609}
1610
1611impl NodeData {
1612    fn same_structure_and_state(&self, other: &Self) -> bool {
1613        macro_rules! compare {
1614            ($($field:ident),+ $(,)?) => {{
1615                // An exhaustive pattern makes new scene fields opt in to comparison.
1616                let Self { properties: _, children: _, paint_only: _, $($field: _,)+ } = self;
1617                $(self.$field == other.$field)&&+
1618            }};
1619        }
1620        compare!(
1621            kind,
1622            table_column_window,
1623            application_window,
1624            id,
1625            owned_id,
1626            fonts,
1627            loaded_fonts,
1628            tumbler_items,
1629            timers,
1630            image_playback,
1631            native_dialogs,
1632            animations,
1633            state_timings,
1634            focus_handle,
1635            scale_rotate_handle,
1636            swipe_handle,
1637            hover_handle,
1638            pointer_handle,
1639            scroll_event_handler,
1640            press_and_hold_handler,
1641            viewport_handle,
1642            scroll_target,
1643            geometry_handle,
1644            instance_geometry_handle,
1645            initial_focus,
1646            key_handlers,
1647            list,
1648            row_locator,
1649            list_row_renderer,
1650            row_heights,
1651            standard_list_stamp,
1652            table_header,
1653            table_column_order,
1654            table_selection,
1655            table_cell_editor,
1656            tree,
1657            stack,
1658            action,
1659            button_group,
1660            tree_selection,
1661            split_weights,
1662            split_fill_pane,
1663            split_fill_index,
1664            split_sizes,
1665            split_resize_handle,
1666            row_key,
1667            row_scope,
1668            precompiled_path,
1669            loaded_path,
1670            static_grid,
1671            static_paint_order,
1672        )
1673    }
1674}
1675
1676pub fn is_text_input(kind: &str) -> bool {
1677    matches!(kind, "TextInput" | "LineEdit" | "SearchField") || is_multiline_text_input(kind)
1678}
1679
1680pub fn editable_table_cell(node: &Node) -> bool {
1681    matches!(node.kind, "TableCell" | "TreeCell")
1682        && node.boolean("editable", false)
1683        && !node.boolean("read-only", false)
1684}
1685
1686pub fn is_multiline_text_input(kind: &str) -> bool {
1687    matches!(kind, "TextEdit" | "TextArea")
1688}
1689
1690pub fn is_toggle(kind: &str) -> bool {
1691    matches!(kind, "CheckBox" | "Switch")
1692}
1693
1694/// Whether a handler can be invoked through dispatch without an event payload.
1695#[doc(hidden)]
1696pub fn supports_untyped_dispatch(kind: &str, event: &str) -> bool {
1697    if matches!(event, "scrolled" | "flicked") || (kind == "SwipeDelegate" && event == "clicked") {
1698        return true;
1699    }
1700    !matches!(
1701        event,
1702        "check-state-changed" | "close-requested" | "pointer-event" | "scroll-event"
1703    ) && !is_multiline_text_input(kind)
1704        && !matches!(
1705            kind,
1706            "Slider"
1707                | "WheelHandler"
1708                | "Dial"
1709                | "ScrollBar"
1710                | "RangeSlider"
1711                | "SpinBox"
1712                | "DoubleSpinBox"
1713                | "SearchField"
1714                | "ComboBox"
1715                | "RadioGroup"
1716                | "ButtonGroup"
1717                | "TabWidget"
1718                | "TabBar"
1719                | "SwipeView"
1720                | "SwipeDelegate"
1721                | "StackView"
1722                | "StackPage"
1723                | "PageIndicator"
1724                | "Tumbler"
1725                | "Calendar"
1726                | "MonthGrid"
1727                | "TimePicker"
1728                | "TimePickerPopup"
1729                | "DatePickerPopup"
1730                | "ColorPickerPopup"
1731                | "FontPickerPopup"
1732                | "ListView"
1733                | "GridView"
1734                | "StandardListView"
1735                | "TableView"
1736                | "StandardTableView"
1737                | "SplitView"
1738                | "TreeView"
1739                | "Dialog"
1740                | "Drawer"
1741                | "PopupWindow"
1742                | "MenuItem"
1743                | "Shortcut"
1744                | "DelayButton"
1745                | "FocusScope"
1746                | "StyledText"
1747                | "AnimatedImage"
1748                | "DragArea"
1749                | "DropArea"
1750                | "GroupBox"
1751        )
1752}
1753
1754impl Node {
1755    #[doc(hidden)]
1756    pub fn table_edit_history_enabled(&self) -> bool {
1757        self.boolean("undoable", false) || self.boolean("pasteable", false)
1758    }
1759
1760    #[doc(hidden)]
1761    pub fn table_edit_history_model(&self, path: &[usize]) -> Option<u64> {
1762        let table = self.interactive_at_path(path)?;
1763        if !table.table_edit_history_enabled() {
1764            return None;
1765        }
1766        table.standard_list_stamp.map(|(model, _)| model)
1767    }
1768
1769    pub fn calendar_cells(&self) -> Option<&[Node]> {
1770        self.children
1771            .last()
1772            .filter(|child| child.kind == "CalendarCells")
1773            .map(|child| child.children.as_slice())
1774    }
1775
1776    pub fn is_item_delegate(&self) -> bool {
1777        self.boolean("__item-delegate", false)
1778    }
1779
1780    #[doc(hidden)]
1781    pub fn enables_children(&self) -> bool {
1782        !self.input_requires_enabled(false) || self.boolean("enabled", true)
1783    }
1784
1785    #[doc(hidden)]
1786    pub fn input_requires_enabled(&self, is_target: bool) -> bool {
1787        is_target
1788            || !(is_drag_area(self.kind)
1789                || matches!(
1790                    self.kind,
1791                    "WindowMoveArea"
1792                        | "ScaleRotateGestureHandler"
1793                        | "SwipeGestureHandler"
1794                        | "WheelHandler"
1795                        | "HoverHandler"
1796                        | "TouchArea"
1797                ))
1798    }
1799    pub fn check_state(&self) -> CheckState {
1800        match self.properties.get("check-state") {
1801            Some(Value::CheckState(state)) if self.kind == "CheckBox" => *state,
1802            _ => self.boolean("checked", false).into(),
1803        }
1804    }
1805
1806    pub fn date(&self, name: &str) -> Option<Date> {
1807        match self.properties.get(name) {
1808            Some(Value::Date(date)) => Some(*date),
1809            _ => None,
1810        }
1811    }
1812
1813    pub fn time(&self, name: &str) -> Option<Time> {
1814        match self.properties.get(name) {
1815            Some(Value::Time(time)) => Some(*time),
1816            _ => None,
1817        }
1818    }
1819
1820    pub fn new(kind: &'static str, id: Option<&'static str>) -> Self {
1821        Self(NodeStorage::Inline(NodeData {
1822            kind,
1823            application_window: false,
1824            id,
1825            owned_id: None,
1826            properties: BTreeMap::new(),
1827            fonts: None,
1828            loaded_fonts: None,
1829            tumbler_items: None,
1830            children: Vec::new(),
1831            table_column_window: TableColumnWindow::default(),
1832            timers: Vec::new(),
1833            image_playback: None,
1834            native_dialogs: Vec::new(),
1835            animations: BTreeMap::new(),
1836            state_timings: None,
1837            focus_handle: None,
1838            scale_rotate_handle: None,
1839            swipe_handle: None,
1840            hover_handle: None,
1841            pointer_handle: None,
1842            scroll_event_handler: false,
1843            press_and_hold_handler: false,
1844            viewport_handle: None,
1845            scroll_target: None,
1846            geometry_handle: None,
1847            instance_geometry_handle: None,
1848            initial_focus: None,
1849            key_handlers: 0,
1850            list: None,
1851            row_locator: None,
1852            list_row_renderer: None,
1853            row_heights: None,
1854            standard_list_stamp: None,
1855            table_header: None,
1856            table_column_order: TableColumnOrder::default(),
1857            table_selection: None,
1858            table_cell_editor: None,
1859            tree: None,
1860            stack: None,
1861            action: None,
1862            button_group: None,
1863            tree_selection: None,
1864            split_weights: None,
1865            split_fill_pane: None,
1866            split_fill_index: None,
1867            split_sizes: None,
1868            split_resize_handle: None,
1869            row_key: None,
1870            row_scope: 0,
1871            paint_only: 0,
1872            static_paint_order: None,
1873            precompiled_path: None,
1874            loaded_path: None,
1875            static_grid: None,
1876        }))
1877    }
1878
1879    /// Freeze a static subtree so subsequent snapshot clones share its storage.
1880    #[doc(hidden)]
1881    pub fn into_shared(self) -> Self {
1882        match self.0 {
1883            NodeStorage::Inline(mut data) => {
1884                data.children = data.children.into_iter().map(Self::into_shared).collect();
1885                Self(NodeStorage::Shared(Arc::new(data)))
1886            }
1887            NodeStorage::Shared(data) => Self(NodeStorage::Shared(data)),
1888        }
1889    }
1890
1891    pub fn shares_storage_with(&self, other: &Self) -> bool {
1892        std::ptr::eq(self, other)
1893            || matches!((&self.0, &other.0), (NodeStorage::Shared(a), NodeStorage::Shared(b)) if Arc::ptr_eq(a, b))
1894    }
1895
1896    #[doc(hidden)]
1897    pub fn set_precompiled_path(&mut self, path: &'static StaticVectorPath) {
1898        self.precompiled_path = Some(path);
1899    }
1900
1901    #[doc(hidden)]
1902    pub fn precompiled_path(&self, commands: &str) -> Option<&'static StaticVectorPath> {
1903        self.precompiled_path
1904            .filter(|path| path.commands == commands)
1905    }
1906    #[doc(hidden)]
1907    pub fn set_loaded_vector_path(&mut self, path: LoadedVectorPath) {
1908        self.loaded_path = Some(path);
1909    }
1910
1911    #[doc(hidden)]
1912    pub fn vector_path_geometry(&self, commands: &str) -> Option<([f32; 4], &[VectorSegment])> {
1913        self.precompiled_path(commands)
1914            .map(|path| (path.bounds, path.segments))
1915            .or_else(|| self.loaded_path.as_ref()?.geometry(commands))
1916    }
1917
1918    /// Mark a generated Rectangle's background as independent of layout and input.
1919
1920    fn data_mut(&mut self) -> &mut NodeData {
1921        match &mut self.0 {
1922            NodeStorage::Inline(data) => data,
1923            NodeStorage::Shared(data) => Arc::make_mut(data),
1924        }
1925    }
1926
1927    #[doc(hidden)]
1928    pub fn set_static_grid(&mut self, cells: &'static [GridCellSlot]) {
1929        self.data_mut().static_grid = Some(ScenePlanSlice::Static(cells));
1930    }
1931
1932    #[doc(hidden)]
1933    pub fn set_shared_grid(&mut self, cells: Arc<[GridCellSlot]>) {
1934        self.data_mut().static_grid = Some(ScenePlanSlice::Shared(cells));
1935    }
1936
1937    #[doc(hidden)]
1938    pub fn static_grid(&self) -> Option<&[GridCellSlot]> {
1939        self.static_grid.as_deref()
1940    }
1941
1942    #[doc(hidden)]
1943    pub fn set_static_paint_order(&mut self, order: &'static [usize]) {
1944        self.data_mut().static_paint_order =
1945            (!order.is_empty()).then_some(ScenePlanSlice::Static(order));
1946    }
1947
1948    #[doc(hidden)]
1949    pub fn set_shared_paint_order(&mut self, order: Arc<[usize]>) {
1950        self.data_mut().static_paint_order = Some(ScenePlanSlice::Shared(order));
1951    }
1952
1953    #[doc(hidden)]
1954    pub fn set_natural_paint_order(&mut self) {
1955        self.data_mut().static_paint_order = Some(ScenePlanSlice::Static(&[]));
1956    }
1957
1958    #[doc(hidden)]
1959    pub fn has_natural_paint_order(&self) -> bool {
1960        self.static_paint_order
1961            .as_deref()
1962            .is_some_and(<[usize]>::is_empty)
1963    }
1964
1965    #[doc(hidden)]
1966    pub fn static_paint_order(&self) -> Option<&[usize]> {
1967        self.paint_order_plan().map(std::ops::Deref::deref)
1968    }
1969
1970    #[doc(hidden)]
1971    pub fn paint_order_plan(&self) -> Option<&ScenePlanSlice<usize>> {
1972        self.static_paint_order
1973            .as_ref()
1974            .filter(|order| !order.is_empty())
1975    }
1976
1977    #[doc(hidden)]
1978    pub fn set_loaded_fonts(&mut self, fonts: Option<LoadedFonts>) {
1979        self.data_mut().loaded_fonts = fonts;
1980    }
1981
1982    #[doc(hidden)]
1983    pub fn set_embedded_fonts(&mut self, fonts: &'static EmbeddedFonts) {
1984        self.data_mut().fonts = Some(fonts);
1985    }
1986
1987    #[doc(hidden)]
1988    pub fn set_row_key(&mut self, key: Option<RowKey>) {
1989        if self.row_key != key {
1990            self.data_mut().row_key = key;
1991        }
1992    }
1993
1994    fn paint_only_bit(&self, property: &str) -> u8 {
1995        match (self.kind, property) {
1996            ("Rectangle", "background") => 1,
1997            ("Text", "color") => 2,
1998            ("Text" | "Label", "text") => 4,
1999            ("Image", "source") => 8,
2000            _ => 0,
2001        }
2002    }
2003
2004    #[doc(hidden)]
2005    pub fn mark_paint_only(&mut self, property: &str) {
2006        let bit = self.paint_only_bit(property);
2007        self.data_mut().paint_only |= bit;
2008    }
2009
2010    #[doc(hidden)]
2011    pub fn mark_paint_only_background(&mut self) {
2012        self.mark_paint_only("background");
2013    }
2014
2015    /// Compare frame inputs, allowing paint-only values to differ.
2016    #[doc(hidden)]
2017    pub fn same_frame_inputs(&self, other: &Self) -> bool {
2018        if self.shares_storage_with(other) {
2019            return true;
2020        }
2021        let paint_only = self.paint_only & other.paint_only;
2022        let ignore_frame = self.kind == "AnimatedImage" && other.kind == "AnimatedImage";
2023        let ignore_colorize =
2024            matches!(self.kind, "Image" | "AnimatedImage") && self.kind == other.kind;
2025        let fixed_visual_box =
2026            |node: &Self| node.length("width").is_some() && node.length("height").is_some();
2027        let relevant = |(name, _): &(&&str, &Value)| match **name {
2028            "text" | "source" if paint_only & self.paint_only_bit(name) != 0 => {
2029                !fixed_visual_box(self) || !fixed_visual_box(other)
2030            }
2031            name if paint_only & self.paint_only_bit(name) != 0 => false,
2032            "opacity" => false,
2033            "drop-shadow-blur"
2034            | "drop-shadow-color"
2035            | "drop-shadow-offset-x"
2036            | "drop-shadow-offset-y"
2037            | "drop-shadow-spread"
2038            | "inner-shadow-blur"
2039            | "inner-shadow-color"
2040            | "inner-shadow-offset-x"
2041            | "inner-shadow-offset-y"
2042            | "inner-shadow-spread" => self.kind != "Rectangle",
2043            "current-frame" => !ignore_frame,
2044            "colorize" => !ignore_colorize,
2045            _ => true,
2046        };
2047        self.same_structure_and_state(other)
2048            && self
2049                .properties
2050                .iter()
2051                .filter(relevant)
2052                .eq(other.properties.iter().filter(relevant))
2053            && self.children.len() == other.children.len()
2054            && self
2055                .children
2056                .iter()
2057                .zip(&other.children)
2058                .all(|(child, other)| child.same_frame_inputs(other))
2059    }
2060
2061    /// Compare a paint layer's content independently of its composited opacity.
2062    #[doc(hidden)]
2063    pub fn same_paint_except_opacity(&self, other: &Self) -> bool {
2064        let without_opacity = |(name, _): &(&&str, &Value)| **name != "opacity";
2065        self.shares_storage_with(other)
2066            || self.same_structure_and_state(other)
2067                && self
2068                    .properties
2069                    .iter()
2070                    .filter(without_opacity)
2071                    .eq(other.properties.iter().filter(without_opacity))
2072                && self.children == other.children
2073    }
2074    /// An empty slot keeps the generated event paths stable across conditional renders.
2075    pub fn hidden() -> Self {
2076        let mut node = Self::new("Empty", None);
2077        node.properties.insert("visible", Value::Bool(false));
2078        node
2079    }
2080    /// The source ID of a named element, including elements loaded at runtime.
2081    pub fn element_id(&self) -> Option<&str> {
2082        self.id.or(self.owned_id.as_deref())
2083    }
2084
2085    #[doc(hidden)]
2086    pub fn shared_element_id(&self) -> Option<Arc<str>> {
2087        self.owned_id.clone()
2088    }
2089
2090    #[doc(hidden)]
2091    pub fn element_id_owned(&self) -> Option<std::borrow::Cow<'static, str>> {
2092        use std::borrow::Cow;
2093        self.id
2094            .map(Cow::Borrowed)
2095            .or_else(|| self.owned_id.as_ref().map(|id| Cow::Owned(id.to_string())))
2096    }
2097
2098    #[doc(hidden)]
2099    pub fn set_owned_id(&mut self, id: Option<Arc<str>>) {
2100        let data = self.data_mut();
2101        data.id = None;
2102        data.owned_id = id;
2103    }
2104
2105    #[doc(hidden)]
2106    pub fn set_static_id(&mut self, id: Option<&'static str>) {
2107        let data = self.data_mut();
2108        data.id = id;
2109        data.owned_id = None;
2110    }
2111
2112    #[doc(hidden)]
2113    pub fn set_instance_geometry_handle(&mut self, handle: GeometryHandle) {
2114        self.data_mut().instance_geometry_handle = Some(handle);
2115    }
2116
2117    /// Set the instance's placement in its parent without invalidating the
2118    /// plans for the component's own children.
2119    #[doc(hidden)]
2120    pub fn set_instance_layout_property(&mut self, name: &'static str, value: Value) {
2121        self.data_mut().properties.insert(name, value);
2122    }
2123
2124    pub fn find(&self, id: &str) -> Option<&Node> {
2125        if self.element_id() == Some(id) {
2126            Some(self)
2127        } else {
2128            self.children.iter().find_map(|n| n.find(id))
2129        }
2130    }
2131
2132    pub fn length(&self, name: &str) -> Option<f32> {
2133        match self.properties.get(name) {
2134            Some(Value::Length(Length(value))) if value.is_finite() => {
2135                Some(value.clamp(-1_000_000.0, 1_000_000.0) as f32)
2136            }
2137            _ => None,
2138        }
2139    }
2140
2141    pub fn relative_length(&self, name: &str, reference: f32) -> Option<f32> {
2142        match self.properties.get(name) {
2143            Some(Value::Percent(Percent(factor))) if factor.is_finite() => {
2144                Some((factor * f64::from(reference)).clamp(-1_000_000.0, 1_000_000.0) as f32)
2145            }
2146            _ => self.length(name),
2147        }
2148    }
2149
2150    pub fn boolean(&self, name: &str, default: bool) -> bool {
2151        match self.properties.get(name) {
2152            Some(Value::Bool(value)) => *value,
2153            _ => default,
2154        }
2155    }
2156
2157    pub fn text(&self, name: &str) -> Option<&str> {
2158        match self.properties.get(name) {
2159            Some(Value::String(value)) => Some(value),
2160            Some(Value::StyledText(value)) => Some(value.text()),
2161            _ => None,
2162        }
2163    }
2164
2165    pub fn font(&self, name: &str) -> Option<&Font> {
2166        match self.properties.get(name) {
2167            Some(Value::Font(font)) => Some(font),
2168            _ => None,
2169        }
2170    }
2171
2172    pub fn font_size(&self) -> Option<f32> {
2173        self.length("font-size")
2174            .or_else(|| self.font("font").and_then(Font::finite_size))
2175    }
2176
2177    pub fn styled_text(&self, name: &str) -> Option<&StyledText> {
2178        match self.properties.get(name) {
2179            Some(Value::StyledText(value)) => Some(value),
2180            _ => None,
2181        }
2182    }
2183
2184    /// Resolve a link only while the displayed document matches the live binding.
2185    #[doc(hidden)]
2186    pub fn try_prepare_text_link<E>(
2187        &self,
2188        index: usize,
2189        input: InputRoute<'_>,
2190        live: impl FnOnce() -> Result<StyledText, E>,
2191    ) -> Result<Option<&str>, E> {
2192        let Some(document) = self.styled_text("text") else {
2193            return Ok(None);
2194        };
2195        let Some(link) = document.links().get(index) else {
2196            return Ok(None);
2197        };
2198        input.try_prepare(
2199            || Ok(true),
2200            || Ok((live()? == *document).then_some(link.href.as_ref())),
2201        )
2202    }
2203
2204    #[doc(hidden)]
2205    pub fn prepare_text_link(
2206        &self,
2207        index: usize,
2208        input: InputRoute<'_>,
2209        live: impl FnOnce() -> StyledText,
2210    ) -> Option<&str> {
2211        self.try_prepare_text_link(index, input, || Ok::<_, std::convert::Infallible>(live()))
2212            .unwrap_or_else(|error| match error {})
2213    }
2214
2215    pub fn strings(&self, name: &str) -> &[String] {
2216        match self.properties.get(name) {
2217            Some(Value::StringList(values)) => values,
2218            _ => &[],
2219        }
2220    }
2221
2222    pub fn float(&self, name: &str) -> Option<f32> {
2223        self.number(name)
2224            .map(|value| value.clamp(-1_000_000.0, 1_000_000.0) as f32)
2225    }
2226
2227    pub fn number(&self, name: &str) -> Option<f64> {
2228        match self.properties.get(name) {
2229            Some(Value::Float(value)) if value.is_finite() => Some(*value),
2230            _ => None,
2231        }
2232    }
2233
2234    /// Visual opacity has no effect on layout, focus or hit testing.
2235    pub fn opacity(&self) -> f32 {
2236        self.number("opacity").unwrap_or(1.0).clamp(0.0, 1.0) as f32
2237    }
2238
2239    /// Finite stacking order within an ordinary sibling list.
2240    pub fn z(&self) -> f64 {
2241        self.number("z").filter(|&z| z != 0.0).unwrap_or_default()
2242    }
2243
2244    pub fn orientation(&self) -> Orientation {
2245        match self.properties.get("orientation") {
2246            Some(Value::Orientation(value)) => *value,
2247            _ if matches!(self.kind, "ScrollBar" | "ScrollIndicator" | "ToolSeparator") => {
2248                Orientation::Vertical
2249            }
2250            _ => Orientation::Horizontal,
2251        }
2252    }
2253
2254    pub fn dial_input_mode(&self) -> DialInputMode {
2255        match self.properties.get("input-mode") {
2256            Some(Value::DialInputMode(value)) => *value,
2257            _ => DialInputMode::Circular,
2258        }
2259    }
2260
2261    pub fn scroll_bar_policy(&self, orientation: Orientation) -> ScrollBarPolicy {
2262        let property = match orientation {
2263            Orientation::Horizontal => "horizontal-scroll-bar-policy",
2264            Orientation::Vertical => "vertical-scroll-bar-policy",
2265        };
2266        match self.properties.get(property) {
2267            Some(Value::ScrollBarPolicy(policy)) => *policy,
2268            _ => ScrollBarPolicy::AsNeeded,
2269        }
2270    }
2271
2272    pub fn text_wrap(&self) -> TextWrap {
2273        match self.properties.get("wrap") {
2274            Some(Value::TextWrap(wrap)) => *wrap,
2275            _ => TextWrap::default(),
2276        }
2277    }
2278
2279    pub fn is_password(&self) -> bool {
2280        self.input_type() == InputType::Password
2281    }
2282
2283    pub fn password_masked(&self) -> bool {
2284        self.is_password() && !self.boolean("password-visible", false)
2285    }
2286
2287    pub fn dialog_role(&self) -> DialogRole {
2288        match self.properties.get("role") {
2289            Some(Value::DialogRole(role)) => *role,
2290            _ => DialogRole::default(),
2291        }
2292    }
2293
2294    pub fn standard_button_kind(&self) -> Option<StandardButtonKind> {
2295        match (self.kind, self.properties.get("kind")) {
2296            ("Button", Some(Value::StandardButtonKind(kind))) => Some(*kind),
2297            _ => None,
2298        }
2299    }
2300
2301    pub fn swipe_side(&self) -> SwipeSide {
2302        match self.properties.get("open-side") {
2303            Some(Value::SwipeSide(side)) => *side,
2304            _ => SwipeSide::Closed,
2305        }
2306    }
2307
2308    #[doc(hidden)]
2309    pub fn accepts_swipe_side(&self, current: SwipeSide, side: SwipeSide) -> bool {
2310        self.swipe_side() == current
2311            && current != side
2312            && (side == SwipeSide::Closed || self.swipe_panel(side).is_some())
2313    }
2314
2315    pub fn swipe_panel(&self, side: SwipeSide) -> Option<&Node> {
2316        let kind = side.panel()?;
2317        self.children
2318            .iter()
2319            .find(|child| child.kind == kind && child.is_visible())
2320    }
2321
2322    pub fn drawer_edge(&self) -> DrawerEdge {
2323        match self.properties.get("edge") {
2324            Some(Value::DrawerEdge(edge)) => *edge,
2325            _ => DrawerEdge::Left,
2326        }
2327    }
2328
2329    pub fn selection_target(&self) -> SelectionTarget {
2330        match self.properties.get("selection-target") {
2331            Some(Value::SelectionTarget(target)) => *target,
2332            _ => SelectionTarget::Rows,
2333        }
2334    }
2335
2336    pub fn is_visible(&self) -> bool {
2337        self.boolean("visible", true)
2338            && (!is_window_overlay(self.kind) || self.boolean("open", false))
2339    }
2340
2341    #[doc(hidden)]
2342    pub fn handles_wheel(&self) -> bool {
2343        self.kind == "WheelHandler" || self.kind == "TouchArea" && self.scroll_event_handler
2344    }
2345
2346    #[doc(hidden)]
2347    pub fn accepts_pointer_button(&self, button: PointerButton) -> bool {
2348        match self.properties.get("accepted-buttons") {
2349            Some(Value::PointerButtons(buttons)) => buttons.contains(button),
2350            _ => true,
2351        }
2352    }
2353
2354    pub fn cursor_shape(&self) -> CursorShape {
2355        match self.properties.get("cursor-shape") {
2356            Some(Value::CursorShape(shape)) => *shape,
2357            _ => CursorShape::Auto,
2358        }
2359    }
2360
2361    pub fn is_modal(&self) -> bool {
2362        is_modal_overlay(self.kind) || self.kind == "PopupWindow" && self.boolean("modal", false)
2363    }
2364
2365    pub fn stack_page_index(&self) -> Option<usize> {
2366        self.stack_route_index(self.stack.as_ref()?.current()?)
2367    }
2368
2369    #[doc(hidden)]
2370    pub fn stack_route_index(&self, page: &str) -> Option<usize> {
2371        self.children
2372            .iter()
2373            .position(|node| node.text("__stack-route").or_else(|| node.element_id()) == Some(page))
2374    }
2375
2376    pub fn int(&self, name: &str) -> Option<i64> {
2377        match self.properties.get(name) {
2378            Some(Value::Int(value)) => Some(*value),
2379            _ => None,
2380        }
2381    }
2382
2383    pub fn image(&self, name: &str) -> Option<Image> {
2384        match self.properties.get(name) {
2385            Some(Value::Image(value)) => Some(*value),
2386            _ => None,
2387        }
2388    }
2389
2390    pub fn image_asset(&self, name: &str) -> Option<ImageAsset> {
2391        match self.properties.get(name) {
2392            Some(Value::Image(value)) => Some((*value).into()),
2393            Some(Value::ImageAsset(value)) => Some(value.clone()),
2394            _ => None,
2395        }
2396    }
2397
2398    pub fn image_fit(&self, name: &str) -> Option<ImageFit> {
2399        match self.properties.get(name) {
2400            Some(Value::ImageFit(value)) => Some(*value),
2401            _ => None,
2402        }
2403    }
2404
2405    pub fn image_tile_mode(&self, name: &str) -> ImageTileMode {
2406        match self.properties.get(name) {
2407            Some(Value::ImageTileMode(value)) => *value,
2408            _ => ImageTileMode::default(),
2409        }
2410    }
2411
2412    pub fn color(&self, name: &str) -> Option<Color> {
2413        match self.properties.get(name) {
2414            Some(Value::Color(value) | Value::Brush(Brush::Solid(value))) => Some(*value),
2415            _ => None,
2416        }
2417    }
2418
2419    pub fn color_scheme(&self) -> Option<ColorScheme> {
2420        match self.properties.get("color-scheme") {
2421            Some(Value::ColorScheme(scheme)) => Some(*scheme),
2422            _ => None,
2423        }
2424    }
2425
2426    /// Look up a child by the logical index used in scene paths.
2427    pub fn child_at(&self, index: usize) -> Option<&Self> {
2428        self.children
2429            .get(self.table_column_window.dense_index(index)?)
2430    }
2431
2432    #[doc(hidden)]
2433    pub fn child_at_mut(&mut self, index: usize) -> Option<&mut Self> {
2434        let index = self.table_column_window.dense_index(index)?;
2435        self.children.get_mut(index)
2436    }
2437
2438    /// Iterate stored children with their logical indices.
2439    pub fn materialized_children(
2440        &self,
2441    ) -> impl DoubleEndedIterator<Item = (usize, &Self)> + ExactSizeIterator {
2442        self.children
2443            .iter()
2444            .enumerate()
2445            .map(|(index, child)| (self.table_column_window.logical_index(index), child))
2446    }
2447
2448    pub fn at_path(&self, path: &[usize]) -> Option<&Self> {
2449        let mut node = self;
2450        for &index in path {
2451            node = node.child_at(index)?;
2452        }
2453        Some(node)
2454    }
2455
2456    /// Check the state that controls which descendants may receive input.
2457    #[doc(hidden)]
2458    pub fn try_input_scope_available<E>(
2459        &self,
2460        child: Option<&Self>,
2461        open: impl FnOnce() -> Result<bool, E>,
2462        checkable: impl FnOnce() -> Result<bool, E>,
2463        checked: impl FnOnce() -> Result<bool, E>,
2464        swipe_side: impl FnOnce() -> Result<SwipeSide, E>,
2465    ) -> Result<bool, E> {
2466        if is_window_overlay(self.kind) && !open()? {
2467            return Ok(false);
2468        }
2469        let Some(child) = child else {
2470            return Ok(true);
2471        };
2472        if self.kind == "GroupBox" && checkable()? && !checked()? {
2473            return Ok(false);
2474        }
2475        if self.kind == "SwipeDelegate" && matches!(child.kind, "SwipeLeft" | "SwipeRight") {
2476            return Ok(swipe_side()?.panel() == Some(child.kind));
2477        }
2478        Ok(true)
2479    }
2480
2481    #[doc(hidden)]
2482    pub fn input_scope_available(
2483        &self,
2484        child: Option<&Self>,
2485        open: impl FnOnce() -> bool,
2486        checkable: impl FnOnce() -> bool,
2487        checked: impl FnOnce() -> bool,
2488        swipe_side: impl FnOnce() -> SwipeSide,
2489    ) -> bool {
2490        self.try_input_scope_available(
2491            child,
2492            || Ok::<_, std::convert::Infallible>(open()),
2493            || Ok(checkable()),
2494            || Ok(checked()),
2495            || Ok(swipe_side()),
2496        )
2497        .unwrap_or_else(|error| match error {})
2498    }
2499
2500    fn scene_input_scope_available(&self, child: Option<&Self>) -> bool {
2501        self.input_scope_available(
2502            child,
2503            || self.boolean("open", false),
2504            || self.group_checkable(),
2505            || self.boolean("checked", true),
2506            || self.swipe_side(),
2507        )
2508    }
2509
2510    pub fn interactive_at_path(&self, path: &[usize]) -> Option<&Self> {
2511        let mut node = self;
2512        for (depth, index) in path.iter().enumerate() {
2513            if !node.boolean("visible", true) || !node.enables_children() {
2514                return None;
2515            }
2516            let child = node.child_at(*index)?;
2517            if !node.scene_input_scope_available(Some(child)) {
2518                return None;
2519            }
2520            let has_page_content = depth + 1 < path.len() || node.kind != "TabWidget";
2521            if has_page_content {
2522                let active = match node.kind {
2523                    "TabWidget" | "SwipeView" => group_index(node),
2524                    "StackView" => node.stack_page_index(),
2525                    _ => Some(*index),
2526                };
2527                if active != Some(*index) {
2528                    return None;
2529                }
2530            }
2531            node = child;
2532        }
2533        (node.boolean("visible", true)
2534            && node.boolean("enabled", true)
2535            && node.scene_input_scope_available(None))
2536        .then_some(node)
2537    }
2538
2539    /// Resolve the editable cell that displayed the draft's original text.
2540    #[doc(hidden)]
2541    pub fn table_cell_commit_target(&self, path: &[usize], original: &str) -> Option<&Self> {
2542        self.interactive_at_path(path).filter(|node| {
2543            editable_table_cell(node) && node.text("text").unwrap_or_default() == original
2544        })
2545    }
2546
2547    /// Resolve a scene target for an event without an explicit payload.
2548    #[doc(hidden)]
2549    pub fn dispatch_target(&self, path: &[usize], event: &str) -> Option<&Self> {
2550        let node = self.at_path(path)?;
2551        let target = if node.terminal_dispatch(event) {
2552            node
2553        } else {
2554            self.interactive_at_path(path)?
2555        };
2556        (event != "accepted" || !is_text_input(target.kind) || target.accepts_text_submission())
2557            .then_some(target)
2558    }
2559
2560    fn terminal_dispatch(&self, event: &str) -> bool {
2561        matches!(
2562            (self.kind, event),
2563            ("ScaleRotateGestureHandler", "ended" | "cancelled")
2564                | ("SwipeGestureHandler", "swiped" | "cancelled")
2565                | ("HoverHandler", "exited")
2566        )
2567    }
2568
2569    #[doc(hidden)]
2570    pub fn focus_event_target(&self, path: &[usize], event: FocusEvent) -> Option<&Self> {
2571        let node = if event.is_loss() {
2572            self.at_path(path)
2573        } else {
2574            self.interactive_at_path(path)
2575        };
2576        node.filter(|node| node.kind == "FocusScope")
2577    }
2578
2579    #[doc(hidden)]
2580    pub fn key_event_target(&self, path: &[usize], phase: KeyPhase) -> Option<&Self> {
2581        self.interactive_at_path(path)
2582            .filter(|node| node.kind == "FocusScope" && node.key_handlers & phase.mask() != 0)
2583    }
2584
2585    pub fn group_checkable(&self) -> bool {
2586        self.kind == "GroupBox" && self.boolean("checkable", false)
2587    }
2588
2589    pub fn group_content_enabled(&self) -> bool {
2590        !self.group_checkable() || self.boolean("checked", true)
2591    }
2592
2593    #[doc(hidden)]
2594    pub fn control_target(&self, path: &[usize], action: ControlAction) -> Option<&Self> {
2595        if action != ControlAction::Drawer(true) {
2596            return self.interactive_at_path(path);
2597        }
2598        let node = match path.split_last() {
2599            Some((&index, parent)) => {
2600                let parent = self.interactive_at_path(parent)?;
2601                if !parent.group_content_enabled() {
2602                    return None;
2603                }
2604                parent.child_at(index)?
2605            }
2606            None => self,
2607        };
2608        (node.kind == "Drawer" && node.boolean("visible", true) && node.boolean("enabled", true))
2609            .then_some(node)
2610    }
2611
2612    /// Identity of the materialized row in its view, for routing and focus.
2613    pub fn routing_row_key(&self) -> Option<RowKey> {
2614        self.row_key.map(|key| key.in_view(self.row_scope))
2615    }
2616
2617    /// Identity of the virtual row containing this scene path.
2618    pub fn row_key_at(&self, path: &[usize]) -> Option<RowKey> {
2619        let mut node = self;
2620        let mut key = None;
2621        for &index in path {
2622            node = node.child_at(index)?;
2623            if node.kind == "ListRow" {
2624                key = node.routing_row_key();
2625            }
2626        }
2627        key
2628    }
2629
2630    /// Find the displayed index of a source row identity. The source index is a lookup hint.
2631    pub fn displayed_row_for_key(&self, key: RowKey, source_index: usize) -> Option<usize> {
2632        if let Some(tree) = &self.tree {
2633            tree.position_of_source_key(key, source_index)
2634        } else {
2635            self.row_locator
2636                .as_ref()?
2637                .position_of_source_key(key, source_index)
2638        }
2639    }
2640}