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