1use crate::{
2 CalendarGeometry, ChoiceKey, ChoiceMenu, ColorPlaneGeometry, ComboCompletion, ComboGeometry,
3 DialGeometry, EditAction, EditSource, LayoutNode, MenuEntry, MenuKey, MenuPanel, MenuShortcut,
4 PageIndicatorGeometry, Point, Rect, ScrollBarGeometry, ScrollGestureEnd, ScrollGestureKind,
5 SearchGeometry, ShortcutOutcome, SliderGeometry, SpinGeometry, SplitGeometry, SplitHandle,
6 SplitHandleRange, StackTransitions, TextEdit, TextPosition, TreeRowGeometry, TumblerScroll,
7 WindowResizeEdge,
8 choice::{
9 ChoicePan, ChoicePopup, MAX_ROWS as CHOICE_PAGE, Typeahead, matches_prefix, next_choice,
10 },
11 delay_button::{ButtonHold, ButtonHoldEvent, ButtonHoldTiming, DelayHold, DelaySource},
12 history::{EditHistories, EditorKey, Group, Record, TextHistory},
13 hover_observers::HoverEntry,
14 list_anchor::{ListAnchor, capture_list_anchors},
15 menu::{MenuPan, MenuPopup, NativeTextMenu, TextMenu},
16 modal,
17 overscroll::Overscroll,
18 scroll_bar::snap_fraction,
19 scroll_gesture::{DRAG_THRESHOLD, DragMotion, FlingMotion, PanDevice, SCROLL_FRAME_INTERVAL},
20 shortcut::{self, PendingShortcut},
21 split::axis_point,
22 swipe_delegate::SwipeDrag,
23 swipe_gesture::{SwipeDelivery, SwipePhase, SwipeTarget, has_swipe_directions},
24 tab_move::TabDrag,
25 tooltip::{self, Source as TooltipSource, TooltipState, TouchTooltip},
26 tumbler::{TumblerDrag, TumblerFlick, TumblerWheel},
27 view_cells::ViewCells,
28 viewport::{MotionOwners, MotionState, UserScrollChange, record_motion, record_motion_owner},
29};
30use std::borrow::Cow;
31use std::collections::{BTreeMap, BTreeSet};
32use std::rc::Rc;
33use std::time::{Duration, Instant};
34use xrack_runtime::{
35 ButtonGroupMembership, CalendarAction, Component, ControlAction, Date, DialInputMode,
36 DialogRole, DrawerEdge, FocusHandle, LayoutDirection, Length, ListMetrics, Node, Orientation,
37 PageIdentity, RangeAction, RowKey, RowSelection, ScrollAction, ScrollAlignment, ScrollBarRange,
38 ScrollRequest, ScrollSnapMode, SelectionTarget, SliderInterval, SliderRange, SpinAction,
39 SpinDecimal, StandardButtonKind, SwipePreviewHandle, SwipeSide, TableEditPosition,
40 TableSelectionAction, TextCommand, TextCommandAvailability, TreeAction, TreeSelectionAction,
41 Tumbler, Value, ViewportHandle, ViewportMotion, combo_editable, combo_index, decimal_separator,
42 delay_millis, dialog_button_action, editable_table_cell, group_index, group_item,
43 is_calendar_control, is_multiline_text_input, is_spin_box, is_text_input, is_toggle,
44 is_window_overlay, page_indicator_count, page_indicator_index, page_indicator_step,
45 radio_value, resizable_table_column, search_suggestion, spin_editable, spin_text,
46 spin_text_is_valid, text_input_value,
47};
48
49#[derive(Clone, Debug)]
50pub(crate) enum ElementId {
51 Static(&'static str),
52 Shared(std::sync::Arc<str>),
53}
54
55impl ElementId {
56 pub(crate) fn of(node: &Node) -> Option<Self> {
57 node.id
58 .map(Self::Static)
59 .or_else(|| node.shared_element_id().map(Self::Shared))
60 }
61
62 pub(crate) fn as_str(&self) -> &str {
63 match self {
64 Self::Static(id) => id,
65 Self::Shared(id) => id,
66 }
67 }
68}
69
70impl PartialEq for ElementId {
71 fn eq(&self, other: &Self) -> bool {
72 self.as_str() == other.as_str()
73 }
74}
75
76impl Eq for ElementId {}
77
78#[derive(Clone, Debug)]
79pub struct Target {
80 pub path: Vec<usize>,
81 pub id: Option<&'static str>,
83 pub focusable: bool,
84 pub row_key: Option<RowKey>,
85 pub text_link: Option<TextLinkTarget>,
86 pub(crate) tab_close: Option<(xrack_runtime::TabClose, String)>,
87 owned_id: Option<std::sync::Arc<str>>,
88 radio_option_key: Option<RowKey>,
89}
90
91impl PartialEq for Target {
92 fn eq(&self, other: &Self) -> bool {
93 self.path == other.path
94 && self.element_id() == other.element_id()
95 && self.focusable == other.focusable
96 && self.row_key == other.row_key
97 && self.tab_close == other.tab_close
98 && self.text_link == other.text_link
99 && self.radio_option_key == other.radio_option_key
100 }
101}
102
103impl Eq for Target {}
104
105#[derive(Clone, Debug, PartialEq, Eq)]
107pub struct TablePasteDestination {
108 pub path: Vec<usize>,
109 pub row: usize,
110 pub columns: Vec<usize>,
111 focus: Target,
112}
113
114#[derive(Clone, Debug, PartialEq, Eq)]
117pub struct TextLinkTarget {
118 index: usize,
119 document: xrack_runtime::StyledText,
120}
121
122impl Target {
123 pub fn from_node(
125 path: Vec<usize>,
126 node: &Node,
127 focusable: bool,
128 row_key: Option<RowKey>,
129 ) -> Self {
130 let mut target = Self::from_element_id(path, ElementId::of(node), focusable, row_key);
131 target.radio_option_key = Self::radio_option_key(node);
132 target
133 }
134
135 pub(crate) fn from_element_id(
136 path: Vec<usize>,
137 id: Option<ElementId>,
138 focusable: bool,
139 row_key: Option<RowKey>,
140 ) -> Self {
141 let mut target = Self {
142 path,
143 id: None,
144 focusable,
145 row_key,
146 text_link: None,
147 tab_close: None,
148 owned_id: None,
149 radio_option_key: None,
150 };
151 target.set_element_id(id);
152 target
153 }
154
155 fn set_element_id(&mut self, id: Option<ElementId>) {
156 (self.id, self.owned_id) = match id {
157 Some(ElementId::Static(id)) => (Some(id), None),
158 Some(ElementId::Shared(id)) => (None, Some(id)),
159 None => (None, None),
160 };
161 }
162
163 pub fn element_id(&self) -> Option<&str> {
165 self.id.or(self.owned_id.as_deref())
166 }
167
168 pub(crate) fn matches_node(&self, node: &Node) -> bool {
169 self.element_id() == node.element_id()
170 && self.radio_option_key == Self::radio_option_key(node)
171 }
172
173 fn radio_option_key(node: &Node) -> Option<RowKey> {
174 if node.kind == "RadioButton" {
175 node.routing_row_key()
176 } else {
177 None
178 }
179 }
180
181 #[doc(hidden)]
182 pub fn node_in<'a>(&self, scene: &'a Node) -> Option<&'a Node> {
183 let node = scene.at_path(&self.path)?;
184 (self.matches_node(node) && self.row_key == scene.row_key_at(&self.path)).then_some(node)
185 }
186
187 pub fn text_link_index(&self) -> Option<usize> {
188 self.text_link.as_ref().map(|link| link.index)
189 }
190
191 pub(crate) fn for_text_link(node: &Node, path: &[usize], index: usize) -> Option<Self> {
192 let document = node.styled_text("text")?;
193 document.links().get(index)?;
194 let mut target = Self::from_node(path.to_vec(), node, true, None);
195 target.text_link = Some(TextLinkTarget {
196 index,
197 document: document.clone(),
198 });
199 Some(target)
200 }
201}
202
203#[derive(Clone, Copy, Debug, PartialEq, Eq)]
204pub enum ActivationKey {
205 Enter,
206 Space,
207}
208
209#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
210pub enum NavigationKey {
211 Left,
212 Right,
213 Up,
214 Down,
215 Home,
216 End,
217 PageUp,
218 PageDown,
219}
220
221pub type SliderKey = NavigationKey;
222
223#[derive(Clone, Copy, Debug, PartialEq, Eq)]
224pub enum TableSelectionKey {
225 Toggle,
226 All,
227 Clear,
228}
229
230#[derive(Clone, Debug, PartialEq)]
231pub struct RangeInput {
232 pub path: Vec<usize>,
233 pub action: RangeAction,
234}
235
236#[derive(Debug, PartialEq)]
237pub enum WheelAdjustment {
238 Pending,
239 Range(RangeInput),
240 Spin(ControlInput),
241}
242
243#[derive(Clone, Debug)]
244struct WheelSteps {
245 path: Vec<usize>,
246 row: Option<RowKey>,
247 handle: Option<usize>,
248 horizontal: bool,
249 is_line: bool,
250 remainder: f64,
251 time: Instant,
252}
253
254#[derive(Clone, Debug, PartialEq)]
255pub enum ScrollBarUpdate {
256 Unchanged,
257 ViewportMoved,
258 Range(RangeInput),
259}
260
261#[derive(Clone, Debug, PartialEq, Eq)]
262pub struct ControlInput {
263 pub path: Vec<usize>,
264 pub action: ControlAction,
265}
266
267fn dismiss_overlay(node: &Node) -> ControlAction {
268 match node.kind {
269 "Drawer" => ControlAction::Drawer(false),
270 "PopupWindow" => ControlAction::Popup(false),
271 _ => ControlAction::Dialog(DialogRole::Reject),
272 }
273}
274
275fn is_modal_path(layout: &LayoutNode, path: &[usize]) -> bool {
276 layout.dialog_paths().iter().any(|modal| modal == path)
277}
278
279pub struct SplitResize {
280 pub path: Vec<usize>,
281 pub weights: Vec<(usize, f32)>,
282 pub sizes: Option<Vec<(usize, f32)>>,
283}
284
285impl ControlInput {
286 #[doc(hidden)]
287 pub fn with_row_selection(mut self, scene: &Node, operation: RowSelection) -> Self {
288 if let Some(node) = scene.at_path(&self.path)
289 && let ControlAction::Select(index) = self.action
290 {
291 if let Some(action) = tree_row_action(node, index, operation) {
292 self.action = action;
293 } else if node.table_selection.is_some() {
294 self.action =
295 ControlAction::TableSelection(TableSelectionAction::Row { index, operation });
296 }
297 }
298 self
299 }
300}
301
302fn tree_row_action(node: &Node, index: usize, operation: RowSelection) -> Option<ControlAction> {
303 node.tree_selection.as_ref()?;
304 let item = node.tree.as_ref()?.rows().get(index)?;
305 Some(ControlAction::Tree(TreeAction::Selection(
306 TreeSelectionAction::Row {
307 key: item.key,
308 row: item.row,
309 operation,
310 },
311 )))
312}
313
314#[derive(Clone, Debug)]
315struct DialogFocus {
316 path: Vec<usize>,
317 row_key: Option<RowKey>,
318 modal: bool,
319 return_focus: Option<Target>,
320}
321
322#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
323struct StackFocusKey {
324 path: Vec<usize>,
325 row: Option<RowKey>,
326 page: usize,
327}
328
329#[derive(Clone, Debug)]
330struct TableResize {
331 target: Target,
332 column: usize,
333 pointer_x: f32,
334 width: f32,
335 mirrored: bool,
336}
337
338#[derive(Clone, Debug)]
339struct TableRowResize {
340 target: Target,
341 key: RowKey,
342 pointer_y: f32,
343 height: f32,
344}
345
346#[derive(Clone, Debug)]
347struct TableColumnMove {
348 target: Target,
349 column: usize,
350 start: Point,
351 order: xrack_runtime::TableColumnOrder,
352 mirrored: bool,
353 claimed: bool,
354 scroll_wake: Option<Instant>,
355}
356
357#[derive(Clone, Debug)]
358struct TableRowMove {
359 table: Target,
360 from: usize,
361 row: xrack_runtime::RowKey,
362 stamp: (u64, u64),
363 start: Point,
364 claimed: bool,
365 touch: bool,
366 scroll_wake: Option<Instant>,
367}
368
369#[derive(Clone, Debug)]
370struct SplitDrag {
371 target: Target,
372 orientation: Orientation,
373 mirrored: bool,
374 after_pane: usize,
375 grab_offset: f32,
376 state: Option<xrack_runtime::SplitResizeHandle>,
377}
378
379impl SplitDrag {
380 fn matches(&self, geometry: &SplitGeometry, handle: &SplitHandle) -> bool {
381 geometry.orientation == self.orientation
382 && geometry.mirrored == self.mirrored
383 && handle.after_pane() == self.after_pane
384 }
385}
386
387#[derive(Clone, Debug)]
388struct WindowMovePress {
389 target: Target,
390 origin: Point,
391}
392
393#[derive(Clone, Debug)]
394struct TableEdit {
395 target: Target,
396 original: String,
397 draft: String,
398 history: TextHistory,
399}
400
401#[derive(Clone, Copy, Debug, PartialEq, Eq)]
402pub enum TableEditCommit {
403 Kept,
404 Unchanged,
405 Changed,
406 Rejected,
407}
408
409pub struct TableEditTarget {
410 table: Vec<usize>,
411 viewport: ViewportHandle,
412 position: TableEditPosition,
413}
414
415impl TableEditTarget {
416 pub fn scroll_request(&self) -> ScrollRequest {
417 ScrollRequest {
418 target: self.viewport.clone(),
419 action: ScrollAction::ToCell {
420 row: self.position.row as i64,
421 column: self.position.column as i64,
422 horizontal: ScrollAlignment::Contain,
423 vertical: ScrollAlignment::Contain,
424 },
425 }
426 }
427}
428
429#[derive(Clone, Debug)]
430struct SpinDraft {
431 text: String,
432 mode: SpinDraftMode,
433 history: TextHistory,
434}
435
436#[derive(Clone, Copy, Debug)]
437enum SpinDraftMode {
438 Integer(Option<i64>),
439 Decimal {
440 original: Option<SpinDecimal>,
441 separator: char,
442 },
443}
444
445impl SpinDraftMode {
446 fn for_node(node: &Node) -> Self {
447 if node.kind == "DoubleSpinBox" {
448 Self::Decimal {
449 original: node.number("value").and_then(SpinDecimal::new),
450 separator: decimal_separator(node),
451 }
452 } else {
453 Self::Integer(node.int("value"))
454 }
455 }
456
457 fn separator(self) -> Option<char> {
458 match self {
459 Self::Decimal { separator, .. } => Some(separator),
460 Self::Integer(_) => None,
461 }
462 }
463
464 fn commit(self, text: &str) -> Option<SpinAction> {
465 Some(match self {
466 Self::Integer(Some(original)) => SpinAction::CommitIfCurrent {
467 original,
468 value: text.parse().ok()?,
469 },
470 Self::Integer(None) => SpinAction::Commit(text.parse().ok()?),
471 Self::Decimal {
472 original,
473 separator,
474 } => SpinAction::CommitDecimalIfCurrent {
475 original,
476 value: SpinDecimal::parse(text, separator)?,
477 },
478 })
479 }
480
481 fn is_current(self, node: &Node) -> bool {
482 spin_editable(node)
483 && match (self, Self::for_node(node)) {
484 (Self::Integer(original), Self::Integer(current)) => {
485 original.is_none() || original == current
486 }
487 (
488 Self::Decimal {
489 original,
490 separator,
491 },
492 Self::Decimal {
493 original: current,
494 separator: current_separator,
495 },
496 ) => original == current && separator == current_separator,
497 _ => false,
498 }
499 }
500}
501
502#[derive(Clone, Debug, PartialEq, Eq)]
503struct ScrollTarget {
504 path: Vec<usize>,
505 orientation: Orientation,
506 row_key: Option<RowKey>,
507 id: Option<ElementId>,
508}
509
510impl ScrollTarget {
511 fn matches_node(&self, node: &Node) -> bool {
512 self.id.as_ref().map(ElementId::as_str) == node.element_id()
513 }
514
515 fn resolve<'a, 'b>(
516 &self,
517 scene: &'a Node,
518 layout: &'b LayoutNode,
519 ) -> Option<(&'a Node, &'b LayoutNode)> {
520 let item = layout.at_path(&self.path)?;
521 let node = scene.interactive_at_path(&self.path)?;
522 (item.visible
523 && item.enabled
524 && item.scroll_on(self.orientation).is_some()
525 && self.matches_node(node)
526 && scene.row_key_at(&self.path) == self.row_key)
527 .then_some((node, item))
528 }
529}
530
531#[derive(Clone, Debug)]
532struct ScrollBarPress {
533 target: ScrollTarget,
534 source: &'static str,
535 viewport: Option<xrack_runtime::ViewportHandle>,
536 reversed: bool,
537 grab: Option<f32>,
538 touch: bool,
539 cancelled: bool,
540 start: Point,
541 last: Point,
542 dragged: bool,
543}
544
545impl ScrollBarPress {
546 fn node<'a>(&self, scene: &'a Node) -> Option<&'a Node> {
547 scene.at_path(&self.target.path).filter(|node| {
548 node.kind == self.source
549 && self.target.matches_node(node)
550 && node.scroll_target == self.viewport
551 })
552 }
553}
554
555#[derive(Clone, Debug)]
556struct ScrollRoute {
557 scope: Vec<usize>,
558 scope_row: Option<RowKey>,
559 scope_id: Option<ElementId>,
560 axes: [Option<ScrollTarget>; 2],
561 mouse_viewport: bool,
562 pan_device: PanDevice,
563}
564
565#[derive(Clone, Debug)]
566struct ScrollGesture {
567 route: ScrollRoute,
568 motion: DragMotion,
569 tap: Option<Hit>,
570 touch_point: Option<Point>,
571 popup: (bool, bool),
572 menu_pan: Option<MenuPan>,
573 choice_pan: Option<ChoicePan>,
574 drawer: Option<DrawerSwipe>,
575 pages: Vec<PageSwipe>,
576 tumbler: Option<TumblerDrag>,
577 tab_move: Option<TabDrag>,
578 switch: Option<SwitchDrag>,
579 swipe_delegate: Option<SwipeDrag>,
580 swipe: Option<SwipeRoute>,
581 delay_touch: bool,
582 table_gesture: Option<PendingTableGesture>,
583}
584
585#[derive(Clone, Copy, Debug, PartialEq, Eq)]
586enum ButtonContactSource {
587 Pointer,
588 Gesture,
589 Key(ActivationKey),
590}
591
592#[derive(Clone, Debug)]
593struct ButtonContact {
594 source: ButtonContactSource,
595 target: Target,
596 handle: xrack_runtime::ButtonPressHandle,
597}
598
599#[derive(Clone, Debug)]
600struct SwitchDrag {
601 target: Target,
602 start: Point,
603 track: Rect,
604 travel: f32,
605 direction: LayoutDirection,
606 initial: bool,
607 position: Option<f32>,
608 cancelled: bool,
609}
610
611impl SwitchDrag {
612 fn new(target: Target, node: &Node, item: &LayoutNode, point: Point) -> Option<Self> {
613 if node.kind != "Switch" {
614 return None;
615 }
616 let geometry = crate::ToggleGeometry::new(node, item.bounds, item.layout_direction);
617 let start = item.map_from_window(point)?;
618 let travel = geometry.switch_travel();
619 (geometry.indicator.contains(start) && travel > 0.0).then_some(Self {
620 target,
621 start,
622 track: geometry.indicator,
623 travel,
624 direction: item.layout_direction,
625 initial: node.boolean("checked", false),
626 position: None,
627 cancelled: false,
628 })
629 }
630
631 fn matches(
632 &self,
633 node: &Node,
634 bounds: Rect,
635 direction: LayoutDirection,
636 row: Option<RowKey>,
637 ) -> bool {
638 if node.kind != "Switch"
639 || !self.target.matches_node(node)
640 || row != self.target.row_key
641 || node.boolean("checked", false) != self.initial
642 || direction != self.direction
643 {
644 return false;
645 }
646 let geometry = crate::ToggleGeometry::new(node, bounds, direction);
647 geometry.indicator == self.track && geometry.switch_travel() == self.travel
648 }
649
650 fn is_current(&self, scene: &Node, layout: &LayoutNode) -> bool {
651 let path = &self.target.path;
652 scene
653 .interactive_at_path(path)
654 .zip(layout.at_path(path))
655 .is_some_and(|(node, item)| {
656 valid(&self.target, scene, layout)
657 && self.matches(
658 node,
659 item.bounds,
660 item.layout_direction,
661 scene.row_key_at(path),
662 )
663 })
664 }
665
666 fn move_thumb(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> bool {
667 if self.cancelled || !self.is_current(scene, layout) {
668 self.cancelled = true;
669 return self.position.take().is_some();
670 }
671 let local = layout
672 .at_path(&self.target.path)
673 .and_then(|item| item.map_from_window(point));
674 let position = local.map(|local| {
675 let sign = if self.direction == LayoutDirection::RightToLeft {
676 -1.0
677 } else {
678 1.0
679 };
680 let origin = if self.initial { 1.0 } else { 0.0 };
681 (origin + sign * (local.x - self.start.x) / self.travel).clamp(0.0, 1.0)
682 });
683 let changed = self.position != position;
684 self.position = position;
685 changed
686 }
687
688 fn accepts_direction(&self, layout: &LayoutNode, point: Point) -> bool {
689 layout
690 .at_path(&self.target.path)
691 .and_then(|item| item.map_from_window(point))
692 .is_some_and(|point| (point.x - self.start.x).abs() > (point.y - self.start.y).abs())
693 }
694
695 fn finish(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
696 let position = self.position?;
697 let checked = position > 0.5 || position == 0.5 && self.initial;
698 (checked != self.initial && self.is_current(scene, layout)).then(|| ControlInput {
699 path: self.target.path.clone(),
700 action: ControlAction::SetSwitch(checked),
701 })
702 }
703}
704
705#[derive(Clone, Debug)]
706struct PendingTableGesture {
707 drag: PendingTableAction,
708 deadline: Option<Instant>,
709}
710
711#[derive(Clone, Debug)]
712enum PendingTableAction {
713 Select(crate::table_drag_selection::TableDragSelection),
714 Move(TableRowMove),
715}
716
717#[derive(Clone, Debug)]
718enum SwipeRoute {
719 Pending(Vec<SwipeTarget>),
720 Captured(SwipeTarget),
721 Cancelled,
722}
723
724impl SwipeRoute {
725 fn cancel(self) -> Option<SwipeDelivery> {
726 match self {
727 Self::Captured(target) => Some(target.delivery(SwipePhase::Cancelled)),
728 _ => None,
729 }
730 }
731}
732
733#[derive(Clone, Debug)]
734struct SwipePagePosition {
735 index: usize,
736 identity: PageIdentity,
737}
738
739impl SwipePagePosition {
740 fn from_view(view: &Node, index: usize) -> Option<Self> {
741 let node = group_item(view, index)?;
742 Some(Self {
743 index,
744 identity: PageIdentity::of(node, index),
745 })
746 }
747
748 fn matches(&self, view: &Node) -> bool {
749 group_item(view, self.index)
750 .is_some_and(|node| PageIdentity::of(node, self.index) == self.identity)
751 }
752}
753
754#[derive(Clone, Debug)]
755struct PageSwipe {
756 target: ScrollTarget,
757 current: SwipePagePosition,
758 previous: Option<SwipePagePosition>,
759 next: Option<SwipePagePosition>,
760 mirrored: bool,
761 start: Point,
762 bounds: Rect,
763 threshold: f32,
764}
765
766impl PageSwipe {
767 fn along_and_across(&self, vector: Point) -> (f32, f32) {
768 match self.target.orientation {
769 Orientation::Horizontal => (vector.x, vector.y.abs()),
770 Orientation::Vertical => (vector.y, vector.x.abs()),
771 }
772 }
773
774 fn movement(&self, point: Point) -> (f32, f32) {
775 self.along_and_across(Point {
776 x: self.start.x - point.x,
777 y: self.start.y - point.y,
778 })
779 }
780
781 fn release_distance(
782 &self,
783 distance: f32,
784 item: &LayoutNode,
785 velocity: Option<(Point, Point)>,
786 ) -> f32 {
787 const MIN_FLICK_SPEED: f32 = 480.0;
788 const PROJECTION_SECONDS: f32 = 0.10;
789
790 let magnitude = distance.abs();
791 let Some((smoothed, latest)) = velocity else {
792 return magnitude;
793 };
794 let Some(latest) = item.map_delta_from_window(latest) else {
795 return magnitude;
796 };
797 let (along, across) = self.along_and_across(latest);
798 if along.abs() < MIN_FLICK_SPEED || along.abs() <= across {
799 return magnitude;
800 }
801
802 let signed = along * distance.signum();
803 let velocity = if signed < 0.0 {
804 signed
806 } else {
807 let Some(smoothed) = item.map_delta_from_window(smoothed) else {
808 return magnitude;
809 };
810 let (along, across) = self.along_and_across(smoothed);
811 let forward = along * distance.signum();
812 if forward < MIN_FLICK_SPEED || forward <= across {
813 return magnitude;
814 }
815 signed.min(forward)
816 };
817 magnitude + (velocity * PROJECTION_SECONDS).clamp(-self.threshold, self.threshold)
818 }
819
820 fn destination(&self, physical_forward: bool) -> Option<&SwipePagePosition> {
821 if physical_forward != self.mirrored {
822 self.next.as_ref()
823 } else {
824 self.previous.as_ref()
825 }
826 }
827
828 fn view<'a, 'b>(
829 &self,
830 scene: &'a Node,
831 layout: &'b LayoutNode,
832 ) -> Option<(&'a Node, &'b LayoutNode)> {
833 let path = &self.target.path;
834 let view = scene.interactive_at_path(path)?;
835 let item = layout.at_path(path)?;
836 (view.kind == "SwipeView"
837 && self.target.matches_node(view)
838 && view.boolean("interactive", true)
839 && view.orientation() == self.target.orientation
840 && self.mirrored == swipe_view_mirrored(view, item)
841 && item.bounds == self.bounds
842 && item.visible
843 && item.enabled
844 && scene.row_key_at(path) == self.target.row_key
845 && group_index(view) == Some(self.current.index)
846 && self.current.matches(view))
847 .then_some((view, item))
848 }
849
850 fn live_destination(&self, view: &Node, forward: bool) -> Option<&SwipePagePosition> {
851 let destination = self.destination(forward)?;
852 (destination.matches(view)
853 && swipe_neighbor(view, self.current.index, forward != self.mirrored)
854 == Some(destination.index))
855 .then_some(destination)
856 }
857
858 fn action(
859 self,
860 scene: &Node,
861 layout: &LayoutNode,
862 point: Point,
863 velocity: Option<(Point, Point)>,
864 ) -> Option<ControlInput> {
865 let (view, item) = self.view(scene, layout)?;
866 let (distance, across) = self.movement(item.map_from_window(point)?);
867 let index = self.live_destination(view, distance > 0.0)?.index;
868 (distance.abs() >= self.threshold * 0.25
869 && distance.abs() > across
870 && self.release_distance(distance, item, velocity) >= self.threshold)
871 .then_some(ControlInput {
872 path: self.target.path,
873 action: ControlAction::Select(index),
874 })
875 }
876}
877
878#[derive(Debug)]
879struct SwipePreviewLease(SwipePreviewHandle);
880
881impl Drop for SwipePreviewLease {
882 fn drop(&mut self) {
883 self.0.clear();
884 }
885}
886
887#[derive(Clone, Debug)]
888struct SwipePageMotion {
889 page: PageSwipe,
890 lease: Rc<SwipePreviewLease>,
891 fraction: f32,
892 duration: Duration,
893 settling: Option<(Instant, f32)>,
894 wake: Option<Instant>,
895}
896
897impl SwipePageMotion {
898 fn settle(&mut self, now: Instant) {
899 self.settling.get_or_insert((now, self.fraction));
900 self.wake.get_or_insert(now + SCROLL_FRAME_INTERVAL);
901 }
902
903 fn advance(&mut self, now: Instant) -> bool {
904 let Some((start, from)) = self.settling else {
905 return false;
906 };
907 let elapsed = now.saturating_duration_since(start);
908 let remaining = (1.0 - elapsed.as_secs_f32() / self.duration.as_secs_f32()).max(0.0);
909 self.fraction = from * remaining.powi(3);
910 self.wake = (elapsed < self.duration).then(|| now + SCROLL_FRAME_INTERVAL);
911 true
912 }
913
914 fn is_current(&self, scene: &Node, layout: &LayoutNode) -> bool {
915 self.page.view(scene, layout).is_some_and(|(view, _)| {
916 view.int("transition-duration").unwrap_or_default() > 0
917 && view
918 .swipe_preview
919 .as_ref()
920 .is_some_and(|preview| preview.handle == self.lease.0)
921 && self
922 .page
923 .live_destination(view, self.fraction > 0.0)
924 .is_some()
925 })
926 }
927}
928
929fn navigation_axis(vertical: bool, direction: LayoutDirection) -> (NavigationKey, NavigationKey) {
930 if vertical {
931 (NavigationKey::Up, NavigationKey::Down)
932 } else if direction == LayoutDirection::RightToLeft {
933 (NavigationKey::Right, NavigationKey::Left)
934 } else {
935 (NavigationKey::Left, NavigationKey::Right)
936 }
937}
938
939fn swipe_view_mirrored(view: &Node, item: &LayoutNode) -> bool {
940 view.orientation() == Orientation::Horizontal
941 && item.layout_direction == LayoutDirection::RightToLeft
942}
943
944fn swipe_neighbor(view: &Node, current: usize, forward: bool) -> Option<usize> {
945 if forward {
946 (current + 1..view.children.len()).find(|&index| group_item(view, index).is_some())
947 } else {
948 (0..current)
949 .rev()
950 .find(|&index| group_item(view, index).is_some())
951 }
952}
953
954pub fn swipe_view_selection(view: &Node, item: &LayoutNode, key: NavigationKey) -> Option<usize> {
956 if view.kind != "SwipeView"
957 || !view.boolean("interactive", true)
958 || !item.enabled
959 || !item.visible
960 {
961 return None;
962 }
963 let current = group_index(view)?;
964 let eligible = |&index: &usize| group_item(view, index).is_some();
965 let index = match (key, view.orientation()) {
966 (NavigationKey::Home, _) => (0..view.children.len()).find(eligible),
967 (NavigationKey::End, _) => (0..view.children.len()).rev().find(eligible),
968 (NavigationKey::Left, Orientation::Horizontal) => {
969 swipe_neighbor(view, current, swipe_view_mirrored(view, item))
970 }
971 (NavigationKey::Right, Orientation::Horizontal) => {
972 swipe_neighbor(view, current, !swipe_view_mirrored(view, item))
973 }
974 (NavigationKey::Up, Orientation::Vertical) => swipe_neighbor(view, current, false),
975 (NavigationKey::Down, Orientation::Vertical) => swipe_neighbor(view, current, true),
976 _ => None,
977 }?;
978 (index != current).then_some(index)
979}
980
981#[derive(Clone, Debug)]
982struct DrawerSwipe {
983 path: Vec<usize>,
984 row_key: Option<RowKey>,
985 id: Option<ElementId>,
986 edge: DrawerEdge,
987 open: bool,
988 start: Point,
989 threshold: f32,
990 viewport: Rect,
991 panel: Rect,
992 reveal: Option<f32>,
993}
994
995impl DrawerSwipe {
996 fn movement(&self, point: Point) -> (f32, f32) {
997 let x = point.x - self.start.x;
998 let y = point.y - self.start.y;
999 let (inward, across) = match self.edge {
1000 DrawerEdge::Left => (x, y),
1001 DrawerEdge::Right => (-x, y),
1002 DrawerEdge::Top => (y, x),
1003 DrawerEdge::Bottom => (-y, x),
1004 };
1005 (if self.open { -inward } else { inward }, across.abs())
1006 }
1007
1008 fn matches(&self, node: &Node, row: Option<RowKey>, viewport: Rect, panel: Rect) -> bool {
1009 node.element_id() == self.id.as_ref().map(ElementId::as_str)
1010 && node.drawer_edge() == self.edge
1011 && node.boolean("open", false) == self.open
1012 && row == self.row_key
1013 && viewport == self.viewport
1014 && panel == self.panel
1015 }
1016
1017 fn current<'a>(
1018 &self,
1019 scene: &'a Node,
1020 layout: &LayoutNode,
1021 modal: Option<&[usize]>,
1022 ) -> Option<&'a Node> {
1023 let action = ControlAction::Drawer(!self.open);
1024 let node = scene.control_target(&self.path, action)?;
1025 let viewport = crate::window_safe_area(scene, layout.bounds);
1026 (modal == self.open.then_some(self.path.as_slice())
1027 && layout.drawer_paths().contains(&self.path)
1028 && self.matches(
1029 node,
1030 scene.row_key_at(&self.path),
1031 viewport,
1032 modal::drawer_bounds(node, viewport),
1033 ))
1034 .then_some(node)
1035 }
1036
1037 fn update(&mut self, point: Point) -> bool {
1038 let (distance, _) = self.movement(point);
1039 let span = modal::drawer_extent(self.edge, self.panel);
1040 let travelled = (distance / span).clamp(0.0, 1.0);
1041 let reveal = if self.open {
1042 1.0 - travelled
1043 } else {
1044 travelled
1045 };
1046 self.reveal.replace(reveal) != Some(reveal)
1047 }
1048
1049 fn action(self, point: Point) -> Option<ControlInput> {
1050 let (distance, across) = self.movement(point);
1051 (distance >= self.threshold && distance >= across).then_some(ControlInput {
1052 path: self.path,
1053 action: ControlAction::Drawer(!self.open),
1054 })
1055 }
1056}
1057
1058#[derive(Clone, Debug)]
1059struct ScrollFling {
1060 route: ScrollRoute,
1061 motion: FlingMotion,
1062 transformed: bool,
1063}
1064
1065enum ScrollInput<'a> {
1066 Wheel,
1067 Pan {
1068 device: PanDevice,
1069 owners: &'a mut MotionOwners,
1070 flicking: bool,
1071 touch_scene: Option<&'a Node>,
1072 },
1073}
1074
1075#[derive(Clone, Copy, Default)]
1076struct AxisMotion {
1077 bounded: bool,
1078 elastic: bool,
1079 dismiss_keyboard: bool,
1080}
1081
1082impl AxisMotion {
1083 fn changed(self) -> bool {
1084 self.bounded || self.elastic
1085 }
1086}
1087
1088#[derive(Clone, Debug)]
1089struct EditorClick {
1090 target: Target,
1091 count: u8,
1092 sample: (Point, Instant),
1093}
1094
1095#[derive(Clone, Debug)]
1096struct TextSelectionScroll {
1097 target: Target,
1098 point: Point,
1099 due: Instant,
1100}
1101
1102#[derive(Clone, Debug, Default)]
1103pub struct Interaction {
1104 pub hovered: Option<Target>,
1105 pub focused: Option<Target>,
1106 focus_reason: xrack_runtime::FocusReason,
1107 pub pressed: Option<Target>,
1108 drag: Option<crate::drag::DragSession>,
1109 file_drag: crate::file_drop::FileDrag,
1110 hovered_scroll_bar: Option<ScrollTarget>,
1111 scroll_bar_press: Option<ScrollBarPress>,
1112 scroll_gesture: Option<ScrollGesture>,
1113 scroll_keyboard_dismissal: bool,
1114 swipe_events: Vec<SwipeDelivery>,
1115 tumbler_wheel: Option<TumblerWheel>,
1116 tumbler_flick: Option<TumblerFlick>,
1117 wheel_steps: Option<WheelSteps>,
1118 scroll_fling: Option<ScrollFling>,
1119 viewport_motion: MotionState,
1120 overscroll: Overscroll,
1121 floating_keyboard: Option<Rect>,
1122 keyboard_avoidance: Option<(Vec<usize>, f32)>,
1123 key_pressed: Option<(ActivationKey, Target)>,
1124 key_standard_button: Option<StandardButtonKind>,
1125 delay_hold: Option<DelayHold>,
1126 button_hold: Option<ButtonHold>,
1127 published_button_presses: Vec<xrack_runtime::ButtonPressHandle>,
1128 button_contacts: Vec<ButtonContact>,
1129 button_press_events: Vec<(ButtonContact, &'static str)>,
1130 pointer_activation_claimed: bool,
1131 key_activation_claimed: Option<ActivationKey>,
1132 range_keys: BTreeMap<SliderKey, Target>,
1133 slider_offset: f64,
1134 slider_anchor: Option<f64>,
1135 slider_fraction: Option<f64>,
1136 range_position_handle: Option<xrack_runtime::RangePositionHandle>,
1137 dial_pointer: Option<Point>,
1138 touch_range: bool,
1139 spin_pressed: Option<SpinAction>,
1140 spin_draft: Option<SpinDraft>,
1141 choice: Option<ChoicePopup>,
1142 search_query: Option<String>,
1143 choice_typeahead: Typeahead,
1144 list_typeahead: Typeahead,
1145 pub(crate) list_composition: Option<(u64, Target)>,
1146 painted_combo_completion: Option<ComboCompletion>,
1147 dismissed_combo_draft: Option<String>,
1148 menu: Option<MenuPopup>,
1149 touch_selection_handles: Option<Target>,
1150 pending_shortcut: Option<PendingShortcut>,
1151 pointer: Option<Point>,
1152 press_origin: Option<Point>,
1153 tooltip: TooltipState,
1154 hovered_radio: Option<(String, String)>,
1155 pressed_radio: Option<(String, String)>,
1156 hovered_list_row: Option<(usize, Option<ElementId>)>,
1157 pressed_list_row: Option<(usize, Option<ElementId>)>,
1158 hovered_tree_indicator: bool,
1159 pressed_tree_indicator: bool,
1160 hovered_table_column: Option<usize>,
1161 pressed_table_column: Option<usize>,
1162 hovered_body_column: Option<usize>,
1163 pressed_body_column: Option<usize>,
1164 hovered_control_part: Option<ControlAction>,
1165 pressed_control_part: Option<ControlAction>,
1166 hovered_standard_button: Option<StandardButtonKind>,
1167 pressed_standard_button: Option<StandardButtonKind>,
1168 hovered_table_grip: Option<(usize, f32, bool)>,
1169 hovered_table_row_grip: Option<(RowKey, f32)>,
1170 table_resize: Option<TableResize>,
1171 table_row_resize: Option<TableRowResize>,
1172 table_column_move: Option<TableColumnMove>,
1173 table_row_move: Option<TableRowMove>,
1174 table_drag_selection: Option<crate::table_drag_selection::TableDragSelection>,
1175 split_drag: Option<SplitDrag>,
1176 split_hover: Option<(xrack_runtime::SplitResizeHandle, usize)>,
1177 table_edit: Option<TableEdit>,
1178 last_table_click: Option<(Target, Instant)>,
1179 editor_press: Option<EditorClick>,
1180 last_editor_click: Option<EditorClick>,
1181 text_selection_scroll: Option<TextSelectionScroll>,
1182 pub editor: Option<TextEdit>,
1183 persistent_editor: Option<PersistentEditor>,
1184 retained_selections: Vec<RetainedSelection>,
1185 editor_window_inactive: bool,
1186 history: EditHistories,
1187 scroll_offsets: BTreeMap<Vec<usize>, f32>,
1188 horizontal_scroll_offsets: BTreeMap<Vec<usize>, f32>,
1189 scroll_selections: BTreeMap<Vec<usize>, ScrollSelection>,
1190 tree_scroll_roots: BTreeMap<Vec<usize>, (i64, Option<RowKey>)>,
1191 pub(crate) scroll_anchors: BTreeMap<Vec<usize>, ListAnchor>,
1192 pub(crate) user_scroll_changes: Vec<UserScrollChange>,
1193 pub(crate) refresh_request: Option<ViewportHandle>,
1194 text_offsets: BTreeMap<Vec<usize>, (Option<RowKey>, Point)>,
1195 dialogs: Vec<DialogFocus>,
1196 stack_focus: BTreeMap<StackFocusKey, Target>,
1197 swipe_page_motion: Option<SwipePageMotion>,
1198 reduce_motion: bool,
1199 swipe_commit: Option<(PageSwipe, f32)>,
1200 page_focus: crate::focus_scope::PageFocusHistory,
1201 calendar_page_focus: Option<CalendarPageFocus>,
1202 scope_focus: crate::focus_scope::FocusHistory,
1203 transitioning_stacks: BTreeSet<Vec<usize>>,
1204 pointer_on_stack_slide: bool,
1205 window_move_press: Option<WindowMovePress>,
1206 dialog_backdrop: Option<Vec<usize>>,
1207}
1208
1209#[derive(Clone, Debug)]
1210struct CalendarPageFocus {
1211 from: Target,
1212 view: Target,
1213 viewport: Option<ViewportHandle>,
1214 order: (u64, u64),
1215 index: usize,
1216}
1217
1218#[derive(Clone, Debug)]
1219struct PersistentEditor {
1220 target: Target,
1221 handle: Option<FocusHandle>,
1222 text: String,
1223 password: bool,
1224}
1225
1226impl PersistentEditor {
1227 fn new(target: &Target, node: &Node) -> Self {
1228 let mut target = target.clone();
1229 target.text_link = None;
1230 Self {
1231 target,
1232 handle: node.focus_handle.clone(),
1233 text: text_input_value(node).to_owned(),
1234 password: node.is_password(),
1235 }
1236 }
1237
1238 fn same_target(&self, target: &Target) -> bool {
1239 self.target.path == target.path
1240 && self.target.row_key == target.row_key
1241 && self.target.element_id() == target.element_id()
1242 }
1243
1244 fn matches(&self, node: &Node) -> bool {
1245 node.boolean("persistent-selection", false)
1246 && (is_text_input(node.kind) || combo_editable(node) || node.selectable_styled_text())
1247 && node.focus_handle == self.handle
1248 && node.is_password() == self.password
1249 && text_input_value(node) == self.text
1250 }
1251}
1252
1253#[derive(Clone, Debug)]
1254struct RetainedSelection {
1255 source: PersistentEditor,
1256 editor: TextEdit,
1257}
1258
1259#[derive(Clone, Debug, PartialEq, Eq)]
1260enum Hit {
1261 None,
1262 Blocked(Vec<usize>),
1263 StackSlide,
1264 WindowMove(Target),
1265 Target(Target),
1266 ControlPart(Target, ControlAction),
1267 ScrollBar(ScrollTarget),
1268 TableRowGrip(Target, usize),
1269}
1270
1271#[derive(Clone, Copy, PartialEq, Eq)]
1272enum HitPurpose<'a> {
1273 Button(xrack_runtime::PointerButton),
1274 Hover,
1275 Gesture(&'a str),
1276}
1277
1278pub(crate) fn focusable(node: &Node) -> bool {
1279 let kind = node.kind;
1280 if matches!(kind, "GroupBox" | "Expander") {
1281 return kind == "Expander" || node.group_checkable();
1282 }
1283 if kind == "PageIndicator" {
1284 return node.boolean("interactive", false) && page_indicator_count(node) != 0;
1285 }
1286 if matches!(kind, "Tumbler" | "PathView") {
1287 return Tumbler::from_node(node).selected().is_some();
1288 }
1289 matches!(
1290 kind,
1291 "Button"
1292 | "FocusScope"
1293 | "Loader"
1294 | "ToolButton"
1295 | "RoundButton"
1296 | "DelayButton"
1297 | "DialogButton"
1298 | "Dialog"
1299 | "Drawer"
1300 | "PopupWindow"
1301 | "Slider"
1302 | "ColorPlane"
1303 | "ScrollBar"
1304 | "Dial"
1305 | "RangeThumb"
1306 | "SpinBox"
1307 | "DoubleSpinBox"
1308 | "ComboBox"
1309 | "Calendar"
1310 | "MonthGrid"
1311 | "RadioButton"
1312 | "Tab"
1313 | "TabButton"
1314 | "SwipeView"
1315 | "SwipeDelegate"
1316 | "StackView"
1317 | "ListView"
1318 | "GridView"
1319 | "StandardListView"
1320 | "TreeView"
1321 | "TableView"
1322 | "TableCell"
1323 | "TreeCell"
1324 | "SplitHandle"
1325 | "Menu"
1326 | "ContextMenuArea"
1327 ) || is_toggle(kind)
1328 || is_text_input(kind)
1329 || node.selectable_styled_text()
1330}
1331
1332fn interactive(node: &Node) -> bool {
1333 matches!(node.kind, "TouchArea" | "ListRow" | "RangeSlider") || focusable(node)
1334}
1335
1336fn list_row(scene: &Node, target: &Target) -> Option<(usize, Option<ElementId>)> {
1337 let (&slot, parent) = target.path.split_last()?;
1338 let list = scene.at_path(parent)?;
1339 let index = list.list?.first_row + slot;
1340 (list.children.get(slot)?.kind == "ListRow").then(|| (index, ElementId::of(list)))
1341}
1342
1343fn table_cell_row<'a>(scene: &Node, path: &'a [usize]) -> Option<(&'a [usize], usize)> {
1344 let [table @ .., slot, 0, _] = path else {
1345 return None;
1346 };
1347 let cell = scene.at_path(path)?;
1348 ((cell.kind == "TableCell" || cell.boolean("table-editor", false))
1349 && scene.at_path(table)?.kind == "TableView")
1350 .then_some((table, *slot))
1351}
1352
1353fn table_cell_target(
1354 scene: &Node,
1355 layout: &LayoutNode,
1356 table: &[usize],
1357 row: usize,
1358 column: usize,
1359) -> Option<Target> {
1360 let view = scene.interactive_at_path(table)?;
1361 let list = view.list?;
1362 if view.kind != "TableView" || row >= list.row_count {
1363 return None;
1364 }
1365 let slot = row.checked_sub(list.first_row)?;
1366 let mut path = table.to_vec();
1367 path.extend([slot, 0, column]);
1368 crate::focus_scope::target_at(scene, layout, &path)
1369}
1370
1371fn list_item_delegate_row<'a>(scene: &Node, path: &'a [usize]) -> Option<(&'a [usize], usize)> {
1372 let [view @ .., slot, 0] = path else {
1373 return None;
1374 };
1375 (scene.at_path(path)?.is_item_delegate()
1376 && matches!(scene.at_path(view)?.kind, "ListView" | "GridView"))
1377 .then_some((view, *slot))
1378}
1379
1380fn tab_close_identity(scene: &Node, path: &[usize]) -> Option<(xrack_runtime::TabClose, String)> {
1381 let (&index, parent) = path.split_last()?;
1382 let request = scene.at_path(parent)?.tab_close(index)?;
1383 let value = scene.at_path(path)?.text("value").unwrap_or("");
1384 Some((request, value.to_owned()))
1385}
1386
1387fn tree_indicator_hit(node: &Node, item: &LayoutNode, point: Point) -> bool {
1388 node.boolean("tree-has-children", false)
1389 && item.contains_clip_point(point)
1390 && TreeRowGeometry::for_layout(node, item)
1391 .zip(item.map_from_window(point))
1392 .is_some_and(|(tree, point)| tree.indicator.contains(point))
1393}
1394
1395fn tree_cell_row<'a>(scene: &Node, path: &'a [usize]) -> Option<(&'a [usize], usize)> {
1396 let cell = scene.at_path(path)?;
1397 if cell.kind != "TreeCell" && !cell.boolean("table-editor", false) {
1398 return None;
1399 }
1400 (0..path.len()).rev().find_map(|depth| {
1401 let parent = &path[..depth];
1402 let tree = scene.at_path(parent)?;
1403 let slot = path[depth];
1404 (tree.kind == "TreeView"
1405 && path.get(depth + 1) == Some(&0)
1406 && tree.children.get(slot)?.kind == "ListRow")
1407 .then_some((parent, slot))
1408 })
1409}
1410
1411#[derive(Clone, Debug, PartialEq, Eq)]
1412enum ScrollSelection {
1413 TabBar(Option<usize>, Orientation, LayoutDirection, u32),
1414 List(Option<usize>, usize),
1415}
1416
1417impl ScrollSelection {
1418 fn new(node: &Node, columns: usize, direction: LayoutDirection, text_scale: f32) -> Self {
1419 let selection = scroll_selection(node);
1420 if matches!(node.kind, "TabBar" | "TabWidget") {
1421 let orientation = node.orientation();
1422 let direction = if orientation == Orientation::Horizontal {
1423 direction
1424 } else {
1425 LayoutDirection::LeftToRight
1426 };
1427 Self::TabBar(selection, orientation, direction, text_scale.to_bits())
1428 } else {
1429 Self::List(selection, columns)
1430 }
1431 }
1432}
1433
1434pub(crate) fn scroll_selection(node: &Node) -> Option<usize> {
1435 if matches!(node.kind, "TabBar" | "TabWidget") {
1436 group_index(node)
1437 } else {
1438 let index = usize::try_from(ListMetrics::selection(node)?).ok()?;
1439 (index < node.list?.row_count).then_some(index)
1440 }
1441}
1442
1443fn current_list_slot(node: &Node) -> Option<usize> {
1444 let index = usize::try_from(ListMetrics::selection(node)?).ok()?;
1445 index.checked_sub(node.list?.first_row)
1446}
1447
1448fn table_hit_row<'a>(scene: &Node, path: &'a [usize]) -> Option<(&'a [usize], usize)> {
1449 if let Some(cell) = table_cell_row(scene, path) {
1450 return Some(cell);
1451 }
1452 let (&slot, table) = path.split_last()?;
1453 (scene.at_path(path)?.kind == "ListRow" && scene.at_path(table)?.kind == "TableView")
1454 .then_some((table, slot))
1455}
1456
1457fn hit(
1458 node: &Node,
1459 layout: &LayoutNode,
1460 window: Point,
1461 path: &mut Vec<usize>,
1462 transitioning_stacks: &BTreeSet<Vec<usize>>,
1463 purpose: HitPurpose<'_>,
1464) -> Hit {
1465 if node.is_control_part() {
1466 return Hit::None;
1467 }
1468 let Some(point) = layout.map_from_window(window) else {
1469 return Hit::None;
1470 };
1471 if node.kind == "Tab"
1472 && layout
1473 .tab_header
1474 .is_some_and(|header| header.contains(point) && layout.contains_clip_point(window))
1475 {
1476 return if layout.enabled {
1477 Hit::Target(Target::from_node(path.clone(), node, true, None))
1478 } else {
1479 Hit::Blocked(path.clone())
1480 };
1481 }
1482 if !layout.contains_subtree_point(window) {
1483 return Hit::None;
1484 }
1485 if node.kind == "ScrollIndicator"
1486 || node.kind == "ScrollBar" && !node.boolean("interactive", true)
1487 {
1488 return Hit::None;
1489 }
1490 if !layout.bounds.contains(point) {
1491 return hit_children(node, layout, window, path, transitioning_stacks, purpose);
1492 }
1493 if node.kind == "RoundButton"
1494 && !(crate::RoundedClip {
1495 bounds: layout.bounds,
1496 radii: crate::corner_radii(node, layout.bounds),
1497 })
1498 .contains(point)
1499 {
1500 return Hit::None;
1501 }
1502 if transitioning_stacks.contains(path) {
1503 return Hit::StackSlide;
1504 }
1505 if layout.enabled
1506 && let Some(slot) = layout
1507 .split
1508 .as_ref()
1509 .and_then(|split| split.expanded_hit(point))
1510 && let Some(child) = layout.children.get(slot)
1511 && let Some(handle) = node.children.get(slot)
1512 && eligible(handle, child)
1513 && child.contains_clip_point(window)
1514 {
1515 let mut target = path.clone();
1516 target.push(slot);
1517 return Hit::Target(Target::from_node(target, handle, true, None));
1518 }
1519 if (node.kind == "Expander" || node.group_checkable())
1520 && layout.group_header(node).contains(point)
1521 {
1522 return if layout.enabled {
1523 Hit::Target(Target::from_node(path.clone(), node, true, None))
1524 } else {
1525 Hit::Blocked(path.clone())
1526 };
1527 }
1528 if let Some(action) = layout.tumbler.as_ref().and_then(|wheel| wheel.hit(point)) {
1529 return if layout.enabled {
1530 Hit::ControlPart(Target::from_node(path.clone(), node, true, None), action)
1531 } else {
1532 Hit::Blocked(path.clone())
1533 };
1534 }
1535 if node.kind == "SearchField"
1536 && let Some(action) = SearchGeometry::for_layout(layout).action_at(node, point)
1537 {
1538 return if layout.enabled {
1539 Hit::ControlPart(Target::from_node(path.clone(), node, true, None), action)
1540 } else {
1541 Hit::Blocked(path.clone())
1542 };
1543 }
1544 if is_calendar_control(node.kind) {
1545 let action = CalendarGeometry::for_layout(node, layout).action_at(point);
1546 return if layout.enabled
1547 && let Some(action) = action
1548 {
1549 Hit::ControlPart(
1550 Target::from_node(path.clone(), node, true, None),
1551 ControlAction::Calendar(action),
1552 )
1553 } else {
1554 Hit::Blocked(path.clone())
1555 };
1556 }
1557 if node.kind == "PageIndicator" {
1558 if !focusable(node) {
1559 return Hit::None;
1560 }
1561 let Some(index) = PageIndicatorGeometry::with_layout_direction(
1562 node,
1563 layout.bounds,
1564 layout.layout_direction,
1565 )
1566 .and_then(|geometry| geometry.marker_at(point)) else {
1567 return Hit::None;
1568 };
1569 return if layout.enabled {
1570 Hit::ControlPart(
1571 Target::from_node(path.clone(), node, true, None),
1572 ControlAction::Select(index),
1573 )
1574 } else {
1575 Hit::Blocked(path.clone())
1576 };
1577 }
1578 if node.kind == "Dial" && !DialGeometry::new(layout.bounds, node).contains(point) {
1579 return Hit::None;
1580 }
1581 if let Some((rect, action)) = layout
1582 .swipe_delegate
1583 .as_deref()
1584 .and_then(crate::SwipeDelegateGeometry::toggle)
1585 && rect.contains(point)
1586 {
1587 return if layout.enabled {
1588 Hit::ControlPart(Target::from_node(path.clone(), node, true, None), action)
1589 } else {
1590 Hit::Blocked(path.clone())
1591 };
1592 }
1593 if let Some(bar) = layout
1594 .scroll_bars(node)
1595 .find(|bar| bar.scrollable() && bar.track.contains(point))
1596 {
1597 return if layout.enabled {
1598 Hit::ScrollBar(ScrollTarget {
1599 path: path.clone(),
1600 orientation: bar.orientation,
1601 row_key: None,
1602 id: ElementId::of(node),
1603 })
1604 } else {
1605 Hit::Blocked(path.clone())
1606 };
1607 }
1608 if node.kind == "ScrollBar" {
1609 return Hit::None;
1610 }
1611 if let Some(slot) = layout
1612 .table
1613 .as_ref()
1614 .and_then(|table| table.row_resize_at(node, layout, point))
1615 {
1616 return if layout.enabled {
1617 Hit::TableRowGrip(Target::from_node(path.clone(), node, true, None), slot)
1618 } else {
1619 Hit::Blocked(path.clone())
1620 };
1621 }
1622 if node.kind != "SplitHandle" {
1623 let child = hit_children(node, layout, window, path, transitioning_stacks, purpose);
1624 if !matches!(child, Hit::None) {
1625 return child;
1626 }
1627 }
1628 if let Some((index, _)) = layout
1629 .text_link_regions()
1630 .find(|(_, rect)| rect.contains(point))
1631 && let Some(target) = Target::for_text_link(node, path, index)
1632 {
1633 return if layout.enabled {
1634 Hit::ControlPart(target, ControlAction::ActivateTextLink(index))
1635 } else {
1636 Hit::Blocked(path.clone())
1637 };
1638 }
1639 if node.kind == "WindowMoveArea" && layout.enabled && node.boolean("enabled", true) {
1640 return Hit::WindowMove(Target::from_node(path.clone(), node, false, None));
1641 }
1642 if purpose == HitPurpose::Gesture(node.kind)
1643 && (node.kind == "WheelHandler"
1644 || node.hover_handle.is_some()
1645 || node.scale_rotate_handle.is_some()
1646 || node.swipe_handle.is_some() && has_swipe_directions(node))
1647 && layout.enabled
1648 && node.boolean("enabled", true)
1649 {
1650 return Hit::Blocked(path.clone());
1651 }
1652 if xrack_runtime::is_pane(node.kind) {
1653 return Hit::Blocked(path.clone());
1654 }
1655 if matches!(node.kind, "Tab" | "GroupBox" | "Expander")
1656 || is_window_overlay(node.kind)
1657 || !interactive(node)
1658 || node.kind == "TouchArea"
1659 && (!node.boolean("enabled", true)
1660 || matches!(purpose, HitPurpose::Button(button) if !node.accepts_pointer_button(button)))
1661 || node.kind == "FocusScope" && !node.boolean("focus-on-click", true)
1662 || node.kind == "TreeCell" && !editable_table_cell(node)
1663 {
1664 return Hit::None;
1665 }
1666 if !layout.enabled {
1667 return Hit::Blocked(path.clone());
1668 }
1669 let target = Target::from_node(path.clone(), node, focusable(node), None);
1670 if is_spin_box(node.kind)
1671 && let Some(action) = SpinGeometry::for_layout(layout, node).action_at(point)
1672 {
1673 return Hit::ControlPart(target, ControlAction::Spin(action));
1674 }
1675 Hit::Target(target)
1676}
1677
1678fn hit_children(
1679 node: &Node,
1680 layout: &LayoutNode,
1681 point: Point,
1682 path: &mut Vec<usize>,
1683 transitioning_stacks: &BTreeSet<Vec<usize>>,
1684 purpose: HitPurpose<'_>,
1685) -> Hit {
1686 for (i, child, child_layout) in layout.children_in_paint_order(node).rev() {
1687 if is_window_overlay(child.kind) {
1688 continue;
1689 }
1690 path.push(i);
1691 let found = hit(
1692 child,
1693 child_layout,
1694 point,
1695 path,
1696 transitioning_stacks,
1697 purpose,
1698 );
1699 path.pop();
1700 if !matches!(found, Hit::None) {
1701 return found;
1702 }
1703 }
1704 Hit::None
1705}
1706
1707fn inspect_at(node: &Node, layout: &LayoutNode, point: Point, path: &mut Vec<usize>) -> bool {
1708 if node.is_control_part() || !layout.contains_subtree_point(point) {
1709 return false;
1710 }
1711 if node.list.is_none() {
1713 for (index, child, item) in layout.children_in_paint_order(node).rev() {
1714 if is_window_overlay(child.kind) {
1715 continue;
1716 }
1717 path.push(index);
1718 if inspect_at(child, item, point, path) {
1719 return true;
1720 }
1721 path.pop();
1722 }
1723 }
1724 layout
1725 .map_from_window(point)
1726 .is_some_and(|point| layout.bounds.contains(point))
1727}
1728
1729impl crate::FileDropScope {
1730 #[doc(hidden)]
1732 pub fn text_target(&self, scene: &Node, layout: &LayoutNode, point: Point) -> Option<Target> {
1733 let (target, node) = self.text_at(scene, layout, point)?;
1734 (!node.text_read_only()).then_some(target)
1735 }
1736
1737 #[doc(hidden)]
1738 pub fn text_drag_source(
1739 &self,
1740 scene: &Node,
1741 layout: &LayoutNode,
1742 point: Point,
1743 ) -> Option<Target> {
1744 let (target, node) = self.text_at(scene, layout, point)?;
1745 (!node.is_password()).then_some(target)
1746 }
1747
1748 fn text_at<'a>(
1749 &self,
1750 scene: &'a Node,
1751 layout: &LayoutNode,
1752 point: Point,
1753 ) -> Option<(Target, &'a Node)> {
1754 if self.blocked || self.text_composing {
1755 return None;
1756 }
1757 let scope = self.scope_at(layout, point);
1758 let (node, item) = scene.at_path(scope).zip(layout.at_path(scope))?;
1759 let Hit::Target(mut target) = hit(
1760 node,
1761 item,
1762 point,
1763 &mut scope.to_vec(),
1764 &self.transitions,
1765 HitPurpose::Button(xrack_runtime::PointerButton::Primary),
1766 ) else {
1767 return None;
1768 };
1769 if !target.focusable
1770 || self
1771 .swiping
1772 .as_ref()
1773 .is_some_and(|path| target.path.starts_with(path))
1774 {
1775 return None;
1776 }
1777 target.row_key = scene.row_key_at(&target.path);
1778 let node = scene.interactive_at_path(&target.path)?;
1779 if !valid(&target, scene, layout) {
1780 return None;
1781 }
1782 if node.kind == "SearchField" || combo_editable(node) {
1783 let item = layout.at_path(&target.path)?;
1784 let part = if node.kind == "SearchField" {
1785 SearchGeometry::for_layout(item).entry
1786 } else {
1787 ComboGeometry::for_control(node, item.bounds, item.layout_direction).entry
1788 };
1789 part.contains(item.map_from_window(point)?)
1790 .then_some((target, node))
1791 } else {
1792 is_text_input(node.kind).then_some((target, node))
1793 }
1794 }
1795}
1796
1797pub(crate) fn valid(target: &Target, scene: &Node, layout: &LayoutNode) -> bool {
1798 let Some(node) = target.node_in(scene) else {
1799 return false;
1800 };
1801 let Some(item) = layout.at_path(&target.path) else {
1802 return false;
1803 };
1804 if let Some(link) = &target.text_link {
1805 return item.enabled
1806 && node.styled_text("text") == Some(&link.document)
1807 && item
1808 .text_link_regions()
1809 .any(|(index, _)| index == link.index);
1810 }
1811 target.focusable == focusable(node) && eligible(node, item)
1812}
1813
1814fn context_menu_area<'a>(
1815 scene: &'a Node,
1816 path: &'a [usize],
1817 scope: &[usize],
1818) -> Option<(&'a [usize], &'a Node, usize)> {
1819 (scope.len()..=path.len()).rev().find_map(|depth| {
1820 let path = &path[..depth];
1821 let area = scene
1822 .interactive_at_path(path)
1823 .filter(|node| node.kind == "ContextMenuArea")?;
1824 let menu = area
1825 .children
1826 .iter()
1827 .position(|child| child.kind == "Menu" && child.is_visible())?;
1828 Some((path, area, menu))
1829 })
1830}
1831
1832fn split_target<'a, 'b>(
1833 target: &'a Target,
1834 scene: &Node,
1835 layout: &'b LayoutNode,
1836) -> Option<(&'a [usize], &'b SplitGeometry, &'b SplitHandle)> {
1837 if scene.at_path(&target.path)?.kind != "SplitHandle" || !valid(target, scene, layout) {
1838 return None;
1839 }
1840 let (&slot, path) = target.path.split_last()?;
1841 let geometry = layout.at_path(path)?.split.as_deref()?;
1842 Some((path, geometry, geometry.handle(slot)?))
1843}
1844
1845fn pending_scroll_offset(
1846 item: &LayoutNode,
1847 offsets: &BTreeMap<Vec<usize>, f32>,
1848 path: &[usize],
1849 axis: Orientation,
1850) -> Option<f32> {
1851 if let Some(renderer) = &item.nested_list {
1852 item.bound_offset(axis).or_else(|| renderer.offset(axis))
1853 } else {
1854 offsets.get(path).copied()
1855 }
1856}
1857
1858fn store_scroll_offset(
1859 item: &LayoutNode,
1860 offsets: &mut BTreeMap<Vec<usize>, f32>,
1861 path: &[usize],
1862 axis: Orientation,
1863 offset: f32,
1864) {
1865 if let Some(renderer) = &item.nested_list {
1866 renderer.set_offset(axis, offset);
1867 } else {
1868 offsets.insert(path.to_vec(), offset);
1869 }
1870}
1871
1872pub(crate) fn moved_row_target(
1873 target: &Target,
1874 scene: &Node,
1875 layout: &LayoutNode,
1876) -> Option<Target> {
1877 let key = target.row_key?;
1878 if key.has_view_scope() {
1879 fn find(node: &Node, target: &Target, path: &mut Vec<usize>) -> Option<Target> {
1880 if matches!(
1881 node.kind,
1882 "ListRow" | "TabButton" | "Tab" | "StackItem" | "SwipePage"
1883 ) && node.routing_row_key() == target.row_key
1884 {
1885 let suffix = target.path.get(path.len()..)?;
1886 let mut moved = target.clone();
1887 moved.path = path.iter().copied().chain(suffix.iter().copied()).collect();
1888 return Some(moved);
1889 }
1890 if path.len() >= target.path.len() {
1891 return None;
1892 }
1893 node.materialized_children().find_map(|(slot, child)| {
1894 path.push(slot);
1895 let found = find(child, target, path);
1896 path.pop();
1897 found
1898 })
1899 }
1900 return find(scene, target, &mut Vec::new()).filter(|moved| valid(moved, scene, layout));
1901 }
1902 for depth in (0..target.path.len()).rev() {
1903 let Some(node) = scene.at_path(&target.path[..depth]) else {
1904 continue;
1905 };
1906 if node.kind == "DynamicContainer" {
1907 let (slot, _) = node
1908 .materialized_children()
1909 .find(|(_, child)| child.dynamic_mount_key() == Some(key))?;
1910 let mut moved = target.clone();
1911 moved.path[depth] = slot;
1912 return valid(&moved, scene, layout).then_some(moved);
1913 }
1914 if !matches!(
1915 node.kind,
1916 "ListView"
1917 | "GridView"
1918 | "StandardListView"
1919 | "TableView"
1920 | "TreeView"
1921 | "TabBar"
1922 | "TabWidget"
1923 | "StackLayout"
1924 | "SwipeView"
1925 ) {
1926 continue;
1927 }
1928 let slot = node
1929 .children
1930 .iter()
1931 .position(|row| row.routing_row_key() == Some(key))?;
1932 let mut moved = target.clone();
1933 moved.path[depth] = slot;
1934 return valid(&moved, scene, layout).then_some(moved);
1935 }
1936 None
1937}
1938
1939fn focus_hitbox(node: &Node, layout: &LayoutNode) -> Option<Rect> {
1940 if node.kind == "PathView"
1941 && layout
1942 .tumbler
1943 .as_ref()
1944 .is_none_or(|view| view.rows.is_empty())
1945 {
1946 return None;
1947 }
1948 if node.kind == "ScrollBar"
1949 && (!node.boolean("interactive", true)
1950 || !layout
1951 .scroll_control_geometry(node)
1952 .is_some_and(ScrollBarGeometry::scrollable))
1953 {
1954 return None;
1955 }
1956 let hitbox = if node.kind == "Tab" {
1957 layout.tab_header
1958 } else if layout.visible && matches!(node.kind, "GroupBox" | "Expander") {
1959 Some(layout.group_header(node))
1960 } else if layout.visible {
1961 Some(layout.bounds)
1962 } else {
1963 None
1964 };
1965 (layout.enabled && interactive(node))
1966 .then_some(hitbox)
1967 .flatten()
1968}
1969
1970pub(crate) fn eligible(node: &Node, layout: &LayoutNode) -> bool {
1971 focus_hitbox(node, layout).is_some_and(|bounds| {
1972 let clipped = layout.clip_rect(bounds);
1973 clipped.width > 0.0 && clipped.height > 0.0
1974 })
1975}
1976
1977pub(crate) fn focus_reachable(
1978 target: &Target,
1979 scene: &Node,
1980 layout: &LayoutNode,
1981 allow_reveal: bool,
1982) -> bool {
1983 valid(target, scene, layout)
1984 || allow_reveal
1985 && target.text_link.is_none()
1986 && target
1987 .node_in(scene)
1988 .zip(layout.at_path(&target.path))
1989 .is_some_and(|(node, item)| {
1990 target.focusable == focusable(node)
1991 && focus_hitbox(node, item).is_some_and(|rect| {
1992 crate::viewport::plan_focus_scroll(scene, layout, &target.path, rect)
1993 .is_some_and(|plan| !plan.is_empty())
1994 })
1995 })
1996}
1997
1998fn scroll_target_visible(item: &LayoutNode) -> bool {
1999 let clip = item.clip_rect(item.bounds);
2000 item.visible && item.enabled && clip.width > 0.0 && clip.height > 0.0
2001}
2002
2003fn primary_vertical_viewport(
2004 node: &Node,
2005 item: &LayoutNode,
2006 path: &mut Vec<usize>,
2007 transitions: &BTreeSet<Vec<usize>>,
2008 primary: &mut Option<(f32, Vec<usize>)>,
2009) {
2010 if !item.visible || !item.enabled || transitions.contains(path) {
2011 return;
2012 }
2013 if item
2014 .scroll_on(Orientation::Vertical)
2015 .is_some_and(|scroll| scroll.max_offset > 0.0)
2016 && scroll_target_visible(item)
2017 {
2018 let bounds = item.visible_window_bounds(item.bounds);
2019 let area = bounds.width * bounds.height;
2020 if area > 0.0 && primary.as_ref().is_none_or(|(best, _)| area > *best) {
2021 *primary = Some((area, path.clone()));
2022 }
2023 return;
2024 }
2025 for (index, child, child_layout) in item.children_in_scene_order(node) {
2026 if !is_window_overlay(child.kind) {
2027 path.push(index);
2028 primary_vertical_viewport(child, child_layout, path, transitions, primary);
2029 path.pop();
2030 }
2031 }
2032}
2033
2034fn first_editable_tree_cell<'a>(
2035 node: &'a Node,
2036 layout: &LayoutNode,
2037 path: &mut Vec<usize>,
2038) -> Option<&'a Node> {
2039 if !layout.enabled || !layout.visible || node.list.is_some() {
2040 return None;
2041 }
2042 if editable_table_cell(node) && eligible(node, layout) {
2043 return Some(node);
2044 }
2045 for (index, child, item) in layout.children_in_scene_order(node) {
2046 path.push(index);
2047 if let Some(cell) = first_editable_tree_cell(child, item, path) {
2048 return Some(cell);
2049 }
2050 path.pop();
2051 }
2052 None
2053}
2054
2055fn group_targets(
2056 node: &Node,
2057 layout: &LayoutNode,
2058 path: &[usize],
2059 include_clipped: bool,
2060) -> impl Iterator<Item = (usize, Target)> {
2061 let scrollable_tabs =
2062 matches!(node.kind, "TabBar" | "TabWidget") && scroll_target_visible(layout);
2063 node.children
2064 .iter()
2065 .zip(&layout.children)
2066 .enumerate()
2067 .filter_map(move |(index, (child, item))| {
2068 let usable = if include_clipped || scrollable_tabs {
2069 focus_hitbox(child, item).is_some_and(|rect| rect.width > 0.0 && rect.height > 0.0)
2070 } else {
2071 eligible(child, item)
2072 };
2073 if group_item(node, index).is_none() || !usable {
2074 return None;
2075 }
2076 let mut child_path = path.to_vec();
2077 child_path.push(index);
2078 Some((index, Target::from_node(child_path, child, true, None)))
2079 })
2080}
2081
2082fn group_focus(node: &Node, layout: &LayoutNode, path: &[usize]) -> Option<Target> {
2083 let selected = group_index(node);
2084 group_targets(node, layout, path, false)
2085 .min_by_key(|(index, _)| Some(*index) != selected)
2086 .map(|(_, target)| target)
2087}
2088
2089pub(crate) fn radio_group_focus(
2090 scene: &Node,
2091 layout: &LayoutNode,
2092 path: &[usize],
2093 allow_reveal: bool,
2094) -> Option<Target> {
2095 let group = scene
2096 .at_path(path)
2097 .filter(|node| node.kind == "RadioGroup")?;
2098 let item = layout.at_path(path)?;
2099 group_targets(group, item, path, allow_reveal)
2100 .filter_map(|(index, mut target)| {
2101 target.row_key = scene.row_key_at(&target.path);
2102 focus_reachable(&target, scene, layout, allow_reveal).then_some((index, target))
2103 })
2104 .min_by_key(|(index, _)| Some(*index) != group_index(group))
2105 .map(|(_, target)| target)
2106}
2107
2108fn attached_radio<'a>(
2109 scene: &'a Node,
2110 path: &'a [usize],
2111) -> Option<(&'a ButtonGroupMembership, &'a [usize])> {
2112 let member = scene
2113 .at_path(path)?
2114 .button_group
2115 .as_ref()
2116 .filter(|member| member.group.exclusive)?;
2117 Some((member, member.component_path(path)?))
2118}
2119
2120fn attached_radio_tab_stop(scene: &Node, path: &[usize], targets: &[Target]) -> Option<usize> {
2121 targets.iter().position(|target| {
2122 attached_radio(scene, &target.path).is_some_and(|(member, component)| {
2123 path.strip_prefix(component)
2124 .is_some_and(|path| member.group.paths().any(|member| member == path))
2125 })
2126 })
2127}
2128
2129pub(crate) fn focus_targets(scene: &Node, layout: &LayoutNode, scope: &[usize]) -> Vec<Target> {
2130 focus_targets_with_reveal(scene, layout, scope, false)
2131}
2132
2133pub(crate) fn focus_targets_with_reveal(
2134 scene: &Node,
2135 layout: &LayoutNode,
2136 scope: &[usize],
2137 allow_reveal: bool,
2138) -> Vec<Target> {
2139 fn collect(
2140 root: (&Node, &LayoutNode),
2141 node: &Node,
2142 layout: &LayoutNode,
2143 path: &mut Vec<usize>,
2144 out: &mut Vec<Target>,
2145 allow_reveal: bool,
2146 clipped_candidates: bool,
2147 ) {
2148 if !layout.visible
2149 || !layout.enabled
2150 || node.kind == "CalendarCells"
2151 || node.is_control_part()
2152 {
2153 return;
2154 }
2155 let clip = layout.clip_rect(layout.bounds);
2156 if !clipped_candidates
2157 && !layout.allows_overflow()
2158 && (clip.width <= 0.0 || clip.height <= 0.0)
2159 {
2160 return;
2161 }
2162 let candidate = |path: &[usize], node: &Node, item: &LayoutNode| {
2163 let target = Target::from_node(path.to_vec(), node, true, root.0.row_key_at(path));
2164 if !clipped_candidates {
2165 return Some(target);
2166 }
2167 (eligible(node, item) || focus_reachable(&target, root.0, root.1, true))
2168 .then_some(target)
2169 };
2170 let before_children = out.len();
2171 if matches!(node.kind, "TabWidget" | "TabBar" | "RadioGroup") {
2172 if clipped_candidates
2173 && !(matches!(node.kind, "TabBar" | "TabWidget") && scroll_target_visible(layout))
2174 {
2175 let selected = group_index(node);
2176 if let Some((_, target)) = group_targets(node, layout, path, true)
2177 .filter_map(|(index, mut target)| {
2178 target.row_key = root.0.row_key_at(&target.path);
2179 focus_reachable(&target, root.0, root.1, true).then_some((index, target))
2180 })
2181 .min_by_key(|(index, _)| Some(*index) != selected)
2182 {
2183 out.push(target);
2184 }
2185 } else if let Some(target) = group_focus(node, layout, path) {
2186 out.push(target);
2187 }
2188 if node.kind != "TabWidget" {
2189 return;
2190 }
2191 } else if !matches!(node.kind, "Tab" | "TreeCell" | "FocusScope" | "Loader")
2192 && !is_window_overlay(node.kind)
2193 && focusable(node)
2194 && (!matches!(node.kind, "GroupBox" | "Expander")
2195 || clipped_candidates
2196 || eligible(node, layout))
2197 {
2198 out.extend(candidate(path, node, layout));
2199 }
2200 if node.kind == "SplitHandle" {
2201 return;
2202 }
2203 if node.kind == "StyledText" {
2204 let indices: BTreeSet<_> = layout.text_link_regions().map(|(index, _)| index).collect();
2205 out.extend(
2206 indices
2207 .into_iter()
2208 .filter_map(|index| Target::for_text_link(node, path, index)),
2209 );
2210 }
2211 let reveal_children =
2212 clipped_candidates || allow_reveal && crate::viewport::reveals_focus(node, layout);
2213 let mut visit = |index: usize| {
2214 if let Some((child, item)) = node.child_at(index).zip(layout.child_at(index))
2215 && !is_window_overlay(child.kind)
2216 {
2217 path.push(index);
2218 collect(root, child, item, path, out, allow_reveal, reveal_children);
2219 path.pop();
2220 }
2221 };
2222 if node.kind == "TreeView" {
2223 if let Some(slot) = current_list_slot(node) {
2224 visit(slot);
2225 }
2226 } else if !node.boolean("__standard-table", false) {
2227 for index in crate::child_reading_order(node) {
2228 visit(index);
2229 }
2230 }
2231 if node.kind == "FocusScope"
2232 && out.len() == before_children
2233 && node.boolean("focus-on-tab-navigation", true)
2234 {
2235 out.extend(candidate(path, node, layout));
2236 }
2237 }
2238 let mut targets = Vec::new();
2239 if let Some((node, item)) = scene.at_path(scope).zip(layout.at_path(scope)) {
2240 let clipped_candidates = allow_reveal
2241 && (0..scope.len())
2242 .rev()
2243 .map(|depth| &scope[..depth])
2244 .map_while(|path| scene.at_path(path).zip(layout.at_path(path)))
2245 .take_while(|(node, _)| !is_window_overlay(node.kind))
2246 .any(|(node, item)| crate::viewport::reveals_focus(node, item));
2247 collect(
2248 (scene, layout),
2249 node,
2250 item,
2251 &mut scope.to_vec(),
2252 &mut targets,
2253 allow_reveal,
2254 clipped_candidates,
2255 );
2256 if targets.is_empty() && is_window_overlay(node.kind) && eligible(node, item) {
2257 targets.push(Target::from_node(scope.to_vec(), node, true, None));
2258 }
2259 }
2260 let mut groups = BTreeMap::new();
2261 let mut stops = Vec::with_capacity(targets.len());
2262 for mut target in targets {
2263 target.row_key = scene.row_key_at(&target.path);
2264 if let Some((member, component)) = attached_radio(scene, &target.path) {
2265 let key = (component.to_vec(), member.group.key.clone());
2266 if let Some(&slot) = groups.get(&key) {
2267 if member.group.selected == Some(member.index) {
2268 stops[slot] = target;
2269 }
2270 continue;
2271 }
2272 groups.insert(key, stops.len());
2273 }
2274 stops.push(target);
2275 }
2276 stops
2277}
2278
2279fn dialog_entry_focus(scene: &Node, layout: &LayoutNode, path: &[usize]) -> Option<Target> {
2280 let node = scene.at_path(path)?;
2281 let targets = focus_targets(scene, layout, path);
2282 let first = targets.iter().find(|target| {
2283 scene
2284 .at_path(&target.path)
2285 .and_then(Node::standard_button_kind)
2286 != Some(StandardButtonKind::Discard)
2287 });
2288 if node.kind == "Dialog"
2289 && first
2290 .and_then(|target| scene.at_path(&target.path))
2291 .and_then(dialog_button_action)
2292 .is_some()
2293 && let Some(primary) = targets.iter().find(|target| {
2294 scene.at_path(&target.path).is_some_and(|button| {
2295 button.boolean("primary", false)
2296 && dialog_button_action(button)
2297 == Some(ControlAction::Dialog(DialogRole::Accept))
2298 })
2299 })
2300 {
2301 return Some(primary.clone());
2302 }
2303 first.cloned().or_else(|| {
2304 eligible(node, layout.at_path(path)?)
2305 .then(|| Target::from_node(path.to_vec(), node, true, scene.row_key_at(path)))
2306 })
2307}
2308
2309fn slider_target<'a, 'b>(
2310 target: &'a Target,
2311 scene: &'b Node,
2312 layout: &LayoutNode,
2313) -> Option<(&'a [usize], &'b Node)> {
2314 let leaf = scene.at_path(&target.path)?;
2315 if matches!(leaf.kind, "Slider" | "RangeSlider" | "Dial" | "ColorPlane") {
2316 return valid(target, scene, layout).then_some((target.path.as_slice(), leaf));
2317 }
2318 if leaf.kind != "RangeThumb" || target.row_key != scene.row_key_at(&target.path) {
2319 return None;
2320 }
2321 let (&index, path) = target.path.split_last()?;
2322 let node = scene.interactive_at_path(path)?;
2323 (index < 2 && node.kind == "RangeSlider" && eligible(node, layout.at_path(path)?))
2324 .then_some((path, node))
2325}
2326
2327fn sibling_menu(
2328 scene: &Node,
2329 layout: &LayoutNode,
2330 target: &Target,
2331 key: MenuKey,
2332) -> Option<Target> {
2333 let (&index, parent) = target.path.split_last()?;
2334 let bar = scene
2335 .at_path(parent)
2336 .filter(|node| node.kind == "MenuBar")?;
2337 let choices: Vec<_> = bar
2338 .children
2339 .iter()
2340 .enumerate()
2341 .filter_map(|(slot, child)| {
2342 if child.kind != "Menu" {
2343 return None;
2344 }
2345 let mut path = parent.to_vec();
2346 path.push(slot);
2347 let row_key = scene.row_key_at(&path);
2348 let sibling = Target::from_node(path, child, true, row_key);
2349 valid(&sibling, scene, layout).then_some((slot, sibling))
2350 })
2351 .collect();
2352 let current = choices.iter().position(|(slot, _)| *slot == index)?;
2353 let rtl = layout.at_path(parent)?.layout_direction == LayoutDirection::RightToLeft;
2354 let previous = (key == MenuKey::Left) != rtl;
2355 let step = if previous { choices.len() - 1 } else { 1 };
2356 Some(choices[(current + step) % choices.len()].1.clone())
2357}
2358
2359impl Interaction {
2360 pub fn begin_pointer_sequence(
2361 &self,
2362 scene: &Node,
2363 layout: &LayoutNode,
2364 point: Point,
2365 event: xrack_runtime::PointerEvent,
2366 now: Instant,
2367 ) -> Option<(crate::PointerSequence, crate::PointerDelivery)> {
2368 if self.menu_open() || self.choice_open() {
2369 return None;
2370 }
2371 let Hit::Target(target) =
2372 self.hit_at_for(scene, layout, point, HitPurpose::Button(event.button))
2373 else {
2374 return None;
2375 };
2376 crate::PointerSequence::begin(target, self, scene, layout, point, event, now)
2377 }
2378
2379 pub(crate) fn touch_area_hover<'a>(
2380 &self,
2381 scene: &'a Node,
2382 layout: &LayoutNode,
2383 point: Point,
2384 ) -> Option<(&'a Node, (Length, Length))> {
2385 if self.menu_open() || self.choice_open() {
2386 return None;
2387 }
2388 let Hit::Target(target) = self.hit_at_for(scene, layout, point, HitPurpose::Hover) else {
2389 return None;
2390 };
2391 let node = scene.interactive_at_path(&target.path)?;
2392 if node.kind != "TouchArea" {
2393 return None;
2394 }
2395 let (_, x, y) =
2396 crate::pointer_events::local_position(layout.at_path(&target.path)?, point)?;
2397 Some((node, (x, y)))
2398 }
2399
2400 pub fn direct_pointer_claimed(&self) -> bool {
2401 self.scroll_table_drag_claimed()
2402 || self.scroll_gesture.as_ref().is_some_and(|gesture| {
2403 gesture.motion.dragging
2404 && (gesture.route.axes.iter().any(Option::is_some)
2405 || gesture.drawer.is_some()
2406 || !gesture.pages.is_empty()
2407 || gesture.tumbler.is_some()
2408 || gesture.switch.is_some()
2409 || gesture.swipe_delegate.is_some()
2410 || matches!(
2411 gesture.swipe,
2412 Some(SwipeRoute::Captured(_) | SwipeRoute::Cancelled)
2413 ))
2414 })
2415 }
2416
2417 pub fn owns_pointer_press(&self, target: &Target) -> bool {
2418 self.pressed.as_ref() == Some(target)
2419 || self.scroll_gesture.as_ref().is_some_and(
2420 |gesture| matches!(&gesture.tap, Some(Hit::Target(tap)) if tap == target),
2421 )
2422 }
2423
2424 pub fn cancel_pointer_activation(&mut self, target: &Target) {
2425 if self.pressed.as_ref() == Some(target) {
2426 self.pressed = None;
2427 self.press_origin = None;
2428 }
2429 if let Some(gesture) = &mut self.scroll_gesture
2430 && matches!(&gesture.tap, Some(Hit::Target(tap)) if tap == target)
2431 {
2432 gesture.tap = None;
2433 }
2434 }
2435
2436 pub(crate) fn hover_entries(
2437 &self,
2438 scene: &Node,
2439 layout: &LayoutNode,
2440 point: Point,
2441 ) -> Vec<HoverEntry> {
2442 if self.menu_open() || self.choice_open() {
2443 return Vec::new();
2444 }
2445 let Some((path, scope_depth)) = self.gesture_hit_path(scene, layout, point, "HoverHandler")
2446 else {
2447 return Vec::new();
2448 };
2449 let mut entries = Vec::new();
2450 for depth in (scope_depth..=path.len()).rev() {
2451 let path = &path[..depth];
2452 let Some((node, item)) = scene.at_path(path).zip(layout.at_path(path)) else {
2453 continue;
2454 };
2455 if !node.boolean("enabled", true) {
2456 continue;
2457 }
2458 let Some((handle, position)) = node
2459 .hover_handle
2460 .as_ref()
2461 .zip(local_handler_position(item, point))
2462 else {
2463 continue;
2464 };
2465 entries.push(HoverEntry {
2466 path: path.to_vec(),
2467 row_key: scene.row_key_at(path),
2468 handle: handle.clone(),
2469 position,
2470 cursor_shape: node.cursor_shape(),
2471 });
2472 if node.boolean("blocking", false) {
2473 break;
2474 }
2475 }
2476 entries
2477 }
2478
2479 pub fn wheel_route(
2480 &self,
2481 scene: &Node,
2482 layout: &LayoutNode,
2483 event: xrack_runtime::WheelEvent,
2484 ) -> Option<WheelRoute> {
2485 if self.menu_open()
2486 || self.choice_open()
2487 || !(event.delta_x.0.is_finite() && event.delta_y.0.is_finite())
2488 || event.delta_x.0 == 0.0 && event.delta_y.0 == 0.0
2489 {
2490 return None;
2491 }
2492 let point = self.pointer?;
2493 let (path, scope_depth) = self.gesture_hit_path(scene, layout, point, "WheelHandler")?;
2494 let mut deliveries = Vec::new();
2495 for depth in (scope_depth..=path.len()).rev() {
2496 let path = &path[..depth];
2497 let node = scene.at_path(path)?;
2498 let item = layout.at_path(path)?;
2499 if !node.handles_wheel() || !item.enabled || !node.boolean("enabled", true) {
2500 continue;
2501 }
2502 let handles_axis = match node.properties.get("orientation") {
2503 Some(Value::Orientation(Orientation::Horizontal)) => event.delta_x.0 != 0.0,
2504 Some(Value::Orientation(Orientation::Vertical)) => event.delta_y.0 != 0.0,
2505 _ => true,
2506 };
2507 if !handles_axis {
2508 continue;
2509 }
2510 if let Some((x, y)) = local_handler_position(item, point) {
2511 deliveries.push((path.to_vec(), xrack_runtime::WheelEvent { x, y, ..event }));
2512 }
2513 }
2514 (!deliveries.is_empty()).then_some(WheelRoute { deliveries })
2515 }
2516
2517 pub fn update_tooltip(&mut self, scene: &Node, layout: &LayoutNode, now: Instant) -> bool {
2518 let scope = self.active_dialog(layout).unwrap_or_default();
2519 let key = match self.tooltip.source {
2520 TooltipSource::Pointer => self.pointer.and_then(|point| {
2521 tooltip::hovered(
2522 scene,
2523 layout,
2524 self.pointer_scope(layout, point),
2525 point,
2526 TooltipSource::Pointer,
2527 )
2528 }),
2529 TooltipSource::Focus => self
2530 .focused
2531 .as_ref()
2532 .filter(|target| valid(target, scene, layout))
2533 .and_then(|target| tooltip::focused(scene, &target.path, scope)),
2534 TooltipSource::Touch => self.tooltip.touch_key(layout, scope),
2535 };
2536 let blocked = self.menu_open()
2537 || self.choice_open()
2538 || self.pressed.is_some()
2539 || self.table_drag_selection_claimed()
2540 || self.dialog_backdrop.is_some();
2541 self.tooltip.advance(scene, key, self.pointer, blocked, now)
2542 }
2543
2544 pub fn tooltip_deadline(&self) -> Option<Instant> {
2545 self.tooltip.deadline()
2546 }
2547
2548 pub fn dismiss_tooltip(&mut self) -> bool {
2549 self.tooltip.dismiss()
2550 }
2551
2552 #[doc(hidden)]
2553 pub fn touch_tooltip_at(
2554 &self,
2555 scene: &Node,
2556 layout: &LayoutNode,
2557 point: Point,
2558 now: Instant,
2559 ) -> Option<(TouchTooltip, Instant)> {
2560 if self.menu_open() || self.choice_open() || self.dialog_backdrop.is_some() {
2561 return None;
2562 }
2563 TouchTooltip::at(scene, layout, self.pointer_scope(layout, point), point, now)
2564 }
2565
2566 #[doc(hidden)]
2567 pub fn show_touch_tooltip(
2568 &mut self,
2569 scene: &Node,
2570 layout: &LayoutNode,
2571 candidate: TouchTooltip,
2572 point: Point,
2573 now: Instant,
2574 ) -> bool {
2575 if !self
2576 .touch_tooltip_at(scene, layout, point, now)
2577 .is_some_and(|(current, _)| current == candidate)
2578 {
2579 return false;
2580 }
2581 self.tooltip.show_touch(candidate, now);
2582 true
2583 }
2584
2585 pub fn tooltip_popup<'a>(
2586 &self,
2587 scene: &'a Node,
2588 layout: &LayoutNode,
2589 ) -> Option<crate::TooltipPopup<'a>> {
2590 if self.menu_open() || self.choice_open() {
2591 return None;
2592 }
2593 self.tooltip.popup(
2594 scene,
2595 layout,
2596 self.active_dialog(layout).unwrap_or_default(),
2597 )
2598 }
2599
2600 pub fn overlay_layers<'a>(
2601 &'a self,
2602 layout: &'a LayoutNode,
2603 ) -> impl DoubleEndedIterator<Item = &'a [usize]> + 'a {
2604 self.dialogs
2605 .iter()
2606 .filter(move |dialog| layout.overlay_paths().contains(&dialog.path))
2607 .map(|dialog| dialog.path.as_slice())
2608 .chain(
2609 layout
2610 .overlay_paths()
2611 .iter()
2612 .filter(move |path| !self.dialogs.iter().any(|dialog| &dialog.path == *path))
2613 .map(Vec::as_slice),
2614 )
2615 }
2616
2617 pub fn dialog_layers<'a>(
2618 &'a self,
2619 layout: &'a LayoutNode,
2620 ) -> impl DoubleEndedIterator<Item = &'a [usize]> + 'a {
2621 self.overlay_layers(layout)
2622 .filter(move |path| is_modal_path(layout, path))
2623 }
2624
2625 fn active_dialog<'a>(&'a self, layout: &'a LayoutNode) -> Option<&'a [usize]> {
2626 self.dialog_layers(layout).next_back()
2627 }
2628
2629 pub fn allows_popup(&self, layout: &LayoutNode, path: &[usize]) -> bool {
2630 self.active_dialog(layout)
2631 .is_none_or(|modal| path.starts_with(modal))
2632 }
2633
2634 fn popups<'a>(&'a self, layout: &'a LayoutNode) -> impl Iterator<Item = &'a [usize]> + 'a {
2635 self.overlay_layers(layout)
2636 .rev()
2637 .filter(move |path| !is_modal_path(layout, path) && self.allows_popup(layout, path))
2638 }
2639
2640 fn popup_at<'a>(&'a self, layout: &'a LayoutNode, point: Point) -> Option<&'a [usize]> {
2641 self.popups(layout).find(|path| {
2642 layout
2643 .at_path(path)
2644 .is_some_and(|item| item.bounds.contains(point))
2645 })
2646 }
2647
2648 fn focused_popup<'a>(&'a self, layout: &'a LayoutNode) -> Option<&'a [usize]> {
2649 let target = self.focused.as_ref()?;
2650 self.popups(layout)
2651 .find(|path| target.path.starts_with(path))
2652 }
2653
2654 fn pointer_scope<'a>(&'a self, layout: &'a LayoutNode, point: Point) -> &'a [usize] {
2655 self.popup_at(layout, point)
2656 .or_else(|| self.active_dialog(layout))
2657 .unwrap_or_default()
2658 }
2659
2660 fn drag_context<'a>(
2661 &'a self,
2662 scene: &'a Node,
2663 layout: &'a LayoutNode,
2664 point: Point,
2665 ) -> crate::drag::Context<'a> {
2666 crate::drag::Context {
2667 scene,
2668 layout,
2669 scope: self.pointer_scope(layout, point),
2670 modal: self.active_dialog(layout),
2671 transitions: &self.transitioning_stacks,
2672 blocked: self.menu_open() || self.choice_open(),
2673 }
2674 }
2675
2676 pub fn arm_drag(&mut self, scene: &Node, layout: &LayoutNode, point: Point) {
2677 self.arm_drag_at(scene, layout, point, None);
2678 }
2679
2680 #[doc(hidden)]
2681 pub fn arm_touch_drag(
2682 &mut self,
2683 scene: &Node,
2684 layout: &LayoutNode,
2685 point: Point,
2686 now: Instant,
2687 ) {
2688 self.arm_drag_at(scene, layout, point, Some(now));
2689 }
2690
2691 fn arm_drag_at(
2692 &mut self,
2693 scene: &Node,
2694 layout: &LayoutNode,
2695 point: Point,
2696 touch_started: Option<Instant>,
2697 ) {
2698 if self.table_resize.is_some()
2699 || self.table_row_resize.is_some()
2700 || self.table_column_move.is_some()
2701 || self.table_row_move.is_some()
2702 || self.table_drag_selection_claimed()
2703 {
2704 self.drag = None;
2705 return;
2706 }
2707 let competing = match self.hit_at(scene, layout, point) {
2708 Hit::Target(target) => scene.at_path(&target.path).is_some_and(|node| {
2709 is_text_input(node.kind)
2710 || combo_editable(node)
2711 || is_spin_box(node.kind)
2712 || matches!(
2713 node.kind,
2714 "Slider"
2715 | "ColorPlane"
2716 | "Dial"
2717 | "RangeSlider"
2718 | "SplitHandle"
2719 | "TableCell"
2720 | "TreeCell"
2721 | "Tumbler"
2722 | "PathView"
2723 | "SwipeDelegate"
2724 )
2725 }),
2726 Hit::None => false,
2727 _ => true,
2728 };
2729 self.drag = if competing {
2730 None
2731 } else {
2732 crate::drag::DragSession::arm(
2733 self.drag_context(scene, layout, point),
2734 point,
2735 touch_started,
2736 )
2737 };
2738 }
2739
2740 pub fn drag_motion(
2741 &mut self,
2742 scene: &Node,
2743 layout: &LayoutNode,
2744 point: Point,
2745 requested: Option<xrack_runtime::DragAction>,
2746 ) -> crate::DragUpdate {
2747 self.drag_motion_at(scene, layout, point, requested, Instant::now())
2748 }
2749
2750 #[doc(hidden)]
2751 pub fn drag_motion_at(
2752 &mut self,
2753 scene: &Node,
2754 layout: &LayoutNode,
2755 point: Point,
2756 requested: Option<xrack_runtime::DragAction>,
2757 now: Instant,
2758 ) -> crate::DragUpdate {
2759 let Some(mut drag) = self.drag.take() else {
2760 return crate::DragUpdate::default();
2761 };
2762 let active = drag.active();
2763 let (update, keep) = drag.motion(
2764 self.drag_context(scene, layout, point),
2765 point,
2766 requested,
2767 now,
2768 );
2769 self.drag = keep.then_some(drag);
2770 if update.captured && !active {
2771 self.cancel_press();
2772 self.pointer_leave();
2773 }
2774 update
2775 }
2776
2777 pub fn finish_drag(
2778 &mut self,
2779 scene: &Node,
2780 layout: &LayoutNode,
2781 point: Point,
2782 requested: Option<xrack_runtime::DragAction>,
2783 ) -> crate::DragUpdate {
2784 self.drag
2785 .take()
2786 .map_or_else(crate::DragUpdate::default, |drag| {
2787 drag.finish(self.drag_context(scene, layout, point), point, requested)
2788 })
2789 }
2790
2791 pub fn cancel_drag(&mut self) -> crate::DragUpdate {
2792 self.drag
2793 .take()
2794 .map_or_else(crate::DragUpdate::default, |mut drag| drag.cancel())
2795 }
2796
2797 pub fn reconcile_drag(
2798 &mut self,
2799 scene: &Node,
2800 layout: &LayoutNode,
2801 requested: Option<xrack_runtime::DragAction>,
2802 ) -> crate::DragUpdate {
2803 let Some(mut drag) = self.drag.take() else {
2804 return crate::DragUpdate::default();
2805 };
2806 let point = drag.point;
2807 let (update, keep) =
2808 drag.reconcile(self.drag_context(scene, layout, point), point, requested);
2809 self.drag = keep.then_some(drag);
2810 update
2811 }
2812
2813 pub fn drag_position(&self) -> Option<Point> {
2814 self.drag.as_ref().map(|drag| drag.point)
2815 }
2816
2817 #[doc(hidden)]
2818 pub fn drag_scroll_deadline(&self, scene: &Node, layout: &LayoutNode) -> Option<Instant> {
2819 let drag = self.drag.as_ref()?;
2820 drag.auto_scroll_offset(self.drag_context(scene, layout, drag.point))?;
2821 drag.scroll_deadline()
2822 }
2823
2824 #[doc(hidden)]
2825 pub fn advance_drag_scroll(&mut self, scene: &Node, layout: &LayoutNode, now: Instant) -> bool {
2826 let Some(drag) = self.drag.as_ref() else {
2827 return false;
2828 };
2829 if drag.scroll_deadline().is_none_or(|deadline| now < deadline) {
2830 return false;
2831 }
2832 let Some((path, offset)) =
2833 drag.auto_scroll_offset(self.drag_context(scene, layout, drag.point))
2834 else {
2835 return false;
2836 };
2837 let path = path.to_vec();
2838 let scrolled = self.scroll_to_user_offset(layout, &path, Orientation::Vertical, offset);
2839 if let Some(drag) = &mut self.drag {
2840 drag.advance_scroll_deadline(now, scrolled);
2841 }
2842 scrolled
2843 }
2844
2845 pub fn drag_action(&self) -> Option<xrack_runtime::DragAction> {
2846 self.drag
2847 .as_ref()
2848 .and_then(crate::drag::DragSession::action)
2849 }
2850
2851 pub fn is_drop_target(&self, node: &Node, path: &[usize]) -> bool {
2852 self.drag.as_ref().is_some_and(|drag| drag.over(node, path))
2853 || self.file_drag.over(node, path)
2854 }
2855
2856 pub fn file_drop_scope(&self, layout: &LayoutNode) -> crate::FileDropScope {
2857 crate::FileDropScope {
2858 modal: self.active_dialog(layout).map(<[usize]>::to_vec),
2859 popups: self.popups(layout).map(<[usize]>::to_vec).collect(),
2860 transitions: self.transitioning_stacks.clone(),
2861 blocked: self.menu_open() || self.choice_open() || self.drag_action().is_some(),
2862 text_composing: self.editor.as_ref().is_some_and(TextEdit::is_composing),
2863 swiping: self
2864 .swipe_page_motion
2865 .as_ref()
2866 .map(|motion| motion.page.target.path.clone()),
2867 }
2868 }
2869
2870 pub fn file_drag_event(
2871 &mut self,
2872 scene: &Node,
2873 layout: &LayoutNode,
2874 input: crate::FileDragInput,
2875 ) -> crate::DragUpdate {
2876 let scope = self.file_drop_scope(layout);
2877 self.file_drag.update(&scope, scene, layout, input)
2878 }
2879
2880 pub fn reconcile_file_drag(&mut self, scene: &Node, layout: &LayoutNode) -> crate::DragUpdate {
2881 if !self.file_drag.has_hover() {
2882 return crate::DragUpdate::default();
2883 }
2884 let scope = self.file_drop_scope(layout);
2885 self.file_drag.reconcile(&scope, scene, layout)
2886 }
2887
2888 pub fn clear_file_drag(&mut self) {
2889 self.file_drag = crate::file_drop::FileDrag::default();
2890 }
2891
2892 pub fn popup_outside_press(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
2893 let path = self.popups(layout).next()?;
2894 let point = self.pointer?;
2895 let popup = scene.at_path(path)?;
2896 let (_, anchor) = path.split_last()?;
2897 let anchor_clicked = self
2898 .target_at(scene, layout, point)
2899 .is_some_and(|target| target.path == anchor);
2900 (!anchor_clicked
2901 && !layout.at_path(path)?.bounds.contains(point)
2902 && popup.boolean("close-on-outside", true))
2903 .then(|| ControlInput {
2904 path: path.to_vec(),
2905 action: ControlAction::Popup(false),
2906 })
2907 }
2908
2909 pub fn dialog_button(
2910 &self,
2911 scene: &Node,
2912 layout: &LayoutNode,
2913 target: &Target,
2914 ) -> Option<ControlInput> {
2915 let path = self.active_dialog(layout)?;
2916 let node = scene.at_path(&target.path)?;
2917 if !target.path.starts_with(path)
2918 || scene.at_path(path)?.kind != "Dialog"
2919 || self
2920 .popups(layout)
2921 .any(|popup| target.path.starts_with(popup))
2922 || !valid(target, scene, layout)
2923 {
2924 return None;
2925 }
2926 Some(ControlInput {
2927 path: path.to_vec(),
2928 action: dialog_button_action(node)?,
2929 })
2930 }
2931
2932 pub fn dialog_accept(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
2933 if self.focused_popup(layout).is_some() {
2934 return None;
2935 }
2936 let path = self.active_dialog(layout)?;
2937 focus_targets(scene, layout, path)
2938 .iter()
2939 .filter_map(|target| {
2940 let action = self.dialog_button(scene, layout, target)?;
2941 if action.action != ControlAction::Dialog(DialogRole::Accept) {
2942 return None;
2943 }
2944 let primary = scene.at_path(&target.path)?.boolean("primary", false);
2945 Some((!primary, action))
2946 })
2947 .min_by_key(|(secondary, _)| *secondary)
2948 .map(|(_, action)| action)
2949 }
2950
2951 pub fn dialog_escape(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
2952 let path = self
2953 .popups(layout)
2954 .next()
2955 .or_else(|| self.active_dialog(layout))?;
2956 let node = scene.at_path(path)?;
2957 node.boolean("close-on-escape", true).then(|| ControlInput {
2958 path: path.to_vec(),
2959 action: dismiss_overlay(node),
2960 })
2961 }
2962
2963 pub fn dialog_pointer_press(&mut self, layout: &LayoutNode) -> bool {
2965 self.dialog_backdrop = None;
2966 let Some(path) = self.active_dialog(layout) else {
2967 return false;
2968 };
2969 let Some(point) = self.pointer else {
2970 return false;
2971 };
2972 if self.popup_at(layout, point).is_some() {
2973 return false;
2974 }
2975 let Some(item) = layout.at_path(path) else {
2976 return false;
2977 };
2978 let outside = !item.bounds.contains(point);
2979 if !outside
2980 && self
2981 .hovered
2982 .as_ref()
2983 .is_some_and(|target| target.path.starts_with(path))
2984 {
2985 return false;
2986 }
2987 let backdrop = outside.then(|| path.to_vec());
2988 self.cancel_press();
2989 self.dialog_backdrop = backdrop;
2990 true
2991 }
2992
2993 pub fn dialog_pointer_release(
2994 &mut self,
2995 scene: &Node,
2996 layout: &LayoutNode,
2997 ) -> Option<ControlInput> {
2998 let pressed = self.dialog_backdrop.take()?;
2999 let path = self.active_dialog(layout)?;
3000 let node = scene.at_path(path)?;
3001 if pressed != path
3002 || layout.at_path(path)?.bounds.contains(self.pointer?)
3003 || self.popup_at(layout, self.pointer?).is_some()
3004 || !node.boolean(
3005 "close-on-outside",
3006 matches!(node.kind, "Drawer" | "PopupWindow"),
3007 )
3008 {
3009 return None;
3010 }
3011 Some(ControlInput {
3012 path: pressed,
3013 action: dismiss_overlay(node),
3014 })
3015 }
3016
3017 fn set_focus(&mut self, focus: Option<Target>) {
3018 self.set_focus_with_reason(focus, xrack_runtime::FocusReason::KeyboardNavigation);
3019 }
3020
3021 #[doc(hidden)]
3022 pub fn clear_focus(&mut self) {
3023 self.set_focus(None);
3024 }
3025
3026 fn set_focus_with_reason(&mut self, focus: Option<Target>, reason: xrack_runtime::FocusReason) {
3027 if self.focused != focus {
3028 self.touch_selection_handles = None;
3029 self.calendar_page_focus = None;
3030 self.text_selection_scroll = None;
3031 self.retain_editor_selection();
3032 self.editor_press = None;
3033 self.last_editor_click = None;
3034 self.focus_reason = reason;
3035 self.cancel_shortcut_sequence();
3036 self.cancel_delay();
3037 self.button_hold = None;
3038 self.history.break_group();
3039 self.spin_draft = None;
3040 self.table_edit = None;
3041 self.last_table_click = None;
3042 Self::clear_choice(&mut self.choice);
3043 self.search_query = None;
3044 self.choice_typeahead = Typeahead::default();
3045 self.reset_list_typeahead();
3046 self.list_composition = None;
3047 self.painted_combo_completion = None;
3048 self.dismissed_combo_draft = None;
3049 self.menu = None;
3050 self.range_keys.clear();
3051 self.focused = focus;
3052 }
3053 }
3054
3055 pub fn menu_open(&self) -> bool {
3056 self.menu.is_some()
3057 }
3058
3059 #[doc(hidden)]
3060 pub fn set_touch_selection_handles(&mut self, visible: bool) {
3061 self.touch_selection_handles = self.focused.clone().filter(|_| visible);
3062 }
3063
3064 #[doc(hidden)]
3065 pub fn touch_selection_target(&self) -> Option<&Target> {
3066 self.touch_selection_handles
3067 .as_ref()
3068 .filter(|target| self.focused.as_ref() == Some(*target))
3069 }
3070
3071 pub fn dismiss_menu(&mut self) {
3072 if self.menu.take().is_some() {
3073 self.cancel_shortcut_sequence();
3074 }
3075 }
3076
3077 pub fn close_menu(&mut self, scene: &Node, layout: &LayoutNode) {
3078 self.dismiss_menu();
3079 if let Some(point) = self.pointer {
3080 self.pointer_move(scene, layout, point);
3081 }
3082 }
3083
3084 pub fn menu_panels<'a>(&'a self, scene: &'a Node, layout: &LayoutNode) -> Vec<MenuPanel<'a>> {
3085 self.menu
3086 .as_ref()
3087 .filter(|menu| self.menu_is_current(menu, scene, layout))
3088 .map_or_else(Vec::new, |menu| menu.panels(scene, layout))
3089 }
3090
3091 pub fn menu_trigger(&self) -> Option<&Target> {
3092 self.menu.as_ref().map(|popup| &popup.trigger)
3093 }
3094
3095 pub fn accessibility_menu_entry(
3096 &mut self,
3097 scene: &Node,
3098 layout: &LayoutNode,
3099 trigger: &Target,
3100 entry: &MenuEntry,
3101 activate: bool,
3102 ) -> Option<ControlInput> {
3103 if !self.reconcile_text_menu(scene, layout) {
3104 return None;
3105 }
3106 let path = self
3107 .menu
3108 .as_mut()?
3109 .accessibility_entry(scene, layout, trigger, entry, activate)?;
3110 self.finish_menu_action(scene, layout, path)
3111 }
3112
3113 pub fn menu_header_open(&self, path: &[usize]) -> bool {
3114 self.menu.as_ref().and_then(MenuPopup::bar_header) == Some(path)
3115 }
3116
3117 pub fn accessibility_close_menu(
3118 &mut self,
3119 scene: &Node,
3120 layout: &LayoutNode,
3121 trigger: &Target,
3122 path: &[usize],
3123 session: u64,
3124 ) {
3125 if self
3126 .menu
3127 .as_mut()
3128 .and_then(|popup| popup.accessibility_close(scene, layout, trigger, path, session))
3129 == Some(true)
3130 {
3131 self.close_menu(scene, layout);
3132 }
3133 }
3134
3135 #[doc(hidden)]
3137 pub fn accessibility_menu_page(
3138 &mut self,
3139 scene: &Node,
3140 layout: &LayoutNode,
3141 trigger: &Target,
3142 path: &[usize],
3143 session: u64,
3144 backward: bool,
3145 ) -> bool {
3146 self.reconcile_text_menu(scene, layout)
3147 && self.menu.as_mut().is_some_and(|popup| {
3148 popup.accessibility_page(scene, layout, trigger, path, session, backward)
3149 })
3150 }
3151
3152 pub fn menu_shortcut(
3153 &self,
3154 scene: &Node,
3155 layout: &LayoutNode,
3156 key: MenuShortcut,
3157 ) -> Option<ControlInput> {
3158 if self.shortcuts_blocked() {
3159 return None;
3160 }
3161 if let Some(menu) = self.menu.as_ref().filter(|menu| menu.text.is_some()) {
3162 return self
3163 .menu_is_current(menu, scene, layout)
3164 .then(|| menu.text_shortcut(key))
3165 .flatten();
3166 }
3167 let scope = self.shortcut_scope(layout);
3168 shortcut::single_action(
3169 shortcut::bindings(
3170 scene,
3171 layout,
3172 scope,
3173 self.menu.as_ref(),
3174 self.focused.as_ref(),
3175 ),
3176 key,
3177 )
3178 }
3179
3180 pub fn shortcut_press(
3181 &mut self,
3182 scene: &Node,
3183 layout: &LayoutNode,
3184 key: MenuShortcut,
3185 repeat: bool,
3186 now: Instant,
3187 ) -> ShortcutOutcome {
3188 let mut pending = self.pending_shortcut.take();
3189 if key.is_escape() && (self.menu_open() || self.choice_open()) {
3190 return ShortcutOutcome::Unmatched;
3191 }
3192 if self.menu.as_ref().is_some_and(|menu| menu.text.is_some()) {
3193 if repeat || !self.reconcile_text_menu(scene, layout) {
3194 return ShortcutOutcome::Consumed;
3195 }
3196 return self
3197 .menu
3198 .as_ref()
3199 .and_then(|menu| menu.text_shortcut(key))
3200 .map_or(ShortcutOutcome::Consumed, ShortcutOutcome::Activate);
3201 }
3202 if self.shortcuts_blocked() {
3203 return ShortcutOutcome::Unmatched;
3204 }
3205 let scope = self.shortcut_scope(layout);
3206 let bindings = shortcut::bindings(
3207 scene,
3208 layout,
3209 scope,
3210 self.menu.as_ref(),
3211 self.focused.as_ref(),
3212 );
3213 let outcome = shortcut::press(&mut pending, bindings, scope, key, repeat, now);
3214 self.pending_shortcut = pending;
3215 outcome
3216 }
3217
3218 pub fn cancel_shortcut_sequence(&mut self) {
3219 self.pending_shortcut = None;
3220 }
3221
3222 fn shortcuts_blocked(&self) -> bool {
3223 self.choice_open()
3224 || self
3225 .editor
3226 .as_ref()
3227 .is_some_and(|edit| !edit.preedit.is_empty())
3228 }
3229
3230 fn shortcut_scope<'a>(&'a self, layout: &'a LayoutNode) -> &'a [usize] {
3231 self.focused_popup(layout)
3232 .or_else(|| self.active_dialog(layout))
3233 .unwrap_or_default()
3234 }
3235
3236 fn target_at(&self, scene: &Node, layout: &LayoutNode, point: Point) -> Option<Target> {
3237 self.target_at_for(
3238 scene,
3239 layout,
3240 point,
3241 HitPurpose::Button(xrack_runtime::PointerButton::Primary),
3242 )
3243 }
3244
3245 pub fn pointer_hover_target(&self, scene: &Node, layout: &LayoutNode) -> Option<Target> {
3246 self.target_at_for(scene, layout, self.pointer?, HitPurpose::Hover)
3247 }
3248
3249 fn target_at_for(
3250 &self,
3251 scene: &Node,
3252 layout: &LayoutNode,
3253 point: Point,
3254 purpose: HitPurpose<'_>,
3255 ) -> Option<Target> {
3256 match self.hit_at_for(scene, layout, point, purpose) {
3257 Hit::Target(target) | Hit::ControlPart(target, _) | Hit::TableRowGrip(target, _) => {
3258 Some(target)
3259 }
3260 _ => None,
3261 }
3262 }
3263
3264 fn hit_at(&self, scene: &Node, layout: &LayoutNode, point: Point) -> Hit {
3265 self.hit_at_for(
3266 scene,
3267 layout,
3268 point,
3269 HitPurpose::Button(xrack_runtime::PointerButton::Primary),
3270 )
3271 }
3272
3273 #[doc(hidden)]
3275 pub fn inspection_path(
3276 &self,
3277 scene: &Node,
3278 layout: &LayoutNode,
3279 point: Point,
3280 ) -> Option<Vec<usize>> {
3281 let scope = self.pointer_scope(layout, point);
3282 let (node, item) = scene.at_path(scope).zip(layout.at_path(scope))?;
3283 let mut path = scope.to_vec();
3284 inspect_at(node, item, point, &mut path).then_some(path)
3285 }
3286
3287 fn hit_at_for(
3288 &self,
3289 scene: &Node,
3290 layout: &LayoutNode,
3291 point: Point,
3292 purpose: HitPurpose<'_>,
3293 ) -> Hit {
3294 let scope = self.pointer_scope(layout, point);
3295 let Some((node, item)) = scene.at_path(scope).zip(layout.at_path(scope)) else {
3296 return Hit::None;
3297 };
3298 let mut result = hit(
3299 node,
3300 item,
3301 point,
3302 &mut scope.to_vec(),
3303 &self.transitioning_stacks,
3304 purpose,
3305 );
3306 if let Some(motion) = &self.swipe_page_motion {
3307 let moving = &motion.page.target.path;
3308 let hit_path = match &result {
3309 Hit::Target(target)
3310 | Hit::ControlPart(target, _)
3311 | Hit::TableRowGrip(target, _) => Some(target.path.as_slice()),
3312 Hit::ScrollBar(target) => Some(target.path.as_slice()),
3313 Hit::Blocked(path) => Some(path.as_slice()),
3314 _ => None,
3315 };
3316 if hit_path.is_some_and(|path| path.starts_with(moving)) {
3317 return Hit::StackSlide;
3318 }
3319 }
3320 if matches!(result, Hit::None) && node.kind == "PopupWindow" && item.bounds.contains(point)
3321 {
3322 result = Hit::Blocked(scope.to_vec());
3323 }
3324 match &mut result {
3325 Hit::Target(target) => {
3326 target.row_key = scene.row_key_at(&target.path);
3327 target.tab_close = (|| {
3328 let item = layout.at_path(&target.path)?;
3329 if !item.tab_close?.contains(item.map_from_window(point)?) {
3330 return None;
3331 }
3332 tab_close_identity(scene, &target.path)
3333 })();
3334 }
3335 Hit::ControlPart(target, _)
3336 | Hit::TableRowGrip(target, _)
3337 | Hit::WindowMove(target) => target.row_key = scene.row_key_at(&target.path),
3338 Hit::ScrollBar(target) => target.row_key = scene.row_key_at(&target.path),
3339 _ => {}
3340 }
3341 result
3342 }
3343
3344 pub fn scale_rotate_target_at(
3345 &self,
3346 scene: &Node,
3347 layout: &LayoutNode,
3348 point: Point,
3349 ) -> Option<crate::ScaleRotateTarget> {
3350 if self.menu_open()
3351 || self.choice_open()
3352 || self.scroll_bar_captured()
3353 || self.drag_position().is_some()
3354 || self
3355 .scroll_gesture
3356 .as_ref()
3357 .is_some_and(|gesture| gesture.motion.dragging)
3358 {
3359 return None;
3360 }
3361 let (path, scope_len) =
3362 self.gesture_hit_path(scene, layout, point, "ScaleRotateGestureHandler")?;
3363 (scope_len..=path.len()).rev().find_map(|depth| {
3364 let target = crate::ScaleRotateTarget::new(scene, &path[..depth])?;
3365 let item = layout.at_path(&target.path)?;
3366 (item.contains_clip_point(point)
3367 && item.bounds.contains(item.map_from_window(point)?)
3368 && target.is_live(scene, layout, self))
3369 .then_some(target)
3370 })
3371 }
3372
3373 fn gesture_hit_path(
3374 &self,
3375 scene: &Node,
3376 layout: &LayoutNode,
3377 point: Point,
3378 kind: &str,
3379 ) -> Option<(Vec<usize>, usize)> {
3380 let scope = self.pointer_scope(layout, point);
3381 let path = match hit(
3382 scene.at_path(scope)?,
3383 layout.at_path(scope)?,
3384 point,
3385 &mut scope.to_vec(),
3386 &self.transitioning_stacks,
3387 HitPurpose::Gesture(kind),
3388 ) {
3389 Hit::Target(target) | Hit::ControlPart(target, _) => target.path,
3390 Hit::Blocked(path) => path,
3391 _ => return None,
3392 };
3393 Some((path, scope.len()))
3394 }
3395
3396 pub fn window_gestures_allowed(&self, scene: &Node, layout: &LayoutNode) -> bool {
3397 scene.kind == "Window"
3398 && scene.is_visible()
3399 && !self.menu_open()
3400 && !self.choice_open()
3401 && self.active_dialog(layout).is_none()
3402 && self.popups(layout).next().is_none()
3403 && self.drag_position().is_none()
3404 }
3405
3406 pub fn window_resize_edge(
3408 &self,
3409 scene: &Node,
3410 layout: &LayoutNode,
3411 ) -> Option<WindowResizeEdge> {
3412 if !scene.boolean("no-frame", false)
3413 || !scene.boolean("resizable", true)
3414 || !self.window_gestures_allowed(scene, layout)
3415 {
3416 return None;
3417 }
3418 let point = self.pointer?;
3419 let edge =
3420 WindowResizeEdge::at(layout.bounds, point, scene.length("resize-border-width")?)?;
3421 matches!(
3422 self.hit_at(scene, layout, point),
3423 Hit::None | Hit::WindowMove(_)
3424 )
3425 .then_some(edge)
3426 }
3427
3428 pub fn arm_window_move(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
3429 let Some(origin) = self
3430 .pointer
3431 .filter(|_| self.window_gestures_allowed(scene, layout))
3432 else {
3433 return false;
3434 };
3435 let Hit::WindowMove(target) = self.hit_at(scene, layout, origin) else {
3436 return false;
3437 };
3438 self.cancel_press();
3439 self.window_move_press = Some(WindowMovePress { target, origin });
3440 true
3441 }
3442
3443 pub fn take_window_move(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> bool {
3444 let Some(press) = &self.window_move_press else {
3445 return false;
3446 };
3447 if !self.window_gestures_allowed(scene, layout)
3448 || !matches!(self.hit_at(scene, layout, press.origin), Hit::WindowMove(target) if target == press.target)
3449 {
3450 self.window_move_press = None;
3451 return false;
3452 }
3453 const THRESHOLD: f32 = 4.0;
3454 let x = point.x - press.origin.x;
3455 let y = point.y - press.origin.y;
3456 if x * x + y * y < THRESHOLD * THRESHOLD {
3457 return false;
3458 }
3459 self.window_move_press = None;
3460 true
3461 }
3462
3463 pub fn cancel_window_move(&mut self) -> bool {
3464 self.window_move_press.take().is_some()
3465 }
3466
3467 pub fn sync_stack_transitions(&mut self, transitions: &StackTransitions) -> bool {
3469 if self
3470 .transitioning_stacks
3471 .iter()
3472 .map(Vec::as_slice)
3473 .eq(transitions.active_paths())
3474 {
3475 return false;
3476 }
3477 self.transitioning_stacks = transitions.active_paths().map(<[usize]>::to_vec).collect();
3478 true
3479 }
3480
3481 pub fn pointer_on_stack_slide(&self) -> bool {
3482 self.pointer_on_stack_slide
3483 }
3484
3485 pub fn open_menu_bar(&mut self, scene: &Node, layout: &LayoutNode, target: Target) -> bool {
3486 self.open_menu_bar_with_touch(scene, layout, target, false)
3487 }
3488
3489 #[doc(hidden)]
3490 pub fn open_menu_bar_with_touch(
3491 &mut self,
3492 scene: &Node,
3493 layout: &LayoutNode,
3494 target: Target,
3495 touch: bool,
3496 ) -> bool {
3497 let Some((_, parent)) = target.path.split_last() else {
3498 return false;
3499 };
3500 let scope = self.active_dialog(layout).unwrap_or_default();
3501 if !target.path.starts_with(scope)
3502 || !scene
3503 .at_path(parent)
3504 .is_some_and(|bar| bar.kind == "MenuBar")
3505 || !scene
3506 .at_path(&target.path)
3507 .is_some_and(|node| node.kind == "Menu")
3508 {
3509 return false;
3510 }
3511 let Some(popup) = MenuPopup::open(
3512 target.clone(),
3513 target.path.clone(),
3514 None,
3515 scene,
3516 layout,
3517 None,
3518 touch,
3519 ) else {
3520 return false;
3521 };
3522 self.dismiss_choice();
3523 self.set_focus(Some(target));
3524 self.cancel_shortcut_sequence();
3525 self.set_split_hover(None);
3526 self.menu = Some(popup);
3527 true
3528 }
3529
3530 pub fn open_context_menu(&mut self, scene: &Node, layout: &LayoutNode, keyboard: bool) -> bool {
3531 let target = if keyboard {
3532 self.focused.clone()
3533 } else {
3534 self.pointer.and_then(|point| {
3535 self.target_at_for(
3536 scene,
3537 layout,
3538 point,
3539 HitPurpose::Button(xrack_runtime::PointerButton::Secondary),
3540 )
3541 })
3542 };
3543 let Some(target) = target else {
3544 return false;
3545 };
3546 self.open_context_menu_at(
3547 scene,
3548 layout,
3549 target,
3550 if keyboard { None } else { self.pointer },
3551 false,
3552 )
3553 }
3554
3555 #[doc(hidden)]
3556 pub fn touch_context_menu_target(
3557 &self,
3558 scene: &Node,
3559 layout: &LayoutNode,
3560 point: Point,
3561 ) -> Option<Target> {
3562 if self.menu_open() || self.choice_open() {
3563 return None;
3564 }
3565 let hit = self.target_at(scene, layout, point)?;
3566 let scope = self.active_dialog(layout).unwrap_or_default();
3567 let (path, area, _) = context_menu_area(scene, &hit.path, scope)?;
3568 Some(Target::from_node(
3569 path.to_vec(),
3570 area,
3571 true,
3572 scene.row_key_at(path),
3573 ))
3574 }
3575
3576 #[doc(hidden)]
3577 pub fn open_touch_context_menu(
3578 &mut self,
3579 scene: &Node,
3580 layout: &LayoutNode,
3581 target: Target,
3582 point: Point,
3583 ) -> bool {
3584 self.touch_context_menu_target(scene, layout, point)
3585 .as_ref()
3586 == Some(&target)
3587 && self.open_context_menu_at(scene, layout, target, Some(point), true)
3588 }
3589
3590 #[doc(hidden)]
3591 pub fn touch_text_target(
3592 &self,
3593 scene: &Node,
3594 layout: &LayoutNode,
3595 point: Point,
3596 ) -> Option<Target> {
3597 if self.menu_open() {
3598 return None;
3599 }
3600 let target = self.target_at_for(
3601 scene,
3602 layout,
3603 point,
3604 HitPurpose::Button(xrack_runtime::PointerButton::Primary),
3605 )?;
3606 let node = self.context_editor(scene, layout, &target)?;
3607 if !target.focusable || !(self.is_text_editor(node, &target) || spin_editable(node)) {
3608 return None;
3609 }
3610 if is_spin_box(node.kind) {
3611 let item = layout.at_path(&target.path)?;
3612 let point = item.map_from_window(point)?;
3613 if !SpinGeometry::for_layout(item, node).text.contains(point) {
3614 return None;
3615 }
3616 }
3617 if self.focused.as_ref() == Some(&target)
3618 && self.editor.as_ref().is_some_and(TextEdit::is_composing)
3619 {
3620 return None;
3621 }
3622 Some(target)
3623 }
3624
3625 #[doc(hidden)]
3626 pub fn open_touch_text_menu(
3627 &mut self,
3628 scene: &Node,
3629 layout: &LayoutNode,
3630 target: Target,
3631 point: Point,
3632 ) -> bool {
3633 self.open_context_menu_at(scene, layout, target, Some(point), true)
3634 }
3635
3636 #[doc(hidden)]
3637 pub fn take_native_text_menu(&mut self) -> Option<NativeTextMenu> {
3638 self.menu
3639 .take_if(|menu| menu.touch && menu.text.is_some())
3640 .map(NativeTextMenu)
3641 }
3642
3643 #[doc(hidden)]
3644 pub fn native_text_menu_is_current(
3645 &self,
3646 menu: &NativeTextMenu,
3647 scene: &Node,
3648 layout: &LayoutNode,
3649 ) -> bool {
3650 self.menu.is_none() && self.menu_is_current(&menu.0, scene, layout)
3651 }
3652
3653 #[doc(hidden)]
3654 pub fn native_text_menu_input(
3655 &self,
3656 menu: NativeTextMenu,
3657 scene: &Node,
3658 layout: &LayoutNode,
3659 entry: usize,
3660 ) -> Option<ControlInput> {
3661 if !self.native_text_menu_is_current(&menu, scene, layout)
3662 || !menu.entries().any(|(index, _)| index == entry)
3663 {
3664 return None;
3665 }
3666 let mut path = menu.0.trigger.path.clone();
3667 path.push(entry);
3668 menu.0.input(path)
3669 }
3670
3671 fn open_context_menu_at(
3672 &mut self,
3673 scene: &Node,
3674 layout: &LayoutNode,
3675 target: Target,
3676 point: Option<Point>,
3677 touch: bool,
3678 ) -> bool {
3679 let scope = self.active_dialog(layout).unwrap_or_default();
3680 if !target.path.starts_with(scope) {
3681 return false;
3682 }
3683 let context = context_menu_area(scene, &target.path, scope);
3684 let keyboard = point.is_none();
3685 let point = if let Some(point) = point {
3686 point
3687 } else {
3688 let Some(item) = layout.at_path(&target.path) else {
3689 return false;
3690 };
3691 let direction = context
3692 .and_then(|(path, area, index)| {
3693 area.child_at(index)
3694 .and_then(Node::layout_direction)
3695 .or_else(|| layout.at_path(path).map(|area| area.layout_direction))
3696 })
3697 .unwrap_or(item.layout_direction);
3698 let anchor = item.visible_window_bounds(item.bounds);
3699 Point {
3700 x: anchor.x
3701 + if direction == LayoutDirection::RightToLeft {
3702 anchor.width
3703 } else {
3704 0.0
3705 },
3706 y: anchor.y + anchor.height,
3707 }
3708 };
3709 let popup = if let Some((path, area, index)) = context {
3710 let trigger = Target::from_node(path.to_vec(), area, true, scene.row_key_at(path));
3711 let mut path = path.to_vec();
3712 path.push(index);
3713 MenuPopup::open(trigger, path, Some(point), scene, layout, None, touch)
3714 } else {
3715 let Some(node) = self.context_editor(scene, layout, &target) else {
3716 return false;
3717 };
3718 if self.focused.as_ref() == Some(&target)
3719 && self.editor.as_ref().is_some_and(TextEdit::is_composing)
3720 {
3721 return false;
3722 }
3723 if !keyboard {
3724 self.set_focus_with_reason(
3725 Some(target.clone()),
3726 xrack_runtime::FocusReason::PointerClick,
3727 );
3728 }
3729 self.sync_editor(scene);
3730 self.break_text_edit_group();
3731 let value = self.editor_value(node);
3732 let Some(editor) = &self.editor else {
3733 return false;
3734 };
3735 let selection = editor.selection_state(&value);
3736 let commands = self.text_command_availability(
3737 scene,
3738 &target,
3739 node,
3740 &value,
3741 !selection.collapsed(),
3742 );
3743 let menu = TextMenu::new(node, value.into_owned(), selection, commands);
3744 MenuPopup::open(
3745 target.clone(),
3746 target.path,
3747 Some(point),
3748 scene,
3749 layout,
3750 Some(menu),
3751 touch,
3752 )
3753 };
3754 let Some(popup) = popup else {
3755 return false;
3756 };
3757 self.dismiss_choice();
3758 self.cancel_press();
3759 self.cancel_shortcut_sequence();
3760 self.set_split_hover(None);
3761 self.menu = Some(popup);
3762 true
3763 }
3764
3765 pub fn supports_context_menu(
3766 &self,
3767 scene: &Node,
3768 layout: &LayoutNode,
3769 target: &Target,
3770 ) -> bool {
3771 let scope = self.active_dialog(layout).unwrap_or_default();
3772 target.path.starts_with(scope)
3773 && (context_menu_area(scene, &target.path, scope).is_some()
3774 || self.context_editor(scene, layout, target).is_some())
3775 }
3776
3777 fn context_editor<'a>(
3778 &self,
3779 scene: &'a Node,
3780 layout: &LayoutNode,
3781 target: &Target,
3782 ) -> Option<&'a Node> {
3783 scene.interactive_at_path(&target.path).filter(|node| {
3784 node.boolean("context-menu-enabled", true)
3785 && (self.is_text_editor(node, target) || spin_editable(node))
3786 && self.spin_draft.as_ref().is_none_or(|draft| {
3787 self.focused.as_ref() != Some(target) || draft.mode.is_current(node)
3788 })
3789 && self.table_edit.as_ref().is_none_or(|draft| {
3790 &draft.target != target || node.text("text").unwrap_or("") == draft.original
3791 })
3792 && valid(target, scene, layout)
3793 })
3794 }
3795
3796 fn editor_history(&self, scene: &Node, target: &Target, node: &Node) -> Option<&TextHistory> {
3797 if is_spin_box(node.kind) {
3798 self.spin_draft.as_ref().map(|draft| &draft.history)
3799 } else if let Some(draft) = self
3800 .table_edit
3801 .as_ref()
3802 .filter(|draft| &draft.target == target)
3803 {
3804 Some(&draft.history)
3805 } else {
3806 self.history.get(&EditorKey::new(scene, target))
3807 }
3808 }
3809
3810 #[doc(hidden)]
3811 pub fn text_command_availability(
3812 &self,
3813 scene: &Node,
3814 target: &Target,
3815 node: &Node,
3816 value: &str,
3817 selected: bool,
3818 ) -> TextCommandAvailability {
3819 if self.editor.as_ref().is_some_and(TextEdit::is_composing) {
3820 return TextCommandAvailability::default();
3821 }
3822 let writable = !node.text_read_only();
3823 let copy = selected && !node.is_password();
3824 let (undo, redo) = self
3825 .editor_history(scene, target, node)
3826 .filter(|_| writable)
3827 .map_or((false, false), |history| history.availability(value));
3828 TextCommandAvailability {
3829 undo,
3830 redo,
3831 copy,
3832 cut: copy && writable,
3833 }
3834 }
3835
3836 fn menu_is_current(&self, menu: &MenuPopup, scene: &Node, layout: &LayoutNode) -> bool {
3837 let Some(text) = &menu.text else {
3838 return true;
3839 };
3840 self.focused.as_ref() == Some(&menu.trigger)
3841 && menu
3842 .trigger
3843 .path
3844 .starts_with(self.active_dialog(layout).unwrap_or_default())
3845 && self
3846 .context_editor(scene, layout, &menu.trigger)
3847 .is_some_and(|node| {
3848 let value = self.editor_value(node);
3849 text.kind == node.kind
3850 && text.password == node.is_password()
3851 && text.writable == !node.text_read_only()
3852 && text.value == value
3853 && self.editor.as_ref().is_some_and(|editor| {
3854 !editor.is_composing()
3855 && editor.selection_state(&value) == text.selection
3856 })
3857 && text.commands
3858 == self.text_command_availability(
3859 scene,
3860 &menu.trigger,
3861 node,
3862 &value,
3863 !text.selection.collapsed(),
3864 )
3865 })
3866 }
3867
3868 pub fn reconcile_text_menu(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
3869 let current = self
3870 .menu
3871 .as_ref()
3872 .is_none_or(|menu| self.menu_is_current(menu, scene, layout));
3873 if !current {
3874 self.close_menu(scene, layout);
3875 }
3876 current
3877 }
3878
3879 pub fn pointer_context_menu_changes_focus(&self, scene: &Node, layout: &LayoutNode) -> bool {
3880 self.pointer
3881 .and_then(|point| {
3882 self.target_at_for(
3883 scene,
3884 layout,
3885 point,
3886 HitPurpose::Button(xrack_runtime::PointerButton::Secondary),
3887 )
3888 })
3889 .is_some_and(|target| {
3890 let scope = self.active_dialog(layout).unwrap_or_default();
3891 self.focused.as_ref() != Some(&target)
3892 && target.path.starts_with(scope)
3893 && context_menu_area(scene, &target.path, scope).is_none()
3894 && self.context_editor(scene, layout, &target).is_some()
3895 })
3896 }
3897
3898 fn finish_menu_action(
3899 &mut self,
3900 scene: &Node,
3901 layout: &LayoutNode,
3902 path: Vec<usize>,
3903 ) -> Option<ControlInput> {
3904 let action = self.menu.as_ref()?.input(path)?;
3905 self.close_menu(scene, layout);
3906 Some(action)
3907 }
3908
3909 pub fn menu_press(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
3910 if !self.menu_open() {
3911 return false;
3912 }
3913 if !self.reconcile_text_menu(scene, layout) {
3914 return true;
3915 }
3916 let touch = self.menu.as_ref().is_some_and(|menu| menu.touch);
3917 self.cancel_press();
3918 if let Some(point) = self.pointer {
3919 if self
3920 .menu
3921 .as_mut()
3922 .is_some_and(|menu| menu.press(scene, layout, point))
3923 {
3924 return true;
3925 }
3926 if let Some(header) = self.target_at(scene, layout, point)
3927 && !self.menu_header_open(&header.path)
3928 && self.open_menu_bar_with_touch(scene, layout, header, touch)
3929 {
3930 return true;
3931 }
3932 }
3933 self.close_menu(scene, layout);
3934 true
3935 }
3936
3937 pub fn menu_release(&mut self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
3938 if !self.reconcile_text_menu(scene, layout) {
3939 return None;
3940 }
3941 let path = self.menu.as_mut()?.release(scene, layout, self.pointer?)?;
3942 self.finish_menu_action(scene, layout, path)
3943 }
3944
3945 pub fn menu_scroll(&mut self, scene: &Node, layout: &LayoutNode, rows: isize) -> bool {
3946 let Some(popup) = &mut self.menu else {
3947 return false;
3948 };
3949 popup.scroll(scene, layout, self.pointer, rows);
3950 true
3951 }
3952
3953 pub fn menu_key(
3954 &mut self,
3955 scene: &Node,
3956 layout: &LayoutNode,
3957 key: MenuKey,
3958 ) -> Option<ControlInput> {
3959 if !self.reconcile_text_menu(scene, layout) {
3960 return None;
3961 }
3962 let Some(popup) = self.menu.as_mut() else {
3963 let target = self.focused.clone().filter(|target| {
3964 scene
3965 .at_path(&target.path)
3966 .is_some_and(|node| node.kind == "Menu")
3967 })?;
3968 match key {
3969 MenuKey::Up | MenuKey::Down | MenuKey::Accept => {
3970 self.open_menu_bar(scene, layout, target);
3971 }
3972 MenuKey::Left | MenuKey::Right => {
3973 if let Some(next) = sibling_menu(scene, layout, &target, key) {
3974 self.set_focus(Some(next));
3975 }
3976 }
3977 _ => {}
3978 }
3979 return None;
3980 };
3981 if key == MenuKey::Escape && popup.at_root() {
3982 self.close_menu(scene, layout);
3983 return None;
3984 }
3985 if key == popup.forward_key(scene, layout) && popup.enter_submenu(scene, layout) {
3986 return None;
3987 }
3988 if matches!(key, MenuKey::Left | MenuKey::Right)
3989 && popup.at_root()
3990 && popup.bar_header().is_some()
3991 && let Some(next) = sibling_menu(scene, layout, &popup.trigger, key)
3992 {
3993 let touch = popup.touch;
3994 self.open_menu_bar_with_touch(scene, layout, next, touch);
3995 return None;
3996 }
3997 let path = popup.key(scene, layout, key)?;
3998 self.finish_menu_action(scene, layout, path)
3999 }
4000
4001 pub fn scroll_offsets(&self) -> &BTreeMap<Vec<usize>, f32> {
4002 &self.scroll_offsets
4003 }
4004
4005 pub(crate) fn tree_root_changed(&self, path: &[usize], node: &Node) -> bool {
4006 node.tree.as_ref().is_some_and(|tree| {
4007 self.tree_scroll_roots
4008 .get(path)
4009 .is_some_and(|root| *root != tree.root_identity())
4010 })
4011 }
4012
4013 pub fn horizontal_scroll_offsets(&self) -> &BTreeMap<Vec<usize>, f32> {
4014 &self.horizontal_scroll_offsets
4015 }
4016
4017 pub(crate) fn scroll_selection_changed(
4018 &self,
4019 node: &Node,
4020 path: &[usize],
4021 columns: usize,
4022 direction: LayoutDirection,
4023 text_scale: f32,
4024 ) -> bool {
4025 self.scroll_selections.get(path).is_some_and(|previous| {
4026 *previous != ScrollSelection::new(node, columns, direction, text_scale)
4027 })
4028 }
4029
4030 pub fn pointer_position(&self) -> Option<Point> {
4031 self.pointer
4032 }
4033
4034 #[doc(hidden)]
4036 pub fn editor_mouse_press(
4037 &mut self,
4038 target: &Target,
4039 point: Point,
4040 now: Instant,
4041 selecting: bool,
4042 ) -> u8 {
4043 let previous = self.last_editor_click.take();
4044 self.editor_press = None;
4045 if selecting
4046 || self.pressed.as_ref() != Some(target)
4047 || self.focused.as_ref() != Some(target)
4048 {
4049 return 0;
4050 }
4051 let sample = (point, now);
4052 let count = previous
4053 .filter(|click| {
4054 click.count < 3
4055 && click.target == *target
4056 && crate::pointer_click_follows(click.sample, sample)
4057 })
4058 .map_or(1, |click| click.count + 1);
4059 self.editor_press = Some(EditorClick {
4060 target: target.clone(),
4061 count,
4062 sample,
4063 });
4064 count
4065 }
4066
4067 #[doc(hidden)]
4068 pub fn clear_editor_click(&mut self) {
4069 self.editor_press = None;
4070 self.last_editor_click = None;
4071 }
4072
4073 pub fn pointer_press_origin(&self) -> Option<Point> {
4074 self.press_origin
4075 }
4076
4077 #[doc(hidden)]
4078 pub fn schedule_text_selection_scroll(
4079 &mut self,
4080 target: &Target,
4081 point: Option<Point>,
4082 now: Instant,
4083 ) {
4084 self.text_selection_scroll = point
4085 .filter(|_| self.pressed.as_ref() == Some(target) && self.editor_active(&target.path))
4086 .map(|point| TextSelectionScroll {
4087 target: target.clone(),
4088 point,
4089 due: self
4090 .text_selection_scroll
4091 .as_ref()
4092 .filter(|scroll| &scroll.target == target)
4093 .map_or(now + SCROLL_FRAME_INTERVAL, |scroll| scroll.due),
4094 });
4095 }
4096
4097 #[doc(hidden)]
4098 pub fn text_selection_scroll_deadline(&self) -> Option<Instant> {
4099 let scroll = self.text_selection_scroll.as_ref()?;
4100 (self.pressed.as_ref() == Some(&scroll.target) && self.editor_active(&scroll.target.path))
4101 .then_some(scroll.due)
4102 }
4103
4104 #[doc(hidden)]
4105 pub fn take_text_selection_scroll(&mut self, now: Instant) -> Option<(Point, Duration)> {
4106 let Some(due) = self.text_selection_scroll_deadline() else {
4107 self.text_selection_scroll = None;
4108 return None;
4109 };
4110 let elapsed = now.checked_duration_since(due)? + SCROLL_FRAME_INTERVAL;
4111 let scroll = self.text_selection_scroll.take()?;
4112 Some((scroll.point, elapsed.min(3 * SCROLL_FRAME_INTERVAL)))
4113 }
4114
4115 pub fn text_scroll(&self, path: &[usize]) -> Point {
4116 self.text_offsets
4117 .get(path)
4118 .map_or(Point::default(), |(_, offset)| *offset)
4119 }
4120
4121 pub fn set_text_scroll(&mut self, target: &Target, offset: Point) {
4122 if offset == Point::default() {
4123 self.text_offsets.remove(&target.path);
4124 } else {
4125 self.text_offsets
4126 .insert(target.path.clone(), (target.row_key, offset));
4127 }
4128 }
4129
4130 pub fn scroll_y(&mut self, layout: &LayoutNode, delta: f32) -> bool {
4131 self.scroll_axis(layout, delta, Orientation::Vertical)
4132 .unwrap_or(false)
4133 }
4134
4135 pub fn scroll_x(&mut self, layout: &LayoutNode, delta: f32) -> bool {
4136 self.scroll_axis(layout, delta, Orientation::Horizontal)
4137 .unwrap_or(false)
4138 }
4139
4140 pub fn scroll_wheel(&mut self, layout: &LayoutNode, delta: Point, shift: bool) -> bool {
4141 if shift
4142 && delta.x == 0.0
4143 && let Some(moved) = self.scroll_axis(layout, delta.y, Orientation::Horizontal)
4144 {
4145 return moved;
4146 }
4147 let x = self.scroll_x(layout, delta.x);
4148 let y = self.scroll_y(layout, delta.y);
4149 x || y
4150 }
4151
4152 pub fn accessibility_scroll_to(
4154 &mut self,
4155 layout: &LayoutNode,
4156 path: &[usize],
4157 orientation: Orientation,
4158 offset: f32,
4159 ) -> bool {
4160 self.scroll_to_user_offset(layout, path, orientation, offset)
4161 }
4162
4163 pub fn scroll_to_top(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
4165 if self.menu_open() || self.choice_open() {
4166 return false;
4167 }
4168 let scope = self
4169 .focused_popup(layout)
4170 .or_else(|| self.active_dialog(layout))
4171 .unwrap_or_default();
4172 let Some((node, item)) = scene.at_path(scope).zip(layout.at_path(scope)) else {
4173 return false;
4174 };
4175 if self
4176 .transitioning_stacks
4177 .iter()
4178 .any(|path| scope.starts_with(path))
4179 {
4180 return false;
4181 }
4182 let mut primary = None;
4183 primary_vertical_viewport(
4184 node,
4185 item,
4186 &mut scope.to_vec(),
4187 &self.transitioning_stacks,
4188 &mut primary,
4189 );
4190 primary.is_some_and(|(_, path)| {
4191 self.scroll_to_user_offset(layout, &path, Orientation::Vertical, 0.0)
4192 })
4193 }
4194
4195 fn scroll_to_user_offset(
4196 &mut self,
4197 layout: &LayoutNode,
4198 path: &[usize],
4199 orientation: Orientation,
4200 offset: f32,
4201 ) -> bool {
4202 if !offset.is_finite()
4203 || self
4204 .active_dialog(layout)
4205 .is_some_and(|scope| !path.starts_with(scope))
4206 {
4207 return false;
4208 }
4209 let Some(mut item) = layout
4210 .at_path(path)
4211 .filter(|item| scroll_target_visible(item))
4212 else {
4213 return false;
4214 };
4215 let mut path = path;
4216 if let Some(bar) = &item.attached_scroll_bar {
4217 if bar.geometry.orientation != orientation || !self.allows_popup(layout, &bar.target) {
4218 return false;
4219 }
4220 path = &bar.target;
4221 let Some(viewport) = layout
4222 .at_path(path)
4223 .filter(|viewport| viewport.visible && viewport.enabled)
4224 else {
4225 return false;
4226 };
4227 item = viewport;
4228 }
4229 let Some(scroll) = item.scroll_on(orientation) else {
4230 return false;
4231 };
4232 if !self.set_viewport_offset(path, item, orientation, f64::from(offset)) {
4233 return false;
4234 }
4235 UserScrollChange::record(
4236 &mut self.user_scroll_changes,
4237 item,
4238 orientation,
4239 scroll.offset,
4240 );
4241 true
4242 }
4243
4244 pub(crate) fn scroll_viewport_by(
4245 &mut self,
4246 path: &[usize],
4247 item: &LayoutNode,
4248 axis: Orientation,
4249 delta: f64,
4250 ) -> bool {
4251 delta.is_finite()
4252 && delta != 0.0
4253 && self.update_viewport_offset(path, item, axis, |previous| f64::from(previous) + delta)
4254 }
4255
4256 pub(crate) fn set_viewport_offset(
4257 &mut self,
4258 path: &[usize],
4259 item: &LayoutNode,
4260 axis: Orientation,
4261 offset: f64,
4262 ) -> bool {
4263 offset.is_finite() && self.update_viewport_offset(path, item, axis, |_| offset)
4264 }
4265
4266 pub(crate) fn current_viewport_offset(
4267 &self,
4268 path: &[usize],
4269 item: &LayoutNode,
4270 axis: Orientation,
4271 ) -> Option<f32> {
4272 let scroll = item.scroll_on(axis)?;
4273 let offsets = match axis {
4274 Orientation::Horizontal => &self.horizontal_scroll_offsets,
4275 Orientation::Vertical => &self.scroll_offsets,
4276 };
4277 Some(
4278 item.bound_offset(axis)
4279 .or_else(|| pending_scroll_offset(item, offsets, path, axis))
4280 .unwrap_or(scroll.offset)
4281 .clamp(0.0, scroll.max_offset),
4282 )
4283 }
4284
4285 fn update_viewport_offset(
4286 &mut self,
4287 path: &[usize],
4288 item: &LayoutNode,
4289 axis: Orientation,
4290 next: impl FnOnce(f32) -> f64,
4291 ) -> bool {
4292 let Some(scroll) = item.scroll_on(axis) else {
4293 return false;
4294 };
4295 let had_overscroll = self.overscroll.has_offset();
4296 self.cancel_scroll_gesture();
4297 let previous = self
4298 .current_viewport_offset(path, item, axis)
4299 .unwrap_or(scroll.offset);
4300 let offsets = match axis {
4301 Orientation::Horizontal => &mut self.horizontal_scroll_offsets,
4302 Orientation::Vertical => &mut self.scroll_offsets,
4303 };
4304 let next = next(previous).clamp(0.0, f64::from(scroll.max_offset)) as f32;
4305 if next == previous {
4306 return had_overscroll;
4307 }
4308 store_scroll_offset(item, offsets, path, axis, next);
4309 item.write_bound_offset(axis, next);
4310 true
4311 }
4312
4313 fn scroll_bar_for_target(
4314 &self,
4315 scene: &Node,
4316 layout: &LayoutNode,
4317 target: &ScrollTarget,
4318 ) -> Option<ScrollBarGeometry> {
4319 let path = &target.path;
4320 if !path.starts_with(self.active_dialog(layout).unwrap_or_default()) {
4321 return None;
4322 }
4323 let item = layout.at_path(path)?;
4324 let node = scene.interactive_at_path(path)?;
4325 if !item.visible
4326 || !item.enabled
4327 || !target.matches_node(node)
4328 || scene.row_key_at(path) != target.row_key
4329 {
4330 return None;
4331 }
4332 if node.kind == "ScrollBar" && !node.boolean("interactive", true) {
4333 return None;
4334 }
4335 if let Some(bar) = &item.attached_scroll_bar
4336 && !self.allows_popup(layout, &bar.target)
4337 {
4338 return None;
4339 }
4340 item.scroll_bars(node)
4341 .find(|bar| bar.orientation == target.orientation && bar.scrollable())
4342 }
4343
4344 pub fn scroll_bar_press(
4346 &mut self,
4347 scene: &Node,
4348 layout: &LayoutNode,
4349 ) -> Option<ScrollBarUpdate> {
4350 let target = self.hovered_scroll_bar.clone()?;
4351 self.press_scroll_bar(scene, layout, target, self.pointer?, false)
4352 }
4353
4354 fn press_scroll_bar(
4355 &mut self,
4356 scene: &Node,
4357 layout: &LayoutNode,
4358 target: ScrollTarget,
4359 point: Point,
4360 touch: bool,
4361 ) -> Option<ScrollBarUpdate> {
4362 if self.menu_open() || self.choice_open() {
4363 return None;
4364 }
4365 let item = layout.at_path(&target.path)?;
4366 let start = point;
4367 let point = item.map_from_window(point)?;
4368 let bar = self.scroll_bar_for_target(scene, layout, &target)?;
4369 if !bar.track.contains(point) {
4370 return None;
4371 }
4372 self.cancel_scroll_gesture();
4373 self.cancel_press();
4374 self.tooltip.dismiss();
4375 let node = scene.at_path(&target.path)?;
4376 if node.kind == "ScrollBar" {
4377 self.set_focus_with_reason(
4378 Some(Target::from_node(
4379 target.path.clone(),
4380 node,
4381 true,
4382 target.row_key,
4383 )),
4384 xrack_runtime::FocusReason::PointerClick,
4385 );
4386 self.remember_focus_scope(scene, layout);
4387 }
4388 let grab = bar.grab(point);
4389 let update = if grab.is_none() {
4390 self.move_scroll_bar(node, layout, &target.path, bar, bar.page_toward(point))
4391 } else {
4392 ScrollBarUpdate::Unchanged
4393 };
4394 self.scroll_bar_press = Some(ScrollBarPress {
4395 target,
4396 source: node.kind,
4397 viewport: node.scroll_target.clone(),
4398 reversed: bar.reversed(),
4399 grab,
4400 touch,
4401 cancelled: false,
4402 start,
4403 last: start,
4404 dragged: false,
4405 });
4406 Some(update)
4407 }
4408
4409 pub fn scroll_bar_drag(
4411 &mut self,
4412 scene: &Node,
4413 layout: &LayoutNode,
4414 ) -> Option<ScrollBarUpdate> {
4415 self.update_scroll_bar_capture(scene, layout, self.pointer, false)
4416 }
4417
4418 pub fn release_scroll_bar(
4419 &mut self,
4420 scene: &Node,
4421 layout: &LayoutNode,
4422 ) -> Option<ScrollBarUpdate> {
4423 let point = self
4424 .pointer
4425 .or_else(|| self.scroll_bar_press.as_ref().map(|press| press.last));
4426 self.update_scroll_bar_capture(scene, layout, point, true)
4427 }
4428
4429 fn update_scroll_bar_capture(
4430 &mut self,
4431 scene: &Node,
4432 layout: &LayoutNode,
4433 point: Option<Point>,
4434 released: bool,
4435 ) -> Option<ScrollBarUpdate> {
4436 let mut press = self.scroll_bar_press.take()?;
4437 let update = point.map_or(ScrollBarUpdate::Unchanged, |point| {
4438 self.update_scroll_bar_drag(scene, layout, &mut press, point, released)
4439 });
4440 if !released {
4441 self.scroll_bar_press = Some(press);
4442 }
4443 Some(update)
4444 }
4445
4446 fn update_scroll_bar_drag(
4447 &mut self,
4448 scene: &Node,
4449 layout: &LayoutNode,
4450 press: &mut ScrollBarPress,
4451 point: Point,
4452 released: bool,
4453 ) -> ScrollBarUpdate {
4454 let Some(grab) = press.grab.filter(|_| !press.cancelled) else {
4455 return ScrollBarUpdate::Unchanged;
4456 };
4457 let target = &press.target;
4458 let Some(node) = press.node(scene) else {
4459 press.cancelled = true;
4460 return ScrollBarUpdate::Unchanged;
4461 };
4462 let Some(bar) = self
4463 .scroll_bar_for_target(scene, layout, target)
4464 .filter(|bar| bar.reversed() == press.reversed)
4465 else {
4466 press.cancelled = true;
4467 return ScrollBarUpdate::Unchanged;
4468 };
4469 let mode = match node.properties.get("snap-mode") {
4470 Some(Value::ScrollSnapMode(mode)) => *mode,
4471 _ => ScrollSnapMode::None,
4472 };
4473 if released && mode == ScrollSnapMode::None {
4474 return ScrollBarUpdate::Unchanged;
4475 }
4476 let Some(item) = layout.at_path(&target.path) else {
4477 return ScrollBarUpdate::Unchanged;
4478 };
4479 let window_point = point;
4480 let (Some(point), Some(start)) = (
4481 item.map_from_window(point),
4482 item.map_from_window(press.start),
4483 ) else {
4484 return ScrollBarUpdate::Unchanged;
4485 };
4486 let mut fraction = bar.drag_fraction(point, grab);
4487 if !fraction.is_finite() {
4488 return ScrollBarUpdate::Unchanged;
4489 }
4490 press.last = window_point;
4491 press.dragged |= fraction != bar.drag_fraction(start, grab);
4492 if !press.dragged {
4493 return ScrollBarUpdate::Unchanged;
4494 }
4495 if mode == ScrollSnapMode::Always || released && mode == ScrollSnapMode::OnRelease {
4496 fraction = snap_fraction(fraction, node.number("step-size").unwrap_or(0.0));
4497 }
4498 self.move_scroll_bar_fraction(node, layout, &target.path, bar, fraction)
4499 }
4500
4501 pub fn scroll_bar_key(
4502 &mut self,
4503 scene: &Node,
4504 layout: &LayoutNode,
4505 key: NavigationKey,
4506 ) -> Option<ScrollBarUpdate> {
4507 let target = self.focused.as_ref()?;
4508 let node = scene.interactive_at_path(&target.path)?;
4509 if node.kind != "ScrollBar"
4510 || !valid(target, scene, layout)
4511 || !self.allows_popup(layout, &target.path)
4512 {
4513 return None;
4514 }
4515 let item = layout.at_path(&target.path)?;
4516 let bar = item.scroll_control_geometry(node)?;
4517 let page = if bar.page > 0.0 { bar.page } else { bar.step };
4518 let offset = match (key, bar.orientation) {
4519 (NavigationKey::Home, _) => 0.0,
4520 (NavigationKey::End, _) => bar.scroll.max_offset,
4521 (NavigationKey::PageUp, _) => bar.scroll.offset - page,
4522 (NavigationKey::PageDown, _) => bar.scroll.offset + page,
4523 (NavigationKey::Left, Orientation::Horizontal)
4524 | (NavigationKey::Up, Orientation::Vertical) => {
4525 bar.scroll.offset + bar.logical_delta(-bar.step)
4526 }
4527 (NavigationKey::Right, Orientation::Horizontal)
4528 | (NavigationKey::Down, Orientation::Vertical) => {
4529 bar.scroll.offset + bar.logical_delta(bar.step)
4530 }
4531 _ => return None,
4532 };
4533 let path = target.path.clone();
4534 Some(self.move_scroll_bar(node, layout, &path, bar, offset))
4535 }
4536
4537 fn move_scroll_bar(
4538 &mut self,
4539 node: &Node,
4540 layout: &LayoutNode,
4541 path: &[usize],
4542 bar: ScrollBarGeometry,
4543 offset: f32,
4544 ) -> ScrollBarUpdate {
4545 if !bar.scrollable() {
4546 return ScrollBarUpdate::Unchanged;
4547 }
4548 let fraction =
4549 f64::from(offset.clamp(0.0, bar.scroll.max_offset)) / f64::from(bar.scroll.max_offset);
4550 self.move_scroll_bar_fraction(node, layout, path, bar, fraction)
4551 }
4552
4553 fn move_scroll_bar_fraction(
4554 &mut self,
4555 node: &Node,
4556 layout: &LayoutNode,
4557 path: &[usize],
4558 bar: ScrollBarGeometry,
4559 fraction: f64,
4560 ) -> ScrollBarUpdate {
4561 if node.kind == "ScrollBar" && node.scroll_target.is_none() {
4562 let action = RangeAction::SetFraction(fraction);
4563 if ScrollBarRange::from_node(node).apply(action).is_some() {
4564 return ScrollBarUpdate::Range(RangeInput {
4565 path: path.to_vec(),
4566 action,
4567 });
4568 }
4569 } else if self.scroll_to_user_offset(
4570 layout,
4571 path,
4572 bar.orientation,
4573 (fraction * f64::from(bar.scroll.max_offset)) as f32,
4574 ) {
4575 return ScrollBarUpdate::ViewportMoved;
4576 }
4577 ScrollBarUpdate::Unchanged
4578 }
4579
4580 pub fn finish_scroll_bar(&mut self) -> bool {
4581 self.scroll_bar_press.take().is_some()
4582 }
4583
4584 pub fn scroll_bar_captured(&self) -> bool {
4585 self.scroll_bar_press.is_some()
4586 }
4587
4588 pub fn touch_scroll_bar_press(
4589 &mut self,
4590 scene: &Node,
4591 layout: &LayoutNode,
4592 point: Point,
4593 ) -> Option<ScrollBarUpdate> {
4594 let Hit::ScrollBar(target) = self.hit_at(scene, layout, point) else {
4595 return None;
4596 };
4597 let moved = self.press_scroll_bar(scene, layout, target.clone(), point, true)?;
4598 self.pointer = Some(point);
4599 self.hovered_scroll_bar = Some(target);
4600 Some(moved)
4601 }
4602
4603 pub fn touch_scroll_bar_drag(
4604 &mut self,
4605 scene: &Node,
4606 layout: &LayoutNode,
4607 point: Point,
4608 ) -> ScrollBarUpdate {
4609 self.pointer = Some(point);
4610 self.scroll_bar_drag(scene, layout)
4611 .unwrap_or(ScrollBarUpdate::Unchanged)
4612 }
4613
4614 pub fn finish_touch_scroll_bar(&mut self) -> bool {
4615 if !self.finish_scroll_bar() {
4616 return false;
4617 }
4618 self.hovered_scroll_bar = None;
4619 self.pointer = None;
4620 true
4621 }
4622
4623 pub fn release_touch_scroll_bar(
4624 &mut self,
4625 scene: &Node,
4626 layout: &LayoutNode,
4627 point: Point,
4628 ) -> Option<ScrollBarUpdate> {
4629 let update = self.update_scroll_bar_capture(scene, layout, Some(point), true)?;
4630 self.hovered_scroll_bar = None;
4631 self.pointer = None;
4632 Some(update)
4633 }
4634
4635 pub(crate) fn scroll_bar_interaction(
4636 &self,
4637 scene: &Node,
4638 layout: &LayoutNode,
4639 path: &[usize],
4640 axis: Orientation,
4641 ) -> (bool, bool) {
4642 let matches = |target: &ScrollTarget| target.path == path && target.orientation == axis;
4643 let pressed = self.scroll_bar_press.as_ref().is_some_and(|press| {
4644 !press.cancelled
4645 && matches(&press.target)
4646 && press.node(scene).is_some()
4647 && self
4648 .scroll_bar_for_target(scene, layout, &press.target)
4649 .is_some_and(|bar| bar.reversed() == press.reversed)
4650 });
4651 let hovered = !self
4652 .scroll_bar_press
4653 .as_ref()
4654 .is_some_and(|press| press.touch)
4655 && self.hovered_scroll_bar.as_ref().is_some_and(|target| {
4656 matches(target) && self.scroll_bar_for_target(scene, layout, target).is_some()
4657 });
4658 (pressed, hovered)
4659 }
4660
4661 pub fn scroll_bar_highlighted(&self, path: &[usize], orientation: Orientation) -> bool {
4662 let matches =
4663 |target: &ScrollTarget| target.path == path && target.orientation == orientation;
4664 self.hovered_scroll_bar.as_ref().is_some_and(matches)
4665 || self.scroll_bar_press.as_ref().is_some_and(|press| {
4666 !press.cancelled && press.grab.is_some() && matches(&press.target)
4667 })
4668 }
4669
4670 fn scroll_axis(
4671 &mut self,
4672 layout: &LayoutNode,
4673 delta: f32,
4674 orientation: Orientation,
4675 ) -> Option<bool> {
4676 if self.pointer_on_stack_slide || !delta.is_finite() || delta == 0.0 {
4677 return None;
4678 }
4679 let point = self.pointer?;
4680 let scope = self.pointer_scope(layout, point);
4681 let scope_len = scope.len();
4682 let path = Self::scroll_path(layout, point, scope, |_, item| {
4683 item.scroll_on(orientation)
4684 .is_some_and(|scroll| scroll.max_offset > 0.0)
4685 })?;
4686 Some(
4687 self.consume_scroll(
4688 layout,
4689 &path,
4690 scope_len,
4691 delta,
4692 orientation,
4693 ScrollInput::Wheel,
4694 )
4695 .changed(),
4696 )
4697 }
4698
4699 fn scroll_path(
4700 layout: &LayoutNode,
4701 point: Point,
4702 scope: &[usize],
4703 accepts: impl Fn(&[usize], &LayoutNode) -> bool,
4704 ) -> Option<Vec<usize>> {
4705 fn target(
4706 layout: &LayoutNode,
4707 point: Point,
4708 path: &mut Vec<usize>,
4709 accepts: &impl Fn(&[usize], &LayoutNode) -> bool,
4710 ) -> bool {
4711 if !layout.enabled || !layout.contains_subtree_point(point) {
4712 return false;
4713 }
4714 for (index, child) in layout
4715 .child_paint_order()
4716 .rev()
4717 .filter_map(|index| layout.child_at(index).map(|child| (index, child)))
4718 {
4719 path.push(index);
4720 if target(child, point, path, accepts) {
4721 return true;
4722 }
4723 path.pop();
4724 }
4725 layout
4726 .map_from_window(point)
4727 .is_some_and(|local| layout.tab_viewport().contains(local))
4728 && accepts(path, layout)
4729 }
4730
4731 let mut path = scope.to_vec();
4732 target(layout.at_path(scope)?, point, &mut path, &accepts).then_some(path)
4733 }
4734
4735 fn consume_scroll(
4736 &mut self,
4737 layout: &LayoutNode,
4738 path: &[usize],
4739 scope_len: usize,
4740 delta: f32,
4741 orientation: Orientation,
4742 mut input: ScrollInput<'_>,
4743 ) -> AxisMotion {
4744 let mut result = AxisMotion::default();
4745 let mut delta = f64::from(delta);
4746 if let ScrollInput::Pan {
4747 owners,
4748 flicking: false,
4749 ..
4750 } = &mut input
4751 {
4752 let (remaining, owner) = self.overscroll.unwind(orientation, delta);
4753 delta = remaining;
4754 if let Some(owner) = owner {
4755 record_motion_owner(owners, &owner, orientation);
4756 result.elastic = true;
4757 }
4758 }
4759 let offsets = match orientation {
4760 Orientation::Horizontal => &mut self.horizontal_scroll_offsets,
4761 Orientation::Vertical => &mut self.scroll_offsets,
4762 };
4763 let mut elastic_owner = None;
4764 let mut refresh_owner = None;
4765 let last_depth = path.len();
4767 for depth in (scope_len..=last_depth).rev() {
4768 let path = &path[..depth];
4769 let Some(item) = layout.at_path(path) else {
4770 continue;
4771 };
4772 if item.tab_strip.is_some() && depth != last_depth {
4773 continue;
4774 }
4775 if let ScrollInput::Pan { device, .. } = &input
4776 && (!item.visible || !item.enabled || !item.accepts_pan(orientation, *device))
4777 {
4778 continue;
4779 }
4780 let Some(scroll) = item.scroll_on(orientation) else {
4781 continue;
4782 };
4783 if delta != 0.0
4784 && let ScrollInput::Pan {
4785 touch_scene: Some(scene),
4786 ..
4787 } = &input
4788 && let Some(node) = scene.at_path(path)
4789 {
4790 result.dismiss_keyboard |= node.boolean("dismiss-keyboard-on-drag", false);
4791 }
4792 let current = pending_scroll_offset(item, offsets, path, orientation)
4793 .unwrap_or(scroll.offset)
4794 .clamp(0.0, scroll.max_offset);
4795 let sign = if item.scroll_axis_reversed(orientation) {
4796 -1.0
4797 } else {
4798 1.0
4799 };
4800 let wanted = f64::from(current) + delta * sign;
4801 let bounded = wanted.clamp(0.0, f64::from(scroll.max_offset));
4802 delta = (wanted - bounded) * sign;
4804 if orientation == Orientation::Vertical
4805 && delta < 0.0
4806 && refresh_owner.is_none()
4807 && let ScrollInput::Pan {
4808 touch_scene: Some(scene),
4809 ..
4810 } = &input
4811 && scene.at_path(path).is_some_and(Node::can_pull_to_refresh)
4812 && item.viewport_handle.is_some()
4813 {
4814 refresh_owner = Some(item);
4815 }
4816 if let ScrollInput::Pan { flicking, .. } = &input
4817 && delta != 0.0
4818 && scroll.max_offset > 0.0
4819 && item.viewport_handle.is_some()
4820 && item
4821 .elastic
4822 .is_some_and(|options| options.behavior.allows_overshoot(*flicking))
4823 {
4824 elastic_owner = Some(item);
4825 }
4826 let next = bounded as f32;
4827 if next != current {
4828 store_scroll_offset(item, offsets, path, orientation, next);
4829 UserScrollChange::commit(
4830 &mut self.user_scroll_changes,
4831 item,
4832 orientation,
4833 scroll.offset,
4834 next,
4835 );
4836 if let ScrollInput::Pan { owners, .. } = &mut input {
4837 record_motion(owners, item, orientation);
4838 }
4839 result.bounded = true;
4840 }
4841 if delta == 0.0 {
4842 break;
4843 }
4844 }
4845 if let Some(item) = refresh_owner
4846 && delta < 0.0
4847 && !self.overscroll.is_rebounding(orientation)
4848 && self
4849 .overscroll
4850 .pull_to_refresh(item, delta, self.reduce_motion)
4851 {
4852 result.elastic = true;
4853 if let ScrollInput::Pan { owners, .. } = &mut input {
4854 record_motion(owners, item, orientation);
4855 }
4856 } else if let Some(item) = elastic_owner
4857 && !self.overscroll.is_rebounding(orientation)
4858 && self.overscroll.pull(item, orientation, delta)
4859 {
4860 result.elastic = true;
4861 if let ScrollInput::Pan {
4862 owners,
4863 flicking: false,
4864 ..
4865 } = &mut input
4866 {
4867 record_motion(owners, item, orientation);
4868 }
4869 }
4870 result
4871 }
4872
4873 pub fn arm_mouse_viewport_pan(
4876 &mut self,
4877 scene: &Node,
4878 layout: &LayoutNode,
4879 point: Point,
4880 now: Instant,
4881 ) -> bool {
4882 if self.press_origin != Some(point)
4883 || self.drag.is_some()
4884 || self.split_resize_active()
4885 || self.scroll_bar_press.is_some()
4886 || self.table_resize.is_some()
4887 || self.table_row_resize.is_some()
4888 || self.table_column_move.is_some()
4889 || self.table_row_move.is_some()
4890 || self.pressed_table_column.is_some()
4891 || self.menu_open()
4892 || self.choice_open()
4893 {
4894 return false;
4895 }
4896 let hit = self.hit_at(scene, layout, point);
4897 let hit_path = match &hit {
4898 Hit::None => None,
4899 Hit::Target(target)
4900 if scene.at_path(&target.path).is_some_and(|node| {
4901 matches!(
4902 node.kind,
4903 "Button"
4904 | "ToolButton"
4905 | "RoundButton"
4906 | "TouchArea"
4907 | "ListRow"
4908 | "ListView"
4909 | "GridView"
4910 | "StandardListView"
4911 | "TableView"
4912 | "TreeView"
4913 ) || is_toggle(node.kind)
4914 }) =>
4915 {
4916 Some(target.path.as_slice())
4917 }
4918 _ => return false,
4919 };
4920 let scope = self.pointer_scope(layout, point).to_vec();
4921 let orientations = [Orientation::Horizontal, Orientation::Vertical];
4922 let can_pan = |item: &LayoutNode, axis| {
4923 item.accepts_pan(axis, PanDevice::LeftMouse)
4924 && item
4925 .scroll_on(axis)
4926 .is_some_and(|scroll| scroll.max_offset > 0.0)
4927 };
4928 let Some(path) = Self::scroll_path(layout, point, &scope, |path, item| {
4929 hit_path.is_none_or(|target| target.starts_with(path))
4930 && orientations.into_iter().any(|axis| can_pan(item, axis))
4931 }) else {
4932 return false;
4933 };
4934 let axes = orientations.map(|orientation| {
4935 (scope.len()..=path.len()).rev().find_map(|depth| {
4936 let path = &path[..depth];
4937 let item = layout.at_path(path)?;
4938 let node = scene.at_path(path)?;
4939 can_pan(item, orientation).then(|| ScrollTarget {
4940 path: path.to_vec(),
4941 orientation,
4942 row_key: scene.row_key_at(path),
4943 id: ElementId::of(node),
4944 })
4945 })
4946 });
4947 self.scroll_gesture = Some(ScrollGesture {
4948 route: ScrollRoute {
4949 scope_row: scene.row_key_at(&scope),
4950 scope_id: scene.at_path(&scope).and_then(ElementId::of),
4951 scope,
4952 axes,
4953 mouse_viewport: true,
4954 pan_device: PanDevice::LeftMouse,
4955 },
4956 motion: DragMotion::new(point, now),
4957 tap: None,
4958 touch_point: None,
4959 popup: (false, false),
4960 menu_pan: None,
4961 choice_pan: None,
4962 drawer: None,
4963 pages: Vec::new(),
4964 tumbler: None,
4965 tab_move: None,
4966 switch: None,
4967 swipe_delegate: None,
4968 swipe: None,
4969 delay_touch: false,
4970 table_gesture: None,
4971 });
4972 true
4973 }
4974
4975 pub fn mouse_viewport_pan_claimed(&self) -> bool {
4976 self.scroll_gesture
4977 .as_ref()
4978 .is_some_and(|gesture| gesture.route.mouse_viewport && gesture.motion.dragging)
4979 }
4980
4981 pub fn begin_scroll_gesture(
4983 &mut self,
4984 scene: &Node,
4985 layout: &LayoutNode,
4986 point: Point,
4987 now: Instant,
4988 kind: ScrollGestureKind,
4989 ) -> bool {
4990 self.begin_scroll_gesture_with_selection(scene, layout, point, now, kind, false)
4991 }
4992
4993 #[doc(hidden)]
4994 pub fn begin_scroll_gesture_with_selection(
4995 &mut self,
4996 scene: &Node,
4997 layout: &LayoutNode,
4998 point: Point,
4999 now: Instant,
5000 kind: ScrollGestureKind,
5001 additive: bool,
5002 ) -> bool {
5003 self.scroll_keyboard_dismissal = false;
5004 self.swipe_commit = None;
5005 if !point.x.is_finite() || !point.y.is_finite() {
5006 return false;
5007 }
5008 let hit = self.hit_at(scene, layout, point);
5009 let picker_button = match (&hit, &self.tumbler_flick) {
5011 (Hit::Target(target), Some(flick)) => self
5012 .dialog_button(scene, layout, target)
5013 .is_some_and(|button| self.time_picker_flick(flick, scene, layout, &button.path)),
5014 _ => false,
5015 };
5016 let tumbler_interrupted = !picker_button && self.interrupt_tumbler_flick();
5017 let interrupted = tumbler_interrupted
5018 || self.scroll_fling.is_some()
5019 || self.overscroll.deadline().is_some();
5020 self.scroll_fling = None;
5021 if interrupted {
5022 self.viewport_motion.clear();
5023 }
5024 let touch = kind == ScrollGestureKind::Touch;
5025 if matches!(
5026 kind,
5027 ScrollGestureKind::Touch | ScrollGestureKind::MouseControl
5028 ) && !interrupted
5029 && self.start_table_selection_handle(scene, layout, point, touch, true)
5030 {
5031 return true;
5032 }
5033 let popup = (self.menu_open(), self.choice_open());
5034 let scope = self.pointer_scope(layout, point).to_vec();
5035 if !popup.0 && !popup.1 && matches!(hit, Hit::StackSlide) {
5036 return false;
5037 }
5038 if kind == ScrollGestureKind::MouseControl
5039 && !popup.0
5040 && !popup.1
5041 && let Hit::Target(target) = &hit
5042 && split_target(target, scene, layout).is_some()
5043 {
5044 return false;
5045 }
5046 let tumbler = match &hit {
5047 Hit::Target(target) | Hit::ControlPart(target, _) if !popup.0 && !popup.1 => scene
5048 .at_path(&target.path)
5049 .zip(layout.at_path(&target.path))
5050 .and_then(|(node, item)| {
5051 matches!(node.kind, "Tumbler" | "PathView").then_some(())?;
5052 TumblerDrag::new(target.clone(), node, item, item.map_from_window(point)?)
5053 }),
5054 _ => None,
5055 };
5056 if kind == ScrollGestureKind::MouseTumbler && tumbler.is_none() {
5057 return false;
5058 }
5059 let tab_move = match &hit {
5060 Hit::Target(target)
5061 if popup == (false, false)
5062 && matches!(
5063 kind,
5064 ScrollGestureKind::Touch | ScrollGestureKind::MouseControl
5065 ) =>
5066 {
5067 TabDrag::new(target, scene, layout, point)
5068 }
5069 _ => None,
5070 };
5071 let switch = match &hit {
5072 Hit::Target(target)
5073 if popup == (false, false)
5074 && matches!(
5075 kind,
5076 ScrollGestureKind::Touch | ScrollGestureKind::MouseControl
5077 ) =>
5078 {
5079 scene
5080 .at_path(&target.path)
5081 .zip(layout.at_path(&target.path))
5082 .and_then(|(node, item)| SwitchDrag::new(target.clone(), node, item, point))
5083 }
5084 _ => None,
5085 };
5086 let swipe_delegate = match &hit {
5087 Hit::Target(target)
5088 if !popup.0 && !popup.1 && kind != ScrollGestureKind::MouseTumbler =>
5089 {
5090 (scope.len()..=target.path.len()).rev().find_map(|depth| {
5091 let path = &target.path[..depth];
5092 let node = scene.interactive_at_path(path)?;
5093 let item = layout.at_path(path)?;
5094 let ancestor = Target::from_node(
5095 path.to_vec(),
5096 node,
5097 focusable(node),
5098 scene.row_key_at(path),
5099 );
5100 SwipeDrag::new(ancestor, node, item, item.map_from_window(point)?)
5101 })
5102 }
5103 _ => None,
5104 };
5105 let table_gesture = match &hit {
5106 Hit::Target(target)
5107 if !interrupted
5108 && popup == (false, false)
5109 && matches!(
5110 kind,
5111 ScrollGestureKind::Touch | ScrollGestureKind::MouseControl
5112 ) =>
5113 {
5114 self.table_gesture_at(scene, layout, target, point, touch, now, additive)
5115 }
5116 _ => None,
5117 };
5118 let swipe = (!popup.0
5119 && !popup.1
5120 && tumbler.is_none()
5121 && tab_move.is_none()
5122 && swipe_delegate.is_none()
5123 && table_gesture
5124 .as_ref()
5125 .is_none_or(|hold| touch && hold.deadline.is_some())
5126 && matches!(
5127 kind,
5128 ScrollGestureKind::Touch | ScrollGestureKind::MouseControl
5129 ))
5130 .then(|| self.swipe_route(scene, layout, point, &hit))
5131 .flatten();
5132 if kind == ScrollGestureKind::MouseControl
5133 && tumbler.is_none()
5134 && tab_move.is_none()
5135 && switch.is_none()
5136 && swipe_delegate.is_none()
5137 && swipe.is_none()
5138 && table_gesture.is_none()
5139 {
5140 return false;
5141 }
5142 let left_mouse_pan =
5143 kind == ScrollGestureKind::MouseControl && (swipe.is_some() || table_gesture.is_some());
5144 let pan_device = match kind {
5145 ScrollGestureKind::Touch => PanDevice::Touch,
5146 ScrollGestureKind::MouseControl if left_mouse_pan => PanDevice::LeftMouse,
5147 _ => PanDevice::MiddleMouse,
5148 };
5149 let pages = if popup.0 || popup.1 || left_mouse_pan {
5150 Vec::new()
5151 } else {
5152 Self::page_swipes(scene, layout, point, &scope, &hit)
5153 };
5154 let drawer =
5155 if popup.0 || popup.1 || left_mouse_pan || self.popup_at(layout, point).is_some() {
5156 None
5157 } else {
5158 self.drawer_swipe(scene, layout, point)
5159 };
5160 let axes = [Orientation::Horizontal, Orientation::Vertical].map(|orientation| {
5161 if popup.0 || popup.1 {
5162 return None;
5163 }
5164 let path = Self::scroll_path(layout, point, &scope, |path, item| {
5165 item.accepts_pan(orientation, pan_device)
5166 && item.scroll_on(orientation).is_some_and(|scroll| {
5167 scroll.max_offset > 0.0
5168 || (touch
5169 && scene.at_path(path).is_some_and(|node| {
5170 node.boolean("dismiss-keyboard-on-drag", false)
5171 || (orientation == Orientation::Vertical
5172 && node.can_pull_to_refresh())
5173 }))
5174 })
5175 })?;
5176 let row_key = scene.row_key_at(&path);
5177 let id = ElementId::of(scene.at_path(&path)?);
5178 Some(ScrollTarget {
5179 path,
5180 orientation,
5181 row_key,
5182 id,
5183 })
5184 });
5185 if kind == ScrollGestureKind::MousePan
5186 && drawer.is_none()
5187 && pages.is_empty()
5188 && tumbler.is_none()
5189 && tab_move.is_none()
5190 && swipe_delegate.is_none()
5191 && axes.iter().all(Option::is_none)
5192 {
5193 return false;
5194 }
5195 let delay_target = match &hit {
5196 Hit::Target(target) if kind == ScrollGestureKind::Touch && !popup.0 && !popup.1 => {
5197 scene
5198 .at_path(&target.path)
5199 .filter(|node| node.kind == "DelayButton" && !node.boolean("checked", false))
5200 .map(|_| target.clone())
5201 }
5202 _ => None,
5203 };
5204 let repeat_target = match &hit {
5205 Hit::Target(target)
5206 if kind == ScrollGestureKind::Touch && !interrupted && popup == (false, false) =>
5207 {
5208 Some(target.clone())
5209 }
5210 _ => None,
5211 };
5212 let tap = (kind != ScrollGestureKind::MousePan && !interrupted).then_some(hit);
5213 let overscroll = if drawer.is_none()
5214 && pages.is_empty()
5215 && tumbler.is_none()
5216 && tab_move.is_none()
5217 && switch.is_none()
5218 && swipe_delegate.is_none()
5219 && swipe.is_none()
5220 {
5221 self.take_drag_overscroll(layout, &axes, scope.len(), pan_device)
5222 } else {
5223 Overscroll::default()
5224 };
5225 let picker_flick = if picker_button {
5226 self.tumbler_flick.take()
5227 } else {
5228 None
5229 };
5230 self.cancel_press();
5231 self.tumbler_flick = picker_flick;
5232 self.overscroll = overscroll;
5233 self.pointer_leave();
5234 let delay_touch = delay_target.is_some_and(|target| {
5235 self.set_focus(Some(target.clone()));
5236 self.begin_delay(scene, layout, target, DelaySource::Touch(point), now)
5237 });
5238 if let Some(target) = repeat_target {
5239 self.begin_button_hold(scene, layout, target, DelaySource::Touch(point), now);
5240 }
5241 if popup == (false, false)
5242 && let Some(Hit::Target(target)) = &tap
5243 {
5244 self.start_button_contact(scene, target.clone(), ButtonContactSource::Gesture);
5245 }
5246 let menu_pan = if touch {
5247 self.menu
5248 .as_ref()
5249 .and_then(|menu| menu.pan_at(scene, layout, point))
5250 } else {
5251 None
5252 };
5253 let choice_pan = if touch {
5254 self.choice
5255 .as_ref()
5256 .and_then(|choice| choice.pan_at(scene, layout, point))
5257 } else {
5258 None
5259 };
5260 self.scroll_gesture = Some(ScrollGesture {
5261 route: ScrollRoute {
5262 scope_row: scene.row_key_at(&scope),
5263 scope_id: scene.at_path(&scope).and_then(ElementId::of),
5264 scope,
5265 axes,
5266 mouse_viewport: false,
5267 pan_device,
5268 },
5269 motion: DragMotion::new(point, now),
5270 tap,
5271 touch_point: (kind == ScrollGestureKind::Touch).then_some(point),
5272 popup,
5273 menu_pan,
5274 choice_pan,
5275 drawer,
5276 pages,
5277 tumbler,
5278 tab_move,
5279 switch,
5280 swipe_delegate,
5281 swipe,
5282 delay_touch,
5283 table_gesture,
5284 });
5285 true
5286 }
5287
5288 fn swipe_route(
5289 &self,
5290 scene: &Node,
5291 layout: &LayoutNode,
5292 point: Point,
5293 hit: &Hit,
5294 ) -> Option<SwipeRoute> {
5295 match hit {
5296 Hit::Target(target)
5297 if scene.at_path(&target.path).is_some_and(|node| {
5298 is_text_input(node.kind)
5299 || is_spin_box(node.kind)
5300 || combo_editable(node)
5301 || matches!(
5302 node.kind,
5303 "Slider"
5304 | "ColorPlane"
5305 | "RangeThumb"
5306 | "RangeSlider"
5307 | "Dial"
5308 | "SplitHandle"
5309 | "DelayButton"
5310 | "TableCell"
5311 | "TreeCell"
5312 | "ComboBox"
5313 )
5314 }) =>
5315 {
5316 return None;
5317 }
5318 Hit::Target(_) | Hit::None | Hit::Blocked(_) => {}
5319 _ => return None,
5320 }
5321 let (path, scope_len) =
5322 self.gesture_hit_path(scene, layout, point, "SwipeGestureHandler")?;
5323 let targets = (scope_len..=path.len())
5324 .rev()
5325 .filter_map(|depth| SwipeTarget::new(scene, layout, &path[..depth], point))
5326 .collect::<Vec<_>>();
5327 if !targets.is_empty()
5328 && crate::drag::DragSession::arm(self.drag_context(scene, layout, point), point, None)
5329 .is_some()
5330 {
5331 return None;
5332 }
5333 (!targets.is_empty()).then_some(SwipeRoute::Pending(targets))
5334 }
5335
5336 fn page_swipes(
5337 scene: &Node,
5338 layout: &LayoutNode,
5339 point: Point,
5340 scope: &[usize],
5341 hit: &Hit,
5342 ) -> Vec<PageSwipe> {
5343 let hit_path = match hit {
5344 Hit::Target(target) => &target.path,
5345 Hit::Blocked(path) => path,
5346 _ => return Vec::new(),
5347 };
5348 (scope.len()..=hit_path.len())
5349 .rev()
5350 .filter_map(|depth| {
5351 let path = &hit_path[..depth];
5352 let view = scene.interactive_at_path(path)?;
5353 let item = layout.at_path(path)?;
5354 if view.kind != "SwipeView"
5355 || !view.boolean("interactive", true)
5356 || !item.enabled
5357 || !item.visible
5358 || !(item.contains_subtree_point(point))
5359 {
5360 return None;
5361 }
5362 let current = SwipePagePosition::from_view(view, group_index(view)?)?;
5363 let neighbor = |forward| {
5364 let index = swipe_neighbor(view, current.index, forward)?;
5365 SwipePagePosition::from_view(view, index)
5366 };
5367 let previous = neighbor(false);
5368 let next = neighbor(true);
5369 let orientation = view.orientation();
5370 let extent = match orientation {
5371 Orientation::Horizontal => item.bounds.width,
5372 Orientation::Vertical => item.bounds.height,
5373 };
5374 (previous.is_some() || next.is_some()).then(|| PageSwipe {
5375 target: ScrollTarget {
5376 path: path.to_vec(),
5377 row_key: scene.row_key_at(path),
5378 orientation,
5379 id: ElementId::of(view),
5380 },
5381 current,
5382 previous,
5383 next,
5384 mirrored: swipe_view_mirrored(view, item),
5385 start: item.map_from_window(point).unwrap_or(point),
5386 bounds: item.bounds,
5387 threshold: (extent * 0.15).clamp(24.0, 96.0),
5388 })
5389 })
5390 .collect()
5391 }
5392
5393 fn page_scroll_can_move(
5394 &self,
5395 scene: &Node,
5396 layout: &LayoutNode,
5397 route: &ScrollRoute,
5398 page: &PageSwipe,
5399 forward: bool,
5400 ) -> bool {
5401 let (axis, offsets) = match page.target.orientation {
5402 Orientation::Horizontal => (0, &self.horizontal_scroll_offsets),
5403 Orientation::Vertical => (1, &self.scroll_offsets),
5404 };
5405 let Some(target) = &route.axes[axis] else {
5406 return false;
5407 };
5408 if !target.path.starts_with(&page.target.path) || target.resolve(scene, layout).is_none() {
5409 return false;
5410 }
5411 (page.target.path.len() + 1..=target.path.len()).any(|depth| {
5412 let path = &target.path[..depth];
5413 layout.at_path(path).is_some_and(|item| {
5414 item.scroll_on(target.orientation).is_some_and(|scroll| {
5415 let offset = pending_scroll_offset(item, offsets, path, target.orientation)
5416 .unwrap_or(scroll.offset)
5417 .clamp(0.0, scroll.max_offset);
5418 if forward != item.scroll_axis_reversed(target.orientation) {
5419 offset < scroll.max_offset
5420 } else {
5421 offset > 0.0
5422 }
5423 })
5424 })
5425 })
5426 }
5427
5428 fn drawer_swipe(&self, scene: &Node, layout: &LayoutNode, point: Point) -> Option<DrawerSwipe> {
5429 let active = self.active_dialog(layout);
5430 let viewport = crate::window_safe_area(scene, layout.bounds);
5432 layout
5433 .drawer_paths()
5434 .iter()
5435 .rev()
5436 .filter_map(|path| {
5437 let node = scene.control_target(path, ControlAction::Drawer(true))?;
5438 let open = node.boolean("open", false);
5439 if active != open.then_some(path.as_slice()) {
5440 return None;
5441 }
5442 let panel = modal::drawer_bounds(node, viewport);
5443 let edge = node.drawer_edge();
5444 let region = if open {
5445 layout.at_path(path)?.bounds
5446 } else {
5447 viewport
5448 };
5449 let span = modal::drawer_extent(edge, panel);
5450 let margin = modal::drawer_margin(node, panel);
5451 let activation_edge = if open { modal::opposite(edge) } else { edge };
5452 let distance = modal::drawer_edge_distance(activation_edge, region, point);
5453 (region.contains(point) && distance < margin).then(|| {
5454 (
5455 distance,
5456 DrawerSwipe {
5457 path: path.clone(),
5458 row_key: scene.row_key_at(path),
5459 id: ElementId::of(node),
5460 edge,
5461 open,
5462 start: point,
5463 threshold: (span * 0.2).clamp(20.0, 80.0),
5464 viewport,
5465 panel,
5466 reveal: None,
5467 },
5468 )
5469 })
5470 })
5471 .min_by(|(a, _), (b, _)| a.total_cmp(b))
5472 .map(|(_, swipe)| swipe)
5473 }
5474
5475 fn scroll_route_is_current(
5476 &self,
5477 scene: &Node,
5478 layout: &LayoutNode,
5479 route: &ScrollRoute,
5480 ) -> bool {
5481 (self.active_dialog(layout).unwrap_or_default() == route.scope
5482 || self.popups(layout).any(|path| path == route.scope))
5483 && scene.row_key_at(&route.scope) == route.scope_row
5484 && scene.at_path(&route.scope).and_then(Node::element_id)
5485 == route.scope_id.as_ref().map(ElementId::as_str)
5486 && (!route.mouse_viewport
5487 || route.axes.iter().flatten().any(|target| {
5488 target.resolve(scene, layout).is_some_and(|(_, item)| {
5489 item.accepts_pan(target.orientation, PanDevice::LeftMouse)
5490 })
5491 }))
5492 }
5493
5494 fn scroll_captured(
5495 &mut self,
5496 scene: &Node,
5497 layout: &LayoutNode,
5498 route: &ScrollRoute,
5499 delta: Point,
5500 flicking: bool,
5501 ) -> ([AxisMotion; 2], MotionOwners) {
5502 let mut owners = MotionOwners::new();
5503 if !self.scroll_route_is_current(scene, layout, route) {
5504 return ([AxisMotion::default(); 2], owners);
5505 }
5506 let moved = std::array::from_fn(|index| {
5507 let Some(target) = &route.axes[index] else {
5508 return AxisMotion::default();
5509 };
5510 if flicking && self.overscroll.owns_axis(target.orientation) {
5511 return AxisMotion::default();
5512 }
5513 let Some((_, item)) = target.resolve(scene, layout) else {
5514 return AxisMotion::default();
5515 };
5516 let Some(delta) = item.map_delta_from_window(delta) else {
5517 return AxisMotion::default();
5518 };
5519 let movement = [delta.x, delta.y][index];
5520 if movement == 0.0 {
5521 return AxisMotion::default();
5522 }
5523 let path = &target.path;
5524 self.consume_scroll(
5525 layout,
5526 path,
5527 route.scope.len(),
5528 movement,
5529 target.orientation,
5530 ScrollInput::Pan {
5531 device: route.pan_device,
5532 owners: &mut owners,
5533 flicking,
5534 touch_scene: (!flicking
5535 && route.pan_device == PanDevice::Touch
5536 && movement.abs() >= [delta.y, delta.x][index].abs())
5537 .then_some(scene),
5538 },
5539 )
5540 });
5541 (moved, owners)
5542 }
5543
5544 fn take_drag_overscroll(
5545 &mut self,
5546 layout: &LayoutNode,
5547 axes: &[Option<ScrollTarget>; 2],
5548 scope_len: usize,
5549 device: PanDevice,
5550 ) -> Overscroll {
5551 let mut overscroll = std::mem::take(&mut self.overscroll);
5552 overscroll.clear_refresh();
5553 overscroll.resume_drag(|axis, handle| {
5554 let Some(target) = &axes[usize::from(axis == Orientation::Vertical)] else {
5555 return false;
5556 };
5557 (scope_len..=target.path.len()).rev().any(|depth| {
5558 layout.at_path(&target.path[..depth]).is_some_and(|item| {
5559 item.visible
5560 && item.enabled
5561 && item.accepts_pan(axis, device)
5562 && item.viewport_handle.as_ref() == Some(handle)
5563 && item
5564 .elastic
5565 .is_some_and(|options| options.behavior.allows_overshoot(false))
5566 })
5567 })
5568 });
5569 overscroll
5570 }
5571
5572 pub fn move_scroll_gesture(
5573 &mut self,
5574 scene: &Node,
5575 layout: &LayoutNode,
5576 point: Point,
5577 now: Instant,
5578 ) -> bool {
5579 self.scroll_keyboard_dismissal = false;
5580 if !point.x.is_finite() || !point.y.is_finite() {
5581 return false;
5582 }
5583 let claimed = self.advance_table_touch_hold(scene, layout, now);
5584 let wake = self
5585 .table_row_move
5586 .as_mut()
5587 .filter(|drag| drag.touch)
5588 .map(|drag| &mut drag.scroll_wake)
5589 .or_else(|| {
5590 self.table_drag_selection
5591 .as_mut()
5592 .filter(|drag| drag.scroll_capture)
5593 .map(|drag| &mut drag.scroll_wake)
5594 });
5595 if let Some(wake) = wake {
5596 if self.pointer == Some(point) {
5597 return claimed;
5598 }
5599 self.pointer = Some(point);
5600 wake.get_or_insert(now + SCROLL_FRAME_INTERVAL);
5601 return true;
5602 }
5603 let Some(mut gesture) = self.scroll_gesture.take() else {
5604 return false;
5605 };
5606 if gesture.touch_point.is_some() {
5607 gesture.touch_point = Some(point);
5608 }
5609 if !self.scroll_route_is_current(scene, layout, &gesture.route)
5610 || gesture.popup != (self.menu_open(), self.choice_open())
5611 {
5612 self.viewport_motion.clear();
5613 let cleared = self.overscroll.clear() | self.swipe_page_motion.take().is_some();
5614 self.swipe_events
5615 .extend(gesture.swipe.take().and_then(SwipeRoute::cancel));
5616 self.cancel_touch_delay();
5617 self.cancel_touch_button_hold();
5618 let tumbler_cleared = gesture.tumbler.is_some_and(|mut drag| drag.cancel());
5619 return cleared
5620 || tumbler_cleared
5621 || (gesture.motion.dragging && gesture.tab_move.is_some())
5622 || gesture.switch.is_some_and(|drag| drag.position.is_some())
5623 || gesture
5624 .swipe_delegate
5625 .is_some_and(|drag| drag.has_preview());
5626 }
5627 if gesture.delay_touch
5628 && let Some(hold) = &mut self.delay_hold
5629 && matches!(hold.source, DelaySource::Touch(_))
5630 {
5631 hold.source = DelaySource::Touch(point);
5632 if !layout
5633 .at_path(&hold.target.path)
5634 .is_some_and(|item| item.contains_subtree_point(point))
5635 {
5636 self.cancel_delay();
5637 }
5638 }
5639 if let Some(repeat) = &mut self.button_hold
5640 && matches!(repeat.source, DelaySource::Touch(_))
5641 {
5642 repeat.source = DelaySource::Touch(point);
5643 if repeat.moved_too_far(point)
5644 || !layout
5645 .at_path(&repeat.target.path)
5646 .is_some_and(|item| item.contains_subtree_point(point))
5647 {
5648 self.cancel_touch_button_hold();
5649 }
5650 }
5651 let was_dragging = gesture.motion.dragging;
5652 if gesture.route.mouse_viewport && !was_dragging {
5653 let delta = gesture.motion.delta_to(point);
5654 let [x, y] = gesture.route.axes.each_ref().map(|target| {
5655 let Some(target) = target else {
5656 return 0.0;
5657 };
5658 let Some((_, item)) = target.resolve(scene, layout) else {
5659 return 0.0;
5660 };
5661 if !item.accepts_pan(target.orientation, PanDevice::LeftMouse) {
5662 return 0.0;
5663 }
5664 item.map_delta_from_window(delta)
5665 .map_or(0.0, |local| match target.orientation {
5666 Orientation::Horizontal => local.x,
5667 Orientation::Vertical => local.y,
5668 })
5669 });
5670 if x.hypot(y) < DRAG_THRESHOLD {
5671 self.scroll_gesture = Some(gesture);
5672 return false;
5673 }
5674 }
5675 let elastic_frame = self.overscroll.frame();
5676 let scrolled = gesture.motion.update(point, now).is_some_and(|delta| {
5677 if let Some(pan) = &mut gesture.menu_pan {
5678 return self
5679 .menu
5680 .as_mut()
5681 .is_some_and(|menu| pan.advance(menu, scene, layout, delta.y));
5682 }
5683 if let Some(pan) = &mut gesture.choice_pan {
5684 return self
5685 .choice
5686 .as_mut()
5687 .is_some_and(|popup| pan.advance(popup, scene, layout, delta.y));
5688 }
5689 let table_gesture = gesture.table_gesture.take();
5690 self.finish_button_contact(ButtonContactSource::Gesture, false);
5691 self.cancel_touch_button_hold();
5692 if let Some(hold) = table_gesture.filter(|hold| hold.deadline.is_none())
5693 && let PendingTableAction::Select(mut drag) = hold.drag
5694 {
5695 drag.claimed = true;
5696 drag.touch = true;
5697 drag.scroll_capture = true;
5698 if self.table_drag_route(scene, layout, &drag, point).is_some() {
5699 self.cancel_touch_delay();
5700 self.overscroll.clear();
5701 self.viewport_motion.clear();
5702 self.capture_table_selection(drag);
5703 self.pointer = Some(point);
5704 return self.move_table_drag_selection(layout, now);
5705 }
5706 }
5707 if gesture.route.mouse_viewport && !was_dragging {
5708 let overscroll = self.take_drag_overscroll(
5709 layout,
5710 &gesture.route.axes,
5711 gesture.route.scope.len(),
5712 gesture.route.pan_device,
5713 );
5714 self.cancel_press();
5715 self.overscroll = overscroll;
5716 self.pointer_leave();
5717 }
5718 if gesture.delay_touch {
5719 self.cancel_touch_delay();
5720 }
5721 if let Some(drag) = &mut gesture.tab_move {
5722 if was_dragging || drag.accepts_direction(scene, layout, point) {
5723 return drag.update(scene, layout, point, now);
5724 }
5725 gesture.tab_move = None;
5726 }
5727 if let Some(drag) = &mut gesture.tumbler {
5728 if let Some(local) = layout
5729 .at_path(&drag.target.path)
5730 .and_then(|item| item.map_from_window(point))
5731 && (was_dragging || drag.accepts_direction(local))
5732 {
5733 return drag.update(scene, layout, local);
5734 }
5735 gesture.tumbler = None;
5736 }
5737 if let Some(drag) = &mut gesture.switch {
5738 if was_dragging || drag.accepts_direction(layout, point) {
5739 return drag.move_thumb(scene, layout, point);
5740 }
5741 gesture.switch = None;
5742 }
5743 if !was_dragging && let Some(swipe) = &gesture.drawer {
5744 let (distance, across) = swipe.movement(point);
5745 if distance <= across {
5746 gesture.drawer = None;
5747 }
5748 }
5749 if let Some(swipe) = &mut gesture.drawer {
5750 gesture.swipe_delegate = None;
5751 if swipe
5752 .current(scene, layout, self.active_dialog(layout))
5753 .is_some()
5754 {
5755 return swipe.update(point);
5756 }
5757 return gesture
5758 .drawer
5759 .take()
5760 .is_some_and(|swipe| swipe.reveal.is_some());
5761 }
5762 if !was_dragging
5763 && gesture.swipe_delegate.as_ref().is_some_and(|swipe| {
5764 layout
5765 .at_path(&swipe.target.path)
5766 .and_then(|item| item.map_from_window(point))
5767 .is_none_or(|local| !swipe.accepts_direction(local))
5768 })
5769 {
5770 gesture.swipe_delegate = None;
5771 }
5772 if let Some(swipe) = &mut gesture.swipe_delegate {
5773 return layout
5774 .at_path(&swipe.target.path)
5775 .and_then(|item| item.map_from_window(point))
5776 .is_some_and(|local| swipe.update(scene, layout, local));
5777 }
5778 if self.move_custom_swipe(scene, layout, &mut gesture.swipe, point) {
5779 return false;
5780 }
5781 if !was_dragging {
5782 let selected = gesture.pages.iter().position(|page| {
5783 let Some(local) = layout
5784 .at_path(&page.target.path)
5785 .and_then(|item| item.map_from_window(point))
5786 else {
5787 return false;
5788 };
5789 let (distance, across) = page.movement(local);
5790 let forward = distance > 0.0;
5791 distance.abs() > across
5792 && page.destination(forward).is_some()
5793 && !self.page_scroll_can_move(scene, layout, &gesture.route, page, forward)
5794 });
5795 if let Some(index) = selected {
5796 gesture.pages.swap(0, index);
5797 gesture.pages.truncate(1);
5798 } else {
5799 gesture.pages.clear();
5800 }
5801 }
5802 if let Some(page) = gesture.pages.first() {
5803 return self.update_swipe_page_motion(page, scene, layout, point);
5804 }
5805 let (moved, owners) = self.scroll_captured(scene, layout, &gesture.route, delta, false);
5806 self.scroll_keyboard_dismissal = moved.iter().any(|axis| axis.dismiss_keyboard);
5807 if moved.into_iter().any(AxisMotion::changed) {
5808 self.viewport_motion
5809 .update(owners, ViewportMotion::Dragging);
5810 true
5811 } else {
5812 false
5813 }
5814 });
5815 if !self.scroll_table_selection_claimed() {
5816 self.scroll_gesture = Some(gesture);
5817 }
5818 scrolled || elastic_frame != self.overscroll.frame()
5819 }
5820
5821 #[doc(hidden)]
5823 pub fn take_scroll_keyboard_dismissal(&mut self) -> bool {
5824 std::mem::take(&mut self.scroll_keyboard_dismissal)
5825 }
5826
5827 fn update_swipe_page_motion(
5828 &mut self,
5829 page: &PageSwipe,
5830 scene: &Node,
5831 layout: &LayoutNode,
5832 point: Point,
5833 ) -> bool {
5834 let preview = (|| {
5835 let (view, item) = page.view(scene, layout)?;
5836 let duration = Duration::from_millis(view.int("transition-duration")?.max(0) as u64);
5837 if duration.is_zero() {
5838 return None;
5839 }
5840 let handle = &view.swipe_preview.as_ref()?.handle;
5841 let (distance, _) = page.movement(item.map_from_window(point)?);
5842 let extent = match page.target.orientation {
5843 Orientation::Horizontal => item.bounds.width,
5844 Orientation::Vertical => item.bounds.height,
5845 };
5846 if extent <= 0.0 || distance == 0.0 {
5847 return None;
5848 }
5849 let destination = page.live_destination(view, distance > 0.0)?;
5850 Some((
5851 handle,
5852 destination,
5853 (distance / extent).clamp(-1.0, 1.0),
5854 duration,
5855 ))
5856 })();
5857 let Some((handle, destination, fraction, duration)) = preview else {
5858 return self.swipe_page_motion.take().is_some();
5859 };
5860 if self
5861 .swipe_page_motion
5862 .as_ref()
5863 .is_some_and(|motion| motion.lease.0 != *handle)
5864 {
5865 self.swipe_page_motion = None;
5866 }
5867 let motion = self
5868 .swipe_page_motion
5869 .get_or_insert_with(|| SwipePageMotion {
5870 page: page.clone(),
5871 lease: Rc::new(SwipePreviewLease(handle.clone())),
5872 fraction: 0.0,
5873 duration,
5874 settling: None,
5875 wake: None,
5876 });
5877 let changed = motion.fraction != fraction || motion.settling.is_some();
5878 motion.page = page.clone();
5879 motion.fraction = fraction;
5880 motion.duration = duration;
5881 motion.settling = None;
5882 motion.wake = None;
5883 handle.request(
5884 (page.current.index, page.current.identity.clone()),
5885 (destination.index, destination.identity.clone()),
5886 );
5887 changed
5888 }
5889
5890 #[doc(hidden)]
5891 pub fn swipe_page_motion(&self, path: &[usize]) -> Option<(usize, f32, Orientation)> {
5892 let motion = self.swipe_page_motion.as_ref()?;
5893 (motion.page.target.path == path).then_some(())?;
5894 let to = motion.page.destination(motion.fraction > 0.0)?;
5895 Some((to.index, motion.fraction, motion.page.target.orientation))
5896 }
5897
5898 pub(crate) fn swipe_commit_fraction(&self, path: &[usize], old: &Node, new: &Node) -> f32 {
5899 let Some((page, fraction)) = &self.swipe_commit else {
5900 return 0.0;
5901 };
5902 let Some((slot, _)) = old
5903 .swipe_preview
5904 .as_ref()
5905 .and_then(|preview| preview.page.as_ref())
5906 else {
5907 return 0.0;
5908 };
5909 if page.target.path != path
5910 || group_index(old) != Some(page.current.index)
5911 || !page.current.matches(old)
5912 {
5913 return 0.0;
5914 }
5915 page.destination(*fraction > 0.0)
5916 .filter(|to| to.index == *slot && group_index(new) == Some(to.index) && to.matches(new))
5917 .map_or(0.0, |_| *fraction)
5918 }
5919
5920 fn move_custom_swipe(
5921 &mut self,
5922 scene: &Node,
5923 layout: &LayoutNode,
5924 swipe: &mut Option<SwipeRoute>,
5925 point: Point,
5926 ) -> bool {
5927 if matches!(swipe, Some(SwipeRoute::Pending(_)))
5928 && let Some(SwipeRoute::Pending(targets)) = swipe.take()
5929 {
5930 *swipe = targets
5931 .into_iter()
5932 .find(|target| target.accepts(scene, layout, self, point))
5933 .map(SwipeRoute::Captured);
5934 }
5935 match swipe {
5936 Some(SwipeRoute::Captured(target))
5937 if target.is_live(scene, layout, self) && !target.cancel_requested() =>
5938 {
5939 self.swipe_events.extend(target.update(point));
5940 true
5941 }
5942 Some(SwipeRoute::Captured(_)) => {
5943 self.swipe_events.extend(
5944 swipe
5945 .replace(SwipeRoute::Cancelled)
5946 .and_then(SwipeRoute::cancel),
5947 );
5948 true
5949 }
5950 Some(SwipeRoute::Cancelled) => true,
5951 _ => false,
5952 }
5953 }
5954
5955 pub fn end_scroll_gesture(
5956 &mut self,
5957 scene: &Node,
5958 layout: &LayoutNode,
5959 point: Point,
5960 now: Instant,
5961 ) -> ScrollGestureEnd {
5962 self.cancel_touch_button_hold();
5963 if !point.x.is_finite() || !point.y.is_finite() {
5964 self.cancel_scroll_gesture();
5965 self.cancel_scroll_table_drag();
5966 return ScrollGestureEnd::default();
5967 }
5968 let scrolled = self.move_scroll_gesture(scene, layout, point, now);
5969 if self.scroll_table_drag_claimed() {
5970 let touch = self.touch_table_drag_claimed();
5971 let control = if self.scroll_table_selection_claimed() {
5972 self.finish_table_drag_selection(scene, layout)
5973 } else {
5974 self.finish_table_row_move(scene, layout)
5975 };
5976 if touch {
5977 self.pointer_leave();
5978 }
5979 return ScrollGestureEnd {
5980 control,
5981 ..ScrollGestureEnd::default()
5982 };
5983 }
5984 let Some(gesture) = self.scroll_gesture.take() else {
5985 return ScrollGestureEnd {
5986 scrolled,
5987 ..ScrollGestureEnd::default()
5988 };
5989 };
5990 let inside = !gesture.motion.dragging
5991 && gesture
5992 .tap
5993 .is_some_and(|hit| hit == self.hit_at(scene, layout, point));
5994 self.finish_button_contact(ButtonContactSource::Gesture, inside);
5995 let tap = inside && !gesture.delay_touch;
5996 match gesture.swipe {
5997 Some(SwipeRoute::Captured(target)) => {
5998 self.swipe_events.push(target.delivery(SwipePhase::Swiped));
5999 return ScrollGestureEnd::default();
6000 }
6001 Some(SwipeRoute::Cancelled) => return ScrollGestureEnd::default(),
6002 _ => {}
6003 }
6004 if gesture.delay_touch && !gesture.motion.dragging {
6005 self.cancel_touch_delay();
6006 return ScrollGestureEnd {
6007 tap: false,
6008 scrolled,
6009 control: None,
6010 };
6011 }
6012 if let Some(drag) = gesture.tab_move {
6013 let control = gesture
6014 .motion
6015 .dragging
6016 .then(|| drag.finish(scene, layout))
6017 .flatten();
6018 return ScrollGestureEnd {
6019 tap,
6020 scrolled: scrolled || gesture.motion.dragging,
6021 control,
6022 };
6023 }
6024 if let Some(mut drag) = gesture.tumbler {
6025 if !gesture.motion.dragging {
6026 return ScrollGestureEnd {
6027 tap,
6028 scrolled,
6029 control: None,
6030 };
6031 }
6032 let target = drag.target.clone();
6033 if !self.reduce_motion {
6034 let velocity = gesture.motion.measured_release_velocity(now);
6035 match drag.settle(scene, layout, velocity, now) {
6036 Ok(flick) => {
6037 self.set_focus(Some(target));
6038 self.tumbler_flick = Some(flick);
6039 return ScrollGestureEnd {
6040 scrolled: true,
6041 ..ScrollGestureEnd::default()
6042 };
6043 }
6044 Err(fallback) => drag = fallback,
6045 }
6046 }
6047 let control = drag.finish(scene, layout);
6048 if control.is_some() {
6049 self.set_focus(Some(target));
6050 }
6051 return ScrollGestureEnd {
6052 tap,
6053 scrolled: true,
6054 control,
6055 };
6056 }
6057 if let Some(drag) = gesture.switch {
6058 let control = drag.finish(scene, layout);
6059 if control.is_some() {
6060 self.set_focus(Some(drag.target));
6061 }
6062 return ScrollGestureEnd {
6063 tap,
6064 scrolled: scrolled || drag.position.is_some(),
6065 control,
6066 };
6067 }
6068 if let Some(swipe) = gesture.drawer {
6069 let had_preview = swipe.reveal.is_some();
6070 let control = if gesture.motion.dragging
6071 && swipe
6072 .current(scene, layout, self.active_dialog(layout))
6073 .is_some()
6074 {
6075 swipe.action(point)
6076 } else {
6077 None
6078 };
6079 return ScrollGestureEnd {
6080 tap,
6081 scrolled: scrolled || had_preview,
6082 control,
6083 };
6084 }
6085 if let Some(swipe) = gesture.swipe_delegate {
6086 let control = swipe.finish(scene, layout);
6087 if control.is_some() {
6088 self.set_focus(Some(swipe.target.clone()));
6089 }
6090 return ScrollGestureEnd {
6091 tap,
6092 scrolled: scrolled || swipe.has_preview(),
6093 control,
6094 };
6095 }
6096 if gesture.motion.dragging
6097 && let Some(page) = gesture.pages.into_iter().next()
6098 {
6099 let control = page.action(
6100 scene,
6101 layout,
6102 point,
6103 gesture.motion.measured_release_velocities(now),
6104 );
6105 if control.is_some()
6106 && let Some(motion) = &self.swipe_page_motion
6107 {
6108 self.swipe_commit = Some((motion.page.clone(), motion.fraction));
6109 }
6110 let cleared = self.settle_swipe_page(now);
6111 return ScrollGestureEnd {
6112 tap,
6113 scrolled: scrolled || cleared,
6114 control,
6115 };
6116 }
6117 let transformed = gesture.route.axes.iter().flatten().any(|target| {
6118 layout
6119 .at_path(&target.path)
6120 .is_some_and(|item| item.world_transform() != crate::Affine::IDENTITY)
6121 });
6122 let mut axes = if transformed {
6123 [true, true]
6124 } else {
6125 gesture.route.axes.each_ref().map(|axis| {
6126 axis.as_ref()
6127 .is_some_and(|target| target.resolve(scene, layout).is_some())
6128 })
6129 };
6130 let elastic_axes = [Orientation::Horizontal, Orientation::Vertical]
6131 .map(|axis| self.overscroll.owns_axis(axis));
6132 if gesture.motion.dragging
6133 && gesture.route.pan_device == PanDevice::Touch
6134 && let Some(owner) = self.overscroll.armed_refresh()
6135 {
6136 self.refresh_request = Some(owner.clone());
6137 }
6138 if transformed && elastic_axes.contains(&true) {
6139 axes = [false; 2];
6140 } else {
6141 for (axis, elastic) in axes.iter_mut().zip(elastic_axes) {
6142 *axis &= !elastic;
6143 }
6144 }
6145 let rebounded = self.overscroll.return_to_bounds(now, None);
6146 self.scroll_fling = gesture.motion.finish(now, axes).map(|motion| ScrollFling {
6147 route: gesture.route,
6148 motion,
6149 transformed,
6150 });
6151 if self.scroll_fling.is_some() {
6152 if !transformed {
6153 self.viewport_motion.retain_axes(axes);
6154 }
6155 self.viewport_motion.set_phase(ViewportMotion::Flicking);
6156 } else {
6157 self.viewport_motion.clear();
6158 }
6159 ScrollGestureEnd {
6160 tap,
6161 scrolled: scrolled || rebounded,
6162 control: None,
6163 }
6164 }
6165
6166 pub fn advance_scroll_motion(
6167 &mut self,
6168 scene: &Node,
6169 layout: &LayoutNode,
6170 now: Instant,
6171 ) -> bool {
6172 let rebounded = self.overscroll.advance(now);
6173 let tab_scroll = self.advance_tab_drag_scroll(scene, layout, now);
6174 let swipe_scroll = self
6175 .swipe_page_motion
6176 .as_mut()
6177 .is_some_and(|motion| motion.advance(now));
6178 if swipe_scroll
6179 && self
6180 .swipe_page_motion
6181 .as_ref()
6182 .is_some_and(|motion| motion.wake.is_none())
6183 {
6184 self.swipe_page_motion = None;
6185 self.swipe_commit = None;
6186 }
6187 self.advance_flick(scene, layout, now) || rebounded || tab_scroll || swipe_scroll
6188 }
6189
6190 fn advance_tab_drag_scroll(&mut self, scene: &Node, layout: &LayoutNode, now: Instant) -> bool {
6191 let Some(drag) = self
6192 .scroll_gesture
6193 .as_mut()
6194 .and_then(|gesture| gesture.tab_move.as_mut())
6195 else {
6196 return false;
6197 };
6198 if !drag.wake.is_some_and(|deadline| deadline <= now) {
6199 return false;
6200 }
6201 let Some((axis, offset)) = drag.scroll_target(scene, layout) else {
6202 drag.wake = None;
6203 return false;
6204 };
6205 drag.wake = Some(now + SCROLL_FRAME_INTERVAL);
6206 let offsets = match axis {
6207 Orientation::Horizontal => &mut self.horizontal_scroll_offsets,
6208 Orientation::Vertical => &mut self.scroll_offsets,
6209 };
6210 offsets.insert(drag.path().to_vec(), offset);
6211 true
6212 }
6213
6214 pub fn tab_move_active(&self) -> bool {
6215 self.scroll_gesture
6216 .as_ref()
6217 .is_some_and(|gesture| gesture.motion.dragging && gesture.tab_move.is_some())
6218 }
6219
6220 pub fn tab_move_marker(&self, bar: &Node, item: &LayoutNode, path: &[usize]) -> Option<Rect> {
6221 let gesture = self.scroll_gesture.as_ref()?;
6222 let drag = gesture.tab_move.as_ref()?;
6223 (gesture.motion.dragging && drag.path() == path).then_some(())?;
6224 drag.marker(bar, item)
6225 }
6226
6227 fn advance_flick(&mut self, scene: &Node, layout: &LayoutNode, now: Instant) -> bool {
6228 let Some(mut fling) = self.scroll_fling.take() else {
6229 return false;
6230 };
6231 if !self.scroll_route_is_current(scene, layout, &fling.route)
6232 || self.menu_open()
6233 || self.choice_open()
6234 {
6235 self.viewport_motion.clear();
6236 return false;
6237 }
6238 let Some(delta) = fling.motion.step(now) else {
6239 self.viewport_motion.clear();
6240 return false;
6241 };
6242 if delta == Point::default() {
6243 self.scroll_fling = Some(fling);
6244 return false;
6245 }
6246 let (moved, mut owners) = self.scroll_captured(scene, layout, &fling.route, delta, true);
6247 self.overscroll.return_to_bounds(now, None);
6248 let continuing = moved.map(|axis| axis.bounded && !axis.elastic);
6249 let axes = if fling.transformed {
6250 [continuing.contains(&true) && !moved.iter().any(|axis| axis.elastic); 2]
6251 } else {
6252 continuing
6253 };
6254 if fling.motion.finish_step(axes) {
6255 self.scroll_fling = Some(fling);
6256 owners.retain_mut(|(_, owner_axes)| {
6257 for (owned, active) in owner_axes.iter_mut().zip(continuing) {
6258 *owned &= active;
6259 }
6260 owner_axes.contains(&true)
6261 });
6262 self.viewport_motion
6263 .update(owners, ViewportMotion::Flicking);
6264 } else {
6265 self.viewport_motion.clear();
6266 }
6267 moved.into_iter().any(AxisMotion::changed)
6268 }
6269
6270 fn interrupt_tumbler_flick(&mut self) -> bool {
6271 self.tumbler_flick
6272 .as_mut()
6273 .is_some_and(TumblerFlick::interrupt)
6274 }
6275
6276 fn tumbler_flick_is_current(
6277 &self,
6278 flick: &TumblerFlick,
6279 scene: &Node,
6280 layout: &LayoutNode,
6281 ) -> bool {
6282 !self.menu_open()
6283 && !self.choice_open()
6284 && self
6285 .active_dialog(layout)
6286 .is_none_or(|scope| flick.drag.target.path.starts_with(scope))
6287 && flick.drag.is_current(scene, layout)
6288 }
6289
6290 fn time_picker_flick(
6291 &self,
6292 flick: &TumblerFlick,
6293 scene: &Node,
6294 layout: &LayoutNode,
6295 dialog: &[usize],
6296 ) -> bool {
6297 flick.active()
6298 && self.active_dialog(layout) == Some(dialog)
6299 && flick.drag.target.path.starts_with(dialog)
6300 && scene
6301 .at_path(dialog)
6302 .and_then(Node::picker_session_id)
6303 .is_some_and(|session| flick.drag.picker_session == Some(session))
6304 && self.tumbler_flick_is_current(flick, scene, layout)
6305 }
6306
6307 #[doc(hidden)]
6309 pub fn settle_time_picker_wheel(
6310 &mut self,
6311 scene: &Node,
6312 layout: &LayoutNode,
6313 dialog: &[usize],
6314 ) -> Option<ControlInput> {
6315 if !self
6316 .tumbler_flick
6317 .as_ref()
6318 .is_some_and(|flick| self.time_picker_flick(flick, scene, layout, dialog))
6319 {
6320 return None;
6321 }
6322 self.tumbler_flick.take()?.drag.finish(scene, layout)
6323 }
6324
6325 pub fn advance_tumbler_motion(
6326 &mut self,
6327 scene: &Node,
6328 layout: &LayoutNode,
6329 now: Instant,
6330 ) -> ScrollGestureEnd {
6331 let Some(mut flick) = self.tumbler_flick.take() else {
6332 return ScrollGestureEnd::default();
6333 };
6334 if !flick.active() || !self.tumbler_flick_is_current(&flick, scene, layout) {
6335 flick.interrupt();
6336 return ScrollGestureEnd {
6337 scrolled: true,
6338 ..ScrollGestureEnd::default()
6339 };
6340 }
6341 if now < flick.wake && !self.reduce_motion {
6342 self.tumbler_flick = Some(flick);
6343 return ScrollGestureEnd::default();
6344 }
6345 let control = if self.reduce_motion || flick.advance(now) {
6347 flick.drag.finish(scene, layout)
6348 } else {
6349 self.tumbler_flick = Some(flick);
6350 None
6351 };
6352 ScrollGestureEnd {
6353 scrolled: true,
6354 control,
6355 tap: false,
6356 }
6357 }
6358
6359 pub fn scroll_motion_active(&self) -> bool {
6360 self.scroll_fling.is_some()
6361 || self.overscroll.deadline().is_some()
6362 || self
6363 .swipe_page_motion
6364 .as_ref()
6365 .is_some_and(|motion| motion.wake.is_some())
6366 || self
6367 .tumbler_flick
6368 .as_ref()
6369 .is_some_and(TumblerFlick::active)
6370 }
6371
6372 pub fn scroll_motion_deadline(&self) -> Option<Instant> {
6373 self.scroll_fling
6374 .as_ref()
6375 .map(|fling| fling.motion.deadline())
6376 .into_iter()
6377 .chain(self.overscroll.deadline())
6378 .chain(
6379 self.swipe_page_motion
6380 .as_ref()
6381 .and_then(|motion| motion.wake),
6382 )
6383 .chain(self.tumbler_flick.as_ref().map(|flick| flick.wake))
6384 .chain(
6385 self.scroll_gesture
6386 .as_ref()
6387 .and_then(|gesture| gesture.tab_move.as_ref()?.wake),
6388 )
6389 .min()
6390 }
6391
6392 fn tumbler_drag(&self) -> Option<&TumblerDrag> {
6393 self.scroll_gesture
6394 .as_ref()
6395 .and_then(|gesture| gesture.tumbler.as_ref())
6396 .or_else(|| {
6397 self.tumbler_flick
6398 .as_ref()
6399 .filter(|flick| flick.active())
6400 .map(|flick| &flick.drag)
6401 })
6402 }
6403
6404 pub fn tumbler_preview(&self) -> Option<(&[usize], f32)> {
6405 let drag = self.tumbler_drag()?;
6406 (drag.offset != 0.0).then_some((&drag.target.path, drag.offset))
6407 }
6408
6409 #[doc(hidden)]
6410 pub fn switch_preview(&self) -> Option<(&[usize], Option<RowKey>, f32)> {
6411 let drag = self.scroll_gesture.as_ref()?.switch.as_ref()?;
6412 Some((&drag.target.path, drag.target.row_key, drag.position?))
6413 }
6414
6415 pub fn has_switch_preview(&self) -> bool {
6416 self.switch_preview().is_some()
6417 }
6418
6419 pub(crate) fn contains_switch_preview(&self, path: &[usize]) -> bool {
6420 self.switch_preview()
6421 .is_some_and(|(target, _, _)| target.starts_with(path))
6422 }
6423
6424 pub(crate) fn switch_position(
6425 &self,
6426 node: &Node,
6427 bounds: Rect,
6428 direction: LayoutDirection,
6429 path: &[usize],
6430 row: Option<RowKey>,
6431 ) -> Option<f32> {
6432 let drag = self.scroll_gesture.as_ref()?.switch.as_ref()?;
6433 drag.position
6434 .filter(|_| drag.target.path == path && drag.matches(node, bounds, direction, row))
6435 }
6436
6437 pub fn has_swipe_preview(&self) -> bool {
6438 self.swipe_preview().is_some()
6439 }
6440
6441 #[doc(hidden)]
6442 pub fn drawer_preview(&self) -> Option<(&[usize], f32)> {
6443 let drawer = self.scroll_gesture.as_ref()?.drawer.as_ref()?;
6444 Some((&drawer.path, drawer.reveal?))
6445 }
6446
6447 pub(crate) fn closing_drawer_reveal(
6448 &self,
6449 node: &Node,
6450 path: &[usize],
6451 row: Option<RowKey>,
6452 viewport: Rect,
6453 panel: Rect,
6454 ) -> Option<f32> {
6455 let drawer = self.scroll_gesture.as_ref()?.drawer.as_ref()?;
6456 if drawer.open && drawer.path == path && drawer.matches(node, row, viewport, panel) {
6457 drawer.reveal
6458 } else {
6459 None
6460 }
6461 }
6462
6463 #[doc(hidden)]
6464 pub fn opening_drawer_preview<'a>(
6465 &self,
6466 scene: &'a Node,
6467 layout: &LayoutNode,
6468 ) -> Option<(&'a Node, Rect, f32)> {
6469 let drawer = self.scroll_gesture.as_ref()?.drawer.as_ref()?;
6470 let reveal = drawer
6471 .reveal
6472 .filter(|reveal| *reveal > 0.0 && !drawer.open)?;
6473 let node = drawer.current(scene, layout, self.active_dialog(layout))?;
6474 Some((node, drawer.viewport, reveal))
6475 }
6476
6477 #[doc(hidden)]
6478 pub fn closing_drawer_scrim(&self, scene: &Node, layout: &LayoutNode, path: &[usize]) -> f32 {
6479 self.scroll_gesture
6480 .as_ref()
6481 .and_then(|gesture| gesture.drawer.as_ref())
6482 .filter(|drawer| drawer.open && drawer.path == path)
6483 .filter(|drawer| {
6484 drawer
6485 .current(scene, layout, self.active_dialog(layout))
6486 .is_some()
6487 })
6488 .and_then(|drawer| drawer.reveal)
6489 .unwrap_or(1.0)
6490 }
6491
6492 fn drawer_retains_focus(&self, target: &Target, scene: &Node, layout: &LayoutNode) -> bool {
6493 let Some(drawer) = self
6494 .scroll_gesture
6495 .as_ref()
6496 .and_then(|gesture| gesture.drawer.as_ref())
6497 else {
6498 return false;
6499 };
6500 drawer.open
6501 && drawer.reveal.is_some()
6502 && target.path.starts_with(&drawer.path)
6503 && drawer
6504 .current(scene, layout, self.active_dialog(layout))
6505 .is_some()
6506 && target
6507 .node_in(scene)
6508 .zip(layout.at_path(&target.path))
6509 .is_some_and(|(node, item)| {
6510 target.focusable == focusable(node) && focus_hitbox(node, item).is_some()
6511 })
6512 }
6513
6514 pub fn swipe_preview(&self) -> Option<(&[usize], Option<RowKey>, f32)> {
6515 self.scroll_gesture
6516 .as_ref()
6517 .and_then(|gesture| gesture.swipe_delegate.as_ref())
6518 .and_then(SwipeDrag::preview_state)
6519 }
6520
6521 pub(crate) fn swipe_preview_offset(
6522 &self,
6523 path: &[usize],
6524 node: &Node,
6525 geometry: &crate::SwipeDelegateGeometry,
6526 row: Option<RowKey>,
6527 ) -> Option<f32> {
6528 self.scroll_gesture
6529 .as_ref()?
6530 .swipe_delegate
6531 .as_ref()?
6532 .preview(path, node, geometry, row)
6533 }
6534
6535 pub(crate) fn tumbler_offset(&self, wheel: &Tumbler<'_>, path: &[usize]) -> f32 {
6536 self.tumbler_drag()
6537 .map_or(0.0, |drag| drag.offset_for(wheel, path))
6538 }
6539
6540 pub fn tumbler_scroll(
6541 &mut self,
6542 scene: &Node,
6543 layout: &LayoutNode,
6544 delta: f32,
6545 lines: bool,
6546 ) -> TumblerScroll {
6547 let target = self.pointer_hover_target(scene, layout);
6548 if let Some(target) = target
6549 && let Some(node) = scene
6550 .at_path(&target.path)
6551 .filter(|node| matches!(node.kind, "Tumbler" | "PathView"))
6552 && let Some(wheel) = layout
6553 .at_path(&target.path)
6554 .and_then(|item| item.tumbler.as_ref())
6555 {
6556 if delta.is_finite() && delta != 0.0 {
6557 self.interrupt_tumbler_flick();
6558 }
6559 return crate::tumbler::scroll(
6560 &mut self.tumbler_wheel,
6561 &target,
6562 &Tumbler::from_node(node),
6563 wheel.step_size(),
6564 delta,
6565 lines,
6566 );
6567 }
6568 self.tumbler_wheel = None;
6569 TumblerScroll::Unhandled
6570 }
6571
6572 pub fn reset_wheel_adjustment(&mut self) {
6573 self.wheel_steps = None;
6574 }
6575
6576 pub fn wheel_adjustment(
6577 &mut self,
6578 scene: &Node,
6579 layout: &LayoutNode,
6580 event: xrack_runtime::WheelEvent,
6581 now: Instant,
6582 ) -> Option<WheelAdjustment> {
6583 let previous = self.wheel_steps.take();
6584 let modifiers = event.modifiers;
6585 if modifiers.shift
6586 || modifiers.control
6587 || modifiers.alt
6588 || modifiers.meta
6589 || self.menu_open()
6590 || self.choice_open()
6591 || self.pressed.is_some()
6592 || !event.delta_x.0.is_finite()
6593 || !event.delta_y.0.is_finite()
6594 {
6595 return None;
6596 }
6597 let point = self.pointer?;
6598 let target = self.pointer_hover_target(scene, layout)?;
6599 let (path, node) = slider_target(&target, scene, layout).or_else(|| {
6600 let node = scene.interactive_at_path(&target.path)?;
6601 valid(&target, scene, layout).then_some((target.path.as_slice(), node))
6602 })?;
6603 if !node.boolean("wheel-enabled", false) {
6604 return None;
6605 }
6606 let horizontal = event.delta_x.0.abs() > event.delta_y.0.abs();
6607 let units = match (horizontal, event.is_line) {
6608 (true, true) => event.lines_x,
6609 (false, true) => -event.lines_y,
6610 (true, false) => event.delta_x.0 / 28.0,
6611 (false, false) => -event.delta_y.0 / 28.0,
6612 };
6613 if !units.is_finite() || units == 0.0 {
6614 return None;
6615 }
6616 let interval = (node.kind == "RangeSlider").then(|| SliderInterval::from_node(node));
6617 let handle = if let Some(interval) = interval {
6618 if target.path.len() > path.len() {
6619 Some(*target.path.last()?)
6620 } else {
6621 let item = layout.at_path(path)?;
6622 let geometry =
6623 SliderGeometry::with_layout_direction(item.bounds, node, item.layout_direction);
6624 let point = item.map_from_window(point)?;
6625 Some(geometry.interval_handle_at(point, geometry.fraction_at(point)?, interval))
6626 }
6627 } else {
6628 None
6629 };
6630 let action_for = |steps| {
6631 if is_spin_box(node.kind) {
6632 let action = self.resolve_spin_action(scene, path, SpinAction::Step(steps))?;
6633 if node.kind == "DoubleSpinBox" {
6634 xrack_runtime::decimal_spin_value_after(node, action)?;
6635 } else {
6636 xrack_runtime::spin_value_after(node, action)?;
6637 }
6638 return Some(WheelAdjustment::Spin(ControlInput {
6639 path: path.to_vec(),
6640 action: ControlAction::Spin(action),
6641 }));
6642 }
6643 let action = RangeAction::Step(steps);
6644 let mut path = path.to_vec();
6645 if let Some((interval, handle)) = interval.zip(handle) {
6646 interval.apply(handle, action)?;
6647 path.push(handle);
6648 } else if matches!(node.kind, "Slider" | "Dial") {
6649 SliderRange::from_node(node).apply(action)?;
6650 } else {
6651 return None;
6652 }
6653 Some(WheelAdjustment::Range(RangeInput { path, action }))
6654 };
6655 action_for(units.signum() as i64)?;
6657 let row = scene.row_key_at(path);
6658 let mut total = units;
6659 if let Some(previous) = previous
6660 && previous.path == path
6661 && previous.row == row
6662 && previous.handle == handle
6663 && previous.horizontal == horizontal
6664 && previous.is_line == event.is_line
6665 && previous.remainder.signum() == units.signum()
6666 && now.saturating_duration_since(previous.time) <= Duration::from_millis(300)
6667 {
6668 total += previous.remainder;
6669 }
6670 let steps = total.trunc() as i64;
6671 let adjustment = if steps == 0 {
6672 WheelAdjustment::Pending
6673 } else {
6674 action_for(steps).unwrap_or(WheelAdjustment::Pending)
6675 };
6676 let remainder = total.fract();
6677 self.wheel_steps = (remainder != 0.0).then(|| WheelSteps {
6678 path: path.to_vec(),
6679 row,
6680 handle,
6681 horizontal,
6682 is_line: event.is_line,
6683 remainder,
6684 time: now,
6685 });
6686 Some(adjustment)
6687 }
6688
6689 pub fn tumbler_key(
6690 &mut self,
6691 scene: &Node,
6692 layout: &LayoutNode,
6693 key: NavigationKey,
6694 ) -> Option<ControlInput> {
6695 let target = self.focused.as_ref()?;
6696 if !valid(target, scene, layout) {
6697 return None;
6698 }
6699 let node = scene
6700 .at_path(&target.path)
6701 .filter(|node| matches!(node.kind, "Tumbler" | "PathView"))?;
6702 let wheel = Tumbler::from_node(node);
6703 let geometry = layout.at_path(&target.path)?.tumbler.as_ref()?;
6704 let (axis, reversed) = geometry.navigation_axis();
6705 let index = match key {
6706 NavigationKey::Left if axis == Orientation::Horizontal => {
6707 wheel.step(if reversed { 1 } else { -1 })?
6708 }
6709 NavigationKey::Right if axis == Orientation::Horizontal => {
6710 wheel.step(if reversed { -1 } else { 1 })?
6711 }
6712 NavigationKey::Up => wheel.step(-1)?,
6713 NavigationKey::Down => wheel.step(1)?,
6714 NavigationKey::Home => 0,
6715 NavigationKey::End => wheel.count().checked_sub(1)?,
6716 NavigationKey::PageUp => wheel.step(-(geometry.visible as i64))?,
6717 NavigationKey::PageDown => wheel.step(geometry.visible as i64)?,
6718 _ => return None,
6719 };
6720 let input = ControlInput {
6721 path: target.path.clone(),
6722 action: wheel.select(index)?,
6723 };
6724 self.interrupt_tumbler_flick();
6725 Some(input)
6726 }
6727
6728 #[doc(hidden)]
6729 pub fn set_reduce_motion(&mut self, reduced: bool) {
6730 self.reduce_motion = reduced;
6731 if reduced
6732 && self
6733 .swipe_page_motion
6734 .as_ref()
6735 .is_some_and(|motion| motion.settling.is_some())
6736 {
6737 self.swipe_page_motion = None;
6738 self.swipe_commit = None;
6739 }
6740 }
6741
6742 pub fn reduce_motion(&self) -> bool {
6744 self.reduce_motion
6745 }
6746
6747 pub fn pull_to_refresh_progress(&self, node: &Node) -> Option<f32> {
6749 self.overscroll
6750 .refresh_progress(node.viewport_handle.as_ref()?)
6751 }
6752
6753 fn settle_swipe_page(&mut self, now: Instant) -> bool {
6754 if self.reduce_motion {
6755 self.swipe_commit = None;
6756 return self.swipe_page_motion.take().is_some();
6757 }
6758 if let Some(motion) = &mut self.swipe_page_motion {
6759 motion.settle(now);
6760 }
6761 false
6762 }
6763
6764 pub fn cancel_scroll_gesture(&mut self) {
6765 self.cancel_scroll_gesture_with_wheel(false);
6766 }
6767
6768 #[doc(hidden)]
6770 pub fn cancel_scroll_gesture_for_picker_key(
6771 &mut self,
6772 scene: &Node,
6773 layout: &LayoutNode,
6774 confirming: bool,
6775 ) {
6776 let keep_wheel = self
6777 .tumbler_flick
6778 .as_ref()
6779 .zip(self.active_dialog(layout))
6780 .is_some_and(|(flick, dialog)| {
6781 self.time_picker_flick(flick, scene, layout, dialog)
6782 && (!confirming
6783 || self.focused.as_ref().is_some_and(|target| {
6784 self.dialog_button(scene, layout, target)
6785 .is_some_and(|input| {
6786 input.action == ControlAction::Dialog(DialogRole::Accept)
6787 })
6788 }))
6789 });
6790 self.cancel_scroll_gesture_with_wheel(keep_wheel);
6791 }
6792
6793 fn cancel_scroll_gesture_with_wheel(&mut self, keep_wheel: bool) {
6794 self.scroll_keyboard_dismissal = false;
6795 self.settle_swipe_page(Instant::now());
6796 self.finish_button_contact(ButtonContactSource::Gesture, false);
6797 if let Some(drag) = self
6798 .scroll_gesture
6799 .as_mut()
6800 .and_then(|gesture| gesture.tumbler.as_mut())
6801 {
6802 drag.cancel();
6803 }
6804 if !keep_wheel && let Some(mut flick) = self.tumbler_flick.take() {
6805 flick.interrupt();
6806 }
6807 self.swipe_events.extend(
6808 self.scroll_gesture
6809 .take()
6810 .and_then(|gesture| gesture.swipe)
6811 .and_then(SwipeRoute::cancel),
6812 );
6813 self.scroll_fling = None;
6814 self.viewport_motion.clear();
6815 self.overscroll.clear();
6816 self.cancel_touch_delay();
6817 self.cancel_touch_button_hold();
6818 }
6819
6820 pub fn overscroll_frame(&self) -> crate::OverscrollFrame {
6821 self.overscroll.frame()
6822 }
6823
6824 pub fn has_overscroll(&self) -> bool {
6825 self.overscroll.has_offset()
6826 }
6827
6828 pub(crate) fn visual_overscroll(&self, handle: &ViewportHandle, axis: Orientation) -> f32 {
6829 self.overscroll.visual_offset(handle, axis)
6830 }
6831
6832 pub(crate) fn return_viewport_to_bounds(&mut self, target: &ViewportHandle) -> bool {
6833 self.overscroll
6834 .return_to_bounds(Instant::now(), Some(target))
6835 }
6836
6837 pub(crate) fn cancel_viewport_flick(&mut self, target: &ViewportHandle) -> bool {
6838 if self.viewport_motion.contains(target) && self.scroll_fling.take().is_some() {
6839 self.viewport_motion.clear();
6840 true
6841 } else {
6842 false
6843 }
6844 }
6845
6846 pub fn has_pending_swipe_events(&self) -> bool {
6847 !self.swipe_events.is_empty() || self.scroll_gesture.as_ref().is_some_and(|gesture|
6848 matches!(&gesture.swipe, Some(SwipeRoute::Captured(target)) if target.cancel_requested()))
6849 }
6850
6851 pub fn reconcile_swipe(&mut self, scene: &Node, layout: &LayoutNode) {
6852 let invalid = self.scroll_gesture.as_ref().is_some_and(|gesture| matches!(&gesture.swipe,
6853 Some(SwipeRoute::Captured(target)) if target.cancel_requested() || !target.is_live(scene, layout, self)));
6854 if invalid && let Some(gesture) = &mut self.scroll_gesture {
6855 self.swipe_events.extend(
6856 gesture
6857 .swipe
6858 .replace(SwipeRoute::Cancelled)
6859 .and_then(SwipeRoute::cancel),
6860 );
6861 }
6862 }
6863
6864 pub fn take_swipe_events(&mut self) -> Vec<SwipeDelivery> {
6865 std::mem::take(&mut self.swipe_events)
6866 }
6867
6868 fn begin_delay(
6869 &mut self,
6870 scene: &Node,
6871 layout: &LayoutNode,
6872 target: Target,
6873 source: DelaySource,
6874 now: Instant,
6875 ) -> bool {
6876 let scope = self.active_dialog(layout).unwrap_or_default();
6877 let Some(node) = scene.at_path(&target.path).filter(|node| {
6878 node.kind == "DelayButton"
6879 && !node.boolean("checked", false)
6880 && target.path.starts_with(scope)
6881 && valid(&target, scene, layout)
6882 }) else {
6883 return false;
6884 };
6885 if self.menu_open() || self.choice_open() {
6886 return false;
6887 }
6888 self.delay_hold = Some(DelayHold::new(
6889 target,
6890 source,
6891 scope.to_vec(),
6892 Duration::from_millis(delay_millis(node)),
6893 now,
6894 ));
6895 true
6896 }
6897
6898 pub fn begin_pointer_delay(&mut self, scene: &Node, layout: &LayoutNode, now: Instant) {
6899 if let Some(target) = self.pressed.clone() {
6900 self.pointer_activation_claimed =
6901 self.begin_delay(scene, layout, target, DelaySource::Pointer, now);
6902 }
6903 }
6904
6905 pub fn begin_key_delay(
6906 &mut self,
6907 scene: &Node,
6908 layout: &LayoutNode,
6909 key: ActivationKey,
6910 now: Instant,
6911 ) {
6912 if let Some((pressed, target)) = self.key_pressed.clone()
6913 && pressed == key
6914 && self.begin_delay(scene, layout, target, DelaySource::Key(key), now)
6915 {
6916 self.key_activation_claimed = Some(key);
6917 }
6918 }
6919
6920 fn begin_button_hold(
6921 &mut self,
6922 scene: &Node,
6923 layout: &LayoutNode,
6924 target: Target,
6925 source: DelaySource,
6926 now: Instant,
6927 ) -> bool {
6928 let scope = self.active_dialog(layout).unwrap_or_default();
6929 if !target.path.starts_with(scope)
6930 || !valid(&target, scene, layout)
6931 || self.menu_open()
6932 || self.choice_open()
6933 {
6934 return false;
6935 }
6936 let Some(timing) = target.node_in(scene).and_then(ButtonHoldTiming::from_node) else {
6937 return false;
6938 };
6939 self.button_hold = Some(ButtonHold::new(
6940 target,
6941 source,
6942 scope.to_vec(),
6943 timing,
6944 match source {
6945 DelaySource::Pointer => self.pointer,
6946 DelaySource::Touch(point) => Some(point),
6947 _ => None,
6948 },
6949 now,
6950 ));
6951 true
6952 }
6953
6954 pub fn begin_pointer_button_hold(
6955 &mut self,
6956 scene: &Node,
6957 layout: &LayoutNode,
6958 now: Instant,
6959 ) -> bool {
6960 self.pressed.clone().is_some_and(|target| {
6961 self.begin_button_hold(scene, layout, target, DelaySource::Pointer, now)
6962 })
6963 }
6964
6965 pub fn begin_key_button_hold(
6966 &mut self,
6967 scene: &Node,
6968 layout: &LayoutNode,
6969 key: ActivationKey,
6970 now: Instant,
6971 ) {
6972 if let Some((pressed, target)) = self.key_pressed.clone()
6973 && pressed == key
6974 {
6975 self.begin_button_hold(scene, layout, target, DelaySource::Key(key), now);
6976 }
6977 }
6978
6979 pub fn button_hold_deadline(&self) -> Option<Instant> {
6980 self.button_hold.as_ref().and_then(|hold| hold.deadline)
6981 }
6982
6983 pub fn advance_button_hold(
6984 &mut self,
6985 scene: &Node,
6986 layout: &LayoutNode,
6987 now: Instant,
6988 ) -> Option<(Target, ButtonHoldEvent)> {
6989 let mut repeat = self.button_hold.take()?;
6990 let pointer_matches =
6991 |point| self.target_at(scene, layout, point).as_ref() == Some(&repeat.target);
6992 let pressed = match repeat.source {
6993 DelaySource::Pointer => {
6994 self.pressed.as_ref() == Some(&repeat.target)
6995 && self.pointer.is_some_and(pointer_matches)
6996 }
6997 DelaySource::Key(key) => {
6998 self.focused.as_ref() == Some(&repeat.target)
6999 && self
7000 .key_pressed
7001 .as_ref()
7002 .is_some_and(|(held, target)| *held == key && target == &repeat.target)
7003 }
7004 DelaySource::Touch(point) => {
7005 self.scroll_gesture
7006 .as_ref()
7007 .is_some_and(|gesture| !gesture.motion.dragging)
7008 && pointer_matches(point)
7009 }
7010 DelaySource::Accessibility => false,
7011 };
7012 if !pressed
7013 || self.menu_open()
7014 || self.choice_open()
7015 || self.active_dialog(layout).unwrap_or_default() != repeat.scope
7016 || !valid(&repeat.target, scene, layout)
7017 || repeat
7018 .target
7019 .node_in(scene)
7020 .and_then(ButtonHoldTiming::from_node)
7021 != Some(repeat.timing)
7022 {
7023 return None;
7024 }
7025 let event = repeat.sample(now);
7026 if event.is_some() {
7027 match repeat.source {
7028 DelaySource::Pointer => self.pointer_activation_claimed = true,
7029 DelaySource::Key(key) => self.key_activation_claimed = Some(key),
7030 DelaySource::Touch(_) => {
7031 if let Some(gesture) = &mut self.scroll_gesture {
7032 gesture.delay_touch = true;
7033 }
7034 if repeat.target.focusable
7035 && repeat
7036 .target
7037 .node_in(scene)
7038 .is_some_and(|node| node.boolean("focus-on-click", true))
7039 {
7040 self.set_focus_with_reason(
7041 Some(repeat.target.clone()),
7042 xrack_runtime::FocusReason::PointerClick,
7043 );
7044 }
7045 }
7046 DelaySource::Accessibility => {}
7047 }
7048 }
7049 let delivery = event.map(|event| (repeat.target.clone(), event));
7050 self.button_hold = Some(repeat);
7051 delivery
7052 }
7053
7054 fn cancel_touch_button_hold(&mut self) {
7055 if self
7056 .button_hold
7057 .as_ref()
7058 .is_some_and(|repeat| matches!(repeat.source, DelaySource::Touch(_)))
7059 {
7060 self.button_hold = None;
7061 }
7062 }
7063
7064 fn delay_current(&self, hold: &DelayHold, scene: &Node, layout: &LayoutNode) -> bool {
7065 if self.focused.as_ref() != Some(&hold.target)
7066 || self.menu_open()
7067 || self.choice_open()
7068 || self.active_dialog(layout).unwrap_or_default() != hold.scope
7069 || !valid(&hold.target, scene, layout)
7070 || !scene.at_path(&hold.target.path).is_some_and(|node| {
7071 node.kind == "DelayButton"
7072 && !node.boolean("checked", false)
7073 && Duration::from_millis(delay_millis(node)) == hold.duration
7074 })
7075 {
7076 return false;
7077 }
7078 match hold.source {
7079 DelaySource::Pointer => {
7080 self.pressed.as_ref() == Some(&hold.target)
7081 && self.pointer.is_some_and(|point| {
7082 self.target_at(scene, layout, point).as_ref() == Some(&hold.target)
7083 })
7084 }
7085 DelaySource::Key(key) => self
7086 .key_pressed
7087 .as_ref()
7088 .is_some_and(|(current, target)| *current == key && target == &hold.target),
7089 DelaySource::Touch(point) => {
7090 self.target_at(scene, layout, point).as_ref() == Some(&hold.target)
7091 }
7092 DelaySource::Accessibility => true,
7093 }
7094 }
7095
7096 pub fn advance_delay(
7097 &mut self,
7098 scene: &Node,
7099 layout: &LayoutNode,
7100 now: Instant,
7101 ) -> Option<ControlInput> {
7102 let mut hold = self.delay_hold.take()?;
7103 if !self.delay_current(&hold, scene, layout) {
7104 return None;
7105 }
7106 if hold.sample(now) && !matches!(hold.source, DelaySource::Accessibility) {
7107 return Some(ControlInput {
7108 path: hold.target.path,
7109 action: ControlAction::DelayButton(true),
7110 });
7111 }
7112 self.delay_hold = Some(hold);
7113 None
7114 }
7115
7116 pub fn accessibility_delay_click(
7117 &mut self,
7118 scene: &Node,
7119 layout: &LayoutNode,
7120 target: Target,
7121 now: Instant,
7122 ) -> Option<ControlInput> {
7123 let node = scene
7124 .at_path(&target.path)
7125 .filter(|node| node.kind == "DelayButton")?;
7126 if !valid(&target, scene, layout)
7127 || self.menu_open()
7128 || self.choice_open()
7129 || !target
7130 .path
7131 .starts_with(self.active_dialog(layout).unwrap_or_default())
7132 {
7133 return None;
7134 }
7135 self.accessibility_focus(target.clone());
7136 if node.boolean("checked", false) {
7137 self.cancel_delay();
7138 return Some(ControlInput {
7139 path: target.path,
7140 action: ControlAction::DelayButton(false),
7141 });
7142 }
7143 if let Some(hold) = self.delay_hold.take()
7144 && matches!(hold.source, DelaySource::Accessibility)
7145 && hold.target == target
7146 && self.delay_current(&hold, scene, layout)
7147 {
7148 return (now >= hold.deadline()).then_some(ControlInput {
7149 path: target.path,
7150 action: ControlAction::DelayButton(true),
7151 });
7152 }
7153 self.begin_delay(scene, layout, target, DelaySource::Accessibility, now);
7154 None
7155 }
7156
7157 pub fn cancel_delay(&mut self) -> bool {
7158 self.delay_hold.take().is_some()
7159 }
7160
7161 fn cancel_touch_delay(&mut self) {
7162 if self
7163 .delay_hold
7164 .as_ref()
7165 .is_some_and(|hold| matches!(hold.source, DelaySource::Touch(_)))
7166 {
7167 self.cancel_delay();
7168 }
7169 }
7170
7171 pub fn delay_deadline(&self) -> Option<Instant> {
7172 self.delay_hold
7173 .as_ref()
7174 .filter(|hold| hold.pending())
7175 .map(DelayHold::deadline)
7176 }
7177
7178 pub fn delay_progress(&self, path: &[usize]) -> Option<(f32, bool)> {
7179 let hold = self
7180 .delay_hold
7181 .as_ref()
7182 .filter(|hold| hold.target.path == path)?;
7183 Some((hold.fraction, hold.pending()))
7184 }
7185
7186 pub fn delay_accessibility(&self) -> Option<(&Target, bool)> {
7187 let hold = self
7188 .delay_hold
7189 .as_ref()
7190 .filter(|hold| matches!(hold.source, DelaySource::Accessibility))?;
7191 Some((&hold.target, !hold.pending()))
7192 }
7193
7194 pub fn editor_value<'a>(&'a self, node: &'a Node) -> Cow<'a, str> {
7195 if is_spin_box(node.kind) {
7196 match &self.spin_draft {
7197 Some(draft) => Cow::Borrowed(&draft.text),
7198 None => Cow::Owned(spin_text(node)),
7199 }
7200 } else if matches!(node.kind, "TableCell" | "TreeCell")
7201 && let Some(edit) = &self.table_edit
7202 {
7203 Cow::Borrowed(&edit.draft)
7204 } else {
7205 Cow::Borrowed(text_input_value(node))
7206 }
7207 }
7208
7209 pub fn table_cell_editing(&self, path: &[usize]) -> bool {
7210 self.table_edit
7211 .as_ref()
7212 .is_some_and(|edit| edit.target.path == path)
7213 }
7214
7215 pub fn table_cell_edit_invalid(&self, node: &Node, path: &[usize]) -> bool {
7216 self.table_edit.as_ref().is_some_and(|edit| {
7217 edit.target.path == path
7218 && node
7219 .table_cell_editor
7220 .is_some_and(|editor| !editor.accepts(&edit.draft))
7221 })
7222 }
7223
7224 pub fn is_text_editor(&self, node: &Node, target: &Target) -> bool {
7225 is_text_input(node.kind)
7226 || combo_editable(node)
7227 || node.selectable_styled_text()
7228 || editable_table_cell(node)
7229 && self
7230 .table_edit
7231 .as_ref()
7232 .is_some_and(|edit| &edit.target == target)
7233 }
7234
7235 pub fn table_cell_click(
7236 &mut self,
7237 scene: &Node,
7238 layout: &LayoutNode,
7239 target: Option<&Target>,
7240 now: Instant,
7241 ) -> bool {
7242 let previous = self.last_table_click.take();
7243 let Some(target) =
7244 target.filter(|target| scene.at_path(&target.path).is_some_and(editable_table_cell))
7245 else {
7246 return false;
7247 };
7248 let double_click = previous.is_some_and(|(prior, when)| {
7249 prior == *target && now.saturating_duration_since(when) <= Duration::from_millis(450)
7250 });
7251 let table = table_cell_row(scene, &target.path)
7252 .and_then(|(path, slot)| scene.at_path(path).map(|table| (table, slot)));
7253 let double_enabled =
7254 table.is_none_or(|(table, _)| table.boolean("edit-on-double-click", true));
7255 let start = double_enabled && double_click
7256 || table.is_some_and(|(table, slot)| {
7257 table.boolean("edit-on-click", false)
7258 || table.boolean("edit-on-selected-click", false)
7259 && table
7260 .children
7261 .get(slot)
7262 .and_then(|row| row.row_key)
7263 .is_some_and(|key| {
7264 let column = target.path.last().copied().unwrap_or_default();
7265 table.table_selection.as_ref().map_or_else(
7266 || current_list_slot(table) == Some(slot),
7267 |selection| selection.contains_cell(key, column),
7268 )
7269 })
7270 });
7271 if start {
7272 return self.begin_cell_edit(scene, layout, target.clone(), self.focus_reason);
7273 }
7274 if double_enabled {
7275 self.last_table_click = Some((target.clone(), now));
7276 }
7277 false
7278 }
7279
7280 pub fn begin_table_edit(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
7281 self.begin_focused_cell_edit(scene, layout, "edit-on-key", true)
7282 }
7283
7284 pub fn begin_accessible_table_edit(
7286 &mut self,
7287 scene: &Node,
7288 layout: &LayoutNode,
7289 target: Target,
7290 ) -> bool {
7291 self.table_edit.is_none()
7292 && self
7293 .accessibility_target(scene, layout, &target.path)
7294 .as_ref()
7295 == Some(&target)
7296 && self.begin_cell_edit(
7297 scene,
7298 layout,
7299 target,
7300 xrack_runtime::FocusReason::Accessibility,
7301 )
7302 }
7303
7304 pub fn begin_table_typing(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
7305 self.begin_focused_cell_edit(scene, layout, "edit-on-typing", false)
7306 }
7307
7308 fn begin_focused_cell_edit(
7309 &mut self,
7310 scene: &Node,
7311 layout: &LayoutNode,
7312 property: &str,
7313 default: bool,
7314 ) -> bool {
7315 let Some(target) = self.focused_edit_target(scene, layout) else {
7316 return false;
7317 };
7318 let enabled = table_cell_row(scene, &target.path)
7319 .and_then(|(path, _)| scene.at_path(path))
7320 .map_or(default, |table| table.boolean(property, default));
7321 enabled
7322 && self.begin_cell_edit(
7323 scene,
7324 layout,
7325 target,
7326 xrack_runtime::FocusReason::KeyboardNavigation,
7327 )
7328 }
7329
7330 fn focused_edit_target(&self, scene: &Node, layout: &LayoutNode) -> Option<Target> {
7331 let focused = self.focused.as_ref()?;
7332 let node = scene.interactive_at_path(&focused.path)?;
7333 let mut target = focused.clone();
7334 if matches!(node.kind, "TableView" | "TreeView") {
7335 let slot = current_list_slot(node)?;
7336 let row = node.children.get(slot)?.children.first()?;
7337 target.path.extend([slot, 0]);
7338 let cell = if node.kind == "TreeView" {
7339 layout
7340 .at_path(&target.path)
7341 .and_then(|item| first_editable_tree_cell(row, item, &mut target.path))
7342 } else {
7343 let current_column = node
7344 .table_selection
7345 .as_ref()
7346 .and_then(|view| view.current_column());
7347 let column_index = target.path.len();
7348 target.path.push(0);
7349 row.materialized_children().find_map(|(column, cell)| {
7350 target.path[column_index] = column;
7351 (current_column.is_none_or(|current| current == column)
7352 && editable_table_cell(cell)
7353 && layout
7354 .at_path(&target.path)
7355 .is_some_and(|item| eligible(cell, item)))
7356 .then_some(cell)
7357 })
7358 };
7359 let cell = cell?;
7360 target.set_element_id(ElementId::of(cell));
7361 target.row_key = scene.row_key_at(&target.path);
7362 }
7363 Some(target)
7364 }
7365
7366 fn begin_cell_edit(
7367 &mut self,
7368 scene: &Node,
7369 layout: &LayoutNode,
7370 target: Target,
7371 reason: xrack_runtime::FocusReason,
7372 ) -> bool {
7373 if self
7374 .table_edit
7375 .as_ref()
7376 .is_some_and(|edit| edit.target == target)
7377 {
7378 return false;
7379 }
7380 let Some(cell) = scene.interactive_at_path(&target.path).filter(|cell| {
7381 target.row_key.is_some() && editable_table_cell(cell) && valid(&target, scene, layout)
7382 }) else {
7383 return false;
7384 };
7385 let original = cell.text("text").unwrap_or("").to_owned();
7386 self.set_focus_with_reason(Some(target.clone()), reason);
7387 let mut editor = TextEdit::at_end(&original);
7388 editor.apply(&original, EditAction::SelectAll);
7389 self.editor = Some(editor);
7390 self.table_edit = Some(TableEdit {
7391 target,
7392 draft: original.clone(),
7393 original,
7394 history: TextHistory::default(),
7395 });
7396 true
7397 }
7398
7399 pub fn cancel_table_edit(&mut self) -> bool {
7400 if self.table_edit.take().is_none() {
7401 return false;
7402 }
7403 self.editor = None;
7404 self.last_table_click = None;
7405 true
7406 }
7407
7408 pub fn commit_table_edit(&mut self, component: &mut impl Component, scene: &Node) -> bool {
7409 self.finish_table_edit(component, scene) == TableEditCommit::Changed
7410 }
7411
7412 pub fn finish_table_edit(
7413 &mut self,
7414 component: &mut impl Component,
7415 scene: &Node,
7416 ) -> TableEditCommit {
7417 let Some(edit) = self.table_edit.as_ref() else {
7418 return TableEditCommit::Rejected;
7419 };
7420 if self
7421 .editor
7422 .as_ref()
7423 .is_some_and(|editor| !editor.preedit.is_empty())
7424 {
7425 return TableEditCommit::Kept;
7426 }
7427 let current = scene
7428 .table_cell_commit_target(&edit.target.path, &edit.original)
7429 .filter(|_| scene.row_key_at(&edit.target.path) == edit.target.row_key);
7430 let Some(cell) = current else {
7431 self.cancel_table_edit();
7432 return TableEditCommit::Rejected;
7433 };
7434 let mut unchanged = edit.draft == edit.original;
7435 if !unchanged
7436 && let Some(editor) = cell.table_cell_editor
7437 && editor != xrack_runtime::TableCellEditor::String
7438 {
7439 let Some(draft) = editor.parse(&edit.draft) else {
7440 return TableEditCommit::Kept;
7441 };
7442 unchanged = editor.parse(&edit.original) == Some(draft);
7443 }
7444 let Some(edit) = self.table_edit.take() else {
7445 return TableEditCommit::Rejected;
7446 };
7447 self.editor = None;
7448 self.last_table_click = None;
7449 if unchanged {
7450 TableEditCommit::Unchanged
7451 } else if component.commit_table_cell(scene, &edit.target.path, &edit.original, edit.draft)
7452 {
7453 TableEditCommit::Changed
7454 } else {
7455 TableEditCommit::Rejected
7456 }
7457 }
7458
7459 pub fn tab_edit_origin(&self, scene: &Node) -> Option<TableEditTarget> {
7460 let edit = self.table_edit.as_ref()?;
7461 let (table, slot) = table_cell_row(scene, &edit.target.path)?;
7462 let view = scene.interactive_at_path(table)?;
7463 if !view.boolean("edit-on-tab", false) || self.focused.as_ref() != Some(&edit.target) {
7464 return None;
7465 }
7466 Some(TableEditTarget {
7467 table: table.to_vec(),
7468 viewport: view.viewport_handle.clone()?,
7469 position: TableEditPosition {
7470 row: view.list?.first_row.checked_add(slot)?,
7471 column: *edit.target.path.last()?,
7472 key: view.children.get(slot)?.row_key?,
7473 },
7474 })
7475 }
7476
7477 pub fn next_table_edit_target(
7478 &self,
7479 component: &impl Component,
7480 scene: &Node,
7481 layout: &LayoutNode,
7482 origin: &TableEditTarget,
7483 backward: bool,
7484 ) -> Option<TableEditTarget> {
7485 let view = scene.interactive_at_path(&origin.table)?;
7486 if view.viewport_handle.as_ref() != Some(&origin.viewport)
7487 || !self.allows_popup(layout, &origin.table)
7488 {
7489 return None;
7490 }
7491 let geometry = layout.at_path(&origin.table)?.table.as_ref()?;
7492 let columns: Vec<_> = geometry
7493 .visual_columns()
7494 .filter(|column| geometry.columns[*column].width > 0.0)
7495 .collect();
7496 let position = component.next_table_edit_cell(
7497 scene,
7498 &origin.table,
7499 origin.position,
7500 &columns,
7501 backward,
7502 )?;
7503 Some(TableEditTarget {
7504 table: origin.table.clone(),
7505 viewport: origin.viewport.clone(),
7506 position,
7507 })
7508 }
7509
7510 pub fn begin_table_edit_target(
7511 &mut self,
7512 scene: &Node,
7513 layout: &LayoutNode,
7514 target: &TableEditTarget,
7515 ) -> bool {
7516 let Some(view) = scene.interactive_at_path(&target.table) else {
7517 return false;
7518 };
7519 if view.viewport_handle.as_ref() != Some(&target.viewport)
7520 || !view.boolean("edit-on-tab", false)
7521 || !self.allows_popup(layout, &target.table)
7522 {
7523 return false;
7524 }
7525 let position = target.position;
7526 if view
7527 .list
7528 .and_then(|list| position.row.checked_sub(list.first_row))
7529 .and_then(|slot| view.children.get(slot))
7530 .and_then(|row| row.row_key)
7531 != Some(position.key)
7532 {
7533 return false;
7534 }
7535 let cell = table_cell_target(scene, layout, &target.table, position.row, position.column);
7536 cell.is_some_and(|cell| {
7537 self.begin_cell_edit(
7538 scene,
7539 layout,
7540 cell,
7541 xrack_runtime::FocusReason::KeyboardNavigation,
7542 )
7543 })
7544 }
7545
7546 pub fn sync_editor(&mut self, scene: &Node) {
7547 let target_node = self
7548 .focused
7549 .as_ref()
7550 .and_then(|target| Some((target, target.node_in(scene)?)));
7551 if let Some((target, node)) = target_node
7552 .filter(|(target, node)| self.is_text_editor(node, target) || spin_editable(node))
7553 {
7554 let persistent = node.boolean("persistent-selection", false)
7555 && (is_text_input(node.kind)
7556 || combo_editable(node)
7557 || node.selectable_styled_text());
7558 if persistent {
7559 if let Some(source) = &mut self.persistent_editor {
7560 if !source.matches(node) {
7561 self.editor = None;
7562 if let Some(handle) = &source.handle {
7563 handle.clear_text_state();
7564 }
7565 *source = PersistentEditor::new(target, node);
7566 } else {
7567 source.target.path.clone_from(&target.path);
7568 }
7569 } else {
7570 if self.editor.is_none()
7571 && let Some(index) = self.retained_selections.iter().position(|selection| {
7572 selection.source.same_target(target) && selection.source.matches(node)
7573 })
7574 {
7575 self.editor = Some(self.retained_selections.remove(index).editor);
7576 }
7577 self.persistent_editor = Some(PersistentEditor::new(target, node));
7578 }
7579 } else {
7580 self.persistent_editor = None;
7581 }
7582 if self.editor.is_none() {
7583 self.editor = Some(TextEdit::at_end(&self.editor_value(node)));
7584 }
7585 if let Some(editor) = &mut self.editor
7586 && editor
7587 .password_echo
7588 .as_ref()
7589 .is_some_and(|echo| !echo.matches(node, text_input_value(node)))
7590 {
7591 editor.password_echo = None;
7592 }
7593 if (is_text_input(node.kind) || combo_editable(node))
7594 && let Some(target) = &self.focused
7595 && let Some(history) = self.history.get_mut(&EditorKey::new(scene, target))
7596 {
7597 history.observe(text_input_value(node));
7598 }
7599 } else {
7600 self.persistent_editor = None;
7601 self.editor = None;
7602 self.spin_draft = None;
7603 }
7604 self.reconcile_text_composition(scene);
7605 }
7606
7607 fn retain_editor_selection(&mut self) {
7608 let old = self.editor.take();
7609 let Some(source) = self.persistent_editor.take() else {
7610 return;
7611 };
7612 let Some(editor) = old else { return };
7613 let state = editor.selection_state(&source.text);
7614 if state.collapsed() {
7615 return;
7616 }
7617 let mut saved = TextEdit::default();
7618 saved.restore_selection(&source.text, state);
7619 saved.set_horizontal_drag_scroll(editor.horizontal_drag_scroll());
7620 if let Some(handle) = &source.handle {
7621 let range = saved.selection(&source.text);
7622 let text = if source.password {
7623 ""
7624 } else {
7625 &source.text[range.clone()]
7626 };
7627 handle.publish_text_selection(saved.caret(&source.text), range, text);
7628 handle.publish_text_commands(Default::default());
7629 }
7630 self.retained_selections.push(RetainedSelection {
7631 source,
7632 editor: saved,
7633 });
7634 }
7635
7636 #[doc(hidden)]
7637 pub fn set_editor_window_active(&mut self, active: bool) {
7638 self.editor_window_inactive = !active;
7639 if !active && let Some(editor) = &mut self.editor {
7640 editor.password_echo = None;
7641 }
7642 }
7643
7644 #[doc(hidden)]
7645 pub fn password_echo_deadline(&self) -> Option<Instant> {
7646 Some(self.editor.as_ref()?.password_echo.as_ref()?.deadline)
7647 }
7648
7649 #[doc(hidden)]
7650 pub fn expire_password_echo(&mut self, now: Instant) -> bool {
7651 if let Some(editor) = &mut self.editor
7652 && editor
7653 .password_echo
7654 .as_ref()
7655 .is_some_and(|echo| now >= echo.deadline)
7656 {
7657 editor.password_echo = None;
7658 return true;
7659 }
7660 false
7661 }
7662
7663 #[doc(hidden)]
7664 pub fn editor_active(&self, path: &[usize]) -> bool {
7665 !self.editor_window_inactive && self.is_focused(path)
7666 }
7667
7668 #[doc(hidden)]
7669 pub fn displayed_editor(&self, node: &Node, path: &[usize]) -> Option<&TextEdit> {
7670 if self.is_focused(path) {
7671 return self.editor.as_ref().filter(|_| {
7672 !self.editor_window_inactive
7673 || self
7674 .persistent_editor
7675 .as_ref()
7676 .is_some_and(|source| source.matches(node))
7677 });
7678 }
7679 self.retained_selections.iter().find_map(|selection| {
7680 (selection.source.target.path == path && selection.source.matches(node))
7681 .then_some(&selection.editor)
7682 })
7683 }
7684
7685 pub(crate) fn retained_editor_for<'a>(
7686 &'a self,
7687 scene: &'a Node,
7688 target: &Target,
7689 handle: &FocusHandle,
7690 ) -> Option<(&'a TextEdit, &'a Node)> {
7691 for selection in &self.retained_selections {
7692 let source = &selection.source;
7693 if source.handle.as_ref() == Some(handle)
7694 && source.target.row_key == target.row_key
7695 && let Some(node) = source
7696 .target
7697 .node_in(scene)
7698 .filter(|node| source.matches(node))
7699 {
7700 return Some((&selection.editor, node));
7701 }
7702 }
7703 let source = self.persistent_editor.as_ref()?;
7704 if !self.editor_window_inactive
7705 || !source.same_target(target)
7706 || source.handle.as_ref() != Some(handle)
7707 {
7708 return None;
7709 }
7710 let node = source
7711 .target
7712 .node_in(scene)
7713 .filter(|node| source.matches(node))?;
7714 Some((self.editor.as_ref()?, node))
7715 }
7716
7717 pub fn break_text_edit_group(&mut self) {
7718 self.history.break_group();
7719 if let Some(draft) = &mut self.spin_draft {
7720 draft.history.break_group();
7721 }
7722 if let Some(edit) = &mut self.table_edit {
7723 edit.history.break_group();
7724 }
7725 }
7726
7727 pub fn edit_text(
7728 &mut self,
7729 component: &mut impl Component,
7730 scene: &Node,
7731 action: EditAction<'_>,
7732 source: EditSource,
7733 now: Instant,
7734 ) -> bool {
7735 self.apply_text_edit(scene, action, source, now, |target, text| {
7736 component.edit_at(scene, &target.path, text)
7737 })
7738 }
7739
7740 fn apply_text_edit(
7741 &mut self,
7742 scene: &Node,
7743 action: EditAction<'_>,
7744 source: EditSource,
7745 now: Instant,
7746 commit: impl FnOnce(&Target, String) -> bool,
7747 ) -> bool {
7748 let Some(target) = self.focused.clone() else {
7749 return false;
7750 };
7751 self.apply_text_edit_at(scene, &target, action, source, now, commit)
7752 }
7753
7754 #[doc(hidden)]
7755 pub fn apply_text_replacement(
7756 &mut self,
7757 component: &mut impl Component,
7758 scene: &Node,
7759 layout: &LayoutNode,
7760 handle: &FocusHandle,
7761 replacement: &xrack_runtime::TextReplacement,
7762 now: Instant,
7763 ) -> Option<Target> {
7764 let modal = self.active_dialog(layout).unwrap_or_default();
7765 let target = crate::focus_scope::handle_target(scene, layout, modal, handle, true)?;
7766 let focused = self.focused.as_ref() == Some(&target);
7767 if focused {
7768 if self.editor.as_ref().is_some_and(TextEdit::is_composing) {
7769 return None;
7770 }
7771 self.sync_editor(scene);
7772 }
7773 let action = EditAction::ReplaceRange {
7774 start: replacement.start,
7775 end: replacement.end,
7776 text: &replacement.text,
7777 };
7778 let changed = self.apply_text_edit_at(
7779 scene,
7780 &target,
7781 action,
7782 EditSource::Atomic,
7783 now,
7784 |target, text| component.edit_at(scene, &target.path, text),
7785 );
7786 if changed && !focused {
7787 handle.discard_editor_changes();
7788 }
7789 changed.then_some(target)
7790 }
7791
7792 fn apply_text_edit_at(
7793 &mut self,
7794 scene: &Node,
7795 target: &Target,
7796 action: EditAction<'_>,
7797 source: EditSource,
7798 now: Instant,
7799 commit: impl FnOnce(&Target, String) -> bool,
7800 ) -> bool {
7801 let Some(node) = scene.interactive_at_path(&target.path).filter(|node| {
7802 self.is_text_editor(node, target) && scene.row_key_at(&target.path) == target.row_key
7803 }) else {
7804 return false;
7805 };
7806 if node.text_read_only() && action.changes_text() {
7807 return false;
7808 }
7809
7810 let active = self.focused.as_ref() == Some(target);
7811 let explicit = matches!(action, EditAction::ReplaceRange { .. });
7812 let mut inactive = (!active).then(|| {
7813 self.displayed_editor(node, &target.path)
7814 .cloned()
7815 .unwrap_or_else(|| TextEdit::at_end(text_input_value(node)))
7816 });
7817 let draft = self
7818 .table_edit
7819 .as_mut()
7820 .filter(|edit| &edit.target == target);
7821 let text = draft
7822 .as_ref()
7823 .map_or_else(|| text_input_value(node), |edit| &edit.draft);
7824 let editor = inactive
7825 .as_mut()
7826 .unwrap_or_else(|| self.editor.get_or_insert_with(|| TextEdit::at_end(text)));
7827 editor.password_echo = None;
7828 let previous = editor.clone();
7829 let before = editor.selection_state(text);
7830 let mask = node.text("input-mask").filter(|mask| !mask.is_empty());
7831 let overwrite = node.boolean("overwrite-mode", false)
7832 && matches!(source, EditSource::Keyboard | EditSource::Ime)
7833 && matches!(action, EditAction::Insert(_))
7834 && before.collapsed();
7835 let Some(mut edit) = editor.apply_mode(
7836 text,
7837 action,
7838 is_multiline_text_input(node.kind),
7839 overwrite && mask.is_none(),
7840 ) else {
7841 if explicit {
7842 *editor = previous;
7843 } else if active {
7844 self.break_text_edit_group();
7845 }
7846 return false;
7847 };
7848 if let Some(mask) = mask {
7849 let delete = match action {
7850 EditAction::Backspace | EditAction::BackspaceWord if before.collapsed() => {
7851 Some(xrack_runtime::MaskDelete::Backward)
7852 }
7853 EditAction::Delete | EditAction::DeleteWord if before.collapsed() => {
7854 Some(xrack_runtime::MaskDelete::Forward)
7855 }
7856 _ => None,
7857 };
7858 let range = edit.start..edit.start + edit.removed.len();
7859 let Some(formatted) = xrack_runtime::InputMask::parse(mask).and_then(|mask| {
7860 if overwrite {
7861 mask.overwrite(text, range.start, &edit.inserted)
7862 } else {
7863 mask.edit(text, range, &edit.inserted, delete)
7864 }
7865 }) else {
7866 *editor = previous;
7867 if !explicit {
7868 editor.set_preedit(String::new(), None);
7869 }
7870 return false;
7871 };
7872 editor.place_caret(
7873 &formatted.text,
7874 TextPosition {
7875 offset: formatted.caret,
7876 trailing: !edit.inserted.is_empty(),
7877 },
7878 false,
7879 );
7880 edit = edit.replace_text(text, formatted.text);
7881 }
7882 if edit.text == text {
7883 if explicit {
7884 *editor = previous;
7885 } else if active {
7886 self.break_text_edit_group();
7887 }
7888 return false;
7889 }
7890 if draft.is_none()
7891 && (!node.allows_text_edit(&edit.text) || !commit(target, edit.text.clone()))
7892 {
7893 *editor = previous;
7894 if !explicit {
7895 editor.set_preedit(String::new(), None);
7896 }
7897 return false;
7898 }
7899 let group = Group::for_edit(source, action, before, &edit);
7900 let after = editor.selection_state(&edit.text);
7901 if active
7902 && !self.editor_window_inactive
7903 && source == EditSource::Keyboard
7904 && let EditAction::Insert(typed) = action
7905 {
7906 editor.password_echo = crate::password::PasswordEcho::new(
7907 node,
7908 &edit.text,
7909 typed,
7910 editor.caret(&edit.text),
7911 now,
7912 );
7913 }
7914 let (next, record) = Record::new(edit, before, after);
7915 if active {
7916 self.painted_combo_completion = None;
7917 self.dismissed_combo_draft = None;
7918 if let Some(source) = &mut self.persistent_editor {
7919 source.text.clone_from(&next);
7920 }
7921 if node.kind == "SearchField" {
7922 self.search_query = (!next.is_empty()).then(|| next.clone());
7923 Self::clear_choice(&mut self.choice);
7924 }
7925 }
7926 if let Some(draft) = draft {
7927 draft.history.observe(&draft.draft);
7928 draft.draft = next.clone();
7929 draft.history.push(next, record, group, now);
7930 } else {
7931 let history = self.history.entry(EditorKey::new(scene, target));
7932 history.observe(text);
7933 history.push(next, record, group, now);
7934 }
7935 true
7936 }
7937
7938 pub fn clear_search(
7939 &mut self,
7940 component: &mut impl Component,
7941 scene: &Node,
7942 path: &[usize],
7943 now: Instant,
7944 ) -> bool {
7945 if self
7946 .focused
7947 .as_ref()
7948 .is_none_or(|target| target.path != path)
7949 || scene
7950 .at_path(path)
7951 .is_none_or(|node| node.kind != "SearchField")
7952 {
7953 return false;
7954 }
7955 self.apply_text_edit(
7956 scene,
7957 EditAction::ReplaceAll(""),
7958 EditSource::Atomic,
7959 now,
7960 |target, _| component.control_at(scene, &target.path, ControlAction::ClearSearch),
7961 )
7962 }
7963
7964 pub fn select_search_suggestion(
7965 &mut self,
7966 component: &mut impl Component,
7967 scene: &Node,
7968 index: usize,
7969 now: Instant,
7970 ) -> bool {
7971 let Some(target) = self
7972 .focused
7973 .as_ref()
7974 .filter(|target| scene.row_key_at(&target.path) == target.row_key)
7975 else {
7976 return false;
7977 };
7978 let Some(node) = scene.interactive_at_path(&target.path) else {
7979 return false;
7980 };
7981 let Some(value) = search_suggestion(node, index) else {
7982 return false;
7983 };
7984 let action = ControlAction::Select(index);
7985 let changed = if value == text_input_value(node) {
7986 component.control_at(scene, &target.path, action)
7987 } else {
7988 self.apply_text_edit(
7989 scene,
7990 EditAction::ReplaceAll(value),
7991 EditSource::Atomic,
7992 now,
7993 |target, _| component.control_at(scene, &target.path, action),
7994 )
7995 };
7996 self.dismiss_choice();
7997 changed
7998 }
7999
8000 pub fn replay_text_edit(
8001 &mut self,
8002 component: &mut impl Component,
8003 scene: &Node,
8004 redo: bool,
8005 ) -> bool {
8006 if self.editor.as_ref().is_some_and(TextEdit::is_composing) {
8007 return false;
8008 }
8009 let Some(target) = &self.focused else {
8010 return false;
8011 };
8012 let Some(node) = scene.interactive_at_path(&target.path).filter(|node| {
8013 (self.is_text_editor(node, target) || spin_editable(node))
8014 && !node.text_read_only()
8015 && scene.row_key_at(&target.path) == target.row_key
8016 }) else {
8017 return false;
8018 };
8019 if is_spin_box(node.kind) {
8020 let Some(draft) = self
8021 .spin_draft
8022 .as_mut()
8023 .filter(|draft| draft.mode.is_current(node))
8024 else {
8025 return false;
8026 };
8027 let Some((next, selection)) = draft.history.replay(redo) else {
8028 return false;
8029 };
8030 self.editor
8031 .get_or_insert_with(|| TextEdit::at_end(&draft.text))
8032 .restore_selection(&next, selection);
8033 draft.text = next.clone();
8034 draft.history.commit_replay(next, redo);
8035 return true;
8036 }
8037 if let Some(edit) = self
8038 .table_edit
8039 .as_mut()
8040 .filter(|edit| &edit.target == target)
8041 {
8042 let Some((next, selection)) = edit.history.replay(redo) else {
8043 return false;
8044 };
8045 self.editor
8046 .get_or_insert_with(|| TextEdit::at_end(&edit.draft))
8047 .restore_selection(&next, selection);
8048 edit.draft = next.clone();
8049 edit.history.commit_replay(next, redo);
8050 return true;
8051 }
8052 let text = text_input_value(node);
8053 let Some(history) = self.history.get_mut(&EditorKey::new(scene, target)) else {
8054 return false;
8055 };
8056 history.observe(text);
8057 let Some((next, selection)) = history.replay(redo) else {
8058 return false;
8059 };
8060 if !node.allows_text_edit(&next) || !component.edit_at(scene, &target.path, next.clone()) {
8061 return false;
8062 }
8063 self.editor
8064 .get_or_insert_with(|| TextEdit::at_end(text))
8065 .restore_selection(&next, selection);
8066 if let Some(source) = &mut self.persistent_editor {
8067 source.text.clone_from(&next);
8068 }
8069 if node.kind == "SearchField" {
8070 self.search_query = (!next.is_empty()).then(|| next.clone());
8071 Self::clear_choice(&mut self.choice);
8072 }
8073 history.commit_replay(next, redo);
8074 self.painted_combo_completion = None;
8075 self.dismissed_combo_draft = None;
8076 true
8077 }
8078
8079 pub fn edit_spin(&mut self, node: &Node, action: EditAction<'_>) {
8080 self.edit_spin_from(node, action, EditSource::Keyboard, Instant::now());
8081 }
8082
8083 pub fn edit_spin_from(
8084 &mut self,
8085 node: &Node,
8086 action: EditAction<'_>,
8087 source: EditSource,
8088 now: Instant,
8089 ) {
8090 if !spin_editable(node) {
8091 return;
8092 }
8093 let text = self.editor_value(node).into_owned();
8094 let edit = self.editor.get_or_insert_with(|| TextEdit::at_end(&text));
8095 let previous = edit.clone();
8096 let Some(change) = edit
8097 .apply_mode(&text, action, false, false)
8098 .filter(|change| change.text != text)
8099 else {
8100 self.break_text_edit_group();
8101 return;
8102 };
8103 let mode = self
8104 .spin_draft
8105 .as_ref()
8106 .map_or_else(|| SpinDraftMode::for_node(node), |draft| draft.mode);
8107 if !spin_text_is_valid(&change.text, mode.separator()) {
8108 *edit = previous;
8109 return;
8110 }
8111 let before = previous.selection_state(&text);
8112 let group = Group::for_edit(source, action, before, &change);
8113 let after = edit.selection_state(&change.text);
8114 let (next, record) = Record::new(change, before, after);
8115 let draft = self.spin_draft.get_or_insert_with(|| SpinDraft {
8116 text: text.clone(),
8117 mode,
8118 history: TextHistory::default(),
8119 });
8120 draft.history.observe(&text);
8121 draft.text = next.clone();
8122 draft.history.push(next, record, group, now);
8123 }
8124
8125 pub fn discard_spin_draft(&mut self) {
8126 self.spin_draft = None;
8127 self.editor = None;
8128 }
8129
8130 pub fn commit_spin_draft(&mut self) -> Option<ControlInput> {
8131 let draft = self.spin_draft.take()?;
8132 self.editor = None;
8133 let path = self.focused.as_ref()?.path.clone();
8134 let action = draft.mode.commit(&draft.text)?;
8135 Some(ControlInput {
8136 path,
8137 action: ControlAction::Spin(action),
8138 })
8139 }
8140
8141 #[doc(hidden)]
8143 pub fn resolve_spin_action(
8144 &self,
8145 scene: &Node,
8146 path: &[usize],
8147 action: SpinAction,
8148 ) -> Option<SpinAction> {
8149 let steps = match action {
8150 SpinAction::Increase => 1,
8151 SpinAction::Decrease => -1,
8152 SpinAction::Step(steps) => steps,
8153 _ => return Some(action),
8154 };
8155 let Some(target) = self.focused.as_ref().filter(|target| target.path == path) else {
8156 return Some(action);
8157 };
8158 let node = target.node_in(scene)?;
8159 if self.editor.as_ref().is_some_and(TextEdit::is_composing) {
8160 return None;
8161 }
8162 let commit = self
8163 .spin_draft
8164 .as_ref()
8165 .filter(|draft| draft.mode.is_current(node))
8166 .and_then(|draft| draft.mode.commit(&draft.text));
8167 Some(match commit {
8168 Some(SpinAction::Commit(draft)) => SpinAction::StepFromIntegerDraft {
8169 original: None,
8170 draft,
8171 steps,
8172 },
8173 Some(SpinAction::CommitIfCurrent { original, value }) => {
8174 SpinAction::StepFromIntegerDraft {
8175 original: Some(original),
8176 draft: value,
8177 steps,
8178 }
8179 }
8180 Some(SpinAction::CommitDecimalIfCurrent { original, value }) => {
8181 SpinAction::StepFromDecimalDraft {
8182 original,
8183 draft: value,
8184 steps,
8185 }
8186 }
8187 _ => action,
8188 })
8189 }
8190
8191 pub fn spin_press(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
8192 self.spin_pressed = (|| {
8193 let target = self.pressed.as_ref()?;
8194 let node = scene.at_path(&target.path)?;
8195 if !valid(target, scene, layout) || !is_spin_box(node.kind) {
8196 return None;
8197 }
8198 let item = layout.at_path(&target.path)?;
8199 SpinGeometry::for_layout(item, node).action_at(item.map_from_window(self.pointer?)?)
8200 })();
8201 self.spin_pressed.is_some()
8202 }
8203
8204 pub fn spin_release(&mut self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
8205 let pressed = self.spin_pressed.take()?;
8206 let target = self.pointer_release_target()?;
8207 let node = scene.at_path(&target.path)?;
8208 if !valid(&target, scene, layout) || !is_spin_box(node.kind) {
8209 return None;
8210 }
8211 let item = layout.at_path(&target.path)?;
8212 let action =
8213 SpinGeometry::for_layout(item, node).action_at(item.map_from_window(self.pointer?)?)?;
8214 (action == pressed).then_some(ControlInput {
8215 path: target.path,
8216 action: ControlAction::Spin(action),
8217 })
8218 }
8219
8220 pub fn combo_completion(&self, node: &Node, path: &[usize]) -> Option<ComboCompletion> {
8221 let target = self
8222 .focused
8223 .as_ref()
8224 .filter(|target| target.path == path && target.matches_node(node))?;
8225 if !combo_editable(node)
8226 || node.is_password()
8227 || !node.boolean("auto-complete", false)
8228 || self.choice_open()
8229 || self.menu_open()
8230 || self
8231 .transitioning_stacks
8232 .iter()
8233 .any(|stack| path.starts_with(stack))
8234 {
8235 return None;
8236 }
8237 let draft = text_input_value(node);
8238 let editor = self.editor.as_ref()?;
8239 if !editor.preedit.is_empty()
8240 || editor.caret(draft) != draft.len()
8241 || !editor.selection(draft).is_empty()
8242 || self.dismissed_combo_draft.as_deref() == Some(draft)
8243 {
8244 return None;
8245 }
8246 let value = crate::choice::completion_value(node, draft)?;
8247 Some(ComboCompletion {
8248 target: target.clone(),
8249 value: value.into_owned(),
8250 draft_len: draft.len(),
8251 })
8252 }
8253
8254 pub fn set_painted_combo_completion(&mut self, completion: Option<ComboCompletion>) {
8255 self.painted_combo_completion = completion;
8256 }
8257
8258 pub fn painted_combo_completion_for(
8259 &self,
8260 node: &Node,
8261 path: &[usize],
8262 ) -> Option<&ComboCompletion> {
8263 let painted = self.painted_combo_completion.as_ref()?;
8264 (self.combo_completion(node, path).as_ref() == Some(painted)).then_some(painted)
8265 }
8266
8267 pub fn combo_completion_accepts(&self, key: NavigationKey) -> bool {
8268 matches!(key, NavigationKey::Left | NavigationKey::Right)
8269 && self
8270 .painted_combo_completion
8271 .as_ref()
8272 .is_some_and(|completion| {
8273 (key == NavigationKey::Left) == completion.continues_left()
8274 })
8275 }
8276
8277 fn take_current_combo_completion(&mut self, scene: &Node) -> Option<ComboCompletion> {
8278 let painted = self.painted_combo_completion.take()?;
8279 let path = &painted.target.path;
8280 let node = scene.interactive_at_path(path)?;
8281 if !painted.target.matches_node(node) || scene.row_key_at(path) != painted.target.row_key {
8282 return None;
8283 }
8284 (self.combo_completion(node, path)? == painted).then_some(painted)
8285 }
8286
8287 pub fn accept_combo_completion(
8288 &mut self,
8289 component: &mut impl Component,
8290 scene: &Node,
8291 now: Instant,
8292 ) -> bool {
8293 let Some(completion) = self.take_current_combo_completion(scene) else {
8294 return false;
8295 };
8296 self.edit_text(
8297 component,
8298 scene,
8299 EditAction::Insert(completion.suffix()),
8300 EditSource::Atomic,
8301 now,
8302 )
8303 }
8304
8305 pub fn dismiss_combo_completion(&mut self, scene: &Node) -> bool {
8306 let Some(completion) = self.take_current_combo_completion(scene) else {
8307 return false;
8308 };
8309 self.dismissed_combo_draft = Some(completion.value[..completion.draft_len].to_owned());
8310 true
8311 }
8312
8313 pub fn open_choice(&mut self, scene: &Node, layout: &LayoutNode, target: Target) -> bool {
8314 if scene.at_path(&target.path).is_some_and(combo_editable)
8315 && self
8316 .editor
8317 .as_ref()
8318 .is_some_and(|edit| !edit.preedit.is_empty())
8319 {
8320 return false;
8321 }
8322 let Some(mut popup) = ChoicePopup::open(target.clone(), scene, layout) else {
8323 return false;
8324 };
8325 self.set_focus(Some(target));
8326 self.cancel_shortcut_sequence();
8327 Self::clear_choice(&mut self.choice);
8328 popup.mounted(scene);
8329 self.choice = Some(popup);
8330 self.choice_typeahead = Typeahead::default();
8331 self.pressed = None;
8332 self.pressed_radio = None;
8333 self.hovered = None;
8334 self.set_split_hover(None);
8335 self.hovered_radio = None;
8336 true
8337 }
8338
8339 pub fn open_choice_at_pointer(
8340 &mut self,
8341 scene: &Node,
8342 layout: &LayoutNode,
8343 target: Target,
8344 ) -> bool {
8345 let origin = self.press_origin.take();
8346 let Some(node) = scene
8347 .at_path(&target.path)
8348 .filter(|node| node.kind == "ComboBox")
8349 else {
8350 return false;
8351 };
8352 if combo_editable(node) {
8353 let Some(item) = layout.at_path(&target.path) else {
8354 return false;
8355 };
8356 let trigger =
8357 ComboGeometry::for_control(node, item.bounds, item.layout_direction).trigger;
8358 if !origin.zip(self.pointer).is_some_and(|(start, end)| {
8359 [start, end].into_iter().all(|point| {
8360 item.map_from_window(point)
8361 .is_some_and(|point| trigger.contains(point))
8362 })
8363 }) {
8364 return false;
8365 }
8366 }
8367 self.open_choice(scene, layout, target)
8368 }
8369
8370 pub fn choice_open(&self) -> bool {
8371 self.choice.is_some()
8372 }
8373
8374 pub fn choice_is_open_for(&self, path: &[usize]) -> bool {
8375 self.choice
8376 .as_ref()
8377 .is_some_and(|popup| popup.target.path == path)
8378 }
8379
8380 #[doc(hidden)]
8381 pub fn choice_artwork_dirty(&self, scene: &Node, layout: &LayoutNode) -> bool {
8382 self.choice
8383 .as_ref()
8384 .is_some_and(|popup| popup.artwork_dirty(scene, layout))
8385 }
8386
8387 pub fn dismiss_choice(&mut self) {
8388 Self::clear_choice(&mut self.choice);
8389 self.search_query = None;
8390 self.choice_typeahead = Typeahead::default();
8391 }
8392
8393 fn clear_choice(choice: &mut Option<ChoicePopup>) {
8394 if let Some(popup) = choice.take() {
8395 popup.closed();
8396 }
8397 }
8398
8399 fn reconcile_search_choice(&mut self, scene: &Node, layout: &LayoutNode) {
8400 let Some(query) = &self.search_query else {
8401 return;
8402 };
8403 let Some(target) = self
8404 .focused
8405 .as_ref()
8406 .filter(|target| valid(target, scene, layout))
8407 else {
8408 self.dismiss_choice();
8409 return;
8410 };
8411 if !scene
8412 .at_path(&target.path)
8413 .is_some_and(|node| node.kind == "SearchField" && text_input_value(node) == query)
8414 || self.menu_open()
8415 || !target
8416 .path
8417 .starts_with(self.active_dialog(layout).unwrap_or_default())
8418 {
8419 self.dismiss_choice();
8420 return;
8421 }
8422 if self.choice.is_none() {
8423 self.choice = ChoicePopup::open(target.clone(), scene, layout);
8424 }
8425 }
8426
8427 pub fn choice_menu<'a>(&self, scene: &'a Node, layout: &LayoutNode) -> Option<ChoiceMenu<'a>> {
8428 self.choice.as_ref()?.view(scene, layout)
8429 }
8430
8431 pub fn choice_press(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
8432 let Some(popup) = &mut self.choice else {
8433 return false;
8434 };
8435 if let Some(point) = self.pointer {
8436 if popup.press(scene, layout, point) {
8437 return true;
8438 }
8439 let within_search = scene
8440 .at_path(&popup.target.path)
8441 .is_some_and(|node| node.kind == "SearchField")
8442 && layout
8443 .at_path(&popup.target.path)
8444 .is_some_and(|item| item.contains_subtree_point(point));
8445 self.dismiss_choice();
8446 if within_search {
8447 self.pointer_move(scene, layout, point);
8448 return false;
8449 }
8450 } else {
8451 self.dismiss_choice();
8452 }
8453 true
8454 }
8455
8456 pub fn choice_release(&mut self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
8457 let popup = self.choice.as_mut()?;
8458 let index = popup.release(scene, layout, self.pointer?)?;
8459 let path = popup.target.path.clone();
8460 self.dismiss_choice();
8461 if scene.at_path(&path).is_some_and(combo_editable) {
8462 self.editor = None;
8463 }
8464 Some(ControlInput {
8465 path,
8466 action: ControlAction::Select(index),
8467 })
8468 }
8469
8470 pub fn choice_scroll(&mut self, scene: &Node, layout: &LayoutNode, rows: isize) -> bool {
8471 if let Some(popup) = &mut self.choice {
8472 popup.scroll(scene, layout, rows);
8473 true
8474 } else {
8475 false
8476 }
8477 }
8478
8479 #[doc(hidden)]
8480 pub fn choice_page(&mut self, scene: &Node, layout: &LayoutNode, backward: bool) -> bool {
8481 let Some(popup) = &mut self.choice else {
8482 return false;
8483 };
8484 let Some(menu) = popup
8485 .view(scene, layout)
8486 .filter(|menu| menu.can_scroll(backward))
8487 else {
8488 return false;
8489 };
8490 let page = menu.rows.len() as isize;
8491 popup.scroll(scene, layout, if backward { -page } else { page })
8492 }
8493
8494 pub fn choice_key(
8495 &mut self,
8496 scene: &Node,
8497 layout: &LayoutNode,
8498 key: ChoiceKey,
8499 ) -> Option<ControlInput> {
8500 self.choice_typeahead = Typeahead::default();
8501 if let Some(popup) = &mut self.choice {
8502 return match key {
8503 ChoiceKey::Escape | ChoiceKey::Open => {
8504 self.dismiss_choice();
8505 None
8506 }
8507 ChoiceKey::Accept => {
8508 let path = popup.target.path.clone();
8509 let action = if let Some(index) = popup.selected(scene, layout) {
8510 ControlAction::Select(index)
8511 } else if scene
8512 .at_path(&path)
8513 .is_some_and(|node| node.kind == "SearchField")
8514 {
8515 ControlAction::SubmitSearch
8516 } else {
8517 return None;
8518 };
8519 self.dismiss_choice();
8520 if scene.at_path(&path).is_some_and(combo_editable) {
8521 self.editor = None;
8522 }
8523 Some(ControlInput { path, action })
8524 }
8525 _ => {
8526 popup.move_highlight(scene, layout, key);
8527 None
8528 }
8529 };
8530 }
8531 let target = self.focused.as_ref()?;
8532 if !valid(target, scene, layout) {
8533 return None;
8534 }
8535 let node = scene.at_path(&target.path)?;
8536 if node.kind == "SearchField" {
8537 return match key {
8538 ChoiceKey::Accept => {
8539 let path = target.path.clone();
8540 self.dismiss_choice();
8541 Some(ControlInput {
8542 path,
8543 action: ControlAction::SubmitSearch,
8544 })
8545 }
8546 ChoiceKey::Open | ChoiceKey::Down | ChoiceKey::Up => {
8547 let text = text_input_value(node);
8548 self.search_query = (!text.is_empty()).then(|| text.to_owned());
8549 self.reconcile_search_choice(scene, layout);
8550 if let Some(popup) = &mut self.choice {
8551 popup.move_highlight(scene, layout, key);
8552 }
8553 None
8554 }
8555 ChoiceKey::Escape => {
8556 self.dismiss_choice();
8557 None
8558 }
8559 _ => None,
8560 };
8561 }
8562 if node.kind != "ComboBox" {
8563 return None;
8564 }
8565 if key == ChoiceKey::Open
8566 || combo_editable(node) && matches!(key, ChoiceKey::Up | ChoiceKey::Down)
8567 {
8568 self.open_choice(scene, layout, target.clone());
8569 return None;
8570 }
8571 if combo_editable(node) {
8572 return (key == ChoiceKey::Accept
8573 && self
8574 .editor
8575 .as_ref()
8576 .is_none_or(|edit| edit.preedit.is_empty()))
8577 .then(|| ControlInput {
8578 path: target.path.clone(),
8579 action: ControlAction::AcceptComboText,
8580 });
8581 }
8582 let current = combo_index(node);
8583 let index = next_choice(node, current, key, CHOICE_PAGE)?;
8584 (current != Some(index)).then(|| ControlInput {
8585 path: target.path.clone(),
8586 action: ControlAction::Select(index),
8587 })
8588 }
8589
8590 pub fn choice_typeahead(
8591 &mut self,
8592 scene: &Node,
8593 layout: &LayoutNode,
8594 text: &str,
8595 now: Instant,
8596 ) -> Option<ControlInput> {
8597 let target = self
8598 .focused
8599 .as_ref()
8600 .filter(|target| valid(target, scene, layout))?;
8601 let node = scene.at_path(&target.path)?;
8602 if node.kind != "ComboBox" || combo_editable(node) {
8603 return None;
8604 }
8605 if let Some(popup) = &mut self.choice {
8606 popup.typeahead(scene, layout, &mut self.choice_typeahead, text, now);
8607 return None;
8608 }
8609 let current = combo_index(node);
8610 let index = self.choice_typeahead.find(node, text, now, current)?;
8611 (current != Some(index)).then(|| ControlInput {
8612 path: target.path.clone(),
8613 action: ControlAction::Select(index),
8614 })
8615 }
8616
8617 fn typeahead_view<'a>(&self, scene: &Node, focus: &'a Target) -> &'a [usize] {
8618 list_item_delegate_row(scene, &focus.path).map_or(focus.path.as_slice(), |(view, _)| view)
8619 }
8620
8621 pub fn list_typeahead_focus(&self, scene: &Node) -> Option<&Target> {
8622 if self.editor.is_some() || self.menu_open() || self.choice_open() {
8623 return None;
8624 }
8625 let focus = self.focused.as_ref()?;
8626 let view = self.typeahead_view(scene, focus);
8627 scene.interactive_at_path(view)?.list_text_search.as_ref()?;
8628 Some(focus)
8629 }
8630
8631 pub fn list_typeahead_ime_area(&self, scene: &Node, layout: &LayoutNode) -> Option<Rect> {
8632 let focus = self
8633 .list_typeahead_focus(scene)
8634 .filter(|focus| valid(focus, scene, layout))?;
8635 let item = layout.at_path(self.typeahead_view(scene, focus))?;
8636 let bounds = item.visible_window_bounds(item.bounds);
8637 (bounds.width > 0.0 && bounds.height > 0.0).then(|| {
8638 let offset = if item.layout_direction == LayoutDirection::RightToLeft {
8639 (bounds.width - 6.0).max(0.0)
8640 } else {
8641 6.0_f32.min(bounds.width)
8642 };
8643 Rect::new(bounds.x + offset, bounds.y, 1.0, bounds.height.min(28.0))
8644 })
8645 }
8646
8647 pub fn reset_list_typeahead(&mut self) {
8648 self.list_typeahead = Typeahead::default();
8649 }
8650
8651 pub fn list_typeahead(
8652 &mut self,
8653 scene: &Node,
8654 layout: &LayoutNode,
8655 text: &str,
8656 now: Instant,
8657 ) -> Option<ControlInput> {
8658 if text.trim().is_empty() {
8659 return None;
8660 }
8661 let focus = self
8662 .list_typeahead_focus(scene)
8663 .filter(|focus| valid(focus, scene, layout))?;
8664 let path = self.typeahead_view(scene, focus).to_vec();
8665 let from_delegate = focus.path != path;
8666 let node = scene.interactive_at_path(&path)?;
8667 let search = node.list_text_search.as_ref()?;
8668 let item = layout.at_path(&path)?;
8669 let current = ListMetrics::selection(node)
8670 .and_then(|index| usize::try_from(index).ok())
8671 .filter(|&index| node.list.is_some_and(|list| index < list.row_count));
8672 let index = self
8673 .list_typeahead
8674 .find_with(text, now, current, |start, prefix| {
8675 search.find(start, |label| matches_prefix(label, prefix))
8676 })?;
8677 self.reveal_row(&path, node, item, index);
8678 if from_delegate {
8679 let saved = std::mem::take(&mut self.list_typeahead);
8680 self.set_focus(Some(Target::from_node(
8681 path.clone(),
8682 node,
8683 true,
8684 scene.row_key_at(&path),
8685 )));
8686 self.list_typeahead = saved;
8687 }
8688 Some(ControlInput {
8689 path,
8690 action: ControlAction::Select(index),
8691 })
8692 }
8693
8694 pub fn pointer_move(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> bool {
8695 if self.pointer != Some(point) {
8696 self.tooltip.source = TooltipSource::Pointer;
8697 }
8698 if self.editor_press.as_ref().is_some_and(|press| {
8699 let start = press.sample.0;
8700 (point.x - start.x).hypot(point.y - start.y)
8701 > crate::pointer_events::PRESS_AND_HOLD_SLOP
8702 }) {
8703 self.editor_press = None;
8704 }
8705 if let Some((start, target)) = self.press_origin.zip(self.pressed.as_ref())
8706 && target.text_link_index().is_some()
8707 && target
8708 .node_in(scene)
8709 .is_some_and(Node::selectable_styled_text)
8710 && (point.x - start.x).hypot(point.y - start.y)
8711 > crate::pointer_events::PRESS_AND_HOLD_SLOP
8712 {
8713 self.pointer_activation_claimed = true;
8714 }
8715 self.pointer = Some(point);
8716 if self.wheel_steps.as_ref().is_some_and(|steps| {
8717 self.pointer_hover_target(scene, layout)
8718 .is_none_or(|target| {
8719 !target.path.starts_with(&steps.path) || target.row_key != steps.row
8720 })
8721 }) {
8722 self.reset_wheel_adjustment();
8723 }
8724 let hit = self.hit_at(scene, layout, point);
8725 let cancelled_delay = self.delay_hold.as_ref().is_some_and(|hold| {
8726 matches!(hold.source, DelaySource::Pointer)
8727 && !matches!(&hit, Hit::Target(target) if *target == hold.target)
8728 });
8729 if cancelled_delay {
8730 self.cancel_delay();
8731 }
8732 if self.button_hold.as_ref().is_some_and(|repeat| {
8733 matches!(repeat.source, DelaySource::Pointer)
8734 && (repeat.moved_too_far(point)
8735 || !matches!(&hit, Hit::Target(target) if *target == repeat.target))
8736 }) {
8737 self.button_hold = None;
8738 }
8739 self.pointer_on_stack_slide = matches!(hit, Hit::StackSlide);
8740 if self.menu.is_some() || self.choice.is_some() {
8741 self.set_split_hover(None);
8742 }
8743 if let Some(popup) = &mut self.menu {
8744 return popup.hover(scene, layout, point);
8745 }
8746 if let Some(popup) = &mut self.choice {
8747 return popup.hover(scene, layout, point);
8748 }
8749 let (next, scroll_bar, control_part, row_grip) = match hit {
8750 Hit::Target(target) => (Some(target), None, None, None),
8751 Hit::ScrollBar(target) => (None, Some(target), None, None),
8752 Hit::ControlPart(target, action) => (Some(target), None, Some(action), None),
8753 Hit::TableRowGrip(target, slot) => {
8754 let grip = scene
8755 .at_path(&target.path)
8756 .zip(layout.at_path(&target.path))
8757 .and_then(|(node, item)| {
8758 Some((
8759 node.children.get(slot)?.row_key?,
8760 item.children.get(slot)?.bounds.height,
8761 ))
8762 });
8763 (Some(target), None, None, grip)
8764 }
8765 _ => (None, None, None, None),
8766 };
8767 let radio = next
8768 .as_ref()
8769 .and_then(|target| scene.at_path(&target.path))
8770 .filter(|node| node.kind == "RadioButton")
8771 .map(|node| (node.text("text").unwrap_or(""), radio_value(node)));
8772 let previous_radio = self
8773 .hovered_radio
8774 .as_ref()
8775 .map(|(label, value)| (label.as_str(), value.as_str()));
8776 let list_row = next.as_ref().and_then(|target| list_row(scene, target));
8777 let standard_button = next
8778 .as_ref()
8779 .and_then(|target| scene.at_path(&target.path))
8780 .and_then(Node::standard_button_kind);
8781 let tree_indicator = next.as_ref().is_some_and(|target| {
8782 scene
8783 .at_path(&target.path)
8784 .zip(layout.at_path(&target.path))
8785 .is_some_and(|(node, item)| tree_indicator_hit(node, item, point))
8786 });
8787 let body_column = next.as_ref().and_then(|target| {
8788 let (path, _) = table_hit_row(scene, &target.path)?;
8789 if scene.at_path(path)?.selection_target() == SelectionTarget::Rows {
8790 return None;
8791 }
8792 let item = layout.at_path(path)?;
8793 item.table
8794 .as_ref()?
8795 .body_column_at(item.map_from_window(point)?)
8796 });
8797 let mut table_grip = None;
8798 let mut table_column = None;
8799 if let Some(target) = &next
8800 && let Some(node) = scene.at_path(&target.path)
8801 && let Some(item) = layout.at_path(&target.path)
8802 && let Some(table) = &item.table
8803 && let Some(point) = item.map_from_window(point)
8804 {
8805 if let Some(index) = table.resize_at(node, item.clip, point) {
8806 let bounds = table.columns[index];
8807 table_grip = Some((index, bounds.width, table.mirrored()));
8808 } else if let Some(index) = table.column_at(point)
8809 && (node.selection_target() == SelectionTarget::Columns
8810 || node
8811 .table_header
8812 .as_ref()
8813 .is_some_and(|header| header.next_sort(index).is_some()))
8814 {
8815 table_column = Some(index);
8816 }
8817 }
8818 let changed = cancelled_delay
8819 || next != self.hovered
8820 || scroll_bar != self.hovered_scroll_bar
8821 || control_part != self.hovered_control_part
8822 || standard_button != self.hovered_standard_button
8823 || radio != previous_radio
8824 || list_row != self.hovered_list_row
8825 || tree_indicator != self.hovered_tree_indicator
8826 || table_column != self.hovered_table_column
8827 || table_grip != self.hovered_table_grip
8828 || row_grip != self.hovered_table_row_grip
8829 || body_column != self.hovered_body_column;
8830 if radio != previous_radio {
8831 self.hovered_radio = radio.map(|(label, value)| (label.to_owned(), value.to_owned()));
8832 }
8833 let split_hover = next.as_ref().and_then(|target| {
8834 let (path, _, handle) = split_target(target, scene, layout)?;
8835 if scene.at_path(&target.path)?.children.is_empty() {
8836 return None;
8837 }
8838 let state = scene.at_path(path)?.split_resize_handle.clone()?;
8839 Some((state, handle.slot))
8840 });
8841 self.set_split_hover(split_hover);
8842 self.hovered = next;
8843 self.hovered_scroll_bar = scroll_bar;
8844 self.hovered_control_part = control_part;
8845 self.hovered_standard_button = standard_button;
8846 self.hovered_list_row = list_row;
8847 self.hovered_tree_indicator = tree_indicator;
8848 self.hovered_table_column = table_column;
8849 self.hovered_table_grip = table_grip;
8850 self.hovered_table_row_grip = row_grip;
8851 self.hovered_body_column = body_column;
8852 changed
8853 }
8854 pub fn pointer_leave(&mut self) -> bool {
8855 let cancelled_table_selection = self.cancel_table_drag_selection();
8856 let cancelled_row_move = self.cancel_table_row_move();
8857 self.cancel_window_move();
8858 let cancelled_delay = self
8859 .delay_hold
8860 .as_ref()
8861 .is_some_and(|hold| matches!(hold.source, DelaySource::Pointer));
8862 if cancelled_delay {
8863 self.cancel_delay();
8864 }
8865 let cancelled_repeat = self
8866 .button_hold
8867 .as_ref()
8868 .is_some_and(|repeat| matches!(repeat.source, DelaySource::Pointer));
8869 if cancelled_repeat {
8870 self.button_hold = None;
8871 }
8872 self.pointer = None;
8873 self.set_split_hover(None);
8874 self.tumbler_wheel = None;
8875 self.reset_wheel_adjustment();
8876 self.pointer_on_stack_slide = false;
8877 let tooltip_was_visible = self.tooltip.pointer_left();
8878 self.hovered_radio = None;
8879 self.hovered_list_row = None;
8880 self.hovered_tree_indicator = false;
8881 self.hovered_table_column = None;
8882 self.hovered_table_grip = None;
8883 self.hovered_table_row_grip = None;
8884 self.hovered_body_column = None;
8885 self.hovered_control_part = None;
8886 self.hovered_standard_button = None;
8887 let bar = self.hovered_scroll_bar.take().is_some();
8888 self.hovered.take().is_some()
8889 || bar
8890 || tooltip_was_visible
8891 || cancelled_delay
8892 || cancelled_repeat
8893 || cancelled_table_selection
8894 || cancelled_row_move
8895 }
8896 pub fn pointer_press(&mut self) {
8897 self.press(None, None, false);
8898 }
8899
8900 pub fn pointer_press_in_scene(&mut self, scene: &Node, layout: &LayoutNode) {
8901 self.replay_tap_in_scene(scene, layout);
8902 if let Some(target) = self.pressed.clone() {
8903 self.start_button_contact(scene, target, ButtonContactSource::Pointer);
8904 }
8905 }
8906
8907 pub fn replay_tap_in_scene(&mut self, scene: &Node, layout: &LayoutNode) {
8909 self.remember_focus_scope(scene, layout);
8910 let proxy = self
8911 .hovered
8912 .as_ref()
8913 .filter(|target| {
8914 scene
8915 .at_path(&target.path)
8916 .is_some_and(|node| node.kind == "FocusScope")
8917 && valid(target, scene, layout)
8918 })
8919 .map(|target| {
8920 self.scope_focus
8921 .choose(scene, layout, target.clone(), false, false)
8922 });
8923
8924 let preserve_focus = self.hovered.as_ref().is_some_and(|target| {
8925 target.tab_close.is_some()
8926 || scene.at_path(&target.path).is_some_and(|node| {
8927 matches!(node.kind, "Button" | "ToolButton" | "RoundButton")
8928 && !node.boolean("focus-on-click", true)
8929 })
8930 });
8931 self.press(proxy, Some(layout), preserve_focus);
8932 if self.table_resize.is_none() && self.table_row_resize.is_none() {
8933 self.table_column_move =
8934 self.pressed
8935 .as_ref()
8936 .zip(self.pointer)
8937 .and_then(|(target, point)| {
8938 Self::table_column_move_at(scene, layout, target, point)
8939 });
8940 }
8941 if self.table_row_resize.is_none() && self.table_column_move.is_none() {
8942 self.table_row_move =
8943 self.pressed
8944 .as_ref()
8945 .zip(self.pointer)
8946 .and_then(|(pressed, point)| {
8947 Self::table_row_move_at(scene, layout, pressed, point)
8948 });
8949 }
8950 self.remember_focus_scope(scene, layout);
8951 }
8952
8953 fn press(&mut self, proxy: Option<Target>, layout: Option<&LayoutNode>, preserve_focus: bool) {
8954 self.text_selection_scroll = None;
8955 self.editor_press = None;
8956 self.cancel_shortcut_sequence();
8957 self.reset_list_typeahead();
8958 self.reset_wheel_adjustment();
8959 self.cancel_delay();
8960 self.button_hold = None;
8961 self.pointer_activation_claimed = false;
8962 if self.pointer_on_stack_slide {
8963 return;
8964 }
8965 self.press_origin = self.pointer;
8966 self.tooltip.source = TooltipSource::Pointer;
8967 self.tooltip.dismiss();
8968 self.pressed = self.hovered.clone();
8969 self.pressed_radio.clone_from(&self.hovered_radio);
8970 self.pressed_list_row = self.hovered_list_row.clone();
8971 self.pressed_tree_indicator = self.hovered_tree_indicator;
8972 self.pressed_table_column = self.hovered_table_column;
8973 self.table_column_move = None;
8974 self.table_row_move = None;
8975 self.table_drag_selection = None;
8976 self.pressed_body_column = self.hovered_body_column;
8977 self.pressed_control_part = self.hovered_control_part;
8978 self.pressed_standard_button = self.hovered_standard_button;
8979 self.table_resize = (|| {
8980 let (column, width, mirrored) = self.hovered_table_grip?;
8981 let target = self.pressed.clone()?;
8982 let pointer = self.pointer?;
8983 let point = match layout {
8984 Some(layout) => layout.at_path(&target.path)?.map_from_window(pointer)?,
8985 None => pointer,
8986 };
8987 Some(TableResize {
8988 target,
8989 column,
8990 pointer_x: point.x,
8991 width,
8992 mirrored,
8993 })
8994 })();
8995 self.table_row_resize = (|| {
8996 let (key, height) = self.hovered_table_row_grip?;
8997 let target = self.pressed.clone()?;
8998 let pointer = self.pointer?;
8999 let point = match layout {
9000 Some(layout) => layout.at_path(&target.path)?.map_from_window(pointer)?,
9001 None => pointer,
9002 };
9003 Some(TableRowResize {
9004 target,
9005 key,
9006 pointer_y: point.y,
9007 height,
9008 })
9009 })();
9010 self.slider_offset = 0.0;
9011 self.slider_anchor = None;
9012 self.slider_fraction = None;
9013 self.clear_range_preview();
9014 self.dial_pointer = None;
9015 self.spin_pressed = None;
9016 let focus = self.hovered.clone().and_then(|mut target| {
9017 if let Some((_, id)) = &self.hovered_list_row {
9018 target.path.pop();
9019 target.set_element_id(id.clone());
9020 target.focusable = true;
9021 target.row_key = None;
9022 }
9023 target.focusable.then_some(target)
9024 });
9025 if self.table_row_resize.is_none() && !preserve_focus {
9026 self.set_focus_with_reason(proxy.or(focus), xrack_runtime::FocusReason::PointerClick);
9027 }
9028 self.key_pressed = None;
9029 }
9030
9031 pub fn split_press(&mut self, scene: &Node, layout: &LayoutNode) {
9032 self.clear_split_drag();
9033 self.split_drag = (|| {
9034 let target = self.pressed.as_ref()?;
9035 let (path, geometry, handle) = split_target(target, scene, layout)?;
9036 let orientation = geometry.orientation;
9037 let point = layout.at_path(path)?.map_from_window(self.pointer?)?;
9038 let position = axis_point(orientation, point);
9039 let state = scene.at_path(path)?.split_resize_handle.clone();
9040 if let Some(state) = &state {
9041 state.publish_pressed(Some((handle.slot, handle.after_pane())));
9042 }
9043 Some(SplitDrag {
9044 target: target.clone(),
9045 orientation,
9046 mirrored: geometry.mirrored,
9047 after_pane: handle.after_pane(),
9048 grab_offset: position - handle.center(orientation),
9049 state,
9050 })
9051 })();
9052 }
9053
9054 pub fn split_resize_active(&self) -> bool {
9055 self.split_drag.is_some()
9056 }
9057
9058 fn set_split_hover(&mut self, next: Option<(xrack_runtime::SplitResizeHandle, usize)>) {
9059 if next == self.split_hover {
9060 return;
9061 }
9062 if let Some((state, _)) = self.split_hover.take()
9063 && next.as_ref().is_none_or(|(next, _)| *next != state)
9064 {
9065 state.publish_hovered(None);
9066 }
9067 if let Some((state, slot)) = &next {
9068 state.publish_hovered(Some(*slot));
9069 }
9070 self.split_hover = next;
9071 }
9072
9073 pub fn touch_split_press(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> bool {
9074 if self.menu.is_some() || self.choice.is_some() {
9075 return false;
9076 }
9077 let Hit::Target(target) = self.hit_at(scene, layout, point) else {
9078 return false;
9079 };
9080 if split_target(&target, scene, layout).is_none() {
9081 return false;
9082 }
9083 self.pointer_move(scene, layout, point);
9084 self.pointer_press_in_scene(scene, layout);
9085 self.split_press(scene, layout);
9086 self.split_resize_active()
9087 }
9088
9089 fn clear_split_drag(&mut self) -> bool {
9090 let Some(drag) = self.split_drag.take() else {
9091 return false;
9092 };
9093 if let Some(state) = drag.state {
9094 state.publish_pressed(None);
9095 }
9096 true
9097 }
9098
9099 pub fn split_orientation(&self, scene: &Node) -> Option<Orientation> {
9100 if let Some(drag) = &self.split_drag {
9101 return Some(drag.orientation);
9102 }
9103 let handle = scene.at_path(&self.hovered.as_ref()?.path)?;
9104 (handle.kind == "SplitHandle").then(|| handle.orientation())
9105 }
9106
9107 pub fn split_drag(&self, scene: &Node, layout: &LayoutNode) -> Option<SplitResize> {
9108 let drag = self.split_drag.as_ref()?;
9109 let (path, geometry, handle) = split_target(&drag.target, scene, layout)?;
9110 if !drag.matches(geometry, handle) {
9111 return None;
9112 }
9113 let point = layout.at_path(path)?.map_from_window(self.pointer?)?;
9114 let position = axis_point(drag.orientation, point) - drag.grab_offset;
9115 geometry.resize(
9116 path.to_vec(),
9117 handle,
9118 geometry.logical_delta(position - handle.center(drag.orientation)),
9119 )
9120 }
9121
9122 pub fn finish_split_resize(&mut self) -> bool {
9123 if !self.clear_split_drag() {
9124 return false;
9125 }
9126 self.cancel_press();
9127 true
9128 }
9129
9130 pub fn split_key(
9131 &self,
9132 scene: &Node,
9133 layout: &LayoutNode,
9134 key: NavigationKey,
9135 ) -> Option<SplitResize> {
9136 let (path, geometry, handle) = split_target(self.focused.as_ref()?, scene, layout)?;
9137 let step = SplitHandleRange::STEP as f32;
9138 let delta = match (geometry.orientation, key) {
9139 (Orientation::Horizontal, NavigationKey::Left)
9140 | (Orientation::Vertical, NavigationKey::Up) => geometry.logical_delta(-step),
9141 (Orientation::Horizontal, NavigationKey::Right)
9142 | (Orientation::Vertical, NavigationKey::Down) => geometry.logical_delta(step),
9143 (_, NavigationKey::Home) => handle.minimum,
9144 (_, NavigationKey::End) => handle.maximum,
9145 _ => return None,
9146 };
9147 geometry.resize(path.to_vec(), handle, delta)
9148 }
9149
9150 pub fn split_set_value(
9152 &self,
9153 scene: &Node,
9154 layout: &LayoutNode,
9155 target: &Target,
9156 value: f64,
9157 ) -> Option<SplitResize> {
9158 if !value.is_finite() {
9159 return None;
9160 }
9161 let (path, geometry, handle) = split_target(target, scene, layout)?;
9162 let range = geometry.handle_range(handle);
9163 let delta = value.clamp(range.minimum, range.maximum) - range.value;
9164 geometry.resize(path.to_vec(), handle, delta as f32)
9165 }
9166
9167 pub fn range_pointer_press(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> bool {
9168 if self.menu.is_some() || self.choice.is_some() {
9169 return false;
9170 }
9171 let Hit::Target(target) = self.hit_at(scene, layout, point) else {
9172 return false;
9173 };
9174 if slider_target(&target, scene, layout).is_none() {
9175 return false;
9176 }
9177 self.pointer_move(scene, layout, point);
9178 self.pointer_press_in_scene(scene, layout);
9179 true
9180 }
9181
9182 pub fn touch_range_press(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> bool {
9183 if !self.range_pointer_press(scene, layout, point) {
9184 return false;
9185 }
9186 self.touch_range = true;
9187 true
9188 }
9189
9190 pub fn touch_range_captured(&self) -> bool {
9191 self.touch_range
9192 }
9193
9194 pub fn finish_touch_range(&mut self) {
9195 if std::mem::take(&mut self.touch_range) {
9196 self.cancel_press();
9197 self.pointer_leave();
9198 }
9199 }
9200
9201 pub fn slider_press(&mut self, scene: &Node, layout: &LayoutNode) -> Option<RangeInput> {
9202 let target = self.pressed.as_ref()?;
9203 let (path, node) = slider_target(target, scene, layout)?;
9204 let item = layout.at_path(path)?;
9205 let bounds = item.bounds;
9206 let point = item.map_from_window(self.pointer?)?;
9207 if node.kind == "ColorPlane" {
9208 return Some(RangeInput {
9209 path: target.path.clone(),
9210 action: ColorPlaneGeometry::new(bounds).action_at(point)?,
9211 });
9212 }
9213 if node.kind == "Dial" {
9214 self.dial_pointer = Some(point);
9215 let geometry = DialGeometry::new(bounds, node);
9216 let current = SliderRange::from_node(node).fraction();
9217 if node.dial_input_mode() != DialInputMode::Circular
9218 || geometry.contains_thumb(current, point)
9219 {
9220 return None;
9221 }
9222 return Some(RangeInput {
9223 path: path.to_vec(),
9224 action: RangeAction::SetFraction(geometry.fraction_at(point)?),
9225 });
9226 }
9227 let geometry = SliderGeometry::with_layout_direction(bounds, node, item.layout_direction);
9228 let fraction = geometry.fraction_at(point)?;
9229 let mut path = path.to_vec();
9230 let current = if node.kind == "RangeSlider" {
9231 let interval = SliderInterval::from_node(node);
9232 let [lower, upper] = interval.fractions();
9233 let handle = geometry.interval_handle_at(point, fraction, interval);
9234 path.push(handle);
9235 self.focus_slider_thumb(scene, &path);
9236 let current = [lower, upper][handle];
9237 if lower == upper && geometry.thumb_bounds(handle, current).contains(point) {
9238 self.slider_anchor = Some(fraction);
9239 }
9240 current
9241 } else {
9242 SliderRange::from_node(node).fraction()
9243 };
9244 let handle = if node.kind == "RangeSlider" {
9245 *path.last()?
9246 } else {
9247 0
9248 };
9249 if geometry.thumb_bounds(handle, current).contains(point) {
9250 self.slider_offset = current - fraction;
9251 None
9252 } else {
9253 self.slider_pointer_action(node, path, fraction)
9254 }
9255 }
9256
9257 fn focus_slider_thumb(&mut self, scene: &Node, path: &[usize]) {
9258 let target = Target::from_element_id(path.to_vec(), None, true, scene.row_key_at(path));
9259 self.set_focus(Some(target.clone()));
9260 self.pressed = Some(target);
9261 }
9262
9263 #[doc(hidden)]
9265 pub fn interval_preview(&self, node: &Node, path: &[usize]) -> Option<(usize, f64)> {
9266 if node.boolean("live", true) {
9267 return None;
9268 }
9269 let (pressed, fraction) = self.slider_preview_position()?;
9270 let (&index, parent) = pressed.split_last()?;
9271 (parent == path && index < Node::RANGE_THUMBS).then_some((index, fraction))
9272 }
9273
9274 #[doc(hidden)]
9275 pub fn slider_preview_position(&self) -> Option<(&[usize], f64)> {
9276 Some((
9277 self.pressed.as_ref()?.path.as_slice(),
9278 self.slider_fraction?,
9279 ))
9280 }
9281
9282 pub fn slider_drag(&mut self, scene: &Node, layout: &LayoutNode) -> Option<RangeInput> {
9283 let target = self.pressed.as_ref()?;
9284 let (owner, node) = slider_target(target, scene, layout)?;
9285 let item = layout.at_path(owner)?;
9286 let bounds = item.bounds;
9287 let point = item.map_from_window(self.pointer?)?;
9288 if node.kind == "ColorPlane" {
9289 return Some(RangeInput {
9290 path: target.path.clone(),
9291 action: ColorPlaneGeometry::new(bounds).action_at(point)?,
9292 });
9293 }
9294 if node.kind == "Dial" {
9295 let previous = self.dial_pointer.replace(point)?;
9296 let delta = DialGeometry::new(bounds, node).drag_delta(
9297 node.dial_input_mode(),
9298 previous,
9299 point,
9300 )?;
9301 let current = SliderRange::from_node(node).fraction();
9302 let next = current + delta;
9303 let next = if node.boolean("wrap", false) && !(0.0..=1.0).contains(&next) {
9304 next.rem_euclid(1.0)
9305 } else {
9306 next.clamp(0.0, 1.0)
9307 };
9308 return (next != current).then(|| RangeInput {
9309 path: target.path.clone(),
9310 action: RangeAction::SetFraction(next),
9311 });
9312 }
9313 let geometry = SliderGeometry::with_layout_direction(bounds, node, item.layout_direction);
9314 let fraction = geometry.fraction_at(point)?;
9315 let mut path = target.path.clone();
9316 if let Some(anchor) = self.slider_anchor {
9317 if fraction == anchor {
9318 return None;
9319 }
9320 if self.touch_range {
9321 let start = item.map_to_window(geometry.position(0.0));
9324 let end = item.map_to_window(geometry.position(1.0));
9325 let travel = (end.x - start.x).hypot(end.y - start.y);
9326 if (fraction - anchor).abs() * f64::from(travel) < f64::from(DRAG_THRESHOLD) {
9327 return None;
9328 }
9329 }
9330 path.truncate(owner.len());
9331 path.push(usize::from(fraction > anchor));
9332 self.focus_slider_thumb(scene, &path);
9333 self.slider_anchor = None;
9334 }
9335 self.slider_pointer_action(node, path, fraction + self.slider_offset)
9336 }
9337
9338 fn slider_pointer_action(
9339 &mut self,
9340 node: &Node,
9341 path: Vec<usize>,
9342 fraction: f64,
9343 ) -> Option<RangeInput> {
9344 let live = node.boolean("live", true);
9345 if !live || SliderRange::from_node(node).snap_mode() == ScrollSnapMode::OnRelease {
9346 self.slider_fraction = Some(fraction);
9347 if self.range_position_handle.as_ref() != node.range_position_handle.as_ref() {
9348 self.clear_range_preview();
9349 self.range_position_handle = node.range_position_handle.clone();
9350 }
9351 if let Some(handle) = &self.range_position_handle {
9352 let index = if node.kind == "RangeSlider" {
9353 path.last().copied().unwrap_or_default()
9354 } else {
9355 0
9356 };
9357 handle.publish_preview(Some((index, fraction)));
9358 }
9359 } else {
9360 self.slider_fraction = None;
9361 self.clear_range_preview();
9362 }
9363 live.then_some(RangeInput {
9364 path,
9365 action: RangeAction::SetFraction(fraction),
9366 })
9367 }
9368
9369 pub fn slider_preview(&self, path: &[usize]) -> Option<f64> {
9370 self.slider_fraction.filter(|_| self.is_pressed(path))
9371 }
9372
9373 pub fn has_slider_preview(&self) -> bool {
9374 self.slider_fraction.is_some() && self.pressed.is_some()
9375 }
9376
9377 pub fn cancel_slider_preview(&mut self) -> bool {
9378 if !self.has_slider_preview() {
9379 return false;
9380 }
9381 self.cancel_press();
9382 true
9383 }
9384
9385 pub fn slider_release(&mut self, scene: &Node, layout: &LayoutNode) -> Option<RangeInput> {
9386 let fraction = self.slider_fraction.take();
9387 self.clear_range_preview();
9388 slider_target(self.pressed.as_ref()?, scene, layout)?;
9389 self.slider_offset = 0.0;
9390 self.slider_anchor = None;
9391 self.dial_pointer = None;
9392 let path = self.pressed.take()?.path;
9393 Some(RangeInput {
9394 path,
9395 action: fraction.map_or(RangeAction::Release, RangeAction::CommitFraction),
9396 })
9397 }
9398
9399 fn clear_range_preview(&mut self) {
9400 if let Some(handle) = self.range_position_handle.take() {
9401 handle.publish_preview(None);
9402 }
9403 }
9404
9405 pub fn slider_key(
9406 &mut self,
9407 scene: &Node,
9408 layout: &LayoutNode,
9409 key: SliderKey,
9410 pressed: bool,
9411 ) -> Option<RangeInput> {
9412 if !pressed {
9413 let target = self.range_keys.remove(&key)?;
9414 if self.focused.as_ref() != Some(&target) {
9415 return None;
9416 }
9417 slider_target(&target, scene, layout)?;
9418 return Some(RangeInput {
9419 path: target.path,
9420 action: RangeAction::Release,
9421 });
9422 }
9423 let target = self.focused.as_ref()?;
9424 if !valid(target, scene, layout) {
9425 return None;
9426 }
9427 let (path, node) = slider_target(target, scene, layout)?;
9428 let action = if node.kind == "ColorPlane" {
9429 let saturation = node.number("saturation").unwrap_or_default();
9430 let brightness = node.number("brightness").unwrap_or_default();
9431 let step = 0.01;
9432 let (x, y) = match key {
9433 SliderKey::Left => (saturation - step, brightness),
9434 SliderKey::Right => (saturation + step, brightness),
9435 SliderKey::Up => (saturation, brightness + step),
9436 SliderKey::Down => (saturation, brightness - step),
9437 _ => return None,
9438 };
9439 RangeAction::SetPoint {
9440 x: x.clamp(0.0, 1.0),
9441 y: y.clamp(0.0, 1.0),
9442 }
9443 } else {
9444 let horizontal = node.kind == "Dial" || node.orientation() == Orientation::Horizontal;
9445 let vertical = node.kind == "Dial" || node.orientation() == Orientation::Vertical;
9446 let mirrored = node.kind != "Dial"
9447 && layout.at_path(path)?.layout_direction == LayoutDirection::RightToLeft;
9448 match key {
9449 SliderKey::Left if horizontal && mirrored => RangeAction::Increase,
9450 SliderKey::Right if horizontal && mirrored => RangeAction::Decrease,
9451 SliderKey::Left if horizontal => RangeAction::Decrease,
9452 SliderKey::Right if horizontal => RangeAction::Increase,
9453 SliderKey::Down if vertical => RangeAction::Decrease,
9454 SliderKey::Up if vertical => RangeAction::Increase,
9455 SliderKey::Home => RangeAction::Minimum,
9456 SliderKey::End => RangeAction::Maximum,
9457 _ => return None,
9458 }
9459 };
9460 self.range_keys.entry(key).or_insert_with(|| target.clone());
9461 Some(RangeInput {
9462 path: target.path.clone(),
9463 action,
9464 })
9465 }
9466
9467 pub fn accessibility_tab_close_target(
9470 &self,
9471 scene: &Node,
9472 layout: &LayoutNode,
9473 path: &[usize],
9474 ) -> Option<Target> {
9475 let mut target = self.accessibility_target(scene, layout, path)?;
9476 target.tab_close = Some(tab_close_identity(scene, path)?);
9477 self.tab_close_action(scene, layout, &target)?;
9478 Some(target)
9479 }
9480
9481 pub fn tab_close_action(
9482 &self,
9483 scene: &Node,
9484 layout: &LayoutNode,
9485 target: &Target,
9486 ) -> Option<ControlInput> {
9487 if !valid(target, scene, layout)
9488 || self.menu_open()
9489 || self.choice_open()
9490 || self
9491 .active_dialog(layout)
9492 .is_some_and(|scope| !target.path.starts_with(scope))
9493 {
9494 return None;
9495 }
9496 let (&index, parent) = target.path.split_last()?;
9497 let item = layout.at_path(&target.path)?;
9498 let rect = item.clip_rect(item.tab_close?);
9499 if rect.width <= 0.0 || rect.height <= 0.0 {
9500 return None;
9501 }
9502 let request = scene.at_path(parent)?.tab_close(index)?;
9503 if let Some((captured, value)) = &target.tab_close
9504 && (*captured != request
9505 || value != scene.at_path(&target.path)?.text("value").unwrap_or(""))
9506 {
9507 return None;
9508 }
9509 Some(ControlInput {
9510 path: parent.to_vec(),
9511 action: ControlAction::CloseTab(request),
9512 })
9513 }
9514
9515 pub fn focused_tab_close(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
9516 self.tab_close_action(scene, layout, self.focused.as_ref()?)
9517 }
9518
9519 pub fn tab_close_hovered(&self, path: &[usize]) -> bool {
9520 self.hovered
9521 .as_ref()
9522 .is_some_and(|target| target.tab_close.is_some() && target.path == path)
9523 }
9524
9525 pub fn select_group_option(
9526 &self,
9527 scene: &Node,
9528 layout: &LayoutNode,
9529 target: &Target,
9530 ) -> Option<ControlInput> {
9531 if target.tab_close.is_some() {
9532 return self.tab_close_action(scene, layout, target);
9533 }
9534 if !valid(target, scene, layout) {
9535 return None;
9536 }
9537 if attached_radio(scene, &target.path).is_some()
9538 && scene.at_path(&target.path)?.kind == "RadioButton"
9539 {
9540 return Some(ControlInput {
9541 path: target.path.clone(),
9542 action: ControlAction::ActivateRadioOption,
9543 });
9544 }
9545 if let Some((view, slot)) =
9546 table_cell_row(scene, &target.path).or_else(|| tree_cell_row(scene, &target.path))
9547 {
9548 if scene.at_path(&target.path)?.boolean("table-editor", false) {
9549 return None;
9550 }
9551 let index = scene.at_path(view)?.list?.first_row.checked_add(slot)?;
9552 return Some(ControlInput {
9553 path: view.to_vec(),
9554 action: ControlAction::Select(index),
9555 });
9556 }
9557 let (&index, path) = target.path.split_last()?;
9558 let index = if let Some((index, _)) = list_row(scene, target) {
9559 index
9560 } else {
9561 group_item(scene.at_path(path)?, index)?;
9562 index
9563 };
9564 Some(ControlInput {
9565 path: path.to_vec(),
9566 action: ControlAction::Select(index),
9567 })
9568 }
9569
9570 pub fn tree_pointer_action(
9571 &self,
9572 scene: &Node,
9573 layout: &LayoutNode,
9574 target: &Target,
9575 ) -> Option<ControlInput> {
9576 let point = self.pointer?;
9577 let node = scene.at_path(&target.path)?;
9578 let item = layout.at_path(&target.path)?;
9579 if !self.hovered_tree_indicator || !tree_indicator_hit(node, item, point) {
9580 return None;
9581 }
9582 self.tree_row_expansion(scene, layout, target, !node.boolean("tree-expanded", false))
9583 }
9584
9585 #[doc(hidden)]
9586 pub fn tree_row_expansion(
9587 &self,
9588 scene: &Node,
9589 layout: &LayoutNode,
9590 target: &Target,
9591 expanded: bool,
9592 ) -> Option<ControlInput> {
9593 if !valid(target, scene, layout) {
9594 return None;
9595 }
9596 let (&slot, path) = target.path.split_last()?;
9597 let node = scene.at_path(path)?;
9598 let index = node.list?.first_row.checked_add(slot)?;
9599 let tree = node.tree.as_ref()?;
9600 if tree.is_filtering() {
9601 return None;
9602 }
9603 let item = tree.rows().get(index)?;
9604 (item.has_children
9605 && item.expanded != expanded
9606 && node.children.get(slot)?.row_key == Some(item.row))
9607 .then_some(ControlInput {
9608 path: path.to_vec(),
9609 action: ControlAction::Tree(TreeAction::SetExpanded {
9610 key: item.key,
9611 row: item.row,
9612 expanded,
9613 }),
9614 })
9615 }
9616
9617 pub fn tree_has_focus(&self, scene: &Node, layout: &LayoutNode) -> bool {
9618 self.focused_tree(scene, layout).is_some()
9619 }
9620
9621 fn focused_tree<'a>(&'a self, scene: &Node, layout: &LayoutNode) -> Option<&'a [usize]> {
9622 let target = self.focused.as_ref()?;
9623 if self.table_edit.is_some()
9624 || !valid(target, scene, layout)
9625 || scene.at_path(&target.path)?.boolean("table-editor", false)
9626 {
9627 return None;
9628 }
9629 let path =
9630 tree_cell_row(scene, &target.path).map_or(target.path.as_slice(), |(path, _)| path);
9631 (scene.at_path(path)?.kind == "TreeView").then_some(path)
9632 }
9633
9634 pub fn tree_toggle(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
9635 let path = self.focused_tree(scene, layout)?;
9636 let node = scene.at_path(path)?;
9637 let tree = node.tree.as_ref()?;
9638 if tree.is_filtering() {
9639 return None;
9640 }
9641 let index = tree.visible_index(node.int("current-key")?)?;
9642 let item = tree.rows().get(index)?;
9643 item.has_children.then_some(ControlInput {
9644 path: path.to_vec(),
9645 action: ControlAction::Tree(TreeAction::SetExpanded {
9646 key: item.key,
9647 row: item.row,
9648 expanded: !item.expanded,
9649 }),
9650 })
9651 }
9652
9653 pub fn tree_key(
9654 &mut self,
9655 scene: &Node,
9656 layout: &LayoutNode,
9657 key: NavigationKey,
9658 ) -> Option<ControlInput> {
9659 if !matches!(key, NavigationKey::Left | NavigationKey::Right) {
9660 return None;
9661 }
9662 let path = self.focused_tree(scene, layout)?.to_vec();
9663 let node = scene.at_path(&path)?;
9664 let view = layout.at_path(&path)?;
9665 let forward = (key == NavigationKey::Right)
9666 != (view.layout_direction == LayoutDirection::RightToLeft);
9667 let tree = node.tree.as_ref()?;
9668 let index = tree.visible_index(node.int("current-key")?)?;
9669 let item = tree.rows().get(index)?;
9670 if !tree.is_filtering() && item.has_children && forward != item.expanded {
9671 return self.tree_toggle(scene, layout);
9672 }
9673 let next = if !forward {
9674 tree.visible_index(item.parent?)?
9675 } else {
9676 index.checked_add(1).filter(|&next| {
9677 tree.rows()
9678 .get(next)
9679 .is_some_and(|next| next.parent == Some(item.key))
9680 })?
9681 };
9682 self.reveal_row(&path, node, view, next);
9683 self.set_focus(Some(Target::from_node(
9684 path.clone(),
9685 node,
9686 true,
9687 scene.row_key_at(&path),
9688 )));
9689 Some(ControlInput {
9690 path,
9691 action: ControlAction::Select(next),
9692 })
9693 }
9694
9695 pub fn tree_key_with_selection(
9696 &mut self,
9697 scene: &Node,
9698 layout: &LayoutNode,
9699 key: NavigationKey,
9700 operation: RowSelection,
9701 ) -> Option<ControlInput> {
9702 Some(
9703 self.tree_key(scene, layout, key)?
9704 .with_row_selection(scene, operation),
9705 )
9706 }
9707
9708 pub fn select_group_option_with_selection(
9709 &self,
9710 scene: &Node,
9711 layout: &LayoutNode,
9712 target: &Target,
9713 operation: RowSelection,
9714 ) -> Option<ControlInput> {
9715 let mut input = self.select_group_option(scene, layout, target)?;
9716 let node = scene.at_path(&input.path)?;
9717 let ControlAction::Select(row) = input.action else {
9718 return Some(input);
9719 };
9720 if let Some(selection) = &node.table_selection {
9721 if self.pointer.is_some_and(|point| {
9722 layout.at_path(&input.path).is_some_and(|item| {
9723 item.table
9724 .as_ref()
9725 .zip(item.map_from_window(point))
9726 .is_some_and(|(table, point)| table.row_header.contains(point))
9727 })
9728 }) && let Some(action) =
9729 self.table_row_header_selection(scene, layout, target, operation)
9730 {
9731 return Some(action);
9732 }
9733 let column = if table_cell_row(scene, &target.path).is_some() {
9734 target.path.last().copied()
9735 } else {
9736 self.hovered_body_column
9737 };
9738 let action = match selection.target() {
9739 SelectionTarget::Rows => TableSelectionAction::Row {
9740 index: row,
9741 operation,
9742 },
9743 SelectionTarget::Cells => TableSelectionAction::Cell {
9744 row,
9745 column: column?,
9746 operation,
9747 },
9748 SelectionTarget::Columns => TableSelectionAction::Column {
9749 column: column?,
9750 operation,
9751 },
9752 };
9753 input.action = ControlAction::TableSelection(action);
9754 } else if let Some(action) = tree_row_action(node, row, operation) {
9755 input.action = action;
9756 }
9757 Some(input)
9758 }
9759
9760 pub fn list_item_delegate_selection(
9761 &self,
9762 scene: &Node,
9763 layout: &LayoutNode,
9764 target: &Target,
9765 ) -> Option<ControlInput> {
9766 if !valid(target, scene, layout) {
9767 return None;
9768 }
9769 target.row_key?;
9770 let (path, slot) = list_item_delegate_row(scene, &target.path)?;
9771 let view = scene.interactive_at_path(path)?;
9772 let row = view.list?.first_row.checked_add(slot)?;
9773 (view.table_selection.is_some() || view.int("current-index") != Some(row as i64)).then_some(
9774 ControlInput {
9775 path: path.to_vec(),
9776 action: ControlAction::Select(row),
9777 },
9778 )
9779 }
9780
9781 pub fn current_item_delegate(
9782 &self,
9783 scene: &Node,
9784 layout: &LayoutNode,
9785 view: &Target,
9786 ) -> Option<Target> {
9787 let node = scene.at_path(&view.path)?;
9788 if !matches!(node.kind, "ListView" | "GridView") {
9789 return None;
9790 }
9791 let slot = current_list_slot(node)?;
9792 self.item_delegate_at_slot(scene, layout, &view.path, slot)
9793 }
9794
9795 pub fn resolve_item_delegate(
9796 &self,
9797 scene: &Node,
9798 layout: &LayoutNode,
9799 view: &[usize],
9800 row: RowKey,
9801 ) -> Option<Target> {
9802 let node = scene.at_path(view)?;
9803 let slot = node
9804 .children
9805 .iter()
9806 .position(|candidate| candidate.routing_row_key() == Some(row))?;
9807 self.item_delegate_at_slot(scene, layout, view, slot)
9808 }
9809
9810 fn item_delegate_at_slot(
9811 &self,
9812 scene: &Node,
9813 layout: &LayoutNode,
9814 view: &[usize],
9815 slot: usize,
9816 ) -> Option<Target> {
9817 let mut path = view.to_vec();
9818 path.extend([slot, 0]);
9819 list_item_delegate_row(scene, &path)?;
9820 self.accessibility_target(scene, layout, &path)
9821 }
9822
9823 pub fn table_row_header_selection(
9824 &self,
9825 scene: &Node,
9826 layout: &LayoutNode,
9827 target: &Target,
9828 operation: RowSelection,
9829 ) -> Option<ControlInput> {
9830 let (path, slot) = Self::visible_table_row_header(scene, layout, target)?;
9831 let table = scene.at_path(path)?;
9832 let index = table.list?.first_row.checked_add(slot)?;
9833 let action =
9834 table
9835 .table_selection
9836 .as_ref()
9837 .map_or(ControlAction::Select(index), |selection| {
9838 ControlAction::TableSelection(selection.row_header_action(index, operation))
9839 });
9840 Some(ControlInput {
9841 path: path.to_vec(),
9842 action,
9843 })
9844 }
9845
9846 fn visible_table_row_header<'a>(
9847 scene: &Node,
9848 layout: &LayoutNode,
9849 target: &'a Target,
9850 ) -> Option<(&'a [usize], usize)> {
9851 if scene.at_path(&target.path)?.kind != "ListRow" || !valid(target, scene, layout) {
9852 return None;
9853 }
9854 let (path, slot) = table_hit_row(scene, &target.path)?;
9855 let item = layout.at_path(path)?;
9856 let table = item.table.as_ref()?;
9857 let row = table
9858 .row_header_cell(item.children.get(slot)?.bounds)
9859 .intersect(table.row_header);
9860 let visible = item.clip_rect(row);
9861 (visible.width > 0.0 && visible.height > 0.0).then_some((path, slot))
9862 }
9863
9864 fn table_column_move_at(
9865 scene: &Node,
9866 layout: &LayoutNode,
9867 target: &Target,
9868 start: Point,
9869 ) -> Option<TableColumnMove> {
9870 let node = target.node_in(scene)?;
9871 if !node.boolean("movable-columns", false) {
9872 return None;
9873 }
9874 let item = layout.at_path(&target.path)?;
9875 let table = item.table.as_ref()?;
9876 let column = table.column_at(item.map_from_window(start)?)?;
9877 Some(TableColumnMove {
9878 target: target.clone(),
9879 column,
9880 start,
9881 order: node.table_column_order.clone(),
9882 mirrored: table.mirrored(),
9883 claimed: false,
9884 scroll_wake: None,
9885 })
9886 }
9887
9888 #[doc(hidden)]
9890 pub fn table_column_header_move(
9891 &self,
9892 scene: &Node,
9893 layout: &LayoutNode,
9894 target: &Target,
9895 column: usize,
9896 direction: NavigationKey,
9897 ) -> Option<ControlInput> {
9898 let (node, table) = self.visible_table_column_header(scene, layout, target, column)?;
9899 if !node.boolean("movable-columns", false) {
9900 return None;
9901 }
9902 let toward_left = match direction {
9903 NavigationKey::Left => true,
9904 NavigationKey::Right => false,
9905 _ => return None,
9906 };
9907 let visible = table.visible_columns();
9908 let adjacent = if toward_left != table.mirrored() {
9909 visible.rev().skip_while(|&index| index != column).nth(1)
9910 } else {
9911 visible.skip_while(|&index| index != column).nth(1)
9912 }?;
9913 Some(ControlInput {
9914 path: target.path.clone(),
9915 action: ControlAction::MoveColumn {
9916 from: table.visual_index(column)?,
9917 to: table.visual_index(adjacent)?,
9918 },
9919 })
9920 }
9921
9922 fn visible_table_column_header<'a, 'b>(
9923 &self,
9924 scene: &'a Node,
9925 layout: &'b LayoutNode,
9926 target: &Target,
9927 column: usize,
9928 ) -> Option<(&'a Node, &'b crate::TableGeometry)> {
9929 if self.menu_open()
9930 || self.choice_open()
9931 || !self.allows_popup(layout, &target.path)
9932 || !valid(target, scene, layout)
9933 {
9934 return None;
9935 }
9936 let item = layout.at_path(&target.path)?;
9937 let table = item.table.as_ref()?;
9938 table.header_cell_bounds(column, item.clip_rect(table.header))?;
9939 Some((target.node_in(scene)?, table))
9940 }
9941
9942 #[doc(hidden)]
9944 pub fn table_column_header_resize(
9945 &self,
9946 scene: &Node,
9947 layout: &LayoutNode,
9948 target: &Target,
9949 column: usize,
9950 increase: bool,
9951 ) -> Option<ControlInput> {
9952 let (node, table) = self.visible_table_column_header(scene, layout, target, column)?;
9953 let definition = resizable_table_column(node, column)?;
9954 let current = table.columns[column].width;
9955 let (min, max) = crate::table::column_limits(definition, table.header.width);
9956 let desired = if increase {
9957 current + 8.0
9958 } else {
9959 current - 8.0
9960 };
9961 let desired = desired.clamp(min, max);
9963 let width = if increase {
9964 desired.ceil()
9965 } else {
9966 desired.floor()
9967 } as u32;
9968 let next = (width as f32).clamp(min, max);
9969 (next != current).then_some(ControlInput {
9970 path: target.path.clone(),
9971 action: ControlAction::ResizeColumn { column, width },
9972 })
9973 }
9974
9975 pub fn press_table_reorder(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
9977 if self.menu_open()
9978 || self.choice_open()
9979 || self.hovered_table_grip.is_some()
9980 || self.hovered_table_row_grip.is_some()
9981 {
9982 return false;
9983 }
9984 let Some((target, point)) = self.hovered.as_ref().zip(self.pointer) else {
9985 return false;
9986 };
9987 if Self::table_column_move_at(scene, layout, target, point).is_none()
9988 && Self::table_row_move_at(scene, layout, target, point).is_none()
9989 {
9990 return false;
9991 }
9992 self.pointer_press_in_scene(scene, layout);
9993 self.table_row_move.is_some() || self.table_column_move.is_some()
9994 }
9995
9996 fn table_row_move_at(
9997 scene: &Node,
9998 layout: &LayoutNode,
9999 target: &Target,
10000 start: Point,
10001 ) -> Option<TableRowMove> {
10002 let (path, slot) = Self::visible_table_row_header(scene, layout, target)?;
10003 let node = scene.at_path(path)?;
10004 let item = layout.at_path(path)?;
10005 if !node.boolean("movable-rows", false)
10006 || !item
10007 .table
10008 .as_ref()?
10009 .row_header
10010 .contains(item.map_from_window(start)?)
10011 {
10012 return None;
10013 }
10014 Some(TableRowMove {
10015 table: Target::from_node(path.to_vec(), node, true, scene.row_key_at(path)),
10016 from: node.list?.first_row.checked_add(slot)?,
10017 row: node.children.get(slot)?.row_key?,
10018 stamp: node.standard_list_stamp?,
10019 start,
10020 claimed: false,
10021 touch: false,
10022 scroll_wake: None,
10023 })
10024 }
10025
10026 pub fn table_row_header_move(
10028 &self,
10029 scene: &Node,
10030 layout: &LayoutNode,
10031 target: &Target,
10032 direction: NavigationKey,
10033 ) -> Option<ControlInput> {
10034 let (path, slot) = Self::visible_table_row_header(scene, layout, target)?;
10035 let node = scene.interactive_at_path(path)?;
10036 let from = node.list?.first_row.checked_add(slot)?;
10037 let row = node.children.get(slot)?.row_key?;
10038 self.adjacent_table_row_move(layout, node, path, from, row, direction)
10039 }
10040
10041 #[doc(hidden)]
10043 pub fn table_row_header_resize(
10044 &self,
10045 scene: &Node,
10046 layout: &LayoutNode,
10047 target: &Target,
10048 increase: bool,
10049 ) -> Option<ControlInput> {
10050 let (path, slot) = Self::visible_table_row_header(scene, layout, target)?;
10051 let node = scene.interactive_at_path(path)?;
10052 if !node.boolean("resizable-rows", false)
10053 || self.menu_open()
10054 || self.choice_open()
10055 || !self.allows_popup(layout, path)
10056 {
10057 return None;
10058 }
10059 let current = layout.at_path(path)?.children.get(slot)?.bounds.height;
10060 let desired = if increase {
10061 current + 8.0
10062 } else {
10063 current - 8.0
10064 };
10065 let height = ListMetrics::clamp_row_height(desired).round();
10066 (height != current).then_some(ControlInput {
10067 path: path.to_vec(),
10068 action: ControlAction::ResizeRow {
10069 row: node.list?.first_row.checked_add(slot)?,
10070 key: node.children.get(slot)?.row_key?,
10071 height: height as u32,
10072 },
10073 })
10074 }
10075
10076 pub fn table_row_move_key(
10077 &self,
10078 scene: &Node,
10079 layout: &LayoutNode,
10080 direction: NavigationKey,
10081 ) -> Option<ControlInput> {
10082 let focused = self.focused.as_ref()?;
10083 let focus_node = scene.at_path(&focused.path)?;
10084 if !valid(focused, scene, layout)
10085 || self.is_text_editor(focus_node, focused)
10086 || spin_editable(focus_node)
10087 || self.table_edit.is_some()
10088 {
10089 return None;
10090 }
10091 let path =
10092 table_cell_row(scene, &focused.path).map_or(focused.path.as_slice(), |(path, _)| path);
10093 let node = scene.interactive_at_path(path)?;
10094 let list = node.list?;
10095 let from = usize::try_from(node.int("current-row")?).ok()?;
10096 let row = from
10097 .checked_sub(list.first_row)
10098 .and_then(|slot| node.children.get(slot)?.row_key)
10099 .or_else(|| node.row_locator.as_ref()?.key_at(from))?;
10100 self.adjacent_table_row_move(layout, node, path, from, row, direction)
10101 }
10102
10103 fn adjacent_table_row_move(
10104 &self,
10105 layout: &LayoutNode,
10106 node: &Node,
10107 path: &[usize],
10108 from: usize,
10109 row: RowKey,
10110 direction: NavigationKey,
10111 ) -> Option<ControlInput> {
10112 if node.kind != "TableView"
10113 || !node.boolean("movable-rows", false)
10114 || self.menu_open()
10115 || self.choice_open()
10116 || self
10117 .active_dialog(layout)
10118 .is_some_and(|scope| !path.starts_with(scope))
10119 {
10120 return None;
10121 }
10122 let to = match direction {
10123 NavigationKey::Up => from.checked_sub(1)?,
10124 NavigationKey::Down => from.checked_add(1)?,
10125 _ => return None,
10126 };
10127 let count = node.list?.row_count;
10128 (from < count && to < count).then_some(ControlInput {
10129 path: path.to_vec(),
10130 action: ControlAction::MoveRow {
10131 from,
10132 to,
10133 row,
10134 stamp: node.standard_list_stamp?,
10135 },
10136 })
10137 }
10138
10139 pub fn table_delegate_selection(
10141 &self,
10142 scene: &Node,
10143 layout: &LayoutNode,
10144 target: &Target,
10145 operation: RowSelection,
10146 ) -> Option<ControlInput> {
10147 if !valid(target, scene, layout) {
10148 return None;
10149 }
10150 let mut node = scene;
10151 for (depth, &index) in target.path.iter().enumerate() {
10152 if node.kind == "TableView" {
10153 let [slot, 0, column, ..] = &target.path[depth..] else {
10154 return None;
10155 };
10156 let cell = scene.at_path(&target.path[..depth + 3])?;
10157 if !cell.boolean("table-delegate-cell", false) {
10158 return None;
10159 }
10160 let row = node.list?.first_row.checked_add(*slot)?;
10161 let action = match node.selection_target() {
10162 SelectionTarget::Rows => TableSelectionAction::Row {
10163 index: row,
10164 operation,
10165 },
10166 SelectionTarget::Cells => TableSelectionAction::Cell {
10167 row,
10168 column: *column,
10169 operation,
10170 },
10171 SelectionTarget::Columns => TableSelectionAction::Column {
10172 column: *column,
10173 operation,
10174 },
10175 };
10176 return Some(ControlInput {
10177 path: target.path[..depth].to_vec(),
10178 action: ControlAction::TableSelection(action),
10179 });
10180 }
10181 node = node.child_at(index)?;
10182 }
10183 None
10184 }
10185
10186 pub fn selection_key_action(
10188 &self,
10189 scene: &Node,
10190 layout: &LayoutNode,
10191 key: &str,
10192 modifiers: xrack_runtime::KeyModifiers,
10193 ) -> Option<ControlInput> {
10194 let additive = modifiers.control || modifiers.meta;
10195 let key = match key {
10196 " " | "Space" => TableSelectionKey::Toggle,
10197 "Escape" => TableSelectionKey::Clear,
10198 key if key.eq_ignore_ascii_case("a")
10199 && additive
10200 && !modifiers.alt
10201 && !modifiers.shift =>
10202 {
10203 TableSelectionKey::All
10204 }
10205 _ => return None,
10206 };
10207 self.table_selection_key(scene, key).or_else(|| {
10208 if key == TableSelectionKey::Toggle && !additive {
10209 return None;
10210 }
10211 self.tree_selection_key(scene, layout, key)
10212 .or_else(|| self.list_selection_key(scene, layout, key))
10213 })
10214 }
10215
10216 fn list_selection_key(
10217 &self,
10218 scene: &Node,
10219 layout: &LayoutNode,
10220 key: TableSelectionKey,
10221 ) -> Option<ControlInput> {
10222 let focused = self.focused.as_ref()?;
10223 if self.editor.is_some()
10224 || self.menu_open()
10225 || self.choice_open()
10226 || !valid(focused, scene, layout)
10227 {
10228 return None;
10229 }
10230 let path = list_item_delegate_row(scene, &focused.path)
10231 .map_or(focused.path.as_slice(), |(view, _)| view);
10232 let node = scene.interactive_at_path(path)?;
10233 if !matches!(node.kind, "ListView" | "GridView" | "StandardListView") {
10234 return None;
10235 }
10236 let selection = node.table_selection.as_ref()?;
10237 let count = node.list?.row_count;
10238 let action = match key {
10239 TableSelectionKey::All if count > 0 => TableSelectionAction::All,
10240 TableSelectionKey::Clear if !selection.is_empty() => TableSelectionAction::Clear,
10241 TableSelectionKey::Toggle => {
10242 let index = usize::try_from(ListMetrics::selection(node)?).ok()?;
10243 if index >= count {
10244 return None;
10245 }
10246 TableSelectionAction::Row {
10247 index,
10248 operation: RowSelection::Toggle,
10249 }
10250 }
10251 _ => return None,
10252 };
10253 Some(ControlInput {
10254 path: path.to_vec(),
10255 action: ControlAction::TableSelection(action),
10256 })
10257 }
10258
10259 pub fn tree_selection_key(
10260 &self,
10261 scene: &Node,
10262 layout: &LayoutNode,
10263 key: TableSelectionKey,
10264 ) -> Option<ControlInput> {
10265 let path = self.focused_tree(scene, layout)?;
10266 let node = scene.at_path(path)?;
10267 let selection = node.tree_selection.as_ref()?;
10268 let tree = node.tree.as_ref()?;
10269 let action = match key {
10270 TableSelectionKey::All if !tree.rows().is_empty() => {
10271 ControlAction::Tree(TreeAction::Selection(TreeSelectionAction::All))
10272 }
10273 TableSelectionKey::Clear if !selection.is_empty() => {
10274 ControlAction::Tree(TreeAction::Selection(TreeSelectionAction::Clear))
10275 }
10276 TableSelectionKey::Toggle => {
10277 let index = tree.visible_index(node.int("current-key")?)?;
10278 tree_row_action(node, index, RowSelection::Toggle)?
10279 }
10280 _ => return None,
10281 };
10282 Some(ControlInput {
10283 path: path.to_vec(),
10284 action,
10285 })
10286 }
10287
10288 pub fn table_selection_key(
10289 &self,
10290 scene: &Node,
10291 key: TableSelectionKey,
10292 ) -> Option<ControlInput> {
10293 if self.editor.is_some() {
10294 return None;
10295 }
10296 let target = self.focused.as_ref()?;
10297 if key == TableSelectionKey::Toggle
10298 && scene
10299 .at_path(&target.path)
10300 .is_some_and(|node| node.boolean("table-editor", false) && is_toggle(node.kind))
10301 {
10302 return None;
10303 }
10304 if scene.row_key_at(&target.path) != target.row_key {
10305 return None;
10306 }
10307 let cell_row = table_cell_row(scene, &target.path);
10308 let path = cell_row.map_or(target.path.as_slice(), |(path, _)| path);
10309 let node = scene.interactive_at_path(path)?;
10310 let selection = node.table_selection.as_ref()?;
10311 node.table_header.as_ref()?;
10312 let list = node.list?;
10313 let action = match key {
10314 TableSelectionKey::All
10315 if selection.multiple()
10316 && (list.row_count > 0 || selection.target() == SelectionTarget::Columns) =>
10317 {
10318 TableSelectionAction::All
10319 }
10320 TableSelectionKey::Clear if !selection.is_empty() => TableSelectionAction::Clear,
10321 TableSelectionKey::Toggle => {
10322 let operation = RowSelection::Toggle;
10323 let header = node.table_header.as_ref()?;
10324 let visible =
10325 |&column: &usize| header.columns.get(column).is_some_and(Node::is_visible);
10326 let column = cell_row
10327 .and_then(|_| target.path.last().copied())
10328 .or(selection.current_column())
10329 .filter(visible)
10330 .or_else(|| {
10331 node.table_column_order
10332 .iter(header.columns.len())
10333 .find(visible)
10334 });
10335 if selection.target() == SelectionTarget::Columns {
10336 TableSelectionAction::Column {
10337 column: column?,
10338 operation,
10339 }
10340 } else {
10341 let row = if let Some((_, slot)) = cell_row {
10342 list.first_row.checked_add(slot)?
10343 } else {
10344 usize::try_from(node.int("current-row")?).ok()?
10345 };
10346 if row >= list.row_count {
10347 return None;
10348 }
10349 if selection.target() == SelectionTarget::Cells {
10350 TableSelectionAction::Cell {
10351 row,
10352 column: column?,
10353 operation,
10354 }
10355 } else {
10356 TableSelectionAction::Row {
10357 index: row,
10358 operation,
10359 }
10360 }
10361 }
10362 }
10363 _ => return None,
10364 };
10365 Some(ControlInput {
10366 path: path.to_vec(),
10367 action: ControlAction::TableSelection(action),
10368 })
10369 }
10370
10371 fn focused_clipboard_table<'a>(
10372 &'a self,
10373 scene: &Node,
10374 layout: &LayoutNode,
10375 ) -> Option<&'a [usize]> {
10376 let focused = self.focused.as_ref()?;
10377 if self.editor.is_some()
10378 || self.menu_open()
10379 || self.choice_open()
10380 || !valid(focused, scene, layout)
10381 {
10382 return None;
10383 }
10384 let path = (0..=focused.path.len())
10385 .rev()
10386 .map(|depth| &focused.path[..depth])
10387 .find(|path| {
10388 scene
10389 .at_path(path)
10390 .is_some_and(|node| node.kind == "TableView")
10391 })?;
10392 scene.interactive_at_path(path)?;
10393 self.allows_popup(layout, path).then_some(path)
10394 }
10395
10396 fn table_clipboard_target(
10397 &self,
10398 scene: &Node,
10399 layout: &LayoutNode,
10400 ) -> Option<(Vec<usize>, Vec<usize>)> {
10401 let path = self.focused_clipboard_table(scene, layout)?;
10402 let geometry = layout.at_path(path)?.table.as_ref()?;
10403 let columns = geometry.visible_columns().collect();
10404 Some((path.to_vec(), columns))
10405 }
10406
10407 pub fn table_edit_history_target<'a>(
10408 &'a self,
10409 scene: &Node,
10410 layout: &LayoutNode,
10411 ) -> Option<&'a [usize]> {
10412 let path = self.focused_clipboard_table(scene, layout)?;
10413 scene
10414 .at_path(path)?
10415 .table_edit_history_enabled()
10416 .then_some(path)
10417 }
10418
10419 #[doc(hidden)]
10420 pub fn table_paste_history_target<'a>(
10421 &'a self,
10422 scene: &Node,
10423 layout: &LayoutNode,
10424 ) -> Option<&'a [usize]> {
10425 self.table_edit_history_target(scene, layout)
10426 }
10427
10428 pub fn table_copy_target(
10429 &self,
10430 scene: &Node,
10431 layout: &LayoutNode,
10432 ) -> Option<(Vec<usize>, Vec<usize>)> {
10433 let (path, columns) = self.table_clipboard_target(scene, layout)?;
10434 scene
10435 .at_path(&path)?
10436 .boolean("copyable", false)
10437 .then_some((path, columns))
10438 }
10439
10440 pub fn table_paste_target(
10441 &self,
10442 scene: &Node,
10443 layout: &LayoutNode,
10444 ) -> Option<TablePasteDestination> {
10445 let (path, mut columns) = self.table_clipboard_target(scene, layout)?;
10446 let table = scene.at_path(&path)?;
10447 let row = usize::try_from(table.int("current-row")?).ok()?;
10448 if !table.boolean("pasteable", false) || row >= table.list?.row_count || columns.is_empty()
10449 {
10450 return None;
10451 }
10452 if let Some(column) = table.table_selection.as_ref().and_then(|selection| {
10453 (selection.target() != SelectionTarget::Rows)
10454 .then(|| selection.current_column())
10455 .flatten()
10456 }) {
10457 let start = columns.iter().position(|&candidate| candidate == column)?;
10458 columns.drain(..start);
10459 }
10460 Some(TablePasteDestination {
10461 path,
10462 row,
10463 columns,
10464 focus: self.focused.clone()?,
10465 })
10466 }
10467
10468 pub fn list_key_with_selection(
10469 &mut self,
10470 scene: &Node,
10471 layout: &LayoutNode,
10472 key: NavigationKey,
10473 operation: RowSelection,
10474 ) -> Option<ControlInput> {
10475 if let Some(input) = self.table_grid_key(scene, layout, key, operation) {
10476 return Some(input);
10477 }
10478 Some(
10479 self.list_key(scene, layout, key)?
10480 .with_row_selection(scene, operation),
10481 )
10482 }
10483
10484 fn table_grid_key(
10485 &mut self,
10486 scene: &Node,
10487 layout: &LayoutNode,
10488 key: NavigationKey,
10489 operation: RowSelection,
10490 ) -> Option<ControlInput> {
10491 let focused = self.focused.as_ref()?;
10492 let cell = table_cell_row(scene, &focused.path);
10493 let path = cell
10494 .map_or(focused.path.as_slice(), |(path, _)| path)
10495 .to_vec();
10496 let node = scene.interactive_at_path(&path)?;
10497 let view = node.table_selection.as_ref()?;
10498 if view.target() == SelectionTarget::Rows {
10499 return None;
10500 }
10501 let item = layout.at_path(&path)?;
10502 let table = item.table.as_ref()?;
10503 let current = view
10504 .current_column()
10505 .or_else(|| cell.and_then(|_| focused.path.last().copied()))
10506 .filter(|&column| column < table.columns.len());
10507 let current_visual = current.and_then(|column| table.visual_index(column));
10508 let visible = |&column: &usize| table.is_column_visible(column);
10509 let visible_current = current.filter(visible);
10510 let (previous, following) = navigation_axis(false, item.layout_direction);
10511 let next = match key {
10512 key if key == previous => table
10513 .visual_columns()
10514 .take(current_visual.unwrap_or(table.columns.len()))
10515 .rev()
10516 .find(visible)
10517 .or(visible_current)
10518 .or_else(|| table.visible_columns().next()),
10519 key if key == following => table
10520 .visual_columns()
10521 .skip(current_visual.map_or(0, |column| column + 1))
10522 .find(visible)
10523 .or(visible_current)
10524 .or_else(|| table.visible_columns().next_back()),
10525 NavigationKey::Home if view.target() == SelectionTarget::Columns => {
10526 table.visible_columns().next()
10527 }
10528 NavigationKey::End if view.target() == SelectionTarget::Columns => {
10529 table.visible_columns().next_back()
10530 }
10531 _ => None,
10532 };
10533 let action = if let Some(column) = next {
10534 if view.target() == SelectionTarget::Columns {
10535 TableSelectionAction::Column { column, operation }
10536 } else {
10537 let list = node.list?;
10538 if list.row_count == 0 {
10539 return None;
10540 }
10541 let row = ListMetrics::selection(node)
10542 .and_then(|value| usize::try_from(value).ok())
10543 .filter(|&row| row < list.row_count)
10544 .unwrap_or(list.first_row);
10545 self.reveal_row(&path, node, item, row);
10546 TableSelectionAction::Cell {
10547 row,
10548 column,
10549 operation,
10550 }
10551 }
10552 } else {
10553 let input = self.list_key(scene, layout, key)?;
10554 let ControlAction::Select(row) = input.action else {
10555 return None;
10556 };
10557 if view.target() == SelectionTarget::Columns {
10558 return Some(ControlInput {
10559 path,
10560 action: ControlAction::TableSelection(TableSelectionAction::Row {
10561 index: row,
10562 operation: RowSelection::Move,
10563 }),
10564 });
10565 }
10566 let column = visible_current.or_else(|| table.visible_columns().next())?;
10567 TableSelectionAction::Cell {
10568 row,
10569 column,
10570 operation,
10571 }
10572 };
10573 let column = match action {
10574 TableSelectionAction::Cell { column, .. }
10575 | TableSelectionAction::Column { column, .. } => column,
10576 _ => unreachable!(),
10577 };
10578 self.reveal_table_column(&path, item, column);
10579 self.set_focus(Some(Target::from_node(
10580 path.clone(),
10581 node,
10582 true,
10583 scene.row_key_at(&path),
10584 )));
10585 Some(ControlInput {
10586 path,
10587 action: ControlAction::TableSelection(action),
10588 })
10589 }
10590
10591 #[doc(hidden)]
10592 pub fn reveal_table_column(
10593 &mut self,
10594 path: &[usize],
10595 item: &LayoutNode,
10596 column: usize,
10597 ) -> bool {
10598 let Some(table) = &item.table else {
10599 return false;
10600 };
10601 let offset = table.reveal_column(column);
10602 if offset == table.horizontal.offset {
10603 return false;
10604 }
10605 store_scroll_offset(
10606 item,
10607 &mut self.horizontal_scroll_offsets,
10608 path,
10609 Orientation::Horizontal,
10610 offset,
10611 );
10612 UserScrollChange::commit(
10613 &mut self.user_scroll_changes,
10614 item,
10615 Orientation::Horizontal,
10616 table.horizontal.offset,
10617 offset,
10618 );
10619 true
10620 }
10621
10622 fn reveal_row(&mut self, path: &[usize], node: &Node, item: &LayoutNode, row: usize) {
10623 let Some(scroll) = item.scroll else {
10624 return;
10625 };
10626 let viewport = item.table.as_ref().map_or(item.bounds, |table| table.body);
10627 let cells = ViewCells::new(node, viewport.width);
10628 let offset = cells.reveal(scroll, row, viewport.height).offset;
10629 if offset != scroll.offset {
10630 store_scroll_offset(
10631 item,
10632 &mut self.scroll_offsets,
10633 path,
10634 Orientation::Vertical,
10635 offset,
10636 );
10637 UserScrollChange::commit(
10638 &mut self.user_scroll_changes,
10639 item,
10640 Orientation::Vertical,
10641 scroll.offset,
10642 offset,
10643 );
10644 }
10645 }
10646
10647 pub fn list_key(
10648 &mut self,
10649 scene: &Node,
10650 layout: &LayoutNode,
10651 key: NavigationKey,
10652 ) -> Option<ControlInput> {
10653 let target = self.focused.as_ref()?;
10654 let cell_view = table_cell_row(scene, &target.path)
10655 .or_else(|| tree_cell_row(scene, &target.path))
10656 .or_else(|| list_item_delegate_row(scene, &target.path))
10657 .map(|(view, _)| view);
10658 let focused_cell = cell_view.is_some();
10659 let path = cell_view.unwrap_or(&target.path);
10660 let node = scene.at_path(path)?;
10661 let list = node.list?;
10662 let last = list.row_count.checked_sub(1)?;
10663 let layout = layout.at_path(path)?;
10664 layout.scroll?;
10665 let viewport = layout
10666 .table
10667 .as_ref()
10668 .map_or(layout.bounds, |table| table.body);
10669 let cells = ViewCells::new(node, viewport.width);
10670 let columns = cells.columns;
10671 let current = ListMetrics::selection(node)
10672 .and_then(|value| usize::try_from(value).ok())
10673 .filter(|&row| row <= last);
10674 let key = if node.kind == "GridView"
10675 && layout.layout_direction == xrack_runtime::LayoutDirection::RightToLeft
10676 {
10677 match key {
10678 NavigationKey::Left => NavigationKey::Right,
10679 NavigationKey::Right => NavigationKey::Left,
10680 key => key,
10681 }
10682 } else {
10683 key
10684 };
10685 let index = match key {
10686 NavigationKey::Left if node.kind == "GridView" => current.map_or(0, |index| {
10687 if index.is_multiple_of(columns) {
10688 index
10689 } else {
10690 index - 1
10691 }
10692 }),
10693 NavigationKey::Right if node.kind == "GridView" => current.map_or(0, |index| {
10694 if (index + 1).is_multiple_of(columns) {
10695 index
10696 } else {
10697 (index + 1).min(last)
10698 }
10699 }),
10700 NavigationKey::Up => {
10701 current.map_or(0, |index| index.checked_sub(columns).unwrap_or(index))
10702 }
10703 NavigationKey::Down => current.map_or(0, |index| {
10704 if index / columns == last / columns {
10705 index
10706 } else {
10707 index.saturating_add(columns).min(last)
10708 }
10709 }),
10710 NavigationKey::Home => 0,
10711 NavigationKey::End => last,
10712 NavigationKey::PageUp => current.map_or(0, |row| {
10713 cells.page(row, viewport.height, list.row_count, false)
10714 }),
10715 NavigationKey::PageDown => current.map_or(0, |row| {
10716 cells.page(row, viewport.height, list.row_count, true)
10717 }),
10718 _ => return None,
10719 };
10720 let action = ControlInput {
10721 path: path.to_vec(),
10722 action: ControlAction::Select(index),
10723 };
10724 self.reset_list_typeahead();
10725 self.reveal_row(&action.path, node, layout, index);
10726 if focused_cell {
10727 self.set_focus(Some(Target::from_node(
10728 action.path.clone(),
10729 node,
10730 true,
10731 scene.row_key_at(&action.path),
10732 )));
10733 }
10734 Some(action)
10735 }
10736
10737 pub fn tab_move_key(
10739 &self,
10740 scene: &Node,
10741 layout: &LayoutNode,
10742 key: NavigationKey,
10743 ) -> Option<Option<ControlInput>> {
10744 self.tab_move_target(scene, layout, self.focused.as_ref()?, key)
10745 }
10746
10747 #[doc(hidden)]
10749 pub fn tab_move_target(
10750 &self,
10751 scene: &Node,
10752 layout: &LayoutNode,
10753 target: &Target,
10754 key: NavigationKey,
10755 ) -> Option<Option<ControlInput>> {
10756 let (&from, path) = target.path.split_last()?;
10757 let bar = scene.at_path(path)?;
10758 let item = layout.at_path(path)?;
10759 if !matches!(bar.kind, "TabBar" | "TabWidget")
10760 || !bar.boolean("reorderable", false)
10761 || !valid(target, scene, layout)
10762 || !self.allows_popup(layout, &target.path)
10763 {
10764 return None;
10765 }
10766 let (previous, following) = navigation_axis(
10767 bar.orientation() == Orientation::Vertical,
10768 item.layout_direction,
10769 );
10770 let available = |slot| group_item(bar, slot).is_some();
10771 let to = if key == previous {
10772 (0..from).rev().find(|&slot| available(slot))
10773 } else if key == following {
10774 (from + 1..bar.children.len()).find(|&slot| available(slot))
10775 } else {
10776 return None;
10777 };
10778 Some(to.and_then(|to| {
10779 Some(ControlInput {
10780 path: path.to_vec(),
10781 action: ControlAction::MoveTab(bar.tab_move(from, to)?),
10782 })
10783 }))
10784 }
10785
10786 pub fn group_key(
10787 &mut self,
10788 scene: &Node,
10789 layout: &LayoutNode,
10790 key: NavigationKey,
10791 ) -> Option<ControlInput> {
10792 let target = self.focused.as_ref()?;
10793 if let Some((member, component)) = attached_radio(scene, &target.path) {
10794 let scope = self
10795 .focused_popup(layout)
10796 .or_else(|| self.active_dialog(layout))
10797 .unwrap_or_default();
10798 let choices: Vec<_> = member
10799 .group
10800 .paths()
10801 .filter_map(|path| {
10802 let path = [component, path].concat();
10803 if !path.starts_with(scope) {
10804 return None;
10805 }
10806 let node = scene.interactive_at_path(&path)?;
10807 let item = layout.at_path(&path)?;
10808 let row_key = scene.row_key_at(&path);
10809 eligible(node, item).then(|| Target::from_node(path, node, true, row_key))
10810 })
10811 .collect();
10812 let position = choices.iter().position(|choice| choice == target)?;
10813 let len = choices.len();
10814 let index = match key {
10815 NavigationKey::Home => 0,
10816 NavigationKey::End => len - 1,
10817 NavigationKey::Up | NavigationKey::Left => (position + len - 1) % len,
10818 NavigationKey::Down | NavigationKey::Right => (position + 1) % len,
10819 _ => return None,
10820 };
10821 let next = choices[index].clone();
10822 let action = ControlInput {
10823 path: next.path.clone(),
10824 action: ControlAction::ActivateRadioOption,
10825 };
10826 self.set_focus(Some(next));
10827 return Some(action);
10828 }
10829 let (¤t, path) = target.path.split_last()?;
10830 let group = scene.at_path(path)?;
10831 group_item(group, current)?;
10832 let vertical =
10833 if group.kind == "RadioGroup" && !group.properties.contains_key("orientation") {
10834 true
10835 } else {
10836 group.orientation() == Orientation::Vertical
10837 };
10838 let group_layout = layout.at_path(path)?;
10839 let choices: Vec<_> = group_targets(group, group_layout, path, false).collect();
10840 let position = choices.iter().position(|(index, _)| *index == current)?;
10841 let len = choices.len();
10842 let (previous, next) = navigation_axis(vertical, group_layout.layout_direction);
10843 let next = match key {
10844 NavigationKey::Home => 0,
10845 NavigationKey::End => len - 1,
10846 key if key == previous => (position + len - 1) % len,
10847 key if key == next => (position + 1) % len,
10848 _ => return None,
10849 };
10850 let (index, next) = &choices[next];
10851 let action = ControlInput {
10852 path: path.to_vec(),
10853 action: ControlAction::Select(*index),
10854 };
10855 let mut next = next.clone();
10856 next.row_key = scene.row_key_at(&next.path);
10857 self.reveal_tab(group, group_layout, &action.path, *index);
10858 self.set_focus(Some(next));
10859 Some(action)
10860 }
10861
10862 #[doc(hidden)]
10863 pub fn reveal_tab(
10864 &mut self,
10865 group: &Node,
10866 item: &LayoutNode,
10867 path: &[usize],
10868 index: usize,
10869 ) -> bool {
10870 if !matches!(group.kind, "TabBar" | "TabWidget") {
10871 return false;
10872 }
10873 let orientation = group.orientation();
10874 let Some(scroll) = item.scroll_on(orientation) else {
10875 return false;
10876 };
10877 let Some(header) = item.tab_item_rect(index) else {
10878 return false;
10879 };
10880 let offset = crate::selection::tab_reveal_offset(
10881 item.tab_viewport(),
10882 header,
10883 orientation,
10884 item.layout_direction,
10885 scroll.offset,
10886 )
10887 .clamp(0.0, scroll.max_offset);
10888 if offset == scroll.offset {
10889 return false;
10890 }
10891 let offsets = match orientation {
10892 Orientation::Horizontal => &mut self.horizontal_scroll_offsets,
10893 Orientation::Vertical => &mut self.scroll_offsets,
10894 };
10895 offsets.insert(path.to_vec(), offset);
10896 true
10897 }
10898
10899 pub fn swipe_key(
10900 &mut self,
10901 scene: &Node,
10902 layout: &LayoutNode,
10903 key: NavigationKey,
10904 ) -> Option<ControlInput> {
10905 let target = self.focused.as_ref()?;
10906 if !valid(target, scene, layout) {
10907 return None;
10908 }
10909 let (path, view) = (0..=target.path.len()).rev().find_map(|depth| {
10910 let path = &target.path[..depth];
10911 let view = scene.interactive_at_path(path)?;
10912 (view.kind == "SwipeView" && view.boolean("interactive", true)).then_some((path, view))
10913 })?;
10914 let index = swipe_view_selection(view, layout.at_path(path)?, key)?;
10915 Some(ControlInput {
10916 path: path.to_vec(),
10917 action: ControlAction::Select(index),
10918 })
10919 }
10920
10921 pub fn swipe_delegate_key(
10922 &self,
10923 scene: &Node,
10924 layout: &LayoutNode,
10925 key: NavigationKey,
10926 ) -> Option<ControlInput> {
10927 let focused = self.focused.as_ref()?;
10928 let scope = self.active_dialog(layout).unwrap_or_default();
10929 if !focused.path.starts_with(scope) || !valid(focused, scene, layout) {
10930 return None;
10931 }
10932 let path = (scope.len()..=focused.path.len()).rev().find_map(|depth| {
10933 let path = &focused.path[..depth];
10934 layout.at_path(path)?.swipe_delegate.as_deref()?;
10935 Some(path)
10936 })?;
10937 let target = self.accessibility_target(scene, layout, path)?;
10938 let geometry = layout.at_path(path)?.swipe_delegate.as_deref()?;
10939 let side = match (key, geometry.side) {
10940 (NavigationKey::Left, SwipeSide::Left) | (NavigationKey::Right, SwipeSide::Right) => {
10941 SwipeSide::Closed
10942 }
10943 (NavigationKey::Left, _) => SwipeSide::Right,
10944 (NavigationKey::Right, _) => SwipeSide::Left,
10945 _ => return None,
10946 };
10947 self.swipe_delegate_action(scene, layout, &target, side)
10948 }
10949
10950 fn swipe_delegate_action(
10951 &self,
10952 scene: &Node,
10953 layout: &LayoutNode,
10954 target: &Target,
10955 side: SwipeSide,
10956 ) -> Option<ControlInput> {
10957 let geometry = layout.at_path(&target.path)?.swipe_delegate.as_deref()?;
10958 (valid(target, scene, layout) && geometry.side != side && geometry.supports(side)).then(
10959 || ControlInput {
10960 path: target.path.clone(),
10961 action: ControlAction::SwipeDelegate(side),
10962 },
10963 )
10964 }
10965
10966 pub fn swipe_delegate_accessibility(
10967 &self,
10968 scene: &Node,
10969 layout: &LayoutNode,
10970 target: &Target,
10971 expand: bool,
10972 ) -> Option<ControlInput> {
10973 let geometry = layout.at_path(&target.path)?.swipe_delegate.as_deref()?;
10974 if expand == (geometry.side != SwipeSide::Closed) {
10975 return None;
10976 }
10977 let side = if !expand {
10978 SwipeSide::Closed
10979 } else if geometry.supports(SwipeSide::Right) {
10980 SwipeSide::Right
10981 } else {
10982 SwipeSide::Left
10983 };
10984 self.swipe_delegate_accessibility_side(scene, layout, target, side)
10985 }
10986
10987 #[doc(hidden)]
10989 pub fn swipe_delegate_accessibility_side(
10990 &self,
10991 scene: &Node,
10992 layout: &LayoutNode,
10993 target: &Target,
10994 side: SwipeSide,
10995 ) -> Option<ControlInput> {
10996 if self.menu_open()
10997 || self.choice_open()
10998 || !self.allows_popup(layout, &target.path)
10999 || !layout
11000 .at_path(&target.path)?
11001 .swipe_delegate
11002 .as_deref()?
11003 .actions_available()
11004 {
11005 return None;
11006 }
11007 self.swipe_delegate_action(scene, layout, target, side)
11008 }
11009
11010 pub fn dismiss_focused_swipe(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
11011 let focused = self.focused.as_ref()?;
11012 (0..=focused.path.len()).rev().find_map(|depth| {
11013 let path = &focused.path[..depth];
11014 let geometry = layout.at_path(path)?.swipe_delegate.as_deref()?;
11015 if geometry.side == SwipeSide::Closed {
11016 return None;
11017 }
11018 let target = self.accessibility_target(scene, layout, path)?;
11019 self.swipe_delegate_action(scene, layout, &target, SwipeSide::Closed)
11020 })
11021 }
11022
11023 pub fn stack_back(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
11024 let focused = self.focused.as_ref()?;
11025 let scope = self.active_dialog(layout).unwrap_or_default();
11026 if !focused.path.starts_with(scope) || !valid(focused, scene, layout) {
11027 return None;
11028 }
11029 (scope.len()..=focused.path.len()).rev().find_map(|depth| {
11030 let path = &focused.path[..depth];
11031 let stack = scene.interactive_at_path(path)?.stack.as_ref()?;
11032 (stack.depth() > 1).then(|| ControlInput {
11033 path: path.to_vec(),
11034 action: ControlAction::StackBack {
11035 revision: stack.revision(),
11036 },
11037 })
11038 })
11039 }
11040
11041 pub fn stack_back_in_window(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
11044 if let Some(action) = self.stack_back(scene, layout) {
11045 return Some(action);
11046 }
11047 fn collect(
11048 node: &Node,
11049 layout: &LayoutNode,
11050 path: &mut Vec<usize>,
11051 candidates: &mut Vec<ControlInput>,
11052 ) {
11053 if !layout.visible || !layout.enabled || candidates.len() > 1 {
11054 return;
11055 }
11056 let before = candidates.len();
11057 for (slot, child, item) in layout.children_in_scene_order(node) {
11059 path.push(slot);
11060 collect(child, item, path, candidates);
11061 path.pop();
11062 if candidates.len() > 1 {
11063 return;
11064 }
11065 }
11066 let visible = layout.bounds.intersect(layout.clip);
11067 if candidates.len() == before
11068 && visible.width > 0.0
11069 && visible.height > 0.0
11070 && let Some(stack) = node.stack.as_ref().filter(|stack| stack.depth() > 1)
11071 {
11072 candidates.push(ControlInput {
11073 path: path.clone(),
11074 action: ControlAction::StackBack {
11075 revision: stack.revision(),
11076 },
11077 });
11078 }
11079 }
11080 let scope = self.active_dialog(layout).unwrap_or_default();
11081 let mut path = scope.to_vec();
11082 let mut candidates = Vec::new();
11083 collect(
11084 scene.at_path(scope)?,
11085 layout.at_path(scope)?,
11086 &mut path,
11087 &mut candidates,
11088 );
11089 (candidates.len() == 1).then(|| candidates.swap_remove(0))
11090 }
11091
11092 pub fn pointer_release(&mut self) -> Option<&'static str> {
11093 self.pointer_release_target().and_then(|target| target.id)
11094 }
11095
11096 pub fn page_marker_release(
11097 &mut self,
11098 scene: &Node,
11099 layout: &LayoutNode,
11100 ) -> Option<ControlInput> {
11101 matches!(self.pressed_control_part, Some(ControlAction::Select(_))).then_some(())?;
11102 self.control_part_release(scene, layout)
11103 }
11104
11105 pub fn control_part_release(
11106 &mut self,
11107 scene: &Node,
11108 layout: &LayoutNode,
11109 ) -> Option<ControlInput> {
11110 let action = self.pressed_control_part?;
11111 let pressed = self.pointer_release_target()?;
11112 let Hit::ControlPart(target, current) = self.hit_at(scene, layout, self.pointer?) else {
11113 return None;
11114 };
11115 (pressed == target && action == current).then_some(ControlInput {
11116 path: target.path,
11117 action,
11118 })
11119 }
11120
11121 pub fn page_marker_hovered(&self, path: &[usize], index: usize) -> bool {
11122 self.hovered_control_part == Some(ControlAction::Select(index)) && self.is_hovered(path)
11123 }
11124
11125 pub fn page_indicator_key(
11126 &self,
11127 scene: &Node,
11128 layout: &LayoutNode,
11129 key: NavigationKey,
11130 ) -> Option<ControlInput> {
11131 let target = self.focused.as_ref()?;
11132 let node = scene.at_path(&target.path)?;
11133 if node.kind != "PageIndicator" || !valid(target, scene, layout) {
11134 return None;
11135 }
11136 let last = page_indicator_count(node).checked_sub(1)?;
11137 let current = page_indicator_index(node);
11138 let vertical = node.orientation() == Orientation::Vertical;
11139 let direction = layout.at_path(&target.path)?.layout_direction;
11140 let (previous, next) = navigation_axis(vertical, direction);
11141 let index = match key {
11142 NavigationKey::Home => 0,
11143 NavigationKey::End => last,
11144 key if key == previous => page_indicator_step(node, false)?,
11145 key if key == next => page_indicator_step(node, true)?,
11146 _ => return None,
11147 };
11148 (current != Some(index)).then(|| ControlInput {
11149 path: target.path.clone(),
11150 action: ControlAction::Select(index),
11151 })
11152 }
11153
11154 #[doc(hidden)]
11156 pub fn calendar_page_key(
11157 &mut self,
11158 scene: &Node,
11159 layout: &LayoutNode,
11160 key: NavigationKey,
11161 ) -> bool {
11162 let step = match key {
11163 NavigationKey::PageUp => -1,
11164 NavigationKey::PageDown => 1,
11165 _ => return false,
11166 };
11167 let Some(from) = self
11168 .focused
11169 .as_ref()
11170 .filter(|target| valid(target, scene, layout))
11171 else {
11172 return false;
11173 };
11174 if !from
11175 .node_in(scene)
11176 .is_some_and(|node| node.kind == "MonthGrid" && node.boolean("fixed-month", false))
11177 {
11178 return false;
11179 }
11180 let Some((view, node, item, index, order)) = (0..from.path.len()).rev().find_map(|depth| {
11181 let view = &from.path[..depth];
11182 let node = scene
11183 .interactive_at_path(view)
11184 .filter(|node| node.kind == "ListView")?;
11185 let item = layout
11186 .at_path(view)
11187 .filter(|item| item.enabled && item.scroll.is_some())?;
11188 let list = node.list?;
11189 let slot = from.path[depth];
11190 let row = node
11191 .child_at(slot)
11192 .filter(|child| child.kind == "ListRow")?
11193 .routing_row_key()?;
11194 let index = list
11195 .first_row
11196 .checked_add(slot)
11197 .filter(|&index| index < list.row_count)?;
11198 let order = node.standard_list_stamp?;
11199 (from.row_key == Some(row)).then_some((view, node, item, index, order))
11200 }) else {
11201 return false;
11202 };
11203 if let Some(index) = index
11204 .checked_add_signed(step)
11205 .filter(|&index| node.list.is_some_and(|list| index < list.row_count))
11206 {
11207 let page = CalendarPageFocus {
11208 from: from.clone(),
11209 view: Target::from_node(view.to_vec(), node, true, scene.row_key_at(view)),
11210 viewport: node.viewport_handle.clone(),
11211 order,
11212 index,
11213 };
11214 self.reveal_row(&page.view.path, node, item, index);
11215 self.calendar_page_focus = Some(page);
11216 }
11217 true
11218 }
11219
11220 fn finish_calendar_page_focus(&mut self, scene: &Node, layout: &LayoutNode) {
11221 let Some(page) = self
11222 .calendar_page_focus
11223 .take()
11224 .filter(|page| self.focused.as_ref() == Some(&page.from))
11225 else {
11226 return;
11227 };
11228 let Some(view) = page.view.node_in(scene).filter(|view| {
11231 view.kind == "ListView"
11232 && view.viewport_handle == page.viewport
11233 && view.standard_list_stamp == Some(page.order)
11234 }) else {
11235 return;
11236 };
11237 let Some(slot) = view
11238 .list
11239 .and_then(|list| page.index.checked_sub(list.first_row))
11240 else {
11241 return;
11242 };
11243 let Some(row) = view
11244 .child_at(slot)
11245 .filter(|row| row.kind == "ListRow")
11246 .and_then(Node::routing_row_key)
11247 else {
11248 return;
11249 };
11250 let mut path = page.view.path;
11251 let tail = &page.from.path[path.len() + 1..];
11252 path.push(slot);
11253 path.extend_from_slice(tail);
11254 let Some(target) = self
11255 .accessibility_target(scene, layout, &path)
11256 .filter(|target| {
11257 target.focusable
11258 && target.row_key == Some(row)
11259 && target.element_id() == page.from.element_id()
11260 && target.node_in(scene).is_some_and(|node| {
11261 node.kind == "MonthGrid" && node.boolean("fixed-month", false)
11262 })
11263 })
11264 else {
11265 return;
11266 };
11267 self.set_focus(Some(target));
11268 self.remember_focus_scope(scene, layout);
11269 }
11270
11271 pub fn calendar_key(
11272 &self,
11273 scene: &Node,
11274 layout: &LayoutNode,
11275 key: NavigationKey,
11276 ) -> Option<ControlInput> {
11277 let target = self.focused.as_ref()?;
11278 let node = scene.at_path(&target.path)?;
11279 if !is_calendar_control(node.kind) || !valid(target, scene, layout) {
11280 return None;
11281 }
11282 let item = layout.at_path(&target.path)?;
11283 let geometry = CalendarGeometry::for_layout(node, item);
11284 let calendar = &geometry.state;
11285 let day = |delta| {
11286 let date = geometry
11287 .navigation_origin()?
11288 .add_days(delta)
11289 .unwrap_or(if delta < 0 { Date::MIN } else { Date::MAX })
11290 .clamp(calendar.minimum, calendar.maximum);
11291 calendar.selectable_from(date, delta > 0)
11292 };
11293 let month = |offset| {
11294 if geometry.has_header() {
11295 calendar.adjacent_month(offset)
11296 } else {
11297 calendar.month.add_months(offset)
11298 }
11299 .unwrap_or(calendar.month)
11300 };
11301 let right_step = if item.layout_direction == LayoutDirection::RightToLeft {
11302 -1
11303 } else {
11304 1
11305 };
11306 let action = match key {
11307 NavigationKey::Left => CalendarAction::Select(day(-right_step)?),
11308 NavigationKey::Right => CalendarAction::Select(day(right_step)?),
11309 NavigationKey::Up => CalendarAction::Select(day(-7)?),
11310 NavigationKey::Down => CalendarAction::Select(day(7)?),
11311 NavigationKey::Home | NavigationKey::End => {
11312 let date = if key == NavigationKey::Home {
11313 calendar.month.max(calendar.minimum)
11314 } else {
11315 calendar.month.last_of_month().min(calendar.maximum)
11316 };
11317 let date = calendar.selectable_from(date, key == NavigationKey::Home)?;
11318 if date.first_of_month() != calendar.month {
11319 return None;
11320 }
11321 CalendarAction::Select(date)
11322 }
11323 NavigationKey::PageUp | NavigationKey::PageDown if calendar.fixed_month => return None,
11324 NavigationKey::PageUp => CalendarAction::Browse(month(-1)),
11325 NavigationKey::PageDown => CalendarAction::Browse(month(1)),
11326 };
11327 Some(ControlInput {
11328 path: target.path.clone(),
11329 action: ControlAction::Calendar(action),
11330 })
11331 }
11332
11333 pub fn text_link_target(
11334 &self,
11335 scene: &Node,
11336 layout: &LayoutNode,
11337 path: &[usize],
11338 index: usize,
11339 ) -> Option<Target> {
11340 let node = scene.at_path(path)?;
11341 let mut target = Target::for_text_link(node, path, index)?;
11342 target.row_key = scene.row_key_at(path);
11343 self.text_link_activation(scene, layout, &target)
11344 .map(|_| target)
11345 }
11346
11347 pub fn text_link_activation(
11348 &self,
11349 scene: &Node,
11350 layout: &LayoutNode,
11351 target: &Target,
11352 ) -> Option<ControlInput> {
11353 let index = target.text_link_index()?;
11354 let scope = self
11355 .focused_popup(layout)
11356 .or_else(|| self.active_dialog(layout));
11357 (self.menu.is_none()
11358 && self.choice.is_none()
11359 && scope.is_none_or(|scope| target.path.starts_with(scope))
11360 && valid(target, scene, layout))
11361 .then(|| ControlInput {
11362 path: target.path.clone(),
11363 action: ControlAction::ActivateTextLink(index),
11364 })
11365 }
11366
11367 pub fn calendar_activate(
11368 &self,
11369 scene: &Node,
11370 layout: &LayoutNode,
11371 target: &Target,
11372 ) -> Option<ControlInput> {
11373 let node = scene.at_path(&target.path)?;
11374 if !is_calendar_control(node.kind) || !valid(target, scene, layout) {
11375 return None;
11376 }
11377 let geometry = CalendarGeometry::for_layout(node, layout.at_path(&target.path)?);
11378 let date = geometry.cursor()?;
11379 geometry.state.allows(date).then(|| ControlInput {
11380 path: target.path.clone(),
11381 action: ControlAction::Calendar(geometry.day_action(date)),
11382 })
11383 }
11384
11385 pub fn pointer_release_target(&mut self) -> Option<Target> {
11386 self.text_selection_scroll = None;
11387 if self.pressed.is_some() {
11388 self.last_editor_click = self.editor_press.take().filter(|press| {
11389 self.pressed.as_ref() == Some(&press.target)
11390 && self.hovered.as_ref() == Some(&press.target)
11391 && !self.pointer_activation_claimed
11392 });
11393 }
11394 self.finish_button_contact(
11395 ButtonContactSource::Pointer,
11396 self.pressed.is_some() && self.pressed == self.hovered,
11397 );
11398 if self
11399 .button_hold
11400 .as_ref()
11401 .is_some_and(|repeat| matches!(repeat.source, DelaySource::Pointer))
11402 {
11403 self.button_hold = None;
11404 }
11405 let split_resized = self.clear_split_drag();
11406 self.table_column_move = None;
11407 if self.cancel_table_row_move() {
11408 return None;
11409 }
11410 if self.cancel_table_drag_selection() {
11411 return None;
11412 }
11413 let claimed = std::mem::take(&mut self.pointer_activation_claimed);
11414 if self
11415 .delay_hold
11416 .as_ref()
11417 .is_some_and(|hold| matches!(hold.source, DelaySource::Pointer))
11418 {
11419 self.cancel_delay();
11420 }
11421 if self.finish_scroll_bar() {
11422 return None;
11423 }
11424 let pressed_radio = self.pressed_radio.take();
11425 let pressed_list = self.pressed_list_row.take();
11426 let pressed_column = self.pressed_table_column.take();
11427 let pressed_body_column = self.pressed_body_column.take();
11428 let pressed_control_part = self.pressed_control_part.take();
11429 let pressed_standard_button = self.pressed_standard_button.take();
11430 let resized = self.table_resize.take().is_some() | self.table_row_resize.take().is_some();
11431 let pressed = self.pressed.take()?;
11432 (!claimed
11433 && !resized
11434 && !split_resized
11435 && self.hovered.as_ref() == Some(&pressed)
11436 && pressed_radio == self.hovered_radio
11437 && pressed_list == self.hovered_list_row
11438 && self.pressed_tree_indicator == self.hovered_tree_indicator
11439 && pressed_column == self.hovered_table_column
11440 && pressed_body_column == self.hovered_body_column
11441 && pressed_control_part == self.hovered_control_part
11442 && pressed_standard_button == self.hovered_standard_button)
11443 .then_some(pressed)
11444 }
11445
11446 pub fn table_sort_release(&mut self) -> Option<ControlInput> {
11447 let column = self.pressed_table_column?;
11448 let target = self.pointer_release_target()?;
11449 Some(ControlInput {
11450 path: target.path,
11451 action: ControlAction::SortColumn(column),
11452 })
11453 }
11454
11455 pub fn table_header_release(
11456 &mut self,
11457 scene: &Node,
11458 operation: RowSelection,
11459 sort: bool,
11460 ) -> Option<ControlInput> {
11461 let mut input = self.table_sort_release()?;
11462 let ControlAction::SortColumn(column) = input.action else {
11463 return None;
11464 };
11465 let table = scene.interactive_at_path(&input.path)?;
11466 if table.selection_target() == SelectionTarget::Columns && !sort {
11467 input.action =
11468 ControlAction::TableSelection(TableSelectionAction::Column { column, operation });
11469 } else {
11470 table.table_header.as_ref()?.next_sort(column)?;
11471 }
11472 Some(input)
11473 }
11474
11475 pub fn table_column_hovered(&self, path: &[usize], column: usize) -> bool {
11476 self.is_hovered(path) && self.hovered_table_column == Some(column)
11477 }
11478
11479 pub fn arm_table_drag_selection(
11481 &mut self,
11482 scene: &Node,
11483 layout: &LayoutNode,
11484 additive: bool,
11485 ) -> bool {
11486 self.table_drag_selection = (|| {
11487 if self.drag.is_some() || self.table_row_resize.is_some() || self.table_resize.is_some()
11488 {
11489 return None;
11490 }
11491 self.table_selection_at(
11492 scene,
11493 layout,
11494 self.pressed.as_ref()?,
11495 self.pointer?,
11496 additive,
11497 )
11498 .filter(|drag| !drag.gesture.uses_hold(false))
11499 })();
11500 self.table_drag_selection.is_some()
11501 }
11502
11503 pub fn press_table_drag_selection(
11505 &mut self,
11506 scene: &Node,
11507 layout: &LayoutNode,
11508 additive: bool,
11509 ) -> bool {
11510 if self.drag.is_some()
11511 || self.hovered_table_row_grip.is_some()
11512 || self.hovered_table_grip.is_some()
11513 || self.menu_open()
11514 || self.choice_open()
11515 {
11516 return false;
11517 }
11518 let Some(drag) = self
11519 .hovered
11520 .as_ref()
11521 .zip(self.pointer)
11522 .and_then(|(target, point)| {
11523 self.table_selection_at(scene, layout, target, point, additive)
11524 .filter(|drag| !drag.gesture.uses_hold(false))
11525 })
11526 else {
11527 return false;
11528 };
11529 self.pointer_press_in_scene(scene, layout);
11530 self.table_drag_selection = Some(drag);
11531 true
11532 }
11533
11534 fn table_selection_at(
11535 &self,
11536 scene: &Node,
11537 layout: &LayoutNode,
11538 target: &Target,
11539 point: Point,
11540 additive: bool,
11541 ) -> Option<crate::table_drag_selection::TableDragSelection> {
11542 if self.is_text_editor(scene.at_path(&target.path)?, target) {
11543 return None;
11544 }
11545 let (path, slot) = table_hit_row(scene, &target.path)?;
11546 let table = scene.at_path(path)?;
11547 let item = layout.at_path(path)?;
11548 let column = item
11549 .table
11550 .as_ref()?
11551 .body_column_at(item.map_from_window(point)?)?;
11552 crate::table_drag_selection::TableDragSelection::new(
11553 path.to_vec(),
11554 table,
11555 (table.list?.first_row + slot, column),
11556 point,
11557 additive,
11558 scene.row_key_at(path),
11559 item.scroll_axis_reversed(Orientation::Horizontal),
11560 )
11561 }
11562
11563 fn table_gesture_at(
11564 &self,
11565 scene: &Node,
11566 layout: &LayoutNode,
11567 target: &Target,
11568 point: Point,
11569 touch: bool,
11570 now: Instant,
11571 additive: bool,
11572 ) -> Option<PendingTableGesture> {
11573 if touch && let Some(drag) = Self::table_row_move_at(scene, layout, target, point) {
11574 return Some(PendingTableGesture {
11575 drag: PendingTableAction::Move(drag),
11576 deadline: Some(now + Duration::from_millis(500)),
11577 });
11578 }
11579 let select = self.table_selection_at(scene, layout, target, point, additive)?;
11580 let hold = select.gesture.uses_hold(touch);
11581 if !touch && !hold {
11582 return None;
11583 }
11584 if select.gesture != xrack_runtime::SelectionGesture::Auto
11587 && !matches!(
11588 scene.at_path(&target.path)?.kind,
11589 "TableCell" | "TableRow" | "ListRow"
11590 )
11591 {
11592 return None;
11593 }
11594 let deadline = hold.then(|| now + Duration::from_millis(select.hold_interval));
11595 Some(PendingTableGesture {
11596 drag: PendingTableAction::Select(select),
11597 deadline,
11598 })
11599 }
11600
11601 pub fn advance_table_touch_hold(
11603 &mut self,
11604 scene: &Node,
11605 layout: &LayoutNode,
11606 now: Instant,
11607 ) -> bool {
11608 let Some(gesture) = &mut self.scroll_gesture else {
11609 return false;
11610 };
11611 let Some(hold) = gesture
11612 .table_gesture
11613 .take_if(|hold| hold.deadline.is_some_and(|deadline| now >= deadline))
11614 else {
11615 return false;
11616 };
11617 let touch = gesture.touch_point.is_some();
11618 if self.drag.is_some() || self.menu_open() || self.choice_open() {
11619 return false;
11620 }
11621 match hold.drag {
11622 PendingTableAction::Select(mut drag) => {
11623 drag.claimed = true;
11624 drag.touch = touch;
11625 drag.scroll_capture = true;
11626 if self
11627 .table_drag_route(scene, layout, &drag, drag.start)
11628 .is_none()
11629 {
11630 return false;
11631 }
11632 self.cancel_scroll_gesture();
11633 self.capture_table_selection(drag);
11634 }
11635 PendingTableAction::Move(mut drag) => {
11636 let Hit::Target(target) = self.hit_at(scene, layout, drag.start) else {
11637 return false;
11638 };
11639 if Self::table_row_move_at(scene, layout, &target, drag.start).is_none_or(
11640 |current| {
11641 current.table != drag.table
11642 || current.row != drag.row
11643 || current.stamp != drag.stamp
11644 },
11645 ) {
11646 return false;
11647 }
11648 drag.claimed = true;
11649 drag.touch = true;
11650 self.cancel_scroll_gesture();
11651 self.pointer = Some(drag.start);
11652 self.claim_table_selection(drag.table.clone());
11653 self.table_row_move = Some(drag);
11654 }
11655 }
11656 true
11657 }
11658
11659 pub fn table_touch_hold_deadline(&self) -> Option<Instant> {
11660 self.scroll_gesture
11661 .as_ref()?
11662 .table_gesture
11663 .as_ref()?
11664 .deadline
11665 }
11666
11667 fn capture_table_selection(
11668 &mut self,
11669 mut drag: crate::table_drag_selection::TableDragSelection,
11670 ) {
11671 drag.begin_presentation();
11672 self.pointer = Some(drag.start);
11673 let focus = drag.focus_target();
11674 self.table_drag_selection = Some(drag);
11675 self.claim_table_selection(focus);
11676 }
11677
11678 fn table_selection_handle_geometry(
11679 &self,
11680 path: &[usize],
11681 node: &Node,
11682 item: &LayoutNode,
11683 ) -> Option<[Option<crate::table_drag_selection::TableSelectionHandle>; 2]> {
11684 if !self.is_focused(path)
11685 || self.menu_open()
11686 || self.choice_open()
11687 || self.table_edit.is_some()
11688 || self.table_drag_selection_claimed()
11689 {
11690 return None;
11691 }
11692 crate::table_drag_selection::selection_handles(node, item)
11693 }
11694
11695 pub fn table_selection_handles(
11697 &self,
11698 path: &[usize],
11699 node: &Node,
11700 item: &LayoutNode,
11701 ) -> impl Iterator<Item = Rect> {
11702 self.table_selection_handle_parts(path, node, item)
11703 .map(|(_, bounds)| bounds)
11704 }
11705
11706 pub fn table_selection_handle_parts(
11708 &self,
11709 path: &[usize],
11710 node: &Node,
11711 item: &LayoutNode,
11712 ) -> impl Iterator<Item = (usize, Rect)> {
11713 let custom =
11714 node.table_selection_part(0).is_some() || node.table_selection_part(1).is_some();
11715 let preview = if custom {
11716 self.table_drag_selection
11717 .as_ref()
11718 .filter(|drag| drag.path == path && drag.valid(node, item))
11719 .zip(self.pointer)
11720 .and_then(|(drag, point)| drag.preview_handles(node, item, point))
11721 } else {
11722 None
11723 };
11724 preview
11725 .or_else(|| self.table_selection_handle_geometry(path, node, item))
11726 .into_iter()
11727 .flatten()
11728 .enumerate()
11729 .filter_map(|(index, handle)| Some((index, handle?.bounds)))
11730 }
11731
11732 pub fn press_table_selection_handle(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
11733 self.pointer.is_some_and(|point| {
11734 self.start_table_selection_handle(scene, layout, point, false, false)
11735 })
11736 }
11737
11738 fn start_table_selection_handle(
11739 &mut self,
11740 scene: &Node,
11741 layout: &LayoutNode,
11742 point: Point,
11743 touch: bool,
11744 scroll_capture: bool,
11745 ) -> bool {
11746 let drag = (|| {
11747 let focus = self.focused.as_ref()?;
11748 let node = scene.interactive_at_path(&focus.path)?;
11749 let item = layout.at_path(&focus.path)?;
11750 let local = item.map_from_window(point)?;
11751 let handle = self
11752 .table_selection_handle_geometry(&focus.path, node, item)?
11753 .into_iter()
11754 .flatten()
11755 .find(|handle| handle.bounds.contains(local))?;
11756 match self.hit_at(scene, layout, point) {
11757 Hit::Target(target)
11758 | Hit::ControlPart(target, _)
11759 | Hit::TableRowGrip(target, _)
11760 if target.path.starts_with(&focus.path) => {}
11761 _ => return None,
11762 }
11763 let mut drag = crate::table_drag_selection::TableDragSelection::new(
11764 focus.path.clone(),
11765 node,
11766 handle.opposite,
11767 point,
11768 false,
11769 focus.row_key,
11770 item.scroll_axis_reversed(Orientation::Horizontal),
11771 )?;
11772 drag.adjust_range(node.table_selection.as_ref()?.drag_range()?);
11773 drag.touch = touch;
11774 drag.scroll_capture = scroll_capture;
11775 self.table_drag_route(scene, layout, &drag, point)?;
11776 Some(drag)
11777 })();
11778 let Some(drag) = drag else { return false };
11779 self.cancel_press();
11780 if touch {
11781 self.pointer_leave();
11782 }
11783 self.capture_table_selection(drag);
11784 true
11785 }
11786
11787 pub fn touch_table_selection_claimed(&self) -> bool {
11788 self.table_drag_selection
11789 .as_ref()
11790 .is_some_and(|drag| drag.claimed && drag.touch)
11791 }
11792
11793 pub fn touch_table_drag_claimed(&self) -> bool {
11794 self.touch_table_selection_claimed()
11795 || self.table_row_move.as_ref().is_some_and(|drag| drag.touch)
11796 }
11797
11798 fn scroll_table_selection_claimed(&self) -> bool {
11799 self.table_drag_selection
11800 .as_ref()
11801 .is_some_and(|drag| drag.claimed && drag.scroll_capture)
11802 }
11803
11804 pub fn scroll_table_drag_claimed(&self) -> bool {
11805 self.scroll_table_selection_claimed()
11806 || self.table_row_move.as_ref().is_some_and(|drag| drag.touch)
11807 }
11808
11809 pub fn cancel_scroll_table_drag(&mut self) -> bool {
11810 if self.scroll_table_selection_claimed() {
11811 self.cancel_table_drag_selection()
11812 } else {
11813 self.cancel_table_touch_drag()
11814 }
11815 }
11816
11817 pub fn cancel_table_touch_drag(&mut self) -> bool {
11818 if self.touch_table_selection_claimed() {
11819 self.cancel_table_drag_selection()
11820 } else if self.touch_table_drag_claimed() {
11821 self.cancel_table_row_move()
11822 } else {
11823 false
11824 }
11825 }
11826
11827 pub fn table_drag_selection_armed(&self) -> bool {
11828 self.table_drag_selection.is_some()
11829 }
11830
11831 pub fn move_table_drag_selection(&mut self, layout: &LayoutNode, now: Instant) -> bool {
11832 let Some(drag) = &mut self.table_drag_selection else {
11833 return false;
11834 };
11835 if !drag.claimed
11836 && let Some(point) = self.pointer
11837 && let Some(item) = layout.at_path(&drag.path)
11838 && let Some(delta) = item.map_delta_from_window(Point {
11839 x: point.x - drag.start.x,
11840 y: point.y - drag.start.y,
11841 })
11842 && delta.x.hypot(delta.y) >= DRAG_THRESHOLD
11843 {
11844 drag.claimed = true;
11845 drag.begin_presentation();
11846 drag.scroll_wake = Some(now + SCROLL_FRAME_INTERVAL);
11847 let focus = drag.focus_target();
11848 self.claim_table_selection(focus);
11849 return true;
11850 }
11851 if drag.claimed && self.pointer.is_some_and(|point| point != drag.start) {
11852 drag.scroll_wake.get_or_insert(now + SCROLL_FRAME_INTERVAL);
11853 }
11854 drag.claimed
11855 }
11856
11857 fn claim_table_selection(&mut self, focus: Target) {
11858 self.last_table_click = None;
11859 self.pressed = None;
11860 self.set_focus_with_reason(Some(focus), xrack_runtime::FocusReason::PointerClick);
11861 }
11862
11863 pub fn table_drag_selection_claimed(&self) -> bool {
11864 self.table_drag_selection
11865 .as_ref()
11866 .is_some_and(|drag| drag.claimed)
11867 }
11868
11869 pub fn cancel_table_drag_selection(&mut self) -> bool {
11870 if let Some(drag) = self.table_drag_selection.take().filter(|drag| drag.claimed) {
11871 if drag.touch {
11872 self.pointer = None;
11873 }
11874 self.cancel_press();
11875 true
11876 } else {
11877 false
11878 }
11879 }
11880
11881 pub fn finish_table_drag_selection(
11882 &mut self,
11883 scene: &Node,
11884 layout: &LayoutNode,
11885 ) -> Option<ControlInput> {
11886 let drag = self.table_drag_selection.take()?;
11887 let point = self.pointer;
11888 self.cancel_press();
11889 let (node, item, point) = self.table_drag_route(scene, layout, &drag, point?)?;
11890 Some(ControlInput {
11891 action: ControlAction::TableSelection(drag.action(node, item, point)?),
11892 path: drag.path,
11893 })
11894 }
11895
11896 fn table_drag_route<'a>(
11897 &self,
11898 scene: &'a Node,
11899 layout: &'a LayoutNode,
11900 drag: &crate::table_drag_selection::TableDragSelection,
11901 point: Point,
11902 ) -> Option<(&'a Node, &'a LayoutNode, Point)> {
11903 if self.menu_open()
11904 || self.choice_open()
11905 || !drag.path.starts_with(self.pointer_scope(layout, point))
11906 || scene.row_key_at(&drag.path) != drag.parent_row
11907 {
11908 return None;
11909 }
11910 let node = scene.interactive_at_path(&drag.path)?;
11911 let item = layout.at_path(&drag.path)?;
11912 drag.valid(node, item).then_some((node, item, point))
11913 }
11914
11915 pub fn table_drag_preview(
11916 &self,
11917 path: &[usize],
11918 node: &Node,
11919 layout: &LayoutNode,
11920 ) -> Vec<Rect> {
11921 match (&self.table_drag_selection, self.pointer) {
11922 (Some(drag), Some(point)) if drag.path == path && drag.valid(node, layout) => {
11923 drag.preview(node, layout, point)
11924 }
11925 _ => Vec::new(),
11926 }
11927 }
11928
11929 fn table_drag_scroll_delta(&self, scene: &Node, layout: &LayoutNode) -> Option<Point> {
11930 let drag = self.table_drag_selection.as_ref()?;
11931 let (_, item, point) = self.table_drag_route(scene, layout, drag, self.pointer?)?;
11932 let delta = drag.scroll_delta(item, point);
11933 (delta != Point::default()).then_some(delta)
11934 }
11935
11936 pub fn table_drag_selection_deadline(
11937 &self,
11938 scene: &Node,
11939 layout: &LayoutNode,
11940 ) -> Option<Instant> {
11941 self.table_drag_scroll_delta(scene, layout)?;
11942 self.table_drag_selection.as_ref()?.scroll_wake
11943 }
11944
11945 pub fn advance_table_drag_selection(
11946 &mut self,
11947 scene: &Node,
11948 layout: &LayoutNode,
11949 now: Instant,
11950 ) -> bool {
11951 let Some(delta) = self.table_drag_scroll_delta(scene, layout) else {
11952 return false;
11953 };
11954 let Some(drag) = self
11955 .table_drag_selection
11956 .as_mut()
11957 .filter(|drag| drag.scroll_wake.is_some_and(|wake| now >= wake))
11958 else {
11959 return false;
11960 };
11961 drag.scroll_wake = Some(now + SCROLL_FRAME_INTERVAL);
11962 let path = drag.path.clone();
11963 let Some(item) = layout.at_path(&path) else {
11964 return false;
11965 };
11966 let mut moved = false;
11967 for (axis, delta) in [
11968 (Orientation::Horizontal, delta.x),
11969 (Orientation::Vertical, delta.y),
11970 ] {
11971 if delta != 0.0
11972 && let Some(scroll) = item.scroll_on(axis)
11973 {
11974 moved |= self.scroll_to_user_offset(layout, &path, axis, scroll.offset + delta);
11975 }
11976 }
11977 moved
11978 }
11979
11980 pub fn table_column_move_drag(&mut self, layout: &LayoutNode, now: Instant) -> bool {
11981 let Some(drag) = &mut self.table_column_move else {
11982 return false;
11983 };
11984 if !drag.claimed
11985 && let Some(point) = self.pointer
11986 && let Some(item) = layout.at_path(&drag.target.path)
11987 && let Some(delta) = item.map_delta_from_window(Point {
11988 x: point.x - drag.start.x,
11989 y: point.y - drag.start.y,
11990 })
11991 {
11992 drag.claimed = delta.x.abs() >= 8.0 && delta.x.abs() >= delta.y.abs();
11993 if drag.claimed {
11994 drag.scroll_wake = Some(now + SCROLL_FRAME_INTERVAL);
11995 }
11996 }
11997 drag.claimed
11998 }
11999
12000 pub fn table_row_move_drag(&mut self, layout: &LayoutNode, now: Instant) -> bool {
12001 let Some(drag) = &mut self.table_row_move else {
12002 return false;
12003 };
12004 if !drag.claimed
12005 && let Some(point) = self.pointer
12006 && let Some(item) = layout.at_path(&drag.table.path)
12007 && let Some(delta) = item.map_delta_from_window(Point {
12008 x: point.x - drag.start.x,
12009 y: point.y - drag.start.y,
12010 })
12011 && delta.y.abs() >= DRAG_THRESHOLD
12012 && delta.y.abs() >= delta.x.abs()
12013 {
12014 drag.claimed = true;
12015 drag.scroll_wake = Some(now + SCROLL_FRAME_INTERVAL);
12016 }
12017 drag.claimed
12018 }
12019
12020 pub fn table_row_move_claimed(&self) -> bool {
12021 self.table_row_move
12022 .as_ref()
12023 .is_some_and(|drag| drag.claimed)
12024 }
12025
12026 pub fn cancel_table_row_move(&mut self) -> bool {
12027 if let Some(drag) = self.table_row_move.take().filter(|drag| drag.claimed) {
12028 if drag.touch {
12029 self.pointer = None;
12030 }
12031 self.cancel_press();
12032 true
12033 } else {
12034 false
12035 }
12036 }
12037
12038 fn row_move_position(
12039 drag: &TableRowMove,
12040 node: &Node,
12041 layout: &LayoutNode,
12042 point: Point,
12043 ) -> Option<(Rect, Point)> {
12044 if !drag.claimed
12045 || !drag.table.matches_node(node)
12046 || node.standard_list_stamp != Some(drag.stamp)
12047 || !node.boolean("movable-rows", false)
12048 || !layout.visible
12049 || !layout.enabled
12050 || !layout.contains_clip_point(point)
12051 {
12052 return None;
12053 }
12054 let table = layout.table.as_ref()?;
12055 let local = layout.map_from_window(point)?;
12056 let visible = table.rows_area().intersect(layout.clip);
12057 (table.row_header.width > 0.0 && visible.contains(local)).then_some((visible, local))
12058 }
12059
12060 fn row_drop(
12061 drag: &TableRowMove,
12062 node: &Node,
12063 layout: &LayoutNode,
12064 point: Point,
12065 ) -> Option<(usize, Rect)> {
12066 let (visible, point) = Self::row_move_position(drag, node, layout, point)?;
12067 let list = node.list?;
12068 let rows = node
12069 .children
12070 .iter()
12071 .zip(&layout.children)
12072 .enumerate()
12073 .filter(|(_, (row, item))| {
12074 row.kind == "ListRow" && item.visible && item.bounds.intersect(visible).height > 0.0
12075 });
12076 let mut edge = None;
12077 for (slot, (_, item)) in rows {
12078 let row = item.bounds;
12079 let index = list.first_row + slot;
12080 if point.y < row.y + row.height * 0.5 {
12081 edge = Some((index, row.y));
12082 break;
12083 }
12084 edge = Some((index + 1, row.y + row.height));
12085 }
12086 let (insertion, y) = edge?;
12087 let to = insertion.saturating_sub(usize::from(insertion > drag.from));
12088 (to != drag.from && to < list.row_count).then(|| {
12089 let y = y.clamp(
12090 visible.y + 1.0_f32.min(visible.height * 0.5),
12091 visible.y + visible.height - 1.0_f32.min(visible.height * 0.5),
12092 );
12093 (
12094 to,
12095 Rect::new(visible.x, y - 1.0, visible.width, 2.0).intersect(visible),
12096 )
12097 })
12098 }
12099
12100 pub fn table_row_move_marker(
12101 &self,
12102 path: &[usize],
12103 node: &Node,
12104 layout: &LayoutNode,
12105 ) -> Option<Rect> {
12106 let drag = self
12107 .table_row_move
12108 .as_ref()
12109 .filter(|drag| drag.table.path == path)?;
12110 Self::row_drop(drag, node, layout, self.pointer?).map(|(_, marker)| marker)
12111 }
12112
12113 pub fn table_row_move_source(&self, path: &[usize], node: &Node) -> Option<RowKey> {
12114 let drag = self.table_row_move.as_ref()?;
12115 (drag.claimed
12116 && drag.table.path == path
12117 && node.boolean("movable-rows", false)
12118 && node.standard_list_stamp == Some(drag.stamp))
12119 .then_some(drag.row)
12120 }
12121
12122 fn table_row_move_scroll_delta(&self, scene: &Node, layout: &LayoutNode) -> Option<f32> {
12123 let drag = self.table_row_move.as_ref()?;
12124 let point = self.pointer?;
12125 let path = &drag.table.path;
12126 if !path.starts_with(self.pointer_scope(layout, point))
12127 || scene.row_key_at(path) != drag.table.row_key
12128 {
12129 return None;
12130 }
12131 let item = layout.at_path(path)?;
12132 let (visible, point) = Self::row_move_position(drag, scene.at_path(path)?, item, point)?;
12133 let delta = crate::table_drag_selection::edge_delta(point.y, visible.y, visible.height);
12134 let scroll = item.scroll?;
12135 ((scroll.offset + delta).clamp(0.0, scroll.max_offset) != scroll.offset).then_some(delta)
12136 }
12137
12138 pub fn table_row_move_deadline(&self, scene: &Node, layout: &LayoutNode) -> Option<Instant> {
12139 self.table_row_move_scroll_delta(scene, layout)?;
12140 self.table_row_move.as_ref()?.scroll_wake
12141 }
12142
12143 pub fn advance_table_row_move(
12144 &mut self,
12145 scene: &Node,
12146 layout: &LayoutNode,
12147 now: Instant,
12148 ) -> bool {
12149 let Some(delta) = self.table_row_move_scroll_delta(scene, layout) else {
12150 return false;
12151 };
12152 let Some(drag) = self
12153 .table_row_move
12154 .as_mut()
12155 .filter(|drag| drag.scroll_wake.is_some_and(|wake| now >= wake))
12156 else {
12157 return false;
12158 };
12159 drag.scroll_wake = Some(now + SCROLL_FRAME_INTERVAL);
12160 let path = drag.table.path.clone();
12161 let Some(scroll) = layout.at_path(&path).and_then(|item| item.scroll) else {
12162 return false;
12163 };
12164 self.scroll_to_user_offset(layout, &path, Orientation::Vertical, scroll.offset + delta)
12165 }
12166
12167 pub fn finish_table_row_move(
12168 &mut self,
12169 scene: &Node,
12170 layout: &LayoutNode,
12171 ) -> Option<ControlInput> {
12172 let drag = self.table_row_move.take()?;
12173 let point = self.pointer;
12174 self.cancel_press();
12175 let point = point?;
12176 let path = &drag.table.path;
12177 if !valid(&drag.table, scene, layout)
12178 || !path.starts_with(self.pointer_scope(layout, point))
12179 {
12180 return None;
12181 }
12182 let (to, _) = Self::row_drop(&drag, scene.at_path(path)?, layout.at_path(path)?, point)?;
12183 Some(ControlInput {
12184 path: drag.table.path,
12185 action: ControlAction::MoveRow {
12186 from: drag.from,
12187 to,
12188 row: drag.row,
12189 stamp: drag.stamp,
12190 },
12191 })
12192 }
12193
12194 pub fn table_column_move_claimed(&self) -> bool {
12195 self.table_column_move
12196 .as_ref()
12197 .is_some_and(|drag| drag.claimed)
12198 }
12199
12200 fn column_drop(
12201 drag: &TableColumnMove,
12202 node: &Node,
12203 layout: &LayoutNode,
12204 point: Point,
12205 ) -> Option<(usize, usize, f32)> {
12206 let (table, point) = Self::column_move_position(drag, node, layout, point)?;
12207 let from = table.visual_index(drag.column)?;
12208 let (to, marker) = table.column_drop(from, point)?;
12209 Some((from, to, marker))
12210 }
12211
12212 fn column_move_position<'a>(
12213 drag: &TableColumnMove,
12214 node: &Node,
12215 layout: &'a LayoutNode,
12216 point: Point,
12217 ) -> Option<(&'a crate::TableGeometry, Point)> {
12218 if !drag.claimed
12219 || !drag.target.matches_node(node)
12220 || !layout.visible
12221 || !layout.enabled
12222 || !node.boolean("movable-columns", false)
12223 || drag.order != node.table_column_order
12224 || !layout.contains_clip_point(point)
12225 {
12226 return None;
12227 }
12228 let table = layout.table.as_ref()?;
12229 if !table.is_column_visible(drag.column) || drag.mirrored != table.mirrored() {
12230 return None;
12231 }
12232 let local = layout.map_from_window(point)?;
12233 table.header.contains(local).then_some((table, local))
12234 }
12235
12236 fn table_column_move_scroll_delta(&self, scene: &Node, layout: &LayoutNode) -> Option<f32> {
12237 let drag = self.table_column_move.as_ref()?;
12238 let point = self.pointer?;
12239 let path = &drag.target.path;
12240 if !path.starts_with(self.pointer_scope(layout, point)) {
12241 return None;
12242 }
12243 let item = layout.at_path(path)?;
12244 let (table, point) =
12245 Self::column_move_position(drag, drag.target.node_in(scene)?, item, point)?;
12246 let visible = table.scrollable_header().intersect(item.clip);
12247 if !visible.contains(point) {
12248 return None;
12249 }
12250 let edge = (visible.width * 0.25).min(20.0);
12251 if edge <= 0.0 {
12252 return None;
12253 }
12254 let left = (visible.x + edge - point.x).clamp(0.0, edge);
12255 let right = (point.x - (visible.x + visible.width - edge)).clamp(0.0, edge);
12256 let delta = table.logical_delta((right - left) / edge * 18.0);
12257 let scroll = table.horizontal;
12258 ((scroll.offset + delta).clamp(0.0, scroll.max_offset) != scroll.offset).then_some(delta)
12259 }
12260
12261 pub fn table_column_move_deadline(&self, scene: &Node, layout: &LayoutNode) -> Option<Instant> {
12262 self.table_column_move_scroll_delta(scene, layout)?;
12263 self.table_column_move.as_ref()?.scroll_wake
12264 }
12265
12266 pub fn advance_table_column_move(
12267 &mut self,
12268 scene: &Node,
12269 layout: &LayoutNode,
12270 now: Instant,
12271 ) -> bool {
12272 let Some(delta) = self.table_column_move_scroll_delta(scene, layout) else {
12273 return false;
12274 };
12275 let Some(drag) = self
12276 .table_column_move
12277 .as_mut()
12278 .filter(|drag| drag.scroll_wake.is_some_and(|wake| now >= wake))
12279 else {
12280 return false;
12281 };
12282 drag.scroll_wake = Some(now + SCROLL_FRAME_INTERVAL);
12283 let path = drag.target.path.clone();
12284 let Some(item) = layout.at_path(&path) else {
12285 return false;
12286 };
12287 let Some(scroll) = item.scroll_on(Orientation::Horizontal) else {
12288 return false;
12289 };
12290 if !self.set_viewport_offset(
12291 &path,
12292 item,
12293 Orientation::Horizontal,
12294 f64::from(scroll.offset + delta),
12295 ) {
12296 return false;
12297 }
12298 UserScrollChange::record(
12299 &mut self.user_scroll_changes,
12300 item,
12301 Orientation::Horizontal,
12302 scroll.offset,
12303 );
12304 true
12305 }
12306
12307 pub fn table_column_move_marker(
12308 &self,
12309 path: &[usize],
12310 node: &Node,
12311 layout: &LayoutNode,
12312 ) -> Option<f32> {
12313 let drag = self
12314 .table_column_move
12315 .as_ref()
12316 .filter(|drag| drag.target.path == path)?;
12317 Self::column_drop(drag, node, layout, self.pointer?).map(|(_, _, marker)| marker)
12318 }
12319
12320 pub fn finish_table_column_move(
12321 &mut self,
12322 scene: &Node,
12323 layout: &LayoutNode,
12324 ) -> Option<ControlInput> {
12325 let drag = self.table_column_move.take()?;
12326 let point = self.pointer;
12327 self.cancel_press();
12328 let point = point?;
12329 if !valid(&drag.target, scene, layout)
12330 || !drag
12331 .target
12332 .path
12333 .starts_with(self.pointer_scope(layout, point))
12334 {
12335 return None;
12336 }
12337 let node = scene.at_path(&drag.target.path)?;
12338 let item = layout.at_path(&drag.target.path)?;
12339 let (from, to, _) = Self::column_drop(&drag, node, item, point)?;
12340 Some(ControlInput {
12341 path: drag.target.path,
12342 action: ControlAction::MoveColumn { from, to },
12343 })
12344 }
12345
12346 pub fn table_resize_drag(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
12347 let drag = self.table_resize.as_ref()?;
12348 if !valid(&drag.target, scene, layout) {
12349 return None;
12350 }
12351 let node = scene.at_path(&drag.target.path)?;
12352 let column = resizable_table_column(node, drag.column)?;
12353 let item = layout.at_path(&drag.target.path)?;
12354 let table = item.table.as_ref()?;
12355 if !table.is_column_visible(drag.column) || drag.mirrored != table.mirrored() {
12356 return None;
12357 }
12358 let bounds = table.columns[drag.column];
12359 let (min, max) = crate::table::column_limits(column, table.header.width);
12360 let point = item.map_from_window(self.pointer?)?;
12361 let width = drag.width + table.logical_delta(point.x - drag.pointer_x);
12362 if !width.is_finite() || (width.clamp(min, max) - bounds.width).abs() < 0.5 {
12363 return None;
12364 }
12365 Some(ControlInput {
12366 path: drag.target.path.clone(),
12367 action: ControlAction::ResizeColumn {
12368 column: drag.column,
12369 width: width.clamp(min, max).round() as u32,
12370 },
12371 })
12372 }
12373
12374 pub fn finish_table_resize(&mut self) -> bool {
12375 let resizing = self.table_resize.is_some() || self.table_row_resize.is_some();
12376 if resizing {
12377 self.pointer_release_target();
12378 }
12379 resizing
12380 }
12381
12382 pub fn table_resize_cursor(&self) -> bool {
12383 self.table_resize.is_some() || self.hovered_table_grip.is_some()
12384 }
12385
12386 pub fn table_row_resize_cursor(&self) -> bool {
12387 self.table_row_resize.is_some() || self.hovered_table_row_grip.is_some()
12388 }
12389
12390 pub fn table_resize_row(&self, path: &[usize]) -> Option<RowKey> {
12391 if let Some(drag) = &self.table_row_resize {
12392 (drag.target.path == path).then_some(drag.key)
12393 } else if self.is_hovered(path) {
12394 self.hovered_table_row_grip.map(|(key, _)| key)
12395 } else {
12396 None
12397 }
12398 }
12399
12400 pub fn table_row_resize_drag(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
12401 let drag = self.table_row_resize.as_ref()?;
12402 if !valid(&drag.target, scene, layout) {
12403 return None;
12404 }
12405 let node = scene.interactive_at_path(&drag.target.path)?;
12406 if !node.boolean("resizable-rows", false) || !self.allows_popup(layout, &drag.target.path) {
12407 return None;
12408 }
12409 let item = layout.at_path(&drag.target.path)?;
12410 let slot = node
12411 .children
12412 .iter()
12413 .position(|row| row.row_key == Some(drag.key))?;
12414 let row = node.list?.first_row.checked_add(slot)?;
12415 let point = item.map_from_window(self.pointer?)?;
12416 let height = drag.height + point.y - drag.pointer_y;
12417 if !height.is_finite() {
12418 return None;
12419 }
12420 let height = ListMetrics::clamp_row_height(height).round();
12421 if (height - item.children.get(slot)?.bounds.height).abs() < 0.5 {
12422 return None;
12423 }
12424 Some(ControlInput {
12425 path: drag.target.path.clone(),
12426 action: ControlAction::ResizeRow {
12427 row,
12428 key: drag.key,
12429 height: height as u32,
12430 },
12431 })
12432 }
12433
12434 pub fn table_resize_column(&self, path: &[usize]) -> Option<usize> {
12435 if let Some(drag) = &self.table_resize {
12436 (drag.target.path == path).then_some(drag.column)
12437 } else if self.is_hovered(path) {
12438 self.hovered_table_grip.map(|(column, _, _)| column)
12439 } else {
12440 None
12441 }
12442 }
12443 pub fn reconcile(&mut self, scene: &Node, layout: &LayoutNode) {
12444 if self
12445 .swipe_page_motion
12446 .as_ref()
12447 .is_some_and(|motion| !motion.is_current(scene, layout))
12448 {
12449 self.swipe_page_motion = None;
12450 }
12451 if self.table_drag_selection.as_ref().is_some_and(|drag| {
12452 drag.claimed
12453 && self
12454 .pointer
12455 .and_then(|point| self.table_drag_route(scene, layout, drag, point))
12456 .is_none()
12457 }) {
12458 self.cancel_table_drag_selection();
12459 }
12460 if let Some(drag) = self
12461 .scroll_gesture
12462 .as_mut()
12463 .and_then(|gesture| gesture.tumbler.as_mut())
12464 && !drag.is_current(scene, layout)
12465 {
12466 drag.cancel();
12467 }
12468 if self.tumbler_flick.as_ref().is_some_and(|flick| {
12469 flick.active() && !self.tumbler_flick_is_current(flick, scene, layout)
12470 }) {
12471 self.interrupt_tumbler_flick();
12472 }
12473 if let Some(drag) = self
12474 .scroll_gesture
12475 .as_mut()
12476 .and_then(|gesture| gesture.switch.as_mut())
12477 && !drag.is_current(scene, layout)
12478 {
12479 drag.position = None;
12480 drag.cancelled = true;
12481 }
12482 self.scope_focus.reconcile(scene, layout);
12483 self.page_focus.reconcile(scene);
12484 self.remember_focus_scope(scene, layout);
12485 self.reconcile_dialogs(scene, layout);
12486 self.finish_calendar_page_focus(scene, layout);
12487 if self.overscroll.has_offset() {
12488 let scope = self.active_dialog(layout).unwrap_or_default();
12489 self.overscroll.reconcile(layout.at_path(scope));
12490 }
12491 let route = self
12492 .scroll_gesture
12493 .as_ref()
12494 .map(|gesture| &gesture.route)
12495 .or_else(|| self.scroll_fling.as_ref().map(|fling| &fling.route));
12496 if let Some(route) = route
12497 && self.scroll_route_is_current(scene, layout, route)
12498 {
12499 self.viewport_motion.reconcile(layout, route.pan_device);
12500 } else {
12501 self.viewport_motion.clear();
12502 }
12503 self.stack_focus.retain(|key, _| {
12504 scene
12505 .at_path(&key.path)
12506 .is_some_and(|view| view.kind == "StackView")
12507 && scene.row_key_at(&key.path) == key.row
12508 });
12509 if self.scroll_bar_press.as_ref().is_some_and(|press| {
12510 !press.cancelled
12511 && (press.node(scene).is_none()
12512 || self
12513 .scroll_bar_for_target(scene, layout, &press.target)
12514 .is_none_or(|bar| bar.reversed() != press.reversed))
12515 }) && let Some(press) = &mut self.scroll_bar_press
12516 {
12517 press.cancelled = true;
12518 }
12519 if self.split_drag.as_ref().is_some_and(|drag| {
12520 !split_target(&drag.target, scene, layout).is_some_and(|(path, geometry, handle)| {
12521 drag.matches(geometry, handle)
12522 && scene
12523 .at_path(path)
12524 .and_then(|node| node.split_resize_handle.as_ref())
12525 == drag.state.as_ref()
12526 })
12527 }) {
12528 self.clear_split_drag();
12529 self.pressed = None;
12530 }
12531 let unavailable = |target: &Target, column, mirrored| {
12532 layout
12533 .at_path(&target.path)
12534 .and_then(|item| item.table.as_ref())
12535 .is_none_or(|table| {
12536 !table.is_column_visible(column) || table.mirrored() != mirrored
12537 })
12538 };
12539 if self
12540 .table_resize
12541 .as_ref()
12542 .is_some_and(|drag| unavailable(&drag.target, drag.column, drag.mirrored))
12543 || self
12544 .table_column_move
12545 .as_ref()
12546 .is_some_and(|drag| unavailable(&drag.target, drag.column, drag.mirrored))
12547 {
12548 self.cancel_press();
12549 }
12550 self.scroll_offsets.retain(|path, value| {
12551 if let Some(scroll) = layout.at_path(path).and_then(|node| node.scroll) {
12552 *value = scroll.offset;
12553 true
12554 } else {
12555 false
12556 }
12557 });
12558 self.horizontal_scroll_offsets.retain(|path, value| {
12559 if let Some(scroll) = layout
12560 .at_path(path)
12561 .and_then(|node| node.scroll_on(Orientation::Horizontal))
12562 && scroll.max_offset > 0.0
12563 {
12564 *value = scroll.offset;
12565 true
12566 } else {
12567 false
12568 }
12569 });
12570 self.tree_scroll_roots = self
12571 .scroll_offsets
12572 .keys()
12573 .filter_map(|path| {
12574 Some((
12575 path.clone(),
12576 scene.at_path(path)?.tree.as_ref()?.root_identity(),
12577 ))
12578 })
12579 .collect();
12580 self.scroll_anchors = capture_list_anchors(scene, layout, &self.scroll_anchors);
12581 for (path, anchor) in &self.scroll_anchors {
12582 if anchor.scope.is_none()
12583 && anchor.offset > 0.0
12584 && !self.scroll_offsets.contains_key(path)
12585 {
12586 self.scroll_offsets.insert(path.clone(), anchor.offset);
12587 }
12588 }
12589 self.scroll_selections = self
12591 .scroll_offsets
12592 .keys()
12593 .chain(self.horizontal_scroll_offsets.keys())
12594 .filter_map(|path| {
12595 let view = scene.at_path(path).filter(|node| {
12596 matches!(
12597 node.kind,
12598 "TabBar" | "TabWidget" | "StandardListView" | "GridView"
12599 ) || node.kind == "TableView" && node.boolean("follow-current", false)
12600 })?;
12601 let item = layout.at_path(path)?;
12602 let cells = ViewCells::new(view, item.bounds.width);
12603 Some((
12604 path.clone(),
12605 ScrollSelection::new(
12606 view,
12607 cells.columns,
12608 item.layout_direction,
12609 layout.popup_typography().scale,
12610 ),
12611 ))
12612 })
12613 .collect();
12614 if self
12615 .pressed
12616 .as_ref()
12617 .is_some_and(|t| !valid(t, scene, layout))
12618 {
12619 self.pressed = None;
12620 self.table_resize = None;
12621 }
12622 if let Some(current) = self
12623 .focused
12624 .as_ref()
12625 .filter(|t| !valid(t, scene, layout) && !self.drawer_retains_focus(t, scene, layout))
12626 .cloned()
12627 {
12628 if let Some(next) = self.restore_stack_focus(¤t, scene, layout) {
12629 self.set_focus_with_reason(Some(next), xrack_runtime::FocusReason::LayoutChange);
12630 } else if let Some(moved) = moved_row_target(¤t, scene, layout) {
12631 if let Some(offset) = self.text_offsets.remove(¤t.path) {
12632 self.text_offsets.insert(moved.path.clone(), offset);
12633 }
12634 if let Some(edit) = &mut self.table_edit
12635 && edit.target == current
12636 {
12637 edit.target = moved.clone();
12638 }
12639 self.focused = Some(moved);
12640 self.range_keys.clear();
12641 } else {
12642 let scope = self
12643 .focused_popup(layout)
12644 .or_else(|| self.active_dialog(layout))
12645 .unwrap_or_default();
12646 let page = self.page_focus.restore(¤t, scene, layout, scope);
12647 let fallback = page.or_else(|| {
12648 let stops = focus_targets(scene, layout, scope);
12649 attached_radio_tab_stop(scene, ¤t.path, &stops)
12650 .map(|index| stops[index].clone())
12651 .filter(|target| target.row_key == current.row_key)
12652 });
12653 let fallback = fallback.or_else(|| {
12654 (0..current.path.len()).rev().find_map(|length| {
12655 let path = ¤t.path[..length];
12656 let node = scene.at_path(path)?;
12657 if scene
12658 .row_key_at(path)
12659 .is_some_and(|key| Some(key) != current.row_key)
12660 {
12661 return None;
12662 }
12663 let item = layout.at_path(path)?;
12664 let mut target = match node.kind {
12665 "ListView" | "GridView" | "StandardListView" | "TableView"
12666 | "TreeView" | "SwipeView" | "SwipeDelegate" | "StackView"
12667 | "GroupBox" | "Expander"
12668 if eligible(node, item) =>
12669 {
12670 Target::from_node(path.to_vec(), node, true, None)
12671 }
12672 "TabWidget" | "TabBar" | "RadioGroup" => group_focus(node, item, path)?,
12673 "Dialog" | "Drawer" => dialog_entry_focus(scene, layout, path)?,
12674 "FocusScope" => {
12675 let target = crate::focus_scope::target_at(scene, layout, path)?;
12676 self.scope_focus.choose(scene, layout, target, false, false)
12677 }
12678
12679 _ => return None,
12680 };
12681 target.row_key = scene.row_key_at(&target.path);
12682 Some(target)
12683 })
12684 });
12685 self.set_focus_with_reason(fallback, xrack_runtime::FocusReason::LayoutChange);
12686 }
12687 self.key_pressed = None;
12688 self.remember_focus_scope(scene, layout);
12689 }
12690 if self.table_edit.as_ref().is_some_and(|edit| {
12691 !scene
12692 .interactive_at_path(&edit.target.path)
12693 .is_some_and(|node| {
12694 editable_table_cell(node) && node.text("text").unwrap_or("") == edit.original
12695 })
12696 }) {
12697 self.cancel_table_edit();
12698 }
12699 if let Some(draft) = &self.spin_draft
12700 && !self
12701 .focused
12702 .as_ref()
12703 .and_then(|target| scene.interactive_at_path(&target.path))
12704 .is_some_and(|node| draft.mode.is_current(node))
12705 {
12706 self.discard_spin_draft();
12707 }
12708 self.text_offsets.retain(|path, (key, _)| {
12709 scene
12710 .at_path(path)
12711 .is_some_and(|node| is_multiline_text_input(node.kind))
12712 && scene.row_key_at(path) == *key
12713 });
12714 self.retained_selections.retain_mut(|selection| {
12715 let source = &mut selection.source;
12716 if !valid(&source.target, scene, layout)
12717 && let Some(target) = moved_row_target(&source.target, scene, layout)
12718 {
12719 source.target = target;
12720 }
12721 let keep = valid(&source.target, scene, layout)
12722 && source
12723 .target
12724 .node_in(scene)
12725 .is_some_and(|node| source.matches(node));
12726 if !keep && let Some(handle) = &source.handle {
12727 handle.clear_text_state();
12728 }
12729 keep
12730 });
12731 if self
12732 .choice
12733 .as_mut()
12734 .is_some_and(|popup| !popup.reconcile(scene, layout))
12735 {
12736 Self::clear_choice(&mut self.choice);
12737 }
12738 self.reconcile_search_choice(scene, layout);
12739 self.reconcile_text_menu(scene, layout);
12740 if self
12741 .menu
12742 .as_mut()
12743 .is_some_and(|popup| !popup.reconcile(scene, layout))
12744 {
12745 self.dismiss_menu();
12746 }
12747 if let Some(mut pending) = self.pending_shortcut.take()
12748 && !self.shortcuts_blocked()
12749 {
12750 let scope = self.shortcut_scope(layout);
12751 let active = shortcut::bindings(
12752 scene,
12753 layout,
12754 scope,
12755 self.menu.as_ref(),
12756 self.focused.as_ref(),
12757 );
12758 if pending.retain_active(scope, &active) {
12759 self.pending_shortcut = Some(pending);
12760 }
12761 }
12762 if let Some(point) = self.pointer {
12763 if !self.choice_open() && !self.menu_open() {
12765 self.pointer_move(scene, layout, point);
12766 } else {
12767 self.set_split_hover(None);
12768 }
12769 }
12770 if let Some(handle) = &self.range_position_handle
12771 && self.pressed.as_ref().and_then(|target| {
12772 let (_, node) = slider_target(target, scene, layout)?;
12773 node.range_position_handle.as_ref()
12774 }) != Some(handle)
12775 {
12776 self.slider_fraction = None;
12777 self.clear_range_preview();
12778 }
12779 self.publish_button_presses(scene, layout);
12780 }
12781
12782 fn restore_stack_focus(
12783 &mut self,
12784 outgoing: &Target,
12785 scene: &Node,
12786 layout: &LayoutNode,
12787 ) -> Option<Target> {
12788 let scope = self.active_dialog(layout).unwrap_or_default();
12789 let (path, view) = (scope.len()..outgoing.path.len()).rev().find_map(|depth| {
12790 let path = &outgoing.path[..depth];
12791 let view = scene.interactive_at_path(path)?;
12792 (view.kind == "StackView"
12793 && path.starts_with(scope)
12794 && layout
12795 .at_path(path)
12796 .is_some_and(|item| eligible(view, item)))
12797 .then_some((path, view))
12798 })?;
12799 let from = outgoing.path[path.len()];
12800 let to = view.stack_page_index()?;
12801 if from == to {
12802 return None;
12803 }
12804 let row = scene.row_key_at(path);
12805 let key = |page| StackFocusKey {
12806 path: path.to_vec(),
12807 row,
12808 page,
12809 };
12810 self.stack_focus.insert(key(from), outgoing.clone());
12811 if let Some(target) = self.stack_focus.remove(&key(to))
12812 && valid(&target, scene, layout)
12813 {
12814 return Some(target);
12815 }
12816 let mut page = path.to_vec();
12817 page.push(to);
12818 focus_targets(scene, layout, &page)
12819 .into_iter()
12820 .next()
12821 .or_else(|| Some(Target::from_node(path.to_vec(), view, true, row)))
12822 }
12823
12824 fn reconcile_dialogs(&mut self, scene: &Node, layout: &LayoutNode) {
12825 let key = |entry: &DialogFocus| (entry.path.clone(), entry.row_key, entry.modal);
12826 let previous_top = self.dialogs.last().map(key);
12827 let previous_modal = self.dialogs.iter().rfind(|entry| entry.modal).map(key);
12828 let mut focus = self.focused.clone();
12829 let mut index = 0;
12830 while index < self.dialogs.len() {
12831 let dialog = &mut self.dialogs[index];
12832 if layout.overlay_paths().contains(&dialog.path)
12833 && scene.row_key_at(&dialog.path) == dialog.row_key
12834 {
12835 dialog.modal = is_modal_path(layout, &dialog.path);
12836 index += 1;
12837 continue;
12838 }
12839 let removed = self.dialogs.remove(index);
12840 let falls_inside = |target: &Option<Target>| {
12841 target
12842 .as_ref()
12843 .is_some_and(|target| target.path.starts_with(&removed.path))
12844 };
12845 if falls_inside(&focus) {
12846 focus = removed.return_focus.clone();
12847 }
12848 for dialog in &mut self.dialogs {
12849 if falls_inside(&dialog.return_focus) {
12850 dialog.return_focus = removed.return_focus.clone();
12851 }
12852 }
12853 }
12854 for path in layout.overlay_paths() {
12855 if self.dialogs.iter().any(|dialog| dialog.path == *path) {
12856 continue;
12857 }
12858 let modal = is_modal_path(layout, path);
12859 self.dialogs.push(DialogFocus {
12860 path: path.clone(),
12861 row_key: scene.row_key_at(path),
12862 modal,
12863 return_focus: focus.clone(),
12864 });
12865 if modal
12866 || self.allows_popup(layout, path)
12867 && scene
12868 .at_path(path)
12869 .is_some_and(|node| node.boolean("focus", true))
12870 {
12871 focus = dialog_entry_focus(scene, layout, path);
12872 }
12873 }
12874 if previous_top == self.dialogs.last().map(key)
12875 && previous_modal == self.dialogs.iter().rfind(|entry| entry.modal).map(key)
12876 && focus == self.focused
12877 {
12878 return;
12879 }
12880 let active = self.active_dialog(layout);
12881 let scope = active.unwrap_or_default();
12882 let focus = focus
12883 .filter(|target| target.path.starts_with(scope) && valid(target, scene, layout))
12884 .or_else(|| active.and_then(|path| dialog_entry_focus(scene, layout, path)));
12885 self.dismiss_choice();
12886 self.dismiss_menu();
12887 self.cancel_press();
12888 self.cancel_shortcut_sequence();
12889 self.set_focus_with_reason(focus, xrack_runtime::FocusReason::PopupActivation);
12890 }
12891 pub fn focus_next(&mut self, scene: &Node, layout: &LayoutNode, reverse: bool) -> bool {
12893 self.remember_focus_scope(scene, layout);
12894 self.tooltip.focus_source();
12895 let scope = self
12896 .focused_popup(layout)
12897 .or_else(|| self.active_dialog(layout))
12898 .unwrap_or_default();
12899 let boundary = scope.len();
12900 let targets = focus_targets_with_reveal(scene, layout, scope, true);
12901 self.key_pressed = None;
12902 if targets.is_empty() {
12903 self.set_focus_with_reason(None, xrack_runtime::FocusReason::TabNavigation);
12904 return false;
12905 }
12906 let current = self.focused.as_ref().and_then(|target| {
12907 targets
12908 .iter()
12909 .position(|entry| entry == target)
12910 .or_else(|| attached_radio_tab_stop(scene, &target.path, &targets))
12911 .or_else(|| {
12912 let (&index, path) = target.path.split_last()?;
12913 let group = scene.at_path(path).filter(|node| {
12914 matches!(node.kind, "TabWidget" | "TabBar" | "RadioGroup")
12915 })?;
12916 group_item(group, index)?;
12917 targets.iter().position(|entry| {
12918 entry
12919 .path
12920 .split_last()
12921 .is_some_and(|(_, parent)| parent == path)
12922 })
12923 })
12924 .or_else(|| {
12925 let (view, _) = tree_cell_row(scene, &target.path).or_else(|| {
12926 table_cell_row(scene, &target.path).filter(|(table, _)| {
12927 scene
12928 .at_path(table)
12929 .is_some_and(|node| node.boolean("__standard-table", false))
12930 })
12931 })?;
12932 targets.iter().position(|entry| entry.path == view)
12933 })
12934 });
12935 let index = match current {
12936 Some(i) if reverse => (i + targets.len() - 1) % targets.len(),
12937 Some(i) => (i + 1) % targets.len(),
12938 None if reverse => targets.len() - 1,
12939 None => 0,
12940 };
12941 let next = self
12942 .page_focus
12943 .tab_entry(
12944 scene,
12945 layout,
12946 self.focused.as_ref(),
12947 &targets[index],
12948 boundary,
12949 &targets,
12950 )
12951 .unwrap_or_else(|| targets[index].clone());
12952 let next = self
12953 .scope_focus
12954 .entered_scope(
12955 scene,
12956 layout,
12957 self.focused.as_ref(),
12958 &next,
12959 boundary,
12960 true,
12961 true,
12962 )
12963 .map_or(next, |scope| {
12964 self.scope_focus.choose(scene, layout, scope, reverse, true)
12965 });
12966 let revealed = next.path.split_last().is_some_and(|(&index, path)| {
12967 scene
12968 .at_path(path)
12969 .zip(layout.at_path(path))
12970 .is_some_and(|(group, item)| self.reveal_tab(group, item, path, index))
12971 });
12972 let revealed = self.reveal_focus_target(scene, layout, &next) || revealed;
12973 self.set_focus_with_reason(Some(next), xrack_runtime::FocusReason::TabNavigation);
12974 self.remember_focus_scope(scene, layout);
12975 revealed
12976 }
12977
12978 #[doc(hidden)]
12980 pub fn next_text_field(&self, scene: &Node, layout: &LayoutNode) -> Option<Target> {
12981 let [_, next] = self.adjacent_text_fields(scene, layout);
12982 next
12983 }
12984
12985 #[doc(hidden)]
12987 pub fn adjacent_text_fields(&self, scene: &Node, layout: &LayoutNode) -> [Option<Target>; 2] {
12988 let Some(current) = self.focused.as_ref() else {
12989 return [None, None];
12990 };
12991 let scope = self
12992 .focused_popup(layout)
12993 .or_else(|| self.active_dialog(layout))
12994 .unwrap_or_default();
12995 let targets = focus_targets_with_reveal(scene, layout, scope, true);
12996 let Some(index) = targets.iter().position(|target| target == current) else {
12997 return [None, None];
12998 };
12999 let editable = |target: &&Target| {
13000 target.node_in(scene).is_some_and(|node| {
13001 !node.text_read_only()
13002 && (is_text_input(node.kind) || combo_editable(node) || spin_editable(node))
13003 })
13004 };
13005 [
13006 targets[..index].iter().rev().find(editable).cloned(),
13007 targets[index + 1..].iter().find(editable).cloned(),
13008 ]
13009 }
13010
13011 #[doc(hidden)]
13013 pub fn focus_next_text_field(&mut self, scene: &Node, layout: &LayoutNode) -> Option<bool> {
13014 self.focus_adjacent_text_field(scene, layout, false)
13015 }
13016
13017 #[doc(hidden)]
13018 pub fn focus_adjacent_text_field(
13019 &mut self,
13020 scene: &Node,
13021 layout: &LayoutNode,
13022 reverse: bool,
13023 ) -> Option<bool> {
13024 let [previous, next] = self.adjacent_text_fields(scene, layout);
13025 let target = (if reverse { previous } else { next })?;
13026 self.remember_focus_scope(scene, layout);
13027 self.dismiss_choice();
13028 self.tooltip.focus_source();
13029 let revealed = self.reveal_focus_target(scene, layout, &target);
13030 self.set_focus_with_reason(Some(target), xrack_runtime::FocusReason::KeyboardNavigation);
13031 self.remember_focus_scope(scene, layout);
13032 Some(revealed)
13033 }
13034
13035 pub fn accessibility_target(
13037 &self,
13038 scene: &Node,
13039 layout: &LayoutNode,
13040 path: &[usize],
13041 ) -> Option<Target> {
13042 if self
13043 .active_dialog(layout)
13044 .is_some_and(|scope| !path.starts_with(scope))
13045 {
13046 return None;
13047 }
13048 let node = scene.interactive_at_path(path)?;
13049 let item = layout.at_path(path)?;
13050 let scrollable = scroll_target_visible(item)
13051 && [Orientation::Horizontal, Orientation::Vertical]
13052 .into_iter()
13053 .any(|axis| {
13054 item.scroll_on(axis)
13055 .is_some_and(|scroll| scroll.max_offset > 0.0)
13056 });
13057 if !eligible(node, item) && !scrollable {
13058 return None;
13059 }
13060 Some(Target::from_node(
13061 path.to_vec(),
13062 node,
13063 focusable(node),
13064 scene.row_key_at(path),
13065 ))
13066 }
13067
13068 #[doc(hidden)]
13070 pub fn refresh_viewport<'a>(
13071 &self,
13072 scene: &'a Node,
13073 layout: &LayoutNode,
13074 path: &[usize],
13075 ) -> Option<&'a ViewportHandle> {
13076 if self.menu_open() || self.choice_open() || !self.allows_popup(layout, path) {
13077 return None;
13078 }
13079 let item = layout
13080 .at_path(path)
13081 .filter(|item| scroll_target_visible(item))?;
13082 item.scroll_on(Orientation::Vertical)?;
13083 let node = scene
13084 .interactive_at_path(path)
13085 .filter(|node| node.can_pull_to_refresh())?;
13086 node.viewport_handle.as_ref()
13087 }
13088
13089 pub(crate) fn focus_reason(&self) -> xrack_runtime::FocusReason {
13090 self.focus_reason
13091 }
13092
13093 pub(crate) fn focus_entries(
13094 &self,
13095 scene: &Node,
13096 layout: &LayoutNode,
13097 ) -> Vec<crate::focus_observers::FocusEntry> {
13098 let Some(focus) = self
13099 .focused
13100 .as_ref()
13101 .filter(|target| valid(target, scene, layout))
13102 else {
13103 return Vec::new();
13104 };
13105 let boundary = self
13106 .focused_popup(layout)
13107 .or_else(|| self.active_dialog(layout))
13108 .unwrap_or_default();
13109 if !focus.path.starts_with(boundary) {
13110 return Vec::new();
13111 }
13112 (boundary.len()..=focus.path.len())
13113 .filter_map(|depth| {
13114 let path = &focus.path[..depth];
13115 let node = scene.at_path(path)?;
13116 Some(crate::focus_observers::FocusEntry {
13117 handle: node.focus_handle.clone()?,
13118 direct: depth == focus.path.len(),
13119 target: Target::from_node(path.to_vec(), node, true, scene.row_key_at(path)),
13120 })
13121 })
13122 .collect()
13123 }
13124
13125 pub fn remember_focus_scope(&mut self, scene: &Node, layout: &LayoutNode) {
13126 self.scope_focus
13127 .remember(scene, layout, self.focused.as_ref());
13128 self.page_focus
13129 .remember(scene, layout, self.focused.as_ref());
13130 }
13131
13132 pub fn key_route(&self, scene: &Node, layout: &LayoutNode) -> Option<crate::KeyRoute> {
13133 if self.menu_open()
13134 || self
13135 .editor
13136 .as_ref()
13137 .is_some_and(|editor| !editor.preedit.is_empty())
13138 {
13139 return None;
13140 }
13141 let focus = self
13142 .focused
13143 .as_ref()
13144 .filter(|target| valid(target, scene, layout))?;
13145 let boundary = self
13146 .focused_popup(layout)
13147 .or_else(|| self.active_dialog(layout))
13148 .unwrap_or_default();
13149 if !focus.path.starts_with(boundary) {
13150 return None;
13151 }
13152 let scopes = (boundary.len()..=focus.path.len())
13153 .filter_map(|depth| {
13154 let path = &focus.path[..depth];
13155 let node = scene.at_path(path)?;
13156 if node.kind != "FocusScope" || node.key_handlers == 0 {
13157 return None;
13158 }
13159 crate::focus_scope::target_at(scene, layout, path)
13160 })
13161 .collect();
13162 crate::KeyRoute::new(focus.clone(), scopes)
13163 }
13164
13165 pub fn discard_range_key(&mut self, key: SliderKey) {
13166 self.range_keys.remove(&key);
13167 }
13168
13169 pub fn focus_target(&mut self, scene: &Node, layout: &LayoutNode, target: Target) {
13171 self.focus_target_with_reason(
13172 scene,
13173 layout,
13174 target,
13175 xrack_runtime::FocusReason::Accessibility,
13176 );
13177 }
13178
13179 #[doc(hidden)]
13180 pub fn focus_text_from_touch(
13181 &mut self,
13182 scene: &Node,
13183 layout: &LayoutNode,
13184 target: Target,
13185 ) -> bool {
13186 self.focus_target_with_reason(
13187 scene,
13188 layout,
13189 target.clone(),
13190 xrack_runtime::FocusReason::PointerClick,
13191 );
13192 self.focused.as_ref() == Some(&target)
13193 }
13194
13195 fn focus_target_with_reason(
13196 &mut self,
13197 scene: &Node,
13198 layout: &LayoutNode,
13199 target: Target,
13200 reason: xrack_runtime::FocusReason,
13201 ) -> bool {
13202 let reveal = reason == xrack_runtime::FocusReason::Programmatic;
13203 let target = if target
13204 .node_in(scene)
13205 .is_some_and(|node| node.kind == "RadioGroup")
13206 {
13207 let Some(target) = radio_group_focus(scene, layout, &target.path, reveal) else {
13208 return false;
13209 };
13210 target
13211 } else {
13212 target
13213 };
13214 if !focus_reachable(&target, scene, layout, reveal)
13215 || self
13216 .active_dialog(layout)
13217 .is_some_and(|modal| !target.path.starts_with(modal))
13218 {
13219 return false;
13220 }
13221 self.remember_focus_scope(scene, layout);
13222 let target = self
13223 .scope_focus
13224 .choose_with_reveal(scene, layout, target, false, false, reveal);
13225 let scrolled = reveal && self.reveal_focus_target(scene, layout, &target);
13226 self.tooltip.focus_source();
13227 self.set_focus_with_reason(Some(target), reason);
13228 self.remember_focus_scope(scene, layout);
13229 scrolled
13230 }
13231
13232 #[doc(hidden)]
13234 pub fn reveal_focused_editor(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
13235 let Some(target) = self.focused_editor_in(scene, layout).cloned() else {
13236 return false;
13237 };
13238 self.reveal_focus_target(scene, layout, &target)
13239 }
13240
13241 #[doc(hidden)]
13243 pub fn reveal_focused_editor_caret(
13244 &mut self,
13245 scene: &Node,
13246 layout: &LayoutNode,
13247 caret: Rect,
13248 ) -> bool {
13249 let Some(target) = self.focused_editor_in(scene, layout).cloned() else {
13250 return false;
13251 };
13252 self.reveal_focus_in_viewports(scene, layout, &target.path, caret)
13253 }
13254
13255 #[doc(hidden)]
13256 pub fn keyboard_avoidance(&self) -> Option<(&[usize], f32)> {
13257 self.keyboard_avoidance
13258 .as_ref()
13259 .map(|(path, shift)| (path.as_slice(), *shift))
13260 }
13261
13262 #[doc(hidden)]
13263 pub fn set_floating_keyboard(&mut self, bounds: Option<Rect>) {
13264 self.floating_keyboard = bounds;
13265 }
13266
13267 #[doc(hidden)]
13268 pub fn floating_keyboard(&self) -> Option<Rect> {
13269 self.floating_keyboard
13270 }
13271
13272 #[doc(hidden)]
13274 pub fn avoid_floating_keyboard(
13275 &mut self,
13276 scene: &Node,
13277 layout: &LayoutNode,
13278 keyboard: Option<Rect>,
13279 multiline_caret: Option<Rect>,
13280 ) -> bool {
13281 let next = keyboard.and_then(|keyboard| {
13282 let target = self.focused_editor_in(scene, layout)?;
13283 let item = layout.at_path(&target.path)?;
13284 let node = target.node_in(scene)?;
13285 let multiline = is_multiline_text_input(node.kind);
13286 let target_rect = if multiline {
13287 if node.text_read_only() {
13288 return None;
13289 }
13290 multiline_caret?
13291 } else {
13292 focus_hitbox(node, item)?
13293 };
13294 crate::viewport::plan_keyboard_avoidance(
13295 scene,
13296 layout,
13297 &target.path,
13298 item.window_bounds(target_rect),
13299 keyboard,
13300 self.keyboard_avoidance(),
13301 multiline,
13302 )
13303 });
13304 if match (&self.keyboard_avoidance, &next) {
13305 (Some((path, shift)), Some((next_path, next_shift))) => {
13306 path == next_path && (shift - next_shift).abs() < 0.01
13307 }
13308 (None, None) => true,
13309 _ => false,
13310 } {
13311 return false;
13312 }
13313 self.keyboard_avoidance = next;
13314 true
13315 }
13316
13317 fn focused_editor_in(&self, scene: &Node, layout: &LayoutNode) -> Option<&Target> {
13318 let target = self.focused.as_ref()?;
13319 let node = target.node_in(scene)?;
13320 (self.allows_popup(layout, &target.path)
13321 && (self.is_text_editor(node, target) || spin_editable(node)))
13322 .then_some(target)
13323 }
13324
13325 fn reveal_focus_target(&mut self, scene: &Node, layout: &LayoutNode, target: &Target) -> bool {
13326 if target.text_link.is_some() {
13327 return false;
13328 }
13329 let Some(rect) = scene
13330 .at_path(&target.path)
13331 .zip(layout.at_path(&target.path))
13332 .and_then(|(node, item)| focus_hitbox(node, item))
13333 else {
13334 return false;
13335 };
13336 self.reveal_focus_in_viewports(scene, layout, &target.path, rect)
13337 }
13338
13339 pub fn apply_focus_requests(
13340 &mut self,
13341 scene: &Node,
13342 layout: &LayoutNode,
13343 requests: impl IntoIterator<Item = xrack_runtime::FocusRequest>,
13344 ) {
13345 for request in requests {
13346 if let Some(command) = self.apply_focus_request(scene, layout, request) {
13347 self.apply_text_selection(scene, command);
13348 }
13349 }
13350 }
13351
13352 pub fn apply_focus_request(
13354 &mut self,
13355 scene: &Node,
13356 layout: &LayoutNode,
13357 request: xrack_runtime::FocusRequest,
13358 ) -> Option<TextCommand> {
13359 self.apply_focus_request_with_scroll(scene, layout, request)
13360 .0
13361 }
13362
13363 #[doc(hidden)]
13364 pub fn apply_focus_request_with_scroll(
13365 &mut self,
13366 scene: &Node,
13367 layout: &LayoutNode,
13368 request: xrack_runtime::FocusRequest,
13369 ) -> (Option<TextCommand>, bool) {
13370 let mut scrolled = false;
13371 let command = (|| {
13372 let modal = self.active_dialog(layout).unwrap_or_default();
13373 let reveal = matches!(request.action, xrack_runtime::FocusAction::Focus);
13374 let target =
13375 crate::focus_scope::handle_target(scene, layout, modal, &request.target, reveal)?;
13376 match request.action {
13377 xrack_runtime::FocusAction::Focus => {
13378 scrolled = self.focus_target_with_reason(
13379 scene,
13380 layout,
13381 target,
13382 xrack_runtime::FocusReason::Programmatic,
13383 );
13384 }
13385 xrack_runtime::FocusAction::Clear => {
13386 let scope = scene.at_path(&target.path).is_some_and(|node| {
13387 matches!(node.kind, "FocusScope" | "Loader" | "RadioGroup")
13388 });
13389 if self.focused.as_ref().is_some_and(|focused| {
13390 *focused == target || scope && focused.path.starts_with(&target.path)
13391 }) {
13392 self.remember_focus_scope(scene, layout);
13393 self.set_focus_with_reason(None, xrack_runtime::FocusReason::Programmatic);
13394 }
13395 }
13396 xrack_runtime::FocusAction::OpenChoice => {
13397 if scene
13398 .at_path(&target.path)
13399 .is_some_and(|node| node.kind == "ComboBox")
13400 && !self.choice_is_open_for(&target.path)
13401 && self.open_choice(scene, layout, target)
13402 {
13403 self.dismiss_menu();
13404 }
13405 }
13406 xrack_runtime::FocusAction::CloseChoice => {
13407 if self.choice_is_open_for(&target.path) {
13408 self.dismiss_choice();
13409 }
13410 }
13411 xrack_runtime::FocusAction::Text(command) => {
13412 let node = scene.interactive_at_path(&target.path)?;
13413 let focused = self.focused.as_ref().is_some_and(|current| {
13414 current == &target
13415 || node.selectable_styled_text()
13416 && current.path == target.path
13417 && current.row_key == target.row_key
13418 });
13419 if !focused
13420 || !self.is_text_editor(node, &target)
13421 || self.editor.as_ref().is_some_and(TextEdit::is_composing)
13422 {
13423 return None;
13424 }
13425 self.sync_editor(scene);
13426 return Some(command);
13427 }
13428 xrack_runtime::FocusAction::EditTableCell { row, column } => {
13429 let row = usize::try_from(row).ok()?;
13430 let column = usize::try_from(column).ok()?;
13431 let cell = table_cell_target(scene, layout, &target.path, row, column)?;
13432 self.begin_cell_edit(
13433 scene,
13434 layout,
13435 cell,
13436 xrack_runtime::FocusReason::Programmatic,
13437 );
13438 }
13439 xrack_runtime::FocusAction::CancelTableEdit => {
13440 if self.table_edit.as_ref().is_some_and(|edit| {
13441 table_cell_row(scene, &edit.target.path)
13442 .is_some_and(|(table, _)| table == target.path)
13443 }) {
13444 self.cancel_table_edit();
13445 }
13446 }
13447 }
13448 None
13449 })();
13450 (command, scrolled)
13451 }
13452
13453 pub fn apply_text_selection(&mut self, scene: &Node, command: TextCommand) {
13454 let Some(target) = &self.focused else {
13455 return;
13456 };
13457 let Some(node) = scene.interactive_at_path(&target.path) else {
13458 return;
13459 };
13460 let value = self.editor_value(node);
13461 let Some(mut editor) = self.editor.clone() else {
13462 return;
13463 };
13464 let (anchor, focus) = match command {
13465 TextCommand::SelectAll => (
13466 0,
13467 TextPosition {
13468 offset: value.len(),
13469 trailing: false,
13470 },
13471 ),
13472 TextCommand::SelectWord => {
13473 let word = TextEdit::word_at(&value, editor.position(&value), node.is_password());
13474 (
13475 word.start,
13476 TextPosition {
13477 offset: word.end,
13478 trailing: true,
13479 },
13480 )
13481 }
13482 TextCommand::ClearSelection => {
13483 let caret = editor.position(&value);
13484 (caret.offset, caret)
13485 }
13486 TextCommand::SetSelection { anchor, focus } => {
13487 let offset = |byte: i64| {
13488 usize::try_from(byte.max(0))
13489 .unwrap_or(usize::MAX)
13490 .min(value.len())
13491 };
13492 (
13493 offset(anchor),
13494 TextPosition {
13495 offset: offset(focus),
13496 trailing: false,
13497 },
13498 )
13499 }
13500 _ => return,
13501 };
13502 editor.set_selection(&value, anchor, focus);
13503 self.editor = Some(editor);
13504 self.break_text_edit_group();
13505 self.painted_combo_completion = None;
13506 }
13507
13508 pub fn accessibility_focus(&mut self, target: Target) {
13509 if target.focusable {
13510 self.tooltip.focus_source();
13511 self.set_focus_with_reason(Some(target), xrack_runtime::FocusReason::Accessibility);
13512 }
13513 }
13514 pub fn key_press(&mut self, key: ActivationKey) {
13515 self.cancel_delay();
13516 self.button_hold = None;
13517 self.key_activation_claimed = None;
13518 self.key_pressed = self.focused.clone().map(|t| (key, t));
13519 self.key_standard_button = None;
13520 }
13521
13522 pub fn key_press_with_scene(&mut self, scene: &Node, key: ActivationKey) {
13523 self.key_press(key);
13524 if let Some(target) = self.focused.clone() {
13525 self.start_button_contact(scene, target, ButtonContactSource::Key(key));
13526 }
13527 self.key_standard_button = self
13528 .focused
13529 .as_ref()
13530 .and_then(|target| scene.at_path(&target.path))
13531 .and_then(Node::standard_button_kind);
13532 }
13533 pub fn key_release(&mut self, key: ActivationKey) -> Option<&'static str> {
13534 self.key_release_target(key).and_then(|target| target.id)
13535 }
13536 pub fn key_release_target(&mut self, key: ActivationKey) -> Option<Target> {
13537 if self.key_pressed.as_ref()?.0 != key {
13538 return None;
13539 }
13540 let (_, target) = self.key_pressed.take()?;
13541 self.finish_button_contact(
13542 ButtonContactSource::Key(key),
13543 self.focused.as_ref() == Some(&target),
13544 );
13545 if self.button_hold.as_ref().is_some_and(
13546 |repeat| matches!(repeat.source, DelaySource::Key(pressed) if pressed == key),
13547 ) {
13548 self.button_hold = None;
13549 }
13550 self.key_standard_button = None;
13551 let claimed = self.key_activation_claimed.take() == Some(key);
13552 if self
13553 .delay_hold
13554 .as_ref()
13555 .is_some_and(|hold| matches!(hold.source, DelaySource::Key(pressed) if pressed == key))
13556 {
13557 self.cancel_delay();
13558 }
13559 (!claimed && self.focused.as_ref() == Some(&target)).then_some(target)
13560 }
13561
13562 pub fn key_release_with_scene(&mut self, scene: &Node, key: ActivationKey) -> Option<Target> {
13563 let kind = self.key_standard_button;
13564 let target = self.key_release_target(key)?;
13565 let node = target.node_in(scene)?;
13566 (node.standard_button_kind() == kind).then_some(target)
13567 }
13568 pub fn cancel_press(&mut self) {
13569 self.text_selection_scroll = None;
13570 self.editor_press = None;
13571 self.last_editor_click = None;
13572 self.button_press_events.extend(
13573 self.button_contacts
13574 .drain(..)
13575 .map(|contact| (contact, "canceled")),
13576 );
13577 for handle in self.published_button_presses.drain(..) {
13578 handle.publish(false);
13579 }
13580 if self.touch_table_drag_claimed() {
13581 self.pointer = None;
13582 }
13583 self.cancel_window_move();
13584 self.cancel_scroll_gesture();
13585 self.cancel_delay();
13586 self.button_hold = None;
13587 self.pointer_activation_claimed = false;
13588 self.key_activation_claimed = None;
13589 self.dialog_backdrop = None;
13590 self.pressed = None;
13591 self.press_origin = None;
13592 self.scroll_bar_press = None;
13593 self.pressed_radio = None;
13594 self.pressed_list_row = None;
13595 self.pressed_tree_indicator = false;
13596 self.pressed_table_column = None;
13597 self.pressed_body_column = None;
13598 self.pressed_control_part = None;
13599 self.pressed_standard_button = None;
13600 self.table_resize = None;
13601 self.table_row_resize = None;
13602 self.table_column_move = None;
13603 self.table_row_move = None;
13604 self.table_drag_selection = None;
13605 self.clear_split_drag();
13606 self.slider_offset = 0.0;
13607 self.slider_anchor = None;
13608 self.slider_fraction = None;
13609 self.clear_range_preview();
13610 self.dial_pointer = None;
13611 self.spin_pressed = None;
13612 self.key_pressed = None;
13613 self.range_keys.clear();
13614 }
13615 pub fn is_hovered(&self, path: &[usize]) -> bool {
13616 self.hovered.as_ref().is_some_and(|t| t.path == path)
13617 }
13618 pub fn is_focused(&self, path: &[usize]) -> bool {
13619 self.focused.as_ref().is_some_and(|t| t.path == path)
13620 }
13621 pub fn publish_button_presses(&mut self, scene: &Node, layout: &LayoutNode) {
13623 let mut next = Vec::new();
13624 if !self.menu_open() && !self.choice_open() {
13625 let pointer = self
13626 .pressed
13627 .as_ref()
13628 .filter(|target| self.hovered.as_ref() == Some(*target));
13629 let key = self
13630 .key_pressed
13631 .as_ref()
13632 .map(|(_, target)| target)
13633 .filter(|target| self.focused.as_ref() == Some(*target));
13634 let touch = self.scroll_gesture.as_ref().and_then(|gesture| {
13635 let point = gesture.touch_point?;
13636 let Some(Hit::Target(target)) = &gesture.tap else {
13637 return None;
13638 };
13639 (!gesture.motion.dragging
13640 && self.target_at(scene, layout, point).as_ref() == Some(target))
13641 .then_some(target)
13642 });
13643 let scope = self.active_dialog(layout).unwrap_or_default();
13644 for target in [pointer, key, touch].into_iter().flatten() {
13645 if target.path.starts_with(scope)
13646 && valid(target, scene, layout)
13647 && let Some(handle) = target
13648 .node_in(scene)
13649 .and_then(|node| node.button_press_handle.as_ref())
13650 && !next.contains(handle)
13651 {
13652 next.push(handle.clone());
13653 }
13654 }
13655 }
13656 for old in &self.published_button_presses {
13657 if !next.contains(old) {
13658 old.publish(false);
13659 }
13660 }
13661 for handle in &next {
13662 handle.publish(true);
13663 }
13664 self.published_button_presses = next;
13665 }
13666
13667 fn start_button_contact(&mut self, scene: &Node, target: Target, source: ButtonContactSource) {
13668 let Some(handle) = target
13669 .node_in(scene)
13670 .and_then(|node| node.button_press_handle.clone())
13671 else {
13672 return;
13673 };
13674 self.finish_button_contact(source, false);
13675 if handle.cancel_animation() {
13676 self.button_press_events.push((
13677 ButtonContact {
13678 source,
13679 target: target.clone(),
13680 handle: handle.clone(),
13681 },
13682 "canceled",
13683 ));
13684 }
13685 self.button_press_events.push((
13686 ButtonContact {
13687 source,
13688 target: target.clone(),
13689 handle: handle.clone(),
13690 },
13691 "pressed",
13692 ));
13693 self.button_contacts.push(ButtonContact {
13694 source,
13695 target,
13696 handle,
13697 });
13698 }
13699
13700 fn finish_button_contact(&mut self, source: ButtonContactSource, released: bool) {
13701 if let Some(index) = self
13702 .button_contacts
13703 .iter()
13704 .position(|contact| contact.source == source)
13705 {
13706 self.button_press_events.push((
13707 self.button_contacts.remove(index),
13708 if released { "released" } else { "canceled" },
13709 ));
13710 }
13711 }
13712
13713 pub fn dispatch_button_press_events(
13715 &mut self,
13716 component: &mut impl Component,
13717 scene: &Node,
13718 layout: &LayoutNode,
13719 ) -> bool {
13720 self.publish_button_presses(scene, layout);
13721 if self.button_contacts.is_empty() && self.button_press_events.is_empty() {
13722 return false;
13723 }
13724 let scope = self.active_dialog(layout).unwrap_or_default().to_vec();
13725 let popup = self.menu_open() || self.choice_open();
13726 let focused = self.focused.as_ref();
13727 let pointer = self.pressed.as_ref();
13728 let key_pressed = self.key_pressed.as_ref();
13729 let gesture = self.scroll_gesture.is_some();
13730 self.button_contacts.retain(|contact| {
13731 let current = contact.target.path.starts_with(&scope)
13732 && !popup
13733 && valid(&contact.target, scene, layout)
13734 && contact
13735 .target
13736 .node_in(scene)
13737 .and_then(|node| node.button_press_handle.as_ref())
13738 == Some(&contact.handle)
13739 && match contact.source {
13740 ButtonContactSource::Pointer => pointer == Some(&contact.target),
13741 ButtonContactSource::Gesture => gesture,
13742 ButtonContactSource::Key(key) => {
13743 focused == Some(&contact.target)
13744 && key_pressed.is_some_and(|(pressed, target)| {
13745 key == *pressed && target == &contact.target
13746 })
13747 }
13748 };
13749 if !current {
13750 self.button_press_events.push((
13751 ButtonContact {
13752 source: contact.source,
13753 target: contact.target.clone(),
13754 handle: contact.handle.clone(),
13755 },
13756 "canceled",
13757 ));
13758 }
13759 current
13760 });
13761 let mut handled = false;
13762 for (contact, event) in std::mem::take(&mut self.button_press_events) {
13763 if contact
13764 .target
13765 .node_in(scene)
13766 .and_then(|node| node.button_press_handle.as_ref())
13767 == Some(&contact.handle)
13768 {
13769 handled |= component.dispatch_at(scene, &contact.target.path, event);
13770 }
13771 }
13772 handled
13773 }
13774
13775 pub fn is_pressed(&self, path: &[usize]) -> bool {
13776 (self.pressed.as_ref().is_some_and(|t| t.path == path)
13777 && self.is_hovered(path)
13778 && self.pressed_list_row == self.hovered_list_row
13779 && self.pressed_standard_button == self.hovered_standard_button)
13780 || self
13781 .key_pressed
13782 .as_ref()
13783 .is_some_and(|(_, t)| t.path == path)
13784 || self.button_hold.as_ref().is_some_and(|repeat| {
13785 matches!(repeat.source, DelaySource::Touch(_)) && repeat.target.path == path
13786 })
13787 }
13788}
13789
13790pub struct WheelRoute {
13792 deliveries: Vec<(Vec<usize>, xrack_runtime::WheelEvent)>,
13793}
13794
13795fn local_handler_position(
13796 item: &LayoutNode,
13797 point: Point,
13798) -> Option<(xrack_runtime::Length, xrack_runtime::Length)> {
13799 let local = item.map_from_window(point)?;
13800 (item.enabled && item.bounds.contains(local) && item.contains_clip_point(point)).then(|| {
13801 (
13802 xrack_runtime::Length(f64::from(local.x - item.bounds.x)),
13803 xrack_runtime::Length(f64::from(local.y - item.bounds.y)),
13804 )
13805 })
13806}
13807
13808impl WheelRoute {
13809 pub fn dispatch(
13810 self,
13811 component: &mut impl Component,
13812 scene: &Node,
13813 ) -> xrack_runtime::EventResult {
13814 for (path, event) in self.deliveries {
13815 if component.wheel_event_at(scene, &path, &event) == xrack_runtime::EventResult::Accept
13816 {
13817 return xrack_runtime::EventResult::Accept;
13818 }
13819 }
13820 xrack_runtime::EventResult::Reject
13821 }
13822}