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