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