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