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 = 1;
6
7mod animation;
8mod button_group;
9mod calendar;
10mod child_window;
11mod color_picker;
12mod combo;
13mod controls;
14mod delegate;
15mod double_spin;
16mod drag;
17mod focus;
18mod font_picker;
19mod geometry;
20mod hover;
21mod image_animation;
22mod keyboard;
23mod list;
24mod localization;
25mod model;
26mod native_dialog;
27mod picker;
28mod pointer;
29mod property;
30mod range;
31mod repeat;
32mod row_heights;
33mod scale_rotate;
34mod scene_plan;
35mod split;
36mod stack;
37mod styled_text;
38mod swipe_gesture;
39mod table_clipboard;
40mod table_history;
41mod table_rows;
42mod table_selection;
43mod text_input;
44mod time_picker;
45mod timer;
46mod tree;
47mod tumbler;
48mod viewport;
49mod window_status;
50pub use animation::{Animation, Easing, SceneTransition, StateTiming};
51#[doc(hidden)]
52pub use button_group::{
53    ButtonGroup, ButtonGroupMembership, ButtonGroupSelection, RadioMembership, bind_button_group,
54    bind_check_group, radio_value, summarize_checks,
55};
56pub use calendar::{CalendarAction, CalendarState, Date, is_calendar_control};
57#[doc(hidden)]
58pub use calendar::{CalendarCell, CalendarCells, DateBounds, DatePopupState};
59#[doc(hidden)]
60pub use child_window::{SecondaryWindowRegistration, SecondaryWindowSlot};
61#[doc(hidden)]
62pub use color_picker::ColorPopupState;
63pub use combo::{
64    ChoiceIdentity, choice_enabled, choice_identity, combo_count, combo_find_enabled_label,
65    combo_find_label, combo_index, combo_label, combo_labels, combo_row_index, combo_row_key,
66    combo_text,
67};
68#[doc(hidden)]
69pub use combo::{ComboItems, ComboModel, combo_model_is_current, combo_value};
70pub use controls::{
71    ActionKey, ControlAction, DialogCommand, DialogRole, PopupPlacement, SpinAction, SpinRange,
72    StandardButtonKind, SwipeSide, TableColumnOrder, TableHeader, TableSort, button_text,
73    combo_editable, delay_millis, dialog_button_action, group_index, group_item, is_button,
74    is_modal_overlay, is_pane, is_spin_box, is_window_overlay, page_indicator_count,
75    page_indicator_index, resizable_table_column, resolve_swipe_index, search_suggestion,
76    search_suggestions, spin_editable, spin_text, spin_value_after, text_input_value,
77};
78#[doc(hidden)]
79pub use delegate::{ComponentRepeater, RowContext};
80pub use double_spin::{
81    DecimalSpinRange, SpinDecimal, decimal_separator, decimal_spin_value_after, spin_text_is_valid,
82};
83pub use drag::{DragAction, DragEvent, is_drag_area};
84pub use focus::{
85    FocusAction, FocusContext, FocusEvent, FocusHandle, FocusReason, FocusRequest, FocusRequests,
86    TextCommand,
87};
88pub use font_picker::Font;
89#[doc(hidden)]
90pub use font_picker::{FontPopupState, is_font_family_choice, set_font_family_choices};
91#[doc(hidden)]
92pub use geometry::{GeometryHandle, GeometryMetric};
93pub use hover::{CursorShape, HoverHandle};
94pub use image_animation::{ImageAnimation, ImageAnimationFrame};
95#[doc(hidden)]
96pub use image_animation::{ImagePlaybackQueue, ImagePlaybackRegistration, ImagePlaybackSlot};
97pub use keyboard::{EventResult, KeyEvent, KeyModifiers, KeyPhase, WheelEvent};
98pub use list::{ListMetrics, RowKey};
99#[doc(hidden)]
100pub use list::{
101    ListModel, ListRowLocator, ListRowRenderer, RowLifetime, TableCellEditor, TableColumnWindow,
102    project_standard_table_rows, standard_list_rows, standard_list_rows_in_view,
103    standard_table_rows, standard_table_rows_in_order, standard_table_rows_with_editors_in_order,
104    standard_table_rows_with_header,
105};
106pub use localization::LocaleContext;
107#[doc(hidden)]
108pub use localization::{LocaleBinding, LocaleId, TranslationCatalog, TranslationValue};
109pub use model::VecModel;
110pub use native_dialog::{
111    FileDialogMode, FileDialogOptions, FileDialogSelection, MessageButtons, MessageDialogOptions,
112    MessageLevel,
113};
114#[doc(hidden)]
115pub use native_dialog::{
116    NativeDialogOptions, NativeDialogPresentation, NativeDialogQueue, NativeDialogRegistration,
117    NativeDialogResult, NativeDialogSlot,
118};
119pub use pointer::{
120    PointerButton, PointerButtons, PointerEvent, PointerEventKind, PointerHandle, TouchPoint,
121    TouchPoints,
122};
123pub use property::{ChangeSignal, InputProperty, Property};
124pub use range::{
125    DialInputMode, IndicatorState, RangeAction, ScrollBarRange, ScrollSnapMode, SliderInterval,
126    SliderRange, indicator_state, progress_value,
127};
128#[doc(hidden)]
129pub use repeat::Repeater;
130#[doc(hidden)]
131pub use row_heights::{RowHeightOverrides, RowHeightProjection, RowHeights};
132pub use scale_rotate::{ScaleRotateHandle, ScaleRotateSample};
133#[doc(hidden)]
134pub use scene_plan::{
135    GridCellPosition, GridCellSlot, GridPlanner, GridTrackInput, StaticVectorPath, VectorSegment,
136};
137#[doc(hidden)]
138pub use split::{
139    SplitHandleInput, SplitResizeHandle, decode_split_sizes, decode_split_state,
140    encode_split_sizes, encode_split_state,
141};
142#[doc(hidden)]
143pub use stack::StackChange;
144pub use stack::{StackNavigation, StackSnapshot, StackState};
145use std::{collections::BTreeMap, rc::Rc, sync::Arc};
146pub use styled_text::{StyledLink, StyledRun, StyledText, StyledTextError, TextStyle};
147pub use swipe_gesture::{SwipeHandle, SwipeSample};
148#[doc(hidden)]
149pub use table_clipboard::{
150    TablePaste, TablePasteInput, paste_table_text, table_paste_bool, table_paste_check_state,
151};
152#[doc(hidden)]
153pub use table_history::{TableEditHistory, TablePasteHistory, TableRowPatch};
154pub use table_rows::{
155    TableEditPosition, TableRowOrder, TableRowPositions, TableRows, next_table_edit_cell,
156};
157pub use table_selection::{
158    RowSelection, SelectionTarget, TableSelection, TableSelectionAction, TableSelectionSnapshot,
159};
160pub use table_selection::{copy_table_text, copy_table_text_in_order};
161pub use text_input::InputType;
162pub use time_picker::Time;
163#[doc(hidden)]
164pub use time_picker::{TimePickerOptions, TimePopupState};
165#[doc(hidden)]
166pub use timer::{
167    TimerCommand, TimerConfig, TimerDelivery, TimerQueue, TimerRegistration, TimerSlot, TimerTick,
168};
169#[doc(hidden)]
170pub use tree::TreeExpansionChange;
171pub use tree::{TreeAction, TreeCommand, TreeItem, TreeSelectionAction, TreeSnapshot, TreeState};
172pub use tumbler::{Tumbler, TumblerItems};
173pub use viewport::{
174    ScrollAction, ScrollAlignment, ScrollContext, ScrollRequest, ScrollRequests, ViewportHandle,
175    ViewportMotion,
176};
177pub use window_status::{WindowCommand, WindowStatus};
178#[doc(hidden)]
179pub use window_status::{WindowMetric, WindowStatusBinding};
180
181/// A UI-thread handle that can be captured by callbacks without keeping a component alive.
182pub struct WeakComponent<C>(Rc<dyn Fn() -> Option<C>>);
183
184impl<C> Clone for WeakComponent<C> {
185    fn clone(&self) -> Self {
186        Self(self.0.clone())
187    }
188}
189
190impl<C: 'static> WeakComponent<C> {
191    #[doc(hidden)]
192    pub fn new<S: 'static>(state: &Rc<S>, wrap: fn(Rc<S>) -> C) -> Self {
193        let state = Rc::downgrade(state);
194        Self(Rc::new(move || state.upgrade().map(wrap)))
195    }
196
197    pub fn upgrade(&self) -> Option<C> {
198        (self.0)()
199    }
200}
201
202/// The backend-independent interface implemented by generated UI components.
203pub trait Component {
204    fn render(&self) -> Node;
205
206    /// Supply the language shared by the desktop hosting this component.
207    #[doc(hidden)]
208    fn set_locale_context(&self, _context: LocaleContext) {}
209
210    /// Return the current scene. Reactive components may reuse a clean snapshot.
211    fn render_shared(&self) -> Rc<Node> {
212        Rc::new(self.render())
213    }
214
215    /// Report invalidation caused by a shared reactive dependency.
216    fn scene_dirty(&self) -> bool {
217        false
218    }
219
220    /// Decide whether the host may close this window.
221    fn close_requested(&mut self) -> bool {
222        true
223    }
224
225    /// Consume a close command emitted by the component.
226    fn take_window_close_request(&mut self) -> bool {
227        false
228    }
229
230    /// Consume presentation commands in the order emitted by the component.
231    fn take_window_commands(&mut self) -> Vec<WindowCommand> {
232        Vec::new()
233    }
234
235    #[doc(hidden)]
236    fn has_window_commands(&self) -> bool {
237        false
238    }
239
240    /// Publish native state after reading it from the window backend.
241    fn publish_window_status(&self, _status: WindowStatus) {}
242
243    /// Native child windows currently requested by this component.
244    #[doc(hidden)]
245    fn secondary_windows(&self) -> Option<Rc<[SecondaryWindowRegistration]>> {
246        None
247    }
248
249    /// Render the requested model rows of a virtual view in a base scene.
250    fn list_rows(&self, _path: &[usize], _rows: std::ops::Range<usize>) -> Vec<Node> {
251        Vec::new()
252    }
253
254    #[doc(hidden)]
255    fn next_table_edit_cell(
256        &self,
257        _scene: &Node,
258        _path: &[usize],
259        _origin: TableEditPosition,
260        _columns: &[usize],
261        _backward: bool,
262    ) -> Option<TableEditPosition> {
263        None
264    }
265
266    #[doc(hidden)]
267    fn copy_table_at(&self, _scene: &Node, _path: &[usize], _columns: &[usize]) -> Option<String> {
268        None
269    }
270
271    #[doc(hidden)]
272    fn prepare_table_paste(
273        &self,
274        _scene: &Node,
275        _path: &[usize],
276        _row: usize,
277        _columns: Vec<usize>,
278    ) -> Option<TablePaste> {
279        None
280    }
281
282    #[doc(hidden)]
283    fn replay_table_paste_at(&self, _scene: &Node, _path: &[usize], _redo: bool) -> bool {
284        false
285    }
286
287    #[doc(hidden)]
288    fn replay_table_edit_at(&self, scene: &Node, path: &[usize], redo: bool) -> bool {
289        self.replay_table_paste_at(scene, path, redo)
290    }
291
292    fn dispatch(&mut self, element_id: &str, event: &str) -> bool;
293
294    /// Commit the complete value of an editable text item after input validation.
295    fn edit_at(&mut self, _scene: &Node, _path: &[usize], _text: String) -> bool {
296        false
297    }
298
299    /// Commit a TableCell or TreeCell draft only if its model row and original value still match.
300    fn commit_table_cell(
301        &mut self,
302        _scene: &Node,
303        _path: &[usize],
304        _original: &str,
305        _text: String,
306    ) -> bool {
307        false
308    }
309
310    /// Apply a range control action through the same path used by pointer and keyboard input.
311    fn adjust_range_at(&mut self, _scene: &Node, _path: &[usize], _action: RangeAction) -> bool {
312        false
313    }
314
315    fn control_at(&mut self, _scene: &Node, _path: &[usize], _action: ControlAction) -> bool {
316        false
317    }
318
319    #[doc(hidden)]
320    fn drag_event_at(&mut self, _scene: &Node, _path: &[usize], _event: &DragEvent) -> bool {
321        false
322    }
323
324    #[doc(hidden)]
325    fn key_event_at(
326        &mut self,
327        _scene: &Node,
328        _path: &[usize],
329        _phase: KeyPhase,
330        _event: &KeyEvent,
331    ) -> EventResult {
332        EventResult::Reject
333    }
334
335    #[doc(hidden)]
336    fn focus_event_at(&mut self, _scene: &Node, _path: &[usize], _event: FocusEvent) -> bool {
337        false
338    }
339
340    #[doc(hidden)]
341    fn wheel_event_at(
342        &mut self,
343        _scene: &Node,
344        _path: &[usize],
345        _event: &WheelEvent,
346    ) -> EventResult {
347        EventResult::Reject
348    }
349
350    #[doc(hidden)]
351    fn pointer_event_at(&mut self, _scene: &Node, _path: &[usize], _event: &PointerEvent) -> bool {
352        false
353    }
354
355    fn resize_split_at(
356        &mut self,
357        _scene: &Node,
358        _path: &[usize],
359        _weights: &[(usize, f32)],
360    ) -> bool {
361        false
362    }
363
364    fn resize_split_sizes_at(
365        &mut self,
366        _scene: &Node,
367        _path: &[usize],
368        _sizes: &[(usize, f32)],
369    ) -> bool {
370        false
371    }
372
373    /// Dispatch to the node hit by the backend. IDs may repeat in component instances.
374    fn dispatch_at(&mut self, scene: &Node, path: &[usize], event: &str) -> bool {
375        scene
376            .at_path(path)
377            .and_then(|node| node.id)
378            .is_some_and(|id| self.dispatch(id, event))
379    }
380}
381
382impl<T: Component + ?Sized> Component for Box<T> {
383    fn render(&self) -> Node {
384        (**self).render()
385    }
386    fn set_locale_context(&self, context: LocaleContext) {
387        (**self).set_locale_context(context);
388    }
389    fn focus_event_at(&mut self, scene: &Node, path: &[usize], event: FocusEvent) -> bool {
390        (**self).focus_event_at(scene, path, event)
391    }
392    fn drag_event_at(&mut self, scene: &Node, path: &[usize], event: &DragEvent) -> bool {
393        (**self).drag_event_at(scene, path, event)
394    }
395    fn key_event_at(
396        &mut self,
397        scene: &Node,
398        path: &[usize],
399        phase: KeyPhase,
400        event: &KeyEvent,
401    ) -> EventResult {
402        (**self).key_event_at(scene, path, phase, event)
403    }
404    fn render_shared(&self) -> Rc<Node> {
405        (**self).render_shared()
406    }
407    fn scene_dirty(&self) -> bool {
408        (**self).scene_dirty()
409    }
410    fn close_requested(&mut self) -> bool {
411        (**self).close_requested()
412    }
413    fn take_window_close_request(&mut self) -> bool {
414        (**self).take_window_close_request()
415    }
416    fn take_window_commands(&mut self) -> Vec<WindowCommand> {
417        (**self).take_window_commands()
418    }
419    fn has_window_commands(&self) -> bool {
420        (**self).has_window_commands()
421    }
422    fn publish_window_status(&self, status: WindowStatus) {
423        (**self).publish_window_status(status);
424    }
425    fn secondary_windows(&self) -> Option<Rc<[SecondaryWindowRegistration]>> {
426        (**self).secondary_windows()
427    }
428
429    fn list_rows(&self, path: &[usize], rows: std::ops::Range<usize>) -> Vec<Node> {
430        (**self).list_rows(path, rows)
431    }
432
433    fn next_table_edit_cell(
434        &self,
435        scene: &Node,
436        path: &[usize],
437        origin: TableEditPosition,
438        columns: &[usize],
439        backward: bool,
440    ) -> Option<TableEditPosition> {
441        (**self).next_table_edit_cell(scene, path, origin, columns, backward)
442    }
443
444    fn copy_table_at(&self, scene: &Node, path: &[usize], columns: &[usize]) -> Option<String> {
445        (**self).copy_table_at(scene, path, columns)
446    }
447
448    fn prepare_table_paste(
449        &self,
450        scene: &Node,
451        path: &[usize],
452        row: usize,
453        columns: Vec<usize>,
454    ) -> Option<TablePaste> {
455        (**self).prepare_table_paste(scene, path, row, columns)
456    }
457
458    fn replay_table_paste_at(&self, scene: &Node, path: &[usize], redo: bool) -> bool {
459        (**self).replay_table_paste_at(scene, path, redo)
460    }
461
462    fn replay_table_edit_at(&self, scene: &Node, path: &[usize], redo: bool) -> bool {
463        (**self).replay_table_edit_at(scene, path, redo)
464    }
465
466    fn dispatch(&mut self, element_id: &str, event: &str) -> bool {
467        (**self).dispatch(element_id, event)
468    }
469
470    fn edit_at(&mut self, scene: &Node, path: &[usize], text: String) -> bool {
471        (**self).edit_at(scene, path, text)
472    }
473
474    fn commit_table_cell(
475        &mut self,
476        scene: &Node,
477        path: &[usize],
478        original: &str,
479        text: String,
480    ) -> bool {
481        (**self).commit_table_cell(scene, path, original, text)
482    }
483
484    fn adjust_range_at(&mut self, scene: &Node, path: &[usize], action: RangeAction) -> bool {
485        (**self).adjust_range_at(scene, path, action)
486    }
487
488    fn control_at(&mut self, scene: &Node, path: &[usize], action: ControlAction) -> bool {
489        (**self).control_at(scene, path, action)
490    }
491
492    fn resize_split_at(&mut self, scene: &Node, path: &[usize], weights: &[(usize, f32)]) -> bool {
493        (**self).resize_split_at(scene, path, weights)
494    }
495    fn resize_split_sizes_at(
496        &mut self,
497        scene: &Node,
498        path: &[usize],
499        sizes: &[(usize, f32)],
500    ) -> bool {
501        (**self).resize_split_sizes_at(scene, path, sizes)
502    }
503
504    fn dispatch_at(&mut self, scene: &Node, path: &[usize], event: &str) -> bool {
505        (**self).dispatch_at(scene, path, event)
506    }
507
508    fn wheel_event_at(&mut self, scene: &Node, path: &[usize], event: &WheelEvent) -> EventResult {
509        (**self).wheel_event_at(scene, path, event)
510    }
511
512    fn pointer_event_at(&mut self, scene: &Node, path: &[usize], event: &PointerEvent) -> bool {
513        (**self).pointer_event_at(scene, path, event)
514    }
515}
516
517#[doc(hidden)]
518pub enum RoutedEvent<'a> {
519    Dispatch(&'a str),
520    Edit(&'a str),
521    CommitCell { original: &'a str, text: &'a str },
522    Range(RangeAction),
523    Control(ControlAction),
524    Drag(&'a DragEvent),
525    Key(KeyPhase, &'a KeyEvent),
526    Wheel(&'a WheelEvent),
527    Pointer(&'a PointerEvent),
528    Focus(FocusEvent),
529    ResizeSplit(&'a [(usize, f32)]),
530    ResizeSplitSizes(&'a [(usize, f32)]),
531}
532
533impl RoutedEvent<'_> {
534    pub fn apply(&self, ui: &mut (impl Component + ?Sized), scene: &Node, path: &[usize]) -> bool {
535        match self {
536            Self::Dispatch(event) => ui.dispatch_at(scene, path, event),
537            Self::Edit(text) => ui.edit_at(scene, path, (*text).into()),
538            Self::CommitCell { original, text } => {
539                ui.commit_table_cell(scene, path, original, (*text).into())
540            }
541            Self::Range(action) => ui.adjust_range_at(scene, path, *action),
542            Self::Control(action) => ui.control_at(scene, path, *action),
543            Self::Drag(event) => ui.drag_event_at(scene, path, event),
544            Self::Key(phase, event) => {
545                ui.key_event_at(scene, path, *phase, event) == EventResult::Accept
546            }
547            Self::Wheel(event) => ui.wheel_event_at(scene, path, event) == EventResult::Accept,
548            Self::Pointer(event) => ui.pointer_event_at(scene, path, event),
549            Self::Focus(event) => ui.focus_event_at(scene, path, *event),
550            Self::ResizeSplit(weights) => ui.resize_split_at(scene, path, weights),
551            Self::ResizeSplitSizes(sizes) => ui.resize_split_sizes_at(scene, path, sizes),
552        }
553    }
554}
555
556#[derive(Clone, Copy, Debug, Default, PartialEq)]
557pub struct Length(pub f64);
558
559#[derive(Clone, Copy, Debug, PartialEq)]
560pub struct Percent(pub f64);
561
562#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
563pub struct Color(pub u32);
564
565#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
566pub enum ColorScheme {
567    #[default]
568    System,
569    Light,
570    Dark,
571}
572
573#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
574pub enum ImageFormat {
575    Png,
576    Svg,
577}
578
579#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
580pub enum Image {
581    #[default]
582    Empty,
583    Embedded {
584        format: ImageFormat,
585        bytes: &'static [u8],
586        size: [u32; 2],
587    },
588    Animated(&'static ImageAnimation),
589    NineSliced {
590        format: ImageFormat,
591        bytes: &'static [u8],
592        size: [u32; 2],
593        edges: NineSlice,
594    },
595}
596
597/// Source edge widths in pixels, clockwise from the top.
598#[derive(Clone, Copy, Debug, PartialEq, Eq)]
599pub struct NineSlice {
600    pub top: u32,
601    pub right: u32,
602    pub bottom: u32,
603    pub left: u32,
604}
605
606impl NineSlice {
607    pub fn fits(self, [width, height]: [u32; 2]) -> bool {
608        self.left.saturating_add(self.right) < width
609            && self.top.saturating_add(self.bottom) < height
610    }
611}
612
613#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
614#[error("nine-slice edges must leave a nonempty center in the source image")]
615pub struct InvalidNineSlice;
616
617impl Image {
618    pub fn size(self) -> [u32; 2] {
619        match self {
620            Self::Empty => [0, 0],
621            Self::Animated(animation) => animation.size(),
622            Self::Embedded { size, .. } | Self::NineSliced { size, .. } => size,
623        }
624    }
625
626    pub fn frame_count(self) -> usize {
627        match self {
628            Self::Empty => 0,
629            Self::Animated(animation) => animation.frame_count(),
630            _ => 1,
631        }
632    }
633
634    pub fn frame(self, index: usize) -> Self {
635        match self {
636            Self::Animated(animation) => animation.frame(index),
637            _ => self,
638        }
639    }
640
641    pub fn with_nine_slice(self, edges: NineSlice) -> Result<Self, InvalidNineSlice> {
642        match self {
643            Self::Embedded {
644                format,
645                bytes,
646                size,
647            }
648            | Self::NineSliced {
649                format,
650                bytes,
651                size,
652                ..
653            } if edges.fits(size) => Ok(Self::NineSliced {
654                format,
655                bytes,
656                size,
657                edges,
658            }),
659            _ => Err(InvalidNineSlice),
660        }
661    }
662}
663
664/// Immutable font data shared by scenes from the same generated UI library.
665pub struct EmbeddedFonts(&'static [&'static [u8]]);
666
667impl EmbeddedFonts {
668    pub const fn new(fonts: &'static [&'static [u8]]) -> Self {
669        Self(fonts)
670    }
671
672    pub fn sources(&self) -> &'static [&'static [u8]] {
673        self.0
674    }
675}
676
677impl PartialEq for EmbeddedFonts {
678    fn eq(&self, other: &Self) -> bool {
679        std::ptr::eq(self, other)
680    }
681}
682
683impl std::fmt::Debug for EmbeddedFonts {
684    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
685        f.debug_struct("EmbeddedFonts")
686            .field("count", &self.0.len())
687            .finish()
688    }
689}
690
691#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
692pub enum ImageFit {
693    Fill,
694    #[default]
695    Contain,
696    Cover,
697    Preserve,
698}
699
700#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
701pub enum ImageTileMode {
702    #[default]
703    Stretch,
704    Repeat,
705    Round,
706}
707
708#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
709pub enum ImageHorizontalAlignment {
710    Left,
711    #[default]
712    Center,
713    Right,
714}
715
716#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
717pub enum ImageVerticalAlignment {
718    Top,
719    #[default]
720    Center,
721    Bottom,
722}
723
724#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
725pub enum ImageRendering {
726    #[default]
727    Smooth,
728    Pixelated,
729}
730
731#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
732pub enum LayoutAlignment {
733    #[default]
734    Stretch,
735    Center,
736    Start,
737    End,
738    SpaceBetween,
739    SpaceAround,
740    SpaceEvenly,
741}
742
743#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
744pub enum CrossAxisAlignment {
745    #[default]
746    Auto,
747    Stretch,
748    Start,
749    End,
750    Center,
751}
752
753#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
754pub enum Orientation {
755    #[default]
756    Horizontal,
757    Vertical,
758}
759
760#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
761pub enum FlickDirection {
762    #[default]
763    Both,
764    Horizontal,
765    Vertical,
766}
767
768#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
769pub enum FlickBoundsBehavior {
770    #[default]
771    StopAtBounds,
772    DragOverBounds,
773    OvershootBounds,
774    DragAndOvershootBounds,
775}
776
777impl FlickBoundsBehavior {
778    pub fn allows_overshoot(self, flick: bool) -> bool {
779        matches!(
780            (self, flick),
781            (Self::DragAndOvershootBounds, _)
782                | (Self::DragOverBounds, false)
783                | (Self::OvershootBounds, true)
784        )
785    }
786}
787
788#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
789pub enum FlickBoundsMovement {
790    #[default]
791    FollowBoundsBehavior,
792    StopAtBounds,
793}
794
795impl FlickDirection {
796    pub fn allows(self, axis: Orientation) -> bool {
797        matches!(
798            (self, axis),
799            (Self::Both, _)
800                | (Self::Horizontal, Orientation::Horizontal)
801                | (Self::Vertical, Orientation::Vertical)
802        )
803    }
804}
805
806#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
807pub enum FlexboxLayoutDirection {
808    #[default]
809    Row,
810    RowReverse,
811    Column,
812    ColumnReverse,
813}
814
815#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
816pub enum FlexboxLayoutWrap {
817    #[default]
818    Wrap,
819    NoWrap,
820    WrapReverse,
821}
822
823#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
824pub enum DrawerEdge {
825    #[default]
826    Left,
827    Right,
828    Top,
829    Bottom,
830}
831
832#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
833pub enum ScrollBarPolicy {
834    #[default]
835    AsNeeded,
836    AlwaysOn,
837    AlwaysOff,
838}
839
840#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
841pub enum TextWrap {
842    #[default]
843    WordWrap,
844    NoWrap,
845    CharWrap,
846}
847
848#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
849pub enum TextHorizontalAlignment {
850    #[default]
851    Start,
852    End,
853    Left,
854    Center,
855    Right,
856}
857
858#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
859pub enum TextVerticalAlignment {
860    #[default]
861    Top,
862    Center,
863    Bottom,
864}
865
866#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
867pub enum TextOverflow {
868    #[default]
869    Clip,
870    Elide,
871}
872
873#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
874pub enum CheckState {
875    #[default]
876    Unchecked,
877    PartiallyChecked,
878    Checked,
879}
880
881impl From<bool> for CheckState {
882    fn from(checked: bool) -> Self {
883        if checked {
884            Self::Checked
885        } else {
886            Self::Unchecked
887        }
888    }
889}
890
891impl CheckState {
892    pub fn next(self, tristate: bool) -> Self {
893        match self {
894            Self::Checked => Self::Unchecked,
895            Self::Unchecked if tristate => Self::PartiallyChecked,
896            _ => Self::Checked,
897        }
898    }
899}
900
901#[derive(Clone, Copy, Debug, PartialEq)]
902pub struct GradientStop {
903    pub color: Color,
904    /// Position along the gradient in the range 0.0 to 1.0.
905    pub offset: f64,
906}
907
908#[derive(Clone, Debug, PartialEq)]
909pub enum Brush {
910    Solid(Color),
911    Linear {
912        angle_degrees: f64,
913        stops: Arc<[GradientStop]>,
914    },
915    Radial {
916        stops: Arc<[GradientStop]>,
917    },
918}
919
920impl Default for Brush {
921    fn default() -> Self {
922        Self::Solid(Color::default())
923    }
924}
925
926#[derive(Clone, Debug, PartialEq)]
927pub enum Value {
928    Int(i64),
929    Float(f64),
930    Bool(bool),
931    String(String),
932    StyledText(StyledText),
933    StringList(Vec<String>),
934    ComboModel(ComboModel),
935    Length(Length),
936    Percent(Percent),
937    Color(Color),
938    Brush(Brush),
939    Image(Image),
940    ImageFit(ImageFit),
941    ImageTileMode(ImageTileMode),
942    ImageHorizontalAlignment(ImageHorizontalAlignment),
943    ImageVerticalAlignment(ImageVerticalAlignment),
944    ImageRendering(ImageRendering),
945    LayoutAlignment(LayoutAlignment),
946    CrossAxisAlignment(CrossAxisAlignment),
947    Orientation(Orientation),
948    FlickDirection(FlickDirection),
949    FlickBoundsBehavior(FlickBoundsBehavior),
950    FlickBoundsMovement(FlickBoundsMovement),
951    FlexboxLayoutDirection(FlexboxLayoutDirection),
952    FlexboxLayoutWrap(FlexboxLayoutWrap),
953    DialInputMode(DialInputMode),
954    ScrollBarPolicy(ScrollBarPolicy),
955    ScrollSnapMode(ScrollSnapMode),
956    ScrollAlignment(ScrollAlignment),
957    TextWrap(TextWrap),
958    TextHorizontalAlignment(TextHorizontalAlignment),
959    TextVerticalAlignment(TextVerticalAlignment),
960    TextOverflow(TextOverflow),
961    InputType(InputType),
962    CursorShape(CursorShape),
963    PointerEventKind(PointerEventKind),
964    PointerButton(PointerButton),
965    PointerButtons(PointerButtons),
966    ColorScheme(ColorScheme),
967    FileDialogMode(FileDialogMode),
968    MessageLevel(MessageLevel),
969    MessageButtons(MessageButtons),
970    CheckState(CheckState),
971    DialogRole(DialogRole),
972    StandardButtonKind(StandardButtonKind),
973    SwipeSide(SwipeSide),
974    DragAction(DragAction),
975    DrawerEdge(DrawerEdge),
976    PopupPlacement(PopupPlacement),
977    SelectionTarget(SelectionTarget),
978    Date(Date),
979    Time(Time),
980    Font(Font),
981}
982
983macro_rules! value_from {
984    ($ty:ty, $variant:ident) => {
985        impl From<$ty> for Value {
986            fn from(value: $ty) -> Self {
987                Self::$variant(value)
988            }
989        }
990    };
991}
992value_from!(i64, Int);
993value_from!(f64, Float);
994value_from!(bool, Bool);
995value_from!(String, String);
996value_from!(StyledText, StyledText);
997value_from!(Vec<String>, StringList);
998
999impl From<VecModel<String>> for Value {
1000    fn from(model: VecModel<String>) -> Self {
1001        Self::StringList(model.snapshot())
1002    }
1003}
1004value_from!(Length, Length);
1005value_from!(Percent, Percent);
1006value_from!(Color, Color);
1007value_from!(Image, Image);
1008value_from!(ImageFit, ImageFit);
1009value_from!(ImageTileMode, ImageTileMode);
1010value_from!(ImageHorizontalAlignment, ImageHorizontalAlignment);
1011value_from!(ImageVerticalAlignment, ImageVerticalAlignment);
1012value_from!(ImageRendering, ImageRendering);
1013value_from!(LayoutAlignment, LayoutAlignment);
1014value_from!(CrossAxisAlignment, CrossAxisAlignment);
1015value_from!(Orientation, Orientation);
1016value_from!(FlickDirection, FlickDirection);
1017value_from!(FlickBoundsBehavior, FlickBoundsBehavior);
1018value_from!(FlickBoundsMovement, FlickBoundsMovement);
1019value_from!(FlexboxLayoutDirection, FlexboxLayoutDirection);
1020value_from!(FlexboxLayoutWrap, FlexboxLayoutWrap);
1021value_from!(DialInputMode, DialInputMode);
1022value_from!(ScrollBarPolicy, ScrollBarPolicy);
1023value_from!(ScrollSnapMode, ScrollSnapMode);
1024value_from!(ScrollAlignment, ScrollAlignment);
1025value_from!(TextWrap, TextWrap);
1026value_from!(TextHorizontalAlignment, TextHorizontalAlignment);
1027value_from!(TextVerticalAlignment, TextVerticalAlignment);
1028value_from!(TextOverflow, TextOverflow);
1029value_from!(InputType, InputType);
1030value_from!(CursorShape, CursorShape);
1031value_from!(PointerEventKind, PointerEventKind);
1032value_from!(PointerButton, PointerButton);
1033value_from!(PointerButtons, PointerButtons);
1034value_from!(ColorScheme, ColorScheme);
1035value_from!(FileDialogMode, FileDialogMode);
1036value_from!(MessageLevel, MessageLevel);
1037value_from!(MessageButtons, MessageButtons);
1038value_from!(CheckState, CheckState);
1039value_from!(DialogRole, DialogRole);
1040value_from!(StandardButtonKind, StandardButtonKind);
1041value_from!(SwipeSide, SwipeSide);
1042value_from!(DragAction, DragAction);
1043value_from!(DrawerEdge, DrawerEdge);
1044value_from!(PopupPlacement, PopupPlacement);
1045value_from!(SelectionTarget, SelectionTarget);
1046value_from!(Date, Date);
1047value_from!(Time, Time);
1048value_from!(Font, Font);
1049
1050impl From<Brush> for Value {
1051    fn from(value: Brush) -> Self {
1052        match value {
1053            Brush::Solid(color) => Self::Color(color),
1054            gradient => Self::Brush(gradient),
1055        }
1056    }
1057}
1058
1059#[derive(Clone, Debug)]
1060pub struct Node(NodeStorage);
1061
1062#[derive(Clone, Debug)]
1063#[allow(clippy::large_enum_variant)] // Keep ordinary dynamic nodes inline.
1064enum NodeStorage {
1065    Inline(NodeData),
1066    Shared(Arc<NodeData>),
1067}
1068
1069/// Scene data shared by clones of a node. Mutating a node detaches its data.
1070#[doc(hidden)]
1071#[derive(Clone, Debug, PartialEq)]
1072pub struct NodeData {
1073    pub kind: &'static str,
1074    #[doc(hidden)]
1075    pub application_window: bool,
1076    pub id: Option<&'static str>,
1077    pub properties: BTreeMap<&'static str, Value>,
1078    #[doc(hidden)]
1079    pub fonts: Option<&'static EmbeddedFonts>,
1080    pub tumbler_items: Option<TumblerItems>,
1081    pub children: Vec<Node>,
1082    #[doc(hidden)]
1083    pub table_column_window: TableColumnWindow,
1084    #[doc(hidden)]
1085    pub timers: Vec<TimerRegistration>,
1086    #[doc(hidden)]
1087    pub image_playback: Option<Rc<ImagePlaybackRegistration>>,
1088    #[doc(hidden)]
1089    pub native_dialogs: Vec<NativeDialogRegistration>,
1090    pub animations: BTreeMap<&'static str, Animation>,
1091    #[doc(hidden)]
1092    pub state_timings: Option<Box<BTreeMap<&'static str, StateTiming>>>,
1093    #[doc(hidden)]
1094    pub focus_handle: Option<FocusHandle>,
1095    #[doc(hidden)]
1096    pub scale_rotate_handle: Option<ScaleRotateHandle>,
1097    #[doc(hidden)]
1098    pub swipe_handle: Option<SwipeHandle>,
1099    #[doc(hidden)]
1100    pub hover_handle: Option<HoverHandle>,
1101    #[doc(hidden)]
1102    pub pointer_handle: Option<PointerHandle>,
1103    #[doc(hidden)]
1104    pub scroll_event_handler: bool,
1105    #[doc(hidden)]
1106    pub press_and_hold_handler: bool,
1107    #[doc(hidden)]
1108    pub viewport_handle: Option<ViewportHandle>,
1109    #[doc(hidden)]
1110    pub scroll_target: Option<ViewportHandle>,
1111    #[doc(hidden)]
1112    pub geometry_handle: Option<GeometryHandle>,
1113    #[doc(hidden)]
1114    pub instance_geometry_handle: Option<GeometryHandle>,
1115    #[doc(hidden)]
1116    pub initial_focus: Option<FocusHandle>,
1117    #[doc(hidden)]
1118    pub key_handlers: u8,
1119    pub list: Option<ListMetrics>,
1120    #[doc(hidden)]
1121    pub row_locator: Option<ListRowLocator>,
1122    #[doc(hidden)]
1123    pub list_row_renderer: Option<ListRowRenderer>,
1124    #[doc(hidden)]
1125    pub row_heights: Option<Arc<RowHeights>>,
1126    /// Selection snapshot for model-backed views. Retains the generated field name.
1127    #[doc(hidden)]
1128    pub standard_list_stamp: Option<(u64, u64)>,
1129    pub table_header: Option<Box<TableHeader>>,
1130    #[doc(hidden)]
1131    pub table_column_order: TableColumnOrder,
1132    pub table_selection: Option<Box<TableSelectionSnapshot>>,
1133    #[doc(hidden)]
1134    pub table_cell_editor: Option<TableCellEditor>,
1135    pub tree: Option<Arc<TreeSnapshot>>,
1136    pub stack: Option<Arc<StackSnapshot>>,
1137    pub action: Option<ActionKey>,
1138    #[doc(hidden)]
1139    pub button_group: Option<ButtonGroupMembership>,
1140    /// Selected TreeView business keys and model row identities, including folded descendants.
1141    pub tree_selection: Option<Arc<BTreeMap<i64, RowKey>>>,
1142    pub split_weights: Option<Arc<[Option<f32>]>>,
1143    #[doc(hidden)]
1144    pub split_fill_pane: Option<&'static str>,
1145    #[doc(hidden)]
1146    pub split_sizes: Option<Arc<[Option<f32>]>>,
1147    #[doc(hidden)]
1148    pub split_resize_handle: Option<SplitResizeHandle>,
1149    pub row_key: Option<RowKey>,
1150    #[doc(hidden)]
1151    pub row_scope: u64,
1152    paint_only: u8,
1153    static_paint_order: Option<&'static [usize]>,
1154    precompiled_path: Option<&'static StaticVectorPath>,
1155    static_grid: Option<&'static [GridCellSlot]>,
1156}
1157
1158impl std::ops::Deref for Node {
1159    type Target = NodeData;
1160
1161    fn deref(&self) -> &Self::Target {
1162        match &self.0 {
1163            NodeStorage::Inline(data) => data,
1164            NodeStorage::Shared(data) => data,
1165        }
1166    }
1167}
1168
1169impl std::ops::DerefMut for Node {
1170    fn deref_mut(&mut self) -> &mut Self::Target {
1171        let data = self.data_mut();
1172        // Public edits can change grid tracks, visibility or child order.
1173        data.static_grid = None;
1174        data.static_paint_order = None;
1175        data
1176    }
1177}
1178
1179impl PartialEq for Node {
1180    fn eq(&self, other: &Self) -> bool {
1181        **self == **other
1182    }
1183}
1184
1185impl NodeData {
1186    fn same_structure_and_state(&self, other: &Self) -> bool {
1187        macro_rules! compare {
1188            ($($field:ident),+ $(,)?) => {{
1189                // An exhaustive pattern makes new scene fields opt in to comparison.
1190                let Self { properties: _, children: _, paint_only: _, $($field: _,)+ } = self;
1191                $(self.$field == other.$field)&&+
1192            }};
1193        }
1194        compare!(
1195            kind,
1196            table_column_window,
1197            application_window,
1198            id,
1199            fonts,
1200            tumbler_items,
1201            timers,
1202            image_playback,
1203            native_dialogs,
1204            animations,
1205            state_timings,
1206            focus_handle,
1207            scale_rotate_handle,
1208            swipe_handle,
1209            hover_handle,
1210            pointer_handle,
1211            scroll_event_handler,
1212            press_and_hold_handler,
1213            viewport_handle,
1214            scroll_target,
1215            geometry_handle,
1216            instance_geometry_handle,
1217            initial_focus,
1218            key_handlers,
1219            list,
1220            row_locator,
1221            list_row_renderer,
1222            row_heights,
1223            standard_list_stamp,
1224            table_header,
1225            table_column_order,
1226            table_selection,
1227            table_cell_editor,
1228            tree,
1229            stack,
1230            action,
1231            button_group,
1232            tree_selection,
1233            split_weights,
1234            split_fill_pane,
1235            split_sizes,
1236            split_resize_handle,
1237            row_key,
1238            row_scope,
1239            precompiled_path,
1240            static_grid,
1241            static_paint_order,
1242        )
1243    }
1244}
1245
1246pub fn is_text_input(kind: &str) -> bool {
1247    matches!(kind, "TextInput" | "LineEdit" | "SearchField") || is_multiline_text_input(kind)
1248}
1249
1250pub fn editable_table_cell(node: &Node) -> bool {
1251    matches!(node.kind, "TableCell" | "TreeCell")
1252        && node.boolean("editable", false)
1253        && !node.boolean("read-only", false)
1254}
1255
1256pub fn is_multiline_text_input(kind: &str) -> bool {
1257    matches!(kind, "TextEdit" | "TextArea")
1258}
1259
1260pub fn is_toggle(kind: &str) -> bool {
1261    matches!(kind, "CheckBox" | "Switch")
1262}
1263
1264impl Node {
1265    #[doc(hidden)]
1266    pub fn table_edit_history_enabled(&self) -> bool {
1267        self.boolean("undoable", false) || self.boolean("pasteable", false)
1268    }
1269
1270    pub fn calendar_cells(&self) -> Option<&[Node]> {
1271        self.children
1272            .last()
1273            .filter(|child| child.kind == "CalendarCells")
1274            .map(|child| child.children.as_slice())
1275    }
1276
1277    pub fn is_item_delegate(&self) -> bool {
1278        self.boolean("__item-delegate", false)
1279    }
1280
1281    #[doc(hidden)]
1282    pub fn enables_children(&self) -> bool {
1283        is_drag_area(self.kind)
1284            || matches!(
1285                self.kind,
1286                "WindowMoveArea"
1287                    | "ScaleRotateGestureHandler"
1288                    | "SwipeGestureHandler"
1289                    | "WheelHandler"
1290                    | "HoverHandler"
1291                    | "TouchArea"
1292            )
1293            || self.boolean("enabled", true)
1294    }
1295    pub fn check_state(&self) -> CheckState {
1296        match self.properties.get("check-state") {
1297            Some(Value::CheckState(state)) if self.kind == "CheckBox" => *state,
1298            _ => self.boolean("checked", false).into(),
1299        }
1300    }
1301
1302    pub fn date(&self, name: &str) -> Option<Date> {
1303        match self.properties.get(name) {
1304            Some(Value::Date(date)) => Some(*date),
1305            _ => None,
1306        }
1307    }
1308
1309    pub fn time(&self, name: &str) -> Option<Time> {
1310        match self.properties.get(name) {
1311            Some(Value::Time(time)) => Some(*time),
1312            _ => None,
1313        }
1314    }
1315
1316    pub fn new(kind: &'static str, id: Option<&'static str>) -> Self {
1317        Self(NodeStorage::Inline(NodeData {
1318            kind,
1319            application_window: false,
1320            id,
1321            properties: BTreeMap::new(),
1322            fonts: None,
1323            tumbler_items: None,
1324            children: Vec::new(),
1325            table_column_window: TableColumnWindow::default(),
1326            timers: Vec::new(),
1327            image_playback: None,
1328            native_dialogs: Vec::new(),
1329            animations: BTreeMap::new(),
1330            state_timings: None,
1331            focus_handle: None,
1332            scale_rotate_handle: None,
1333            swipe_handle: None,
1334            hover_handle: None,
1335            pointer_handle: None,
1336            scroll_event_handler: false,
1337            press_and_hold_handler: false,
1338            viewport_handle: None,
1339            scroll_target: None,
1340            geometry_handle: None,
1341            instance_geometry_handle: None,
1342            initial_focus: None,
1343            key_handlers: 0,
1344            list: None,
1345            row_locator: None,
1346            list_row_renderer: None,
1347            row_heights: None,
1348            standard_list_stamp: None,
1349            table_header: None,
1350            table_column_order: TableColumnOrder::default(),
1351            table_selection: None,
1352            table_cell_editor: None,
1353            tree: None,
1354            stack: None,
1355            action: None,
1356            button_group: None,
1357            tree_selection: None,
1358            split_weights: None,
1359            split_fill_pane: None,
1360            split_sizes: None,
1361            split_resize_handle: None,
1362            row_key: None,
1363            row_scope: 0,
1364            paint_only: 0,
1365            static_paint_order: None,
1366            precompiled_path: None,
1367            static_grid: None,
1368        }))
1369    }
1370
1371    /// Freeze a static subtree so subsequent snapshot clones share its storage.
1372    #[doc(hidden)]
1373    pub fn into_shared(self) -> Self {
1374        match self.0 {
1375            NodeStorage::Inline(mut data) => {
1376                data.children = data.children.into_iter().map(Self::into_shared).collect();
1377                Self(NodeStorage::Shared(Arc::new(data)))
1378            }
1379            NodeStorage::Shared(data) => Self(NodeStorage::Shared(data)),
1380        }
1381    }
1382
1383    pub fn shares_storage_with(&self, other: &Self) -> bool {
1384        std::ptr::eq(self, other)
1385            || matches!((&self.0, &other.0), (NodeStorage::Shared(a), NodeStorage::Shared(b)) if Arc::ptr_eq(a, b))
1386    }
1387
1388    #[doc(hidden)]
1389    pub fn set_precompiled_path(&mut self, path: &'static StaticVectorPath) {
1390        self.precompiled_path = Some(path);
1391    }
1392
1393    #[doc(hidden)]
1394    pub fn precompiled_path(&self, commands: &str) -> Option<&'static StaticVectorPath> {
1395        self.precompiled_path
1396            .filter(|path| path.commands == commands)
1397    }
1398    /// Mark a generated Rectangle's background as independent of layout and input.
1399
1400    fn data_mut(&mut self) -> &mut NodeData {
1401        match &mut self.0 {
1402            NodeStorage::Inline(data) => data,
1403            NodeStorage::Shared(data) => Arc::make_mut(data),
1404        }
1405    }
1406
1407    #[doc(hidden)]
1408    pub fn set_static_grid(&mut self, cells: &'static [GridCellSlot]) {
1409        self.data_mut().static_grid = Some(cells);
1410    }
1411
1412    #[doc(hidden)]
1413    pub fn static_grid(&self) -> Option<&'static [GridCellSlot]> {
1414        self.static_grid
1415    }
1416
1417    #[doc(hidden)]
1418    pub fn set_static_paint_order(&mut self, order: &'static [usize]) {
1419        self.data_mut().static_paint_order = Some(order);
1420    }
1421
1422    #[doc(hidden)]
1423    pub fn static_paint_order(&self) -> Option<&'static [usize]> {
1424        self.static_paint_order
1425    }
1426
1427    fn paint_only_bit(&self, property: &str) -> u8 {
1428        match (self.kind, property) {
1429            ("Rectangle", "background") => 1,
1430            ("Text", "color") => 2,
1431            _ => 0,
1432        }
1433    }
1434
1435    #[doc(hidden)]
1436    pub fn mark_paint_only(&mut self, property: &str) {
1437        let bit = self.paint_only_bit(property);
1438        self.data_mut().paint_only |= bit;
1439    }
1440
1441    #[doc(hidden)]
1442    pub fn mark_paint_only_background(&mut self) {
1443        self.mark_paint_only("background");
1444    }
1445
1446    /// Compare frame inputs, allowing paint-only values to differ.
1447    #[doc(hidden)]
1448    pub fn same_frame_inputs(&self, other: &Self) -> bool {
1449        if self.shares_storage_with(other) {
1450            return true;
1451        }
1452        let paint_only = self.paint_only & other.paint_only;
1453        let ignore_frame = self.kind == "AnimatedImage" && other.kind == "AnimatedImage";
1454        let ignore_colorize =
1455            matches!(self.kind, "Image" | "AnimatedImage") && self.kind == other.kind;
1456        let relevant = |(name, _): &(&&str, &Value)| match **name {
1457            name if paint_only & self.paint_only_bit(name) != 0 => false,
1458            "opacity" => false,
1459            "drop-shadow-blur"
1460            | "drop-shadow-color"
1461            | "drop-shadow-offset-x"
1462            | "drop-shadow-offset-y"
1463            | "drop-shadow-spread"
1464            | "inner-shadow-blur"
1465            | "inner-shadow-color"
1466            | "inner-shadow-offset-x"
1467            | "inner-shadow-offset-y"
1468            | "inner-shadow-spread" => self.kind != "Rectangle",
1469            "current-frame" => !ignore_frame,
1470            "colorize" => !ignore_colorize,
1471            _ => true,
1472        };
1473        self.same_structure_and_state(other)
1474            && self
1475                .properties
1476                .iter()
1477                .filter(relevant)
1478                .eq(other.properties.iter().filter(relevant))
1479            && self.children.len() == other.children.len()
1480            && self
1481                .children
1482                .iter()
1483                .zip(&other.children)
1484                .all(|(child, other)| child.same_frame_inputs(other))
1485    }
1486    /// An empty slot keeps the generated event paths stable across conditional renders.
1487    pub fn hidden() -> Self {
1488        let mut node = Self::new("Empty", None);
1489        node.properties.insert("visible", Value::Bool(false));
1490        node
1491    }
1492    pub fn find(&self, id: &str) -> Option<&Node> {
1493        if self.id == Some(id) {
1494            Some(self)
1495        } else {
1496            self.children.iter().find_map(|n| n.find(id))
1497        }
1498    }
1499
1500    pub fn length(&self, name: &str) -> Option<f32> {
1501        match self.properties.get(name) {
1502            Some(Value::Length(Length(value))) if value.is_finite() => {
1503                Some(value.clamp(-1_000_000.0, 1_000_000.0) as f32)
1504            }
1505            _ => None,
1506        }
1507    }
1508
1509    pub fn relative_length(&self, name: &str, reference: f32) -> Option<f32> {
1510        match self.properties.get(name) {
1511            Some(Value::Percent(Percent(factor))) if factor.is_finite() => {
1512                Some((factor * f64::from(reference)).clamp(-1_000_000.0, 1_000_000.0) as f32)
1513            }
1514            _ => self.length(name),
1515        }
1516    }
1517
1518    pub fn boolean(&self, name: &str, default: bool) -> bool {
1519        match self.properties.get(name) {
1520            Some(Value::Bool(value)) => *value,
1521            _ => default,
1522        }
1523    }
1524
1525    pub fn text(&self, name: &str) -> Option<&str> {
1526        match self.properties.get(name) {
1527            Some(Value::String(value)) => Some(value),
1528            Some(Value::StyledText(value)) => Some(value.text()),
1529            _ => None,
1530        }
1531    }
1532
1533    pub fn font(&self, name: &str) -> Option<&Font> {
1534        match self.properties.get(name) {
1535            Some(Value::Font(font)) => Some(font),
1536            _ => None,
1537        }
1538    }
1539
1540    pub fn font_size(&self) -> Option<f32> {
1541        self.length("font-size")
1542            .or_else(|| self.font("font").and_then(Font::finite_size))
1543    }
1544
1545    pub fn styled_text(&self, name: &str) -> Option<&StyledText> {
1546        match self.properties.get(name) {
1547            Some(Value::StyledText(value)) => Some(value),
1548            _ => None,
1549        }
1550    }
1551
1552    pub fn strings(&self, name: &str) -> &[String] {
1553        match self.properties.get(name) {
1554            Some(Value::StringList(values)) => values,
1555            _ => &[],
1556        }
1557    }
1558
1559    pub fn float(&self, name: &str) -> Option<f32> {
1560        self.number(name)
1561            .map(|value| value.clamp(-1_000_000.0, 1_000_000.0) as f32)
1562    }
1563
1564    pub fn number(&self, name: &str) -> Option<f64> {
1565        match self.properties.get(name) {
1566            Some(Value::Float(value)) if value.is_finite() => Some(*value),
1567            _ => None,
1568        }
1569    }
1570
1571    /// Visual opacity has no effect on layout, focus or hit testing.
1572    pub fn opacity(&self) -> f32 {
1573        self.number("opacity").unwrap_or(1.0).clamp(0.0, 1.0) as f32
1574    }
1575
1576    /// Finite stacking order within an ordinary sibling list.
1577    pub fn z(&self) -> f64 {
1578        self.number("z").filter(|&z| z != 0.0).unwrap_or_default()
1579    }
1580
1581    pub fn orientation(&self) -> Orientation {
1582        match self.properties.get("orientation") {
1583            Some(Value::Orientation(value)) => *value,
1584            _ if matches!(self.kind, "ScrollBar" | "ScrollIndicator" | "ToolSeparator") => {
1585                Orientation::Vertical
1586            }
1587            _ => Orientation::Horizontal,
1588        }
1589    }
1590
1591    pub fn dial_input_mode(&self) -> DialInputMode {
1592        match self.properties.get("input-mode") {
1593            Some(Value::DialInputMode(value)) => *value,
1594            _ => DialInputMode::Circular,
1595        }
1596    }
1597
1598    pub fn scroll_bar_policy(&self, orientation: Orientation) -> ScrollBarPolicy {
1599        let property = match orientation {
1600            Orientation::Horizontal => "horizontal-scroll-bar-policy",
1601            Orientation::Vertical => "vertical-scroll-bar-policy",
1602        };
1603        match self.properties.get(property) {
1604            Some(Value::ScrollBarPolicy(policy)) => *policy,
1605            _ => ScrollBarPolicy::AsNeeded,
1606        }
1607    }
1608
1609    pub fn text_wrap(&self) -> TextWrap {
1610        match self.properties.get("wrap") {
1611            Some(Value::TextWrap(wrap)) => *wrap,
1612            _ => TextWrap::default(),
1613        }
1614    }
1615
1616    pub fn is_password(&self) -> bool {
1617        self.input_type() == InputType::Password
1618    }
1619
1620    pub fn password_masked(&self) -> bool {
1621        self.is_password() && !self.boolean("password-visible", false)
1622    }
1623
1624    pub fn dialog_role(&self) -> DialogRole {
1625        match self.properties.get("role") {
1626            Some(Value::DialogRole(role)) => *role,
1627            _ => DialogRole::default(),
1628        }
1629    }
1630
1631    pub fn standard_button_kind(&self) -> Option<StandardButtonKind> {
1632        match (self.kind, self.properties.get("kind")) {
1633            ("Button", Some(Value::StandardButtonKind(kind))) => Some(*kind),
1634            _ => None,
1635        }
1636    }
1637
1638    pub fn swipe_side(&self) -> SwipeSide {
1639        match self.properties.get("open-side") {
1640            Some(Value::SwipeSide(side)) => *side,
1641            _ => SwipeSide::Closed,
1642        }
1643    }
1644
1645    pub fn swipe_panel(&self, side: SwipeSide) -> Option<&Node> {
1646        let kind = side.panel()?;
1647        self.children
1648            .iter()
1649            .find(|child| child.kind == kind && child.is_visible())
1650    }
1651
1652    pub fn drawer_edge(&self) -> DrawerEdge {
1653        match self.properties.get("edge") {
1654            Some(Value::DrawerEdge(edge)) => *edge,
1655            _ => DrawerEdge::Left,
1656        }
1657    }
1658
1659    pub fn selection_target(&self) -> SelectionTarget {
1660        match self.properties.get("selection-target") {
1661            Some(Value::SelectionTarget(target)) => *target,
1662            _ => SelectionTarget::Rows,
1663        }
1664    }
1665
1666    pub fn is_visible(&self) -> bool {
1667        self.boolean("visible", true)
1668            && (!is_window_overlay(self.kind) || self.boolean("open", false))
1669    }
1670
1671    #[doc(hidden)]
1672    pub fn handles_wheel(&self) -> bool {
1673        self.kind == "WheelHandler" || self.kind == "TouchArea" && self.scroll_event_handler
1674    }
1675
1676    #[doc(hidden)]
1677    pub fn accepts_pointer_button(&self, button: PointerButton) -> bool {
1678        match self.properties.get("accepted-buttons") {
1679            Some(Value::PointerButtons(buttons)) => buttons.contains(button),
1680            _ => true,
1681        }
1682    }
1683
1684    pub fn cursor_shape(&self) -> CursorShape {
1685        match self.properties.get("cursor-shape") {
1686            Some(Value::CursorShape(shape)) => *shape,
1687            _ => CursorShape::Auto,
1688        }
1689    }
1690
1691    pub fn is_modal(&self) -> bool {
1692        is_modal_overlay(self.kind) || self.kind == "PopupWindow" && self.boolean("modal", false)
1693    }
1694
1695    pub fn stack_page_index(&self) -> Option<usize> {
1696        let page = self.stack.as_ref()?.current()?;
1697        self.children.iter().position(|node| node.id == Some(page))
1698    }
1699
1700    pub fn int(&self, name: &str) -> Option<i64> {
1701        match self.properties.get(name) {
1702            Some(Value::Int(value)) => Some(*value),
1703            _ => None,
1704        }
1705    }
1706
1707    pub fn image(&self, name: &str) -> Option<Image> {
1708        match self.properties.get(name) {
1709            Some(Value::Image(value)) => Some(*value),
1710            _ => None,
1711        }
1712    }
1713
1714    pub fn image_fit(&self, name: &str) -> Option<ImageFit> {
1715        match self.properties.get(name) {
1716            Some(Value::ImageFit(value)) => Some(*value),
1717            _ => None,
1718        }
1719    }
1720
1721    pub fn image_tile_mode(&self, name: &str) -> ImageTileMode {
1722        match self.properties.get(name) {
1723            Some(Value::ImageTileMode(value)) => *value,
1724            _ => ImageTileMode::default(),
1725        }
1726    }
1727
1728    pub fn color(&self, name: &str) -> Option<Color> {
1729        match self.properties.get(name) {
1730            Some(Value::Color(value) | Value::Brush(Brush::Solid(value))) => Some(*value),
1731            _ => None,
1732        }
1733    }
1734
1735    pub fn color_scheme(&self) -> Option<ColorScheme> {
1736        match self.properties.get("color-scheme") {
1737            Some(Value::ColorScheme(scheme)) => Some(*scheme),
1738            _ => None,
1739        }
1740    }
1741
1742    /// Look up a child by the logical index used in scene paths.
1743    pub fn child_at(&self, index: usize) -> Option<&Self> {
1744        self.children
1745            .get(self.table_column_window.dense_index(index)?)
1746    }
1747
1748    #[doc(hidden)]
1749    pub fn child_at_mut(&mut self, index: usize) -> Option<&mut Self> {
1750        let index = self.table_column_window.dense_index(index)?;
1751        self.children.get_mut(index)
1752    }
1753
1754    /// Iterate stored children with their logical indices.
1755    pub fn materialized_children(
1756        &self,
1757    ) -> impl DoubleEndedIterator<Item = (usize, &Self)> + ExactSizeIterator {
1758        self.children
1759            .iter()
1760            .enumerate()
1761            .map(|(index, child)| (self.table_column_window.logical_index(index), child))
1762    }
1763
1764    pub fn at_path(&self, path: &[usize]) -> Option<&Self> {
1765        let mut node = self;
1766        for &index in path {
1767            node = node.child_at(index)?;
1768        }
1769        Some(node)
1770    }
1771
1772    pub fn interactive_at_path(&self, path: &[usize]) -> Option<&Self> {
1773        let mut node = self;
1774        for index in path {
1775            if !node.is_visible() || !node.enables_children() || !node.group_content_enabled() {
1776                return None;
1777            }
1778            let child = node.child_at(*index)?;
1779            if node.kind == "SwipeDelegate"
1780                && matches!(child.kind, "SwipeLeft" | "SwipeRight")
1781                && node.swipe_side().panel() != Some(child.kind)
1782            {
1783                return None;
1784            }
1785            node = child;
1786        }
1787        (node.is_visible() && node.boolean("enabled", true)).then_some(node)
1788    }
1789
1790    pub fn group_checkable(&self) -> bool {
1791        self.kind == "GroupBox" && self.boolean("checkable", false)
1792    }
1793
1794    pub fn group_content_enabled(&self) -> bool {
1795        !self.group_checkable() || self.boolean("checked", true)
1796    }
1797
1798    #[doc(hidden)]
1799    pub fn control_target(&self, path: &[usize], action: ControlAction) -> Option<&Self> {
1800        if action != ControlAction::Drawer(true) {
1801            return self.interactive_at_path(path);
1802        }
1803        let node = match path.split_last() {
1804            Some((&index, parent)) => {
1805                let parent = self.interactive_at_path(parent)?;
1806                if !parent.group_content_enabled() {
1807                    return None;
1808                }
1809                parent.child_at(index)?
1810            }
1811            None => self,
1812        };
1813        (node.kind == "Drawer" && node.boolean("visible", true) && node.boolean("enabled", true))
1814            .then_some(node)
1815    }
1816
1817    /// Identity of the materialized row in its view, for routing and focus.
1818    pub fn routing_row_key(&self) -> Option<RowKey> {
1819        self.row_key.map(|key| key.in_view(self.row_scope))
1820    }
1821
1822    /// Identity of the virtual row containing this scene path.
1823    pub fn row_key_at(&self, path: &[usize]) -> Option<RowKey> {
1824        let mut node = self;
1825        let mut key = None;
1826        for &index in path {
1827            node = node.child_at(index)?;
1828            if node.kind == "ListRow" {
1829                key = node.routing_row_key();
1830            }
1831        }
1832        key
1833    }
1834
1835    /// Find the displayed index of a source row identity. The source index is a lookup hint.
1836    pub fn displayed_row_for_key(&self, key: RowKey, source_index: usize) -> Option<usize> {
1837        if let Some(tree) = &self.tree {
1838            tree.position_of_source_key(key, source_index)
1839        } else {
1840            self.row_locator
1841                .as_ref()?
1842                .position_of_source_key(key, source_index)
1843        }
1844    }
1845}