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::{ChoicePopup, MAX_ROWS as CHOICE_PAGE, Typeahead, matches_prefix, next_choice},
9 delay_button::{ButtonHold, ButtonHoldEvent, ButtonHoldTiming, DelayHold, DelaySource},
10 history::{EditHistories, EditorKey, Group, Record, TextHistory},
11 hover_observers::HoverEntry,
12 list_anchor::{ListAnchor, capture_list_anchors},
13 menu::{MenuPopup, TextMenu},
14 modal,
15 overscroll::Overscroll,
16 scroll_bar::snap_fraction,
17 scroll_gesture::{DRAG_THRESHOLD, DragMotion, FlingMotion, PanDevice, SCROLL_FRAME_INTERVAL},
18 shortcut::{self, PendingShortcut},
19 split::axis_point,
20 swipe_delegate::SwipeDrag,
21 swipe_gesture::{SwipeDelivery, SwipePhase, SwipeTarget, has_swipe_directions},
22 tab_move::TabDrag,
23 tooltip::{self, Source as TooltipSource, TooltipState},
24 tumbler::{TumblerDrag, TumblerFlick, TumblerWheel},
25 view_cells::ViewCells,
26 viewport::{MotionOwners, MotionState, UserScrollChange, record_motion, record_motion_owner},
27};
28use std::borrow::Cow;
29use std::collections::{BTreeMap, BTreeSet};
30use std::rc::Rc;
31use std::time::{Duration, Instant};
32use xrack_runtime::{
33 ButtonGroupMembership, CalendarAction, Component, ControlAction, Date, DialInputMode,
34 DialogRole, DrawerEdge, FocusHandle, LayoutDirection, Length, ListMetrics, Node, Orientation,
35 PageIdentity, RangeAction, RowKey, RowSelection, ScrollAction, ScrollAlignment, ScrollBarRange,
36 ScrollRequest, ScrollSnapMode, SelectionTarget, SliderInterval, SliderRange, SpinAction,
37 SpinDecimal, StandardButtonKind, SwipePreviewHandle, SwipeSide, TableEditPosition,
38 TableSelectionAction, TextCommand, TextCommandAvailability, TreeAction, TreeSelectionAction,
39 Tumbler, Value, ViewportHandle, ViewportMotion, combo_editable, combo_index, decimal_separator,
40 delay_millis, dialog_button_action, editable_table_cell, group_index, group_item,
41 is_calendar_control, is_multiline_text_input, is_spin_box, is_text_input, is_toggle,
42 is_window_overlay, page_indicator_count, page_indicator_index, radio_value,
43 resizable_table_column, search_suggestion, spin_editable, spin_text, spin_text_is_valid,
44 text_input_value,
45};
46
47#[derive(Clone, Debug)]
48pub(crate) enum ElementId {
49 Static(&'static str),
50 Shared(std::sync::Arc<str>),
51}
52
53impl ElementId {
54 pub(crate) fn of(node: &Node) -> Option<Self> {
55 node.id
56 .map(Self::Static)
57 .or_else(|| node.shared_element_id().map(Self::Shared))
58 }
59
60 pub(crate) fn as_str(&self) -> &str {
61 match self {
62 Self::Static(id) => id,
63 Self::Shared(id) => id,
64 }
65 }
66}
67
68impl PartialEq for ElementId {
69 fn eq(&self, other: &Self) -> bool {
70 self.as_str() == other.as_str()
71 }
72}
73
74impl Eq for ElementId {}
75
76#[derive(Clone, Debug)]
77pub struct Target {
78 pub path: Vec<usize>,
79 pub id: Option<&'static str>,
81 pub focusable: bool,
82 pub row_key: Option<RowKey>,
83 pub text_link: Option<TextLinkTarget>,
84 pub(crate) tab_close: Option<(xrack_runtime::TabClose, String)>,
85 owned_id: Option<std::sync::Arc<str>>,
86 radio_option_key: Option<RowKey>,
87}
88
89impl PartialEq for Target {
90 fn eq(&self, other: &Self) -> bool {
91 self.path == other.path
92 && self.element_id() == other.element_id()
93 && self.focusable == other.focusable
94 && self.row_key == other.row_key
95 && self.tab_close == other.tab_close
96 && self.text_link == other.text_link
97 && self.radio_option_key == other.radio_option_key
98 }
99}
100
101impl Eq for Target {}
102
103#[derive(Clone, Debug, PartialEq, Eq)]
105pub struct TablePasteDestination {
106 pub path: Vec<usize>,
107 pub row: usize,
108 pub columns: Vec<usize>,
109 focus: Target,
110}
111
112#[derive(Clone, Debug, PartialEq, Eq)]
115pub struct TextLinkTarget {
116 index: usize,
117 document: xrack_runtime::StyledText,
118}
119
120impl Target {
121 pub fn from_node(
123 path: Vec<usize>,
124 node: &Node,
125 focusable: bool,
126 row_key: Option<RowKey>,
127 ) -> Self {
128 let mut target = Self::from_element_id(path, ElementId::of(node), focusable, row_key);
129 target.radio_option_key = Self::radio_option_key(node);
130 target
131 }
132
133 pub(crate) fn from_element_id(
134 path: Vec<usize>,
135 id: Option<ElementId>,
136 focusable: bool,
137 row_key: Option<RowKey>,
138 ) -> Self {
139 let mut target = Self {
140 path,
141 id: None,
142 focusable,
143 row_key,
144 text_link: None,
145 tab_close: None,
146 owned_id: None,
147 radio_option_key: None,
148 };
149 target.set_element_id(id);
150 target
151 }
152
153 fn set_element_id(&mut self, id: Option<ElementId>) {
154 (self.id, self.owned_id) = match id {
155 Some(ElementId::Static(id)) => (Some(id), None),
156 Some(ElementId::Shared(id)) => (None, Some(id)),
157 None => (None, None),
158 };
159 }
160
161 pub fn element_id(&self) -> Option<&str> {
163 self.id.or(self.owned_id.as_deref())
164 }
165
166 pub(crate) fn matches_node(&self, node: &Node) -> bool {
167 self.element_id() == node.element_id()
168 && self.radio_option_key == Self::radio_option_key(node)
169 }
170
171 fn radio_option_key(node: &Node) -> Option<RowKey> {
172 if node.kind == "RadioButton" {
173 node.routing_row_key()
174 } else {
175 None
176 }
177 }
178
179 pub(crate) fn node_in<'a>(&self, scene: &'a Node) -> Option<&'a Node> {
180 let node = scene.at_path(&self.path)?;
181 (self.matches_node(node) && self.row_key == scene.row_key_at(&self.path)).then_some(node)
182 }
183
184 pub fn text_link_index(&self) -> Option<usize> {
185 self.text_link.as_ref().map(|link| link.index)
186 }
187
188 pub(crate) fn for_text_link(node: &Node, path: &[usize], index: usize) -> Option<Self> {
189 let document = node.styled_text("text")?;
190 document.links().get(index)?;
191 let mut target = Self::from_node(path.to_vec(), node, true, None);
192 target.text_link = Some(TextLinkTarget {
193 index,
194 document: document.clone(),
195 });
196 Some(target)
197 }
198}
199
200#[derive(Clone, Copy, Debug, PartialEq, Eq)]
201pub enum ActivationKey {
202 Enter,
203 Space,
204}
205
206#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
207pub enum NavigationKey {
208 Left,
209 Right,
210 Up,
211 Down,
212 Home,
213 End,
214 PageUp,
215 PageDown,
216}
217
218pub type SliderKey = NavigationKey;
219
220#[derive(Clone, Copy, Debug, PartialEq, Eq)]
221pub enum TableSelectionKey {
222 Toggle,
223 All,
224 Clear,
225}
226
227#[derive(Clone, Debug, PartialEq)]
228pub struct RangeInput {
229 pub path: Vec<usize>,
230 pub action: RangeAction,
231}
232
233#[derive(Debug, PartialEq)]
234pub enum WheelAdjustment {
235 Pending,
236 Range(RangeInput),
237 Spin(ControlInput),
238}
239
240#[derive(Clone, Debug)]
241struct WheelSteps {
242 path: Vec<usize>,
243 row: Option<RowKey>,
244 handle: Option<usize>,
245 horizontal: bool,
246 is_line: bool,
247 remainder: f64,
248 time: Instant,
249}
250
251#[derive(Clone, Debug, PartialEq)]
252pub enum ScrollBarUpdate {
253 Unchanged,
254 ViewportMoved,
255 Range(RangeInput),
256}
257
258#[derive(Clone, Debug, PartialEq, Eq)]
259pub struct ControlInput {
260 pub path: Vec<usize>,
261 pub action: ControlAction,
262}
263
264fn dismiss_overlay(node: &Node) -> ControlAction {
265 match node.kind {
266 "Drawer" => ControlAction::Drawer(false),
267 "PopupWindow" => ControlAction::Popup(false),
268 _ => ControlAction::Dialog(DialogRole::Reject),
269 }
270}
271
272fn is_modal_path(layout: &LayoutNode, path: &[usize]) -> bool {
273 layout.dialog_paths().iter().any(|modal| modal == path)
274}
275
276pub struct SplitResize {
277 pub path: Vec<usize>,
278 pub weights: Vec<(usize, f32)>,
279 pub sizes: Option<Vec<(usize, f32)>>,
280}
281
282impl ControlInput {
283 #[doc(hidden)]
284 pub fn with_row_selection(mut self, scene: &Node, operation: RowSelection) -> Self {
285 if let Some(node) = scene.at_path(&self.path)
286 && let ControlAction::Select(index) = self.action
287 {
288 if let Some(action) = tree_row_action(node, index, operation) {
289 self.action = action;
290 } else if node.table_selection.is_some() {
291 self.action =
292 ControlAction::TableSelection(TableSelectionAction::Row { index, operation });
293 }
294 }
295 self
296 }
297}
298
299fn tree_row_action(node: &Node, index: usize, operation: RowSelection) -> Option<ControlAction> {
300 node.tree_selection.as_ref()?;
301 let item = node.tree.as_ref()?.rows().get(index)?;
302 Some(ControlAction::Tree(TreeAction::Selection(
303 TreeSelectionAction::Row {
304 key: item.key,
305 row: item.row,
306 operation,
307 },
308 )))
309}
310
311#[derive(Clone, Debug)]
312struct DialogFocus {
313 path: Vec<usize>,
314 row_key: Option<RowKey>,
315 modal: bool,
316 return_focus: Option<Target>,
317}
318
319#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
320struct StackFocusKey {
321 path: Vec<usize>,
322 row: Option<RowKey>,
323 page: usize,
324}
325
326#[derive(Clone, Debug)]
327struct TableResize {
328 target: Target,
329 column: usize,
330 pointer_x: f32,
331 width: f32,
332 mirrored: bool,
333}
334
335#[derive(Clone, Debug)]
336struct TableRowResize {
337 target: Target,
338 key: RowKey,
339 pointer_y: f32,
340 height: f32,
341}
342
343#[derive(Clone, Debug)]
344struct TableColumnMove {
345 target: Target,
346 column: usize,
347 start: Point,
348 order: xrack_runtime::TableColumnOrder,
349 mirrored: bool,
350 claimed: bool,
351 scroll_wake: Option<Instant>,
352}
353
354#[derive(Clone, Debug)]
355struct TableRowMove {
356 table: Target,
357 from: usize,
358 row: xrack_runtime::RowKey,
359 stamp: (u64, u64),
360 start: Point,
361 claimed: bool,
362 touch: bool,
363 scroll_wake: Option<Instant>,
364}
365
366#[derive(Clone, Debug)]
367struct SplitDrag {
368 target: Target,
369 orientation: Orientation,
370 mirrored: bool,
371 after_pane: usize,
372 grab_offset: f32,
373 state: Option<xrack_runtime::SplitResizeHandle>,
374}
375
376impl SplitDrag {
377 fn matches(&self, geometry: &SplitGeometry, handle: &SplitHandle) -> bool {
378 geometry.orientation == self.orientation
379 && geometry.mirrored == self.mirrored
380 && handle.after_pane() == self.after_pane
381 }
382}
383
384#[derive(Clone, Debug)]
385struct WindowMovePress {
386 target: Target,
387 origin: Point,
388}
389
390#[derive(Clone, Debug)]
391struct TableEdit {
392 target: Target,
393 original: String,
394 draft: String,
395 history: TextHistory,
396}
397
398#[derive(Clone, Copy, Debug, PartialEq, Eq)]
399pub enum TableEditCommit {
400 Kept,
401 Unchanged,
402 Changed,
403 Rejected,
404}
405
406pub struct TableEditTarget {
407 table: Vec<usize>,
408 viewport: ViewportHandle,
409 position: TableEditPosition,
410}
411
412impl TableEditTarget {
413 pub fn scroll_request(&self) -> ScrollRequest {
414 ScrollRequest {
415 target: self.viewport.clone(),
416 action: ScrollAction::ToCell {
417 row: self.position.row as i64,
418 column: self.position.column as i64,
419 horizontal: ScrollAlignment::Contain,
420 vertical: ScrollAlignment::Contain,
421 },
422 }
423 }
424}
425
426#[derive(Clone, Debug)]
427struct SpinDraft {
428 text: String,
429 mode: SpinDraftMode,
430 history: TextHistory,
431}
432
433#[derive(Clone, Copy, Debug)]
434enum SpinDraftMode {
435 Integer(Option<i64>),
436 Decimal {
437 original: Option<SpinDecimal>,
438 separator: char,
439 },
440}
441
442impl SpinDraftMode {
443 fn for_node(node: &Node) -> Self {
444 if node.kind == "DoubleSpinBox" {
445 Self::Decimal {
446 original: node.number("value").and_then(SpinDecimal::new),
447 separator: decimal_separator(node),
448 }
449 } else {
450 Self::Integer(node.int("value"))
451 }
452 }
453
454 fn separator(self) -> Option<char> {
455 match self {
456 Self::Decimal { separator, .. } => Some(separator),
457 Self::Integer(_) => None,
458 }
459 }
460
461 fn commit(self, text: &str) -> Option<SpinAction> {
462 Some(match self {
463 Self::Integer(Some(original)) => SpinAction::CommitIfCurrent {
464 original,
465 value: text.parse().ok()?,
466 },
467 Self::Integer(None) => SpinAction::Commit(text.parse().ok()?),
468 Self::Decimal {
469 original,
470 separator,
471 } => SpinAction::CommitDecimalIfCurrent {
472 original,
473 value: SpinDecimal::parse(text, separator)?,
474 },
475 })
476 }
477
478 fn is_current(self, node: &Node) -> bool {
479 spin_editable(node)
480 && match (self, Self::for_node(node)) {
481 (Self::Integer(original), Self::Integer(current)) => {
482 original.is_none() || original == current
483 }
484 (
485 Self::Decimal {
486 original,
487 separator,
488 },
489 Self::Decimal {
490 original: current,
491 separator: current_separator,
492 },
493 ) => original == current && separator == current_separator,
494 _ => false,
495 }
496 }
497}
498
499#[derive(Clone, Debug, PartialEq, Eq)]
500struct ScrollTarget {
501 path: Vec<usize>,
502 orientation: Orientation,
503 row_key: Option<RowKey>,
504 id: Option<ElementId>,
505}
506
507impl ScrollTarget {
508 fn matches_node(&self, node: &Node) -> bool {
509 self.id.as_ref().map(ElementId::as_str) == node.element_id()
510 }
511
512 fn resolve<'a, 'b>(
513 &self,
514 scene: &'a Node,
515 layout: &'b LayoutNode,
516 ) -> Option<(&'a Node, &'b LayoutNode)> {
517 let item = layout.at_path(&self.path)?;
518 let node = scene.interactive_at_path(&self.path)?;
519 (item.visible
520 && item.enabled
521 && item.scroll_on(self.orientation).is_some()
522 && self.matches_node(node)
523 && scene.row_key_at(&self.path) == self.row_key)
524 .then_some((node, item))
525 }
526}
527
528#[derive(Clone, Debug)]
529struct ScrollBarPress {
530 target: ScrollTarget,
531 source: &'static str,
532 viewport: Option<xrack_runtime::ViewportHandle>,
533 reversed: bool,
534 grab: Option<f32>,
535 touch: bool,
536 cancelled: bool,
537 start: Point,
538 last: Point,
539 dragged: bool,
540}
541
542impl ScrollBarPress {
543 fn node<'a>(&self, scene: &'a Node) -> Option<&'a Node> {
544 scene.at_path(&self.target.path).filter(|node| {
545 node.kind == self.source
546 && self.target.matches_node(node)
547 && node.scroll_target == self.viewport
548 })
549 }
550}
551
552#[derive(Clone, Debug)]
553struct ScrollRoute {
554 scope: Vec<usize>,
555 scope_row: Option<RowKey>,
556 scope_id: Option<ElementId>,
557 axes: [Option<ScrollTarget>; 2],
558 mouse_viewport: bool,
559 pan_device: PanDevice,
560}
561
562#[derive(Clone, Debug)]
563struct ScrollGesture {
564 route: ScrollRoute,
565 motion: DragMotion,
566 tap: Option<Hit>,
567 touch_point: Option<Point>,
568 popup: (bool, bool),
569 drawer: Option<DrawerSwipe>,
570 pages: Vec<PageSwipe>,
571 tumbler: Option<TumblerDrag>,
572 tab_move: Option<TabDrag>,
573 switch: Option<SwitchDrag>,
574 swipe_delegate: Option<SwipeDrag>,
575 swipe: Option<SwipeRoute>,
576 delay_touch: bool,
577 table_gesture: Option<PendingTableGesture>,
578}
579
580#[derive(Clone, Copy, Debug, PartialEq, Eq)]
581enum ButtonContactSource {
582 Pointer,
583 Gesture,
584 Key(ActivationKey),
585}
586
587#[derive(Clone, Debug)]
588struct ButtonContact {
589 source: ButtonContactSource,
590 target: Target,
591 handle: xrack_runtime::ButtonPressHandle,
592}
593
594#[derive(Clone, Debug)]
595struct SwitchDrag {
596 target: Target,
597 start: Point,
598 track: Rect,
599 travel: f32,
600 direction: LayoutDirection,
601 initial: bool,
602 position: Option<f32>,
603 cancelled: bool,
604}
605
606impl SwitchDrag {
607 fn new(target: Target, node: &Node, item: &LayoutNode, point: Point) -> Option<Self> {
608 if node.kind != "Switch" {
609 return None;
610 }
611 let geometry = crate::ToggleGeometry::new(node, item.bounds, item.layout_direction);
612 let start = item.map_from_window(point)?;
613 let travel = geometry.switch_travel();
614 (geometry.indicator.contains(start) && travel > 0.0).then_some(Self {
615 target,
616 start,
617 track: geometry.indicator,
618 travel,
619 direction: item.layout_direction,
620 initial: node.boolean("checked", false),
621 position: None,
622 cancelled: false,
623 })
624 }
625
626 fn matches(
627 &self,
628 node: &Node,
629 bounds: Rect,
630 direction: LayoutDirection,
631 row: Option<RowKey>,
632 ) -> bool {
633 if node.kind != "Switch"
634 || !self.target.matches_node(node)
635 || row != self.target.row_key
636 || node.boolean("checked", false) != self.initial
637 || direction != self.direction
638 {
639 return false;
640 }
641 let geometry = crate::ToggleGeometry::new(node, bounds, direction);
642 geometry.indicator == self.track && geometry.switch_travel() == self.travel
643 }
644
645 fn is_current(&self, scene: &Node, layout: &LayoutNode) -> bool {
646 let path = &self.target.path;
647 scene
648 .interactive_at_path(path)
649 .zip(layout.at_path(path))
650 .is_some_and(|(node, item)| {
651 valid(&self.target, scene, layout)
652 && self.matches(
653 node,
654 item.bounds,
655 item.layout_direction,
656 scene.row_key_at(path),
657 )
658 })
659 }
660
661 fn move_thumb(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> bool {
662 if self.cancelled || !self.is_current(scene, layout) {
663 self.cancelled = true;
664 return self.position.take().is_some();
665 }
666 let local = layout
667 .at_path(&self.target.path)
668 .and_then(|item| item.map_from_window(point));
669 let position = local.map(|local| {
670 let sign = if self.direction == LayoutDirection::RightToLeft {
671 -1.0
672 } else {
673 1.0
674 };
675 let origin = if self.initial { 1.0 } else { 0.0 };
676 (origin + sign * (local.x - self.start.x) / self.travel).clamp(0.0, 1.0)
677 });
678 let changed = self.position != position;
679 self.position = position;
680 changed
681 }
682
683 fn accepts_direction(&self, layout: &LayoutNode, point: Point) -> bool {
684 layout
685 .at_path(&self.target.path)
686 .and_then(|item| item.map_from_window(point))
687 .is_some_and(|point| (point.x - self.start.x).abs() > (point.y - self.start.y).abs())
688 }
689
690 fn finish(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
691 let position = self.position?;
692 let checked = position > 0.5 || position == 0.5 && self.initial;
693 (checked != self.initial && self.is_current(scene, layout)).then(|| ControlInput {
694 path: self.target.path.clone(),
695 action: ControlAction::SetSwitch(checked),
696 })
697 }
698}
699
700#[derive(Clone, Debug)]
701struct PendingTableGesture {
702 drag: PendingTableAction,
703 deadline: Option<Instant>,
704}
705
706#[derive(Clone, Debug)]
707enum PendingTableAction {
708 Select(crate::table_drag_selection::TableDragSelection),
709 Move(TableRowMove),
710}
711
712#[derive(Clone, Debug)]
713enum SwipeRoute {
714 Pending(Vec<SwipeTarget>),
715 Captured(SwipeTarget),
716 Cancelled,
717}
718
719impl SwipeRoute {
720 fn cancel(self) -> Option<SwipeDelivery> {
721 match self {
722 Self::Captured(target) => Some(target.delivery(SwipePhase::Cancelled)),
723 _ => None,
724 }
725 }
726}
727
728#[derive(Clone, Debug)]
729struct SwipePagePosition {
730 index: usize,
731 identity: PageIdentity,
732}
733
734impl SwipePagePosition {
735 fn from_view(view: &Node, index: usize) -> Option<Self> {
736 let node = group_item(view, index)?;
737 Some(Self {
738 index,
739 identity: PageIdentity::of(node, index),
740 })
741 }
742
743 fn matches(&self, view: &Node) -> bool {
744 group_item(view, self.index)
745 .is_some_and(|node| PageIdentity::of(node, self.index) == self.identity)
746 }
747}
748
749#[derive(Clone, Debug)]
750struct PageSwipe {
751 target: ScrollTarget,
752 current: SwipePagePosition,
753 previous: Option<SwipePagePosition>,
754 next: Option<SwipePagePosition>,
755 mirrored: bool,
756 start: Point,
757 bounds: Rect,
758 threshold: f32,
759}
760
761impl PageSwipe {
762 fn along_and_across(&self, vector: Point) -> (f32, f32) {
763 match self.target.orientation {
764 Orientation::Horizontal => (vector.x, vector.y.abs()),
765 Orientation::Vertical => (vector.y, vector.x.abs()),
766 }
767 }
768
769 fn movement(&self, point: Point) -> (f32, f32) {
770 self.along_and_across(Point {
771 x: self.start.x - point.x,
772 y: self.start.y - point.y,
773 })
774 }
775
776 fn release_distance(
777 &self,
778 distance: f32,
779 item: &LayoutNode,
780 velocity: Option<(Point, Point)>,
781 ) -> f32 {
782 const MIN_FLICK_SPEED: f32 = 480.0;
783 const PROJECTION_SECONDS: f32 = 0.10;
784
785 let magnitude = distance.abs();
786 let Some((smoothed, latest)) = velocity else {
787 return magnitude;
788 };
789 let Some(latest) = item.map_delta_from_window(latest) else {
790 return magnitude;
791 };
792 let (along, across) = self.along_and_across(latest);
793 if along.abs() < MIN_FLICK_SPEED || along.abs() <= across {
794 return magnitude;
795 }
796
797 let signed = along * distance.signum();
798 let velocity = if signed < 0.0 {
799 signed
801 } else {
802 let Some(smoothed) = item.map_delta_from_window(smoothed) else {
803 return magnitude;
804 };
805 let (along, across) = self.along_and_across(smoothed);
806 let forward = along * distance.signum();
807 if forward < MIN_FLICK_SPEED || forward <= across {
808 return magnitude;
809 }
810 signed.min(forward)
811 };
812 magnitude + (velocity * PROJECTION_SECONDS).clamp(-self.threshold, self.threshold)
813 }
814
815 fn destination(&self, physical_forward: bool) -> Option<&SwipePagePosition> {
816 if physical_forward != self.mirrored {
817 self.next.as_ref()
818 } else {
819 self.previous.as_ref()
820 }
821 }
822
823 fn view<'a, 'b>(
824 &self,
825 scene: &'a Node,
826 layout: &'b LayoutNode,
827 ) -> Option<(&'a Node, &'b LayoutNode)> {
828 let path = &self.target.path;
829 let view = scene.interactive_at_path(path)?;
830 let item = layout.at_path(path)?;
831 (view.kind == "SwipeView"
832 && self.target.matches_node(view)
833 && view.boolean("interactive", true)
834 && view.orientation() == self.target.orientation
835 && self.mirrored == swipe_view_mirrored(view, item)
836 && item.bounds == self.bounds
837 && item.visible
838 && item.enabled
839 && scene.row_key_at(path) == self.target.row_key
840 && group_index(view) == Some(self.current.index)
841 && self.current.matches(view))
842 .then_some((view, item))
843 }
844
845 fn live_destination(&self, view: &Node, forward: bool) -> Option<&SwipePagePosition> {
846 let destination = self.destination(forward)?;
847 (destination.matches(view)
848 && swipe_neighbor(view, self.current.index, forward != self.mirrored)
849 == Some(destination.index))
850 .then_some(destination)
851 }
852
853 fn action(
854 self,
855 scene: &Node,
856 layout: &LayoutNode,
857 point: Point,
858 velocity: Option<(Point, Point)>,
859 ) -> Option<ControlInput> {
860 let (view, item) = self.view(scene, layout)?;
861 let (distance, across) = self.movement(item.map_from_window(point)?);
862 let index = self.live_destination(view, distance > 0.0)?.index;
863 (distance.abs() >= self.threshold * 0.25
864 && distance.abs() > across
865 && self.release_distance(distance, item, velocity) >= self.threshold)
866 .then_some(ControlInput {
867 path: self.target.path,
868 action: ControlAction::Select(index),
869 })
870 }
871}
872
873#[derive(Debug)]
874struct SwipePreviewLease(SwipePreviewHandle);
875
876impl Drop for SwipePreviewLease {
877 fn drop(&mut self) {
878 self.0.clear();
879 }
880}
881
882#[derive(Clone, Debug)]
883struct SwipePageMotion {
884 page: PageSwipe,
885 lease: Rc<SwipePreviewLease>,
886 fraction: f32,
887 duration: Duration,
888 settling: Option<(Instant, f32)>,
889 wake: Option<Instant>,
890}
891
892impl SwipePageMotion {
893 fn settle(&mut self, now: Instant) {
894 self.settling.get_or_insert((now, self.fraction));
895 self.wake.get_or_insert(now + SCROLL_FRAME_INTERVAL);
896 }
897
898 fn advance(&mut self, now: Instant) -> bool {
899 let Some((start, from)) = self.settling else {
900 return false;
901 };
902 let elapsed = now.saturating_duration_since(start);
903 let remaining = (1.0 - elapsed.as_secs_f32() / self.duration.as_secs_f32()).max(0.0);
904 self.fraction = from * remaining.powi(3);
905 self.wake = (elapsed < self.duration).then(|| now + SCROLL_FRAME_INTERVAL);
906 true
907 }
908
909 fn is_current(&self, scene: &Node, layout: &LayoutNode) -> bool {
910 self.page.view(scene, layout).is_some_and(|(view, _)| {
911 view.int("transition-duration").unwrap_or_default() > 0
912 && view
913 .swipe_preview
914 .as_ref()
915 .is_some_and(|preview| preview.handle == self.lease.0)
916 && self
917 .page
918 .live_destination(view, self.fraction > 0.0)
919 .is_some()
920 })
921 }
922}
923
924fn navigation_axis(vertical: bool, direction: LayoutDirection) -> (NavigationKey, NavigationKey) {
925 if vertical {
926 (NavigationKey::Up, NavigationKey::Down)
927 } else if direction == LayoutDirection::RightToLeft {
928 (NavigationKey::Right, NavigationKey::Left)
929 } else {
930 (NavigationKey::Left, NavigationKey::Right)
931 }
932}
933
934fn swipe_view_mirrored(view: &Node, item: &LayoutNode) -> bool {
935 view.orientation() == Orientation::Horizontal
936 && item.layout_direction == LayoutDirection::RightToLeft
937}
938
939fn swipe_neighbor(view: &Node, current: usize, forward: bool) -> Option<usize> {
940 if forward {
941 (current + 1..view.children.len()).find(|&index| group_item(view, index).is_some())
942 } else {
943 (0..current)
944 .rev()
945 .find(|&index| group_item(view, index).is_some())
946 }
947}
948
949#[derive(Clone, Debug)]
950struct DrawerSwipe {
951 path: Vec<usize>,
952 row_key: Option<RowKey>,
953 id: Option<ElementId>,
954 edge: DrawerEdge,
955 open: bool,
956 start: Point,
957 threshold: f32,
958}
959
960impl DrawerSwipe {
961 fn movement(&self, point: Point) -> (f32, f32) {
962 let x = point.x - self.start.x;
963 let y = point.y - self.start.y;
964 let (inward, across) = match self.edge {
965 DrawerEdge::Left => (x, y),
966 DrawerEdge::Right => (-x, y),
967 DrawerEdge::Top => (y, x),
968 DrawerEdge::Bottom => (-y, x),
969 };
970 (if self.open { -inward } else { inward }, across.abs())
971 }
972
973 fn action(self, scene: &Node, layout: &LayoutNode, point: Point) -> Option<ControlInput> {
974 let action = ControlAction::Drawer(!self.open);
975 let node = scene.control_target(&self.path, action)?;
976 let (distance, across) = self.movement(point);
977 (distance >= self.threshold
978 && distance >= across
979 && node.element_id() == self.id.as_ref().map(ElementId::as_str)
980 && node.drawer_edge() == self.edge
981 && node.boolean("open", false) == self.open
982 && scene.row_key_at(&self.path) == self.row_key
983 && layout.drawer_paths().contains(&self.path))
984 .then_some(ControlInput {
985 path: self.path,
986 action,
987 })
988 }
989}
990
991#[derive(Clone, Debug)]
992struct ScrollFling {
993 route: ScrollRoute,
994 motion: FlingMotion,
995 transformed: bool,
996}
997
998enum ScrollInput<'a> {
999 Wheel,
1000 Pan {
1001 device: PanDevice,
1002 owners: &'a mut MotionOwners,
1003 flicking: bool,
1004 },
1005}
1006
1007#[derive(Clone, Copy, Default)]
1008struct AxisMotion {
1009 bounded: bool,
1010 elastic: bool,
1011}
1012
1013impl AxisMotion {
1014 fn changed(self) -> bool {
1015 self.bounded || self.elastic
1016 }
1017}
1018
1019#[derive(Clone, Debug)]
1020struct EditorClick {
1021 target: Target,
1022 sample: (Point, Instant),
1023}
1024
1025#[derive(Clone, Debug)]
1026struct TextSelectionScroll {
1027 target: Target,
1028 point: Point,
1029 due: Instant,
1030}
1031
1032#[derive(Clone, Debug, Default)]
1033pub struct Interaction {
1034 pub hovered: Option<Target>,
1035 pub focused: Option<Target>,
1036 focus_reason: xrack_runtime::FocusReason,
1037 pub pressed: Option<Target>,
1038 drag: Option<crate::drag::DragSession>,
1039 file_drag: crate::file_drop::FileDrag,
1040 hovered_scroll_bar: Option<ScrollTarget>,
1041 scroll_bar_press: Option<ScrollBarPress>,
1042 scroll_gesture: Option<ScrollGesture>,
1043 swipe_events: Vec<SwipeDelivery>,
1044 tumbler_wheel: Option<TumblerWheel>,
1045 tumbler_flick: Option<TumblerFlick>,
1046 wheel_steps: Option<WheelSteps>,
1047 scroll_fling: Option<ScrollFling>,
1048 viewport_motion: MotionState,
1049 overscroll: Overscroll,
1050 key_pressed: Option<(ActivationKey, Target)>,
1051 key_standard_button: Option<StandardButtonKind>,
1052 delay_hold: Option<DelayHold>,
1053 button_hold: Option<ButtonHold>,
1054 published_button_presses: Vec<xrack_runtime::ButtonPressHandle>,
1055 button_contacts: Vec<ButtonContact>,
1056 button_press_events: Vec<(ButtonContact, &'static str)>,
1057 pointer_activation_claimed: bool,
1058 key_activation_claimed: Option<ActivationKey>,
1059 range_keys: BTreeMap<SliderKey, Target>,
1060 slider_offset: f64,
1061 slider_anchor: Option<f64>,
1062 slider_fraction: Option<f64>,
1063 range_position_handle: Option<xrack_runtime::RangePositionHandle>,
1064 dial_pointer: Option<Point>,
1065 touch_range: bool,
1066 spin_pressed: Option<SpinAction>,
1067 spin_draft: Option<SpinDraft>,
1068 choice: Option<ChoicePopup>,
1069 search_query: Option<String>,
1070 choice_typeahead: Typeahead,
1071 list_typeahead: Typeahead,
1072 pub(crate) list_composition: Option<(u64, Target)>,
1073 painted_combo_completion: Option<ComboCompletion>,
1074 dismissed_combo_draft: Option<String>,
1075 menu: Option<MenuPopup>,
1076 pending_shortcut: Option<PendingShortcut>,
1077 pointer: Option<Point>,
1078 press_origin: Option<Point>,
1079 tooltip: TooltipState,
1080 hovered_radio: Option<(String, String)>,
1081 pressed_radio: Option<(String, String)>,
1082 hovered_list_row: Option<(usize, Option<ElementId>)>,
1083 pressed_list_row: Option<(usize, Option<ElementId>)>,
1084 hovered_tree_indicator: bool,
1085 pressed_tree_indicator: bool,
1086 hovered_table_column: Option<usize>,
1087 pressed_table_column: Option<usize>,
1088 hovered_body_column: Option<usize>,
1089 pressed_body_column: Option<usize>,
1090 hovered_control_part: Option<ControlAction>,
1091 pressed_control_part: Option<ControlAction>,
1092 hovered_standard_button: Option<StandardButtonKind>,
1093 pressed_standard_button: Option<StandardButtonKind>,
1094 hovered_table_grip: Option<(usize, f32, bool)>,
1095 hovered_table_row_grip: Option<(RowKey, f32)>,
1096 table_resize: Option<TableResize>,
1097 table_row_resize: Option<TableRowResize>,
1098 table_column_move: Option<TableColumnMove>,
1099 table_row_move: Option<TableRowMove>,
1100 table_drag_selection: Option<crate::table_drag_selection::TableDragSelection>,
1101 split_drag: Option<SplitDrag>,
1102 split_hover: Option<(xrack_runtime::SplitResizeHandle, usize)>,
1103 table_edit: Option<TableEdit>,
1104 last_table_click: Option<(Target, Instant)>,
1105 editor_press: Option<EditorClick>,
1106 last_editor_click: Option<EditorClick>,
1107 text_selection_scroll: Option<TextSelectionScroll>,
1108 pub editor: Option<TextEdit>,
1109 persistent_editor: Option<PersistentEditor>,
1110 retained_selections: Vec<RetainedSelection>,
1111 editor_window_inactive: bool,
1112 history: EditHistories,
1113 scroll_offsets: BTreeMap<Vec<usize>, f32>,
1114 horizontal_scroll_offsets: BTreeMap<Vec<usize>, f32>,
1115 scroll_selections: BTreeMap<Vec<usize>, ScrollSelection>,
1116 tree_scroll_roots: BTreeMap<Vec<usize>, (i64, Option<RowKey>)>,
1117 pub(crate) scroll_anchors: BTreeMap<Vec<usize>, ListAnchor>,
1118 pub(crate) user_scroll_changes: Vec<UserScrollChange>,
1119 text_offsets: BTreeMap<Vec<usize>, (Option<RowKey>, Point)>,
1120 dialogs: Vec<DialogFocus>,
1121 stack_focus: BTreeMap<StackFocusKey, Target>,
1122 swipe_page_motion: Option<SwipePageMotion>,
1123 swipe_commit: Option<(PageSwipe, f32)>,
1124 page_focus: crate::focus_scope::PageFocusHistory,
1125 calendar_page_focus: Option<CalendarPageFocus>,
1126 scope_focus: crate::focus_scope::FocusHistory,
1127 transitioning_stacks: BTreeSet<Vec<usize>>,
1128 pointer_on_stack_slide: bool,
1129 window_move_press: Option<WindowMovePress>,
1130 dialog_backdrop: Option<Vec<usize>>,
1131}
1132
1133#[derive(Clone, Debug)]
1134struct CalendarPageFocus {
1135 from: Target,
1136 view: Target,
1137 viewport: Option<ViewportHandle>,
1138 order: (u64, u64),
1139 index: usize,
1140}
1141
1142#[derive(Clone, Debug)]
1143struct PersistentEditor {
1144 target: Target,
1145 handle: Option<FocusHandle>,
1146 text: String,
1147 password: bool,
1148}
1149
1150impl PersistentEditor {
1151 fn new(target: &Target, node: &Node) -> Self {
1152 let mut target = target.clone();
1153 target.text_link = None;
1154 Self {
1155 target,
1156 handle: node.focus_handle.clone(),
1157 text: text_input_value(node).to_owned(),
1158 password: node.is_password(),
1159 }
1160 }
1161
1162 fn same_target(&self, target: &Target) -> bool {
1163 self.target.path == target.path
1164 && self.target.row_key == target.row_key
1165 && self.target.element_id() == target.element_id()
1166 }
1167
1168 fn matches(&self, node: &Node) -> bool {
1169 node.boolean("persistent-selection", false)
1170 && (is_text_input(node.kind) || combo_editable(node) || node.selectable_styled_text())
1171 && node.focus_handle == self.handle
1172 && node.is_password() == self.password
1173 && text_input_value(node) == self.text
1174 }
1175}
1176
1177#[derive(Clone, Debug)]
1178struct RetainedSelection {
1179 source: PersistentEditor,
1180 editor: TextEdit,
1181}
1182
1183#[derive(Clone, Debug, PartialEq, Eq)]
1184enum Hit {
1185 None,
1186 Blocked(Vec<usize>),
1187 StackSlide,
1188 WindowMove(Target),
1189 Target(Target),
1190 ControlPart(Target, ControlAction),
1191 ScrollBar(ScrollTarget),
1192 TableRowGrip(Target, usize),
1193}
1194
1195#[derive(Clone, Copy, PartialEq, Eq)]
1196enum HitPurpose<'a> {
1197 Button(xrack_runtime::PointerButton),
1198 Hover,
1199 Gesture(&'a str),
1200}
1201
1202pub(crate) fn focusable(node: &Node) -> bool {
1203 let kind = node.kind;
1204 if matches!(kind, "GroupBox" | "Expander") {
1205 return kind == "Expander" || node.group_checkable();
1206 }
1207 if kind == "PageIndicator" {
1208 return node.boolean("interactive", false) && page_indicator_count(node) != 0;
1209 }
1210 if matches!(kind, "Tumbler" | "PathView") {
1211 return Tumbler::from_node(node).selected().is_some();
1212 }
1213 matches!(
1214 kind,
1215 "Button"
1216 | "FocusScope"
1217 | "Loader"
1218 | "ToolButton"
1219 | "RoundButton"
1220 | "DelayButton"
1221 | "DialogButton"
1222 | "Dialog"
1223 | "Drawer"
1224 | "PopupWindow"
1225 | "Slider"
1226 | "ColorPlane"
1227 | "ScrollBar"
1228 | "Dial"
1229 | "RangeThumb"
1230 | "SpinBox"
1231 | "DoubleSpinBox"
1232 | "ComboBox"
1233 | "Calendar"
1234 | "MonthGrid"
1235 | "RadioButton"
1236 | "Tab"
1237 | "TabButton"
1238 | "SwipeView"
1239 | "SwipeDelegate"
1240 | "StackView"
1241 | "ListView"
1242 | "GridView"
1243 | "StandardListView"
1244 | "TreeView"
1245 | "TableView"
1246 | "TableCell"
1247 | "TreeCell"
1248 | "SplitHandle"
1249 | "Menu"
1250 | "ContextMenuArea"
1251 ) || is_toggle(kind)
1252 || is_text_input(kind)
1253 || node.selectable_styled_text()
1254}
1255
1256fn interactive(node: &Node) -> bool {
1257 matches!(node.kind, "TouchArea" | "ListRow" | "RangeSlider") || focusable(node)
1258}
1259
1260fn list_row(scene: &Node, target: &Target) -> Option<(usize, Option<ElementId>)> {
1261 let (&slot, parent) = target.path.split_last()?;
1262 let list = scene.at_path(parent)?;
1263 let index = list.list?.first_row + slot;
1264 (list.children.get(slot)?.kind == "ListRow").then(|| (index, ElementId::of(list)))
1265}
1266
1267fn table_cell_row<'a>(scene: &Node, path: &'a [usize]) -> Option<(&'a [usize], usize)> {
1268 let [table @ .., slot, 0, _] = path else {
1269 return None;
1270 };
1271 let cell = scene.at_path(path)?;
1272 ((cell.kind == "TableCell" || cell.boolean("table-editor", false))
1273 && scene.at_path(table)?.kind == "TableView")
1274 .then_some((table, *slot))
1275}
1276
1277fn table_cell_target(
1278 scene: &Node,
1279 layout: &LayoutNode,
1280 table: &[usize],
1281 row: usize,
1282 column: usize,
1283) -> Option<Target> {
1284 let view = scene.interactive_at_path(table)?;
1285 let list = view.list?;
1286 if view.kind != "TableView" || row >= list.row_count {
1287 return None;
1288 }
1289 let slot = row.checked_sub(list.first_row)?;
1290 let mut path = table.to_vec();
1291 path.extend([slot, 0, column]);
1292 crate::focus_scope::target_at(scene, layout, &path)
1293}
1294
1295fn list_item_delegate_row<'a>(scene: &Node, path: &'a [usize]) -> Option<(&'a [usize], usize)> {
1296 let [view @ .., slot, 0] = path else {
1297 return None;
1298 };
1299 (scene.at_path(path)?.is_item_delegate()
1300 && matches!(scene.at_path(view)?.kind, "ListView" | "GridView"))
1301 .then_some((view, *slot))
1302}
1303
1304fn tree_indicator_hit(node: &Node, item: &LayoutNode, point: Point) -> bool {
1305 node.boolean("tree-has-children", false)
1306 && item.contains_clip_point(point)
1307 && TreeRowGeometry::for_layout(node, item)
1308 .zip(item.map_from_window(point))
1309 .is_some_and(|(tree, point)| tree.indicator.contains(point))
1310}
1311
1312fn tree_cell_row<'a>(scene: &Node, path: &'a [usize]) -> Option<(&'a [usize], usize)> {
1313 let cell = scene.at_path(path)?;
1314 if cell.kind != "TreeCell" && !cell.boolean("table-editor", false) {
1315 return None;
1316 }
1317 (0..path.len()).rev().find_map(|depth| {
1318 let parent = &path[..depth];
1319 let tree = scene.at_path(parent)?;
1320 let slot = path[depth];
1321 (tree.kind == "TreeView"
1322 && path.get(depth + 1) == Some(&0)
1323 && tree.children.get(slot)?.kind == "ListRow")
1324 .then_some((parent, slot))
1325 })
1326}
1327
1328#[derive(Clone, Debug, PartialEq, Eq)]
1329enum ScrollSelection {
1330 TabBar(Option<usize>, Orientation, LayoutDirection),
1331 List(Option<usize>, usize),
1332}
1333
1334impl ScrollSelection {
1335 fn new(node: &Node, columns: usize, direction: LayoutDirection) -> Self {
1336 let selection = scroll_selection(node);
1337 if matches!(node.kind, "TabBar" | "TabWidget") {
1338 let orientation = node.orientation();
1339 let direction = if orientation == Orientation::Horizontal {
1340 direction
1341 } else {
1342 LayoutDirection::LeftToRight
1343 };
1344 Self::TabBar(selection, orientation, direction)
1345 } else {
1346 Self::List(selection, columns)
1347 }
1348 }
1349}
1350
1351pub(crate) fn scroll_selection(node: &Node) -> Option<usize> {
1352 if matches!(node.kind, "TabBar" | "TabWidget") {
1353 group_index(node)
1354 } else {
1355 let index = usize::try_from(ListMetrics::selection(node)?).ok()?;
1356 (index < node.list?.row_count).then_some(index)
1357 }
1358}
1359
1360fn current_list_slot(node: &Node) -> Option<usize> {
1361 let index = usize::try_from(ListMetrics::selection(node)?).ok()?;
1362 index.checked_sub(node.list?.first_row)
1363}
1364
1365fn table_hit_row<'a>(scene: &Node, path: &'a [usize]) -> Option<(&'a [usize], usize)> {
1366 if let Some(cell) = table_cell_row(scene, path) {
1367 return Some(cell);
1368 }
1369 let (&slot, table) = path.split_last()?;
1370 (scene.at_path(path)?.kind == "ListRow" && scene.at_path(table)?.kind == "TableView")
1371 .then_some((table, slot))
1372}
1373
1374fn hit(
1375 node: &Node,
1376 layout: &LayoutNode,
1377 window: Point,
1378 path: &mut Vec<usize>,
1379 transitioning_stacks: &BTreeSet<Vec<usize>>,
1380 purpose: HitPurpose<'_>,
1381) -> Hit {
1382 if node.is_control_part() {
1383 return Hit::None;
1384 }
1385 let Some(point) = layout.map_from_window(window) else {
1386 return Hit::None;
1387 };
1388 if node.kind == "Tab"
1389 && layout
1390 .tab_header
1391 .is_some_and(|header| header.contains(point) && layout.contains_clip_point(window))
1392 {
1393 return if layout.enabled {
1394 Hit::Target(Target::from_node(path.clone(), node, true, None))
1395 } else {
1396 Hit::Blocked(path.clone())
1397 };
1398 }
1399 if !layout.contains_subtree_point(window) {
1400 return Hit::None;
1401 }
1402 if node.kind == "ScrollIndicator"
1403 || node.kind == "ScrollBar" && !node.boolean("interactive", true)
1404 {
1405 return Hit::None;
1406 }
1407 if !layout.bounds.contains(point) {
1408 return hit_children(node, layout, window, path, transitioning_stacks, purpose);
1409 }
1410 if node.kind == "RoundButton"
1411 && !(crate::RoundedClip {
1412 bounds: layout.bounds,
1413 radii: crate::corner_radii(node, layout.bounds),
1414 })
1415 .contains(point)
1416 {
1417 return Hit::None;
1418 }
1419 if transitioning_stacks.contains(path) {
1420 return Hit::StackSlide;
1421 }
1422 if layout.enabled
1423 && let Some(slot) = layout
1424 .split
1425 .as_ref()
1426 .and_then(|split| split.expanded_hit(point))
1427 && let Some(child) = layout.children.get(slot)
1428 && let Some(handle) = node.children.get(slot)
1429 && eligible(handle, child)
1430 && child.contains_clip_point(window)
1431 {
1432 let mut target = path.clone();
1433 target.push(slot);
1434 return Hit::Target(Target::from_node(target, handle, true, None));
1435 }
1436 if (node.kind == "Expander" || node.group_checkable())
1437 && layout.group_header(node).contains(point)
1438 {
1439 return if layout.enabled {
1440 Hit::Target(Target::from_node(path.clone(), node, true, None))
1441 } else {
1442 Hit::Blocked(path.clone())
1443 };
1444 }
1445 if let Some(action) = layout.tumbler.as_ref().and_then(|wheel| wheel.hit(point)) {
1446 return if layout.enabled {
1447 Hit::ControlPart(Target::from_node(path.clone(), node, true, None), action)
1448 } else {
1449 Hit::Blocked(path.clone())
1450 };
1451 }
1452 if node.kind == "SearchField"
1453 && let Some(action) = SearchGeometry::for_layout(layout).action_at(node, point)
1454 {
1455 return if layout.enabled {
1456 Hit::ControlPart(Target::from_node(path.clone(), node, true, None), action)
1457 } else {
1458 Hit::Blocked(path.clone())
1459 };
1460 }
1461 if is_calendar_control(node.kind) {
1462 let action = CalendarGeometry::for_layout(node, layout).action_at(point);
1463 return if layout.enabled
1464 && let Some(action) = action
1465 {
1466 Hit::ControlPart(
1467 Target::from_node(path.clone(), node, true, None),
1468 ControlAction::Calendar(action),
1469 )
1470 } else {
1471 Hit::Blocked(path.clone())
1472 };
1473 }
1474 if node.kind == "PageIndicator" {
1475 if !focusable(node) {
1476 return Hit::None;
1477 }
1478 let Some(index) = PageIndicatorGeometry::with_layout_direction(
1479 node,
1480 layout.bounds,
1481 layout.layout_direction,
1482 )
1483 .and_then(|geometry| geometry.marker_at(point)) else {
1484 return Hit::None;
1485 };
1486 return if layout.enabled {
1487 Hit::ControlPart(
1488 Target::from_node(path.clone(), node, true, None),
1489 ControlAction::Select(index),
1490 )
1491 } else {
1492 Hit::Blocked(path.clone())
1493 };
1494 }
1495 if node.kind == "Dial" && !DialGeometry::new(layout.bounds, node).contains(point) {
1496 return Hit::None;
1497 }
1498 if let Some((rect, action)) = layout
1499 .swipe_delegate
1500 .as_deref()
1501 .and_then(crate::SwipeDelegateGeometry::toggle)
1502 && rect.contains(point)
1503 {
1504 return if layout.enabled {
1505 Hit::ControlPart(Target::from_node(path.clone(), node, true, None), action)
1506 } else {
1507 Hit::Blocked(path.clone())
1508 };
1509 }
1510 if let Some(bar) = layout
1511 .scroll_bars(node)
1512 .find(|bar| bar.scrollable() && bar.track.contains(point))
1513 {
1514 return if layout.enabled {
1515 Hit::ScrollBar(ScrollTarget {
1516 path: path.clone(),
1517 orientation: bar.orientation,
1518 row_key: None,
1519 id: ElementId::of(node),
1520 })
1521 } else {
1522 Hit::Blocked(path.clone())
1523 };
1524 }
1525 if node.kind == "ScrollBar" {
1526 return Hit::None;
1527 }
1528 if let Some(slot) = layout
1529 .table
1530 .as_ref()
1531 .and_then(|table| table.row_resize_at(node, layout, point))
1532 {
1533 return if layout.enabled {
1534 Hit::TableRowGrip(Target::from_node(path.clone(), node, true, None), slot)
1535 } else {
1536 Hit::Blocked(path.clone())
1537 };
1538 }
1539 if node.kind != "SplitHandle" {
1540 let child = hit_children(node, layout, window, path, transitioning_stacks, purpose);
1541 if !matches!(child, Hit::None) {
1542 return child;
1543 }
1544 }
1545 if let Some((index, _)) = layout
1546 .text_link_regions()
1547 .find(|(_, rect)| rect.contains(point))
1548 && let Some(target) = Target::for_text_link(node, path, index)
1549 {
1550 return if layout.enabled {
1551 Hit::ControlPart(target, ControlAction::ActivateTextLink(index))
1552 } else {
1553 Hit::Blocked(path.clone())
1554 };
1555 }
1556 if node.kind == "WindowMoveArea" && layout.enabled && node.boolean("enabled", true) {
1557 return Hit::WindowMove(Target::from_node(path.clone(), node, false, None));
1558 }
1559 if purpose == HitPurpose::Gesture(node.kind)
1560 && (node.kind == "WheelHandler"
1561 || node.hover_handle.is_some()
1562 || node.scale_rotate_handle.is_some()
1563 || node.swipe_handle.is_some() && has_swipe_directions(node))
1564 && layout.enabled
1565 && node.boolean("enabled", true)
1566 {
1567 return Hit::Blocked(path.clone());
1568 }
1569 if xrack_runtime::is_pane(node.kind) {
1570 return Hit::Blocked(path.clone());
1571 }
1572 if matches!(node.kind, "Tab" | "GroupBox" | "Expander")
1573 || is_window_overlay(node.kind)
1574 || !interactive(node)
1575 || node.kind == "TouchArea"
1576 && (!node.boolean("enabled", true)
1577 || matches!(purpose, HitPurpose::Button(button) if !node.accepts_pointer_button(button)))
1578 || node.kind == "FocusScope" && !node.boolean("focus-on-click", true)
1579 || node.kind == "TreeCell" && !editable_table_cell(node)
1580 {
1581 return Hit::None;
1582 }
1583 if !layout.enabled {
1584 return Hit::Blocked(path.clone());
1585 }
1586 let target = Target::from_node(path.clone(), node, focusable(node), None);
1587 if is_spin_box(node.kind)
1588 && let Some(action) = SpinGeometry::for_layout(layout, node).action_at(point)
1589 {
1590 return Hit::ControlPart(target, ControlAction::Spin(action));
1591 }
1592 Hit::Target(target)
1593}
1594
1595fn hit_children(
1596 node: &Node,
1597 layout: &LayoutNode,
1598 point: Point,
1599 path: &mut Vec<usize>,
1600 transitioning_stacks: &BTreeSet<Vec<usize>>,
1601 purpose: HitPurpose<'_>,
1602) -> Hit {
1603 for (i, child, child_layout) in layout.children_in_paint_order(node).rev() {
1604 if is_window_overlay(child.kind) {
1605 continue;
1606 }
1607 path.push(i);
1608 let found = hit(
1609 child,
1610 child_layout,
1611 point,
1612 path,
1613 transitioning_stacks,
1614 purpose,
1615 );
1616 path.pop();
1617 if !matches!(found, Hit::None) {
1618 return found;
1619 }
1620 }
1621 Hit::None
1622}
1623
1624fn inspect_at(node: &Node, layout: &LayoutNode, point: Point, path: &mut Vec<usize>) -> bool {
1625 if node.is_control_part() || !layout.contains_subtree_point(point) {
1626 return false;
1627 }
1628 if node.list.is_none() {
1630 for (index, child, item) in layout.children_in_paint_order(node).rev() {
1631 if is_window_overlay(child.kind) {
1632 continue;
1633 }
1634 path.push(index);
1635 if inspect_at(child, item, point, path) {
1636 return true;
1637 }
1638 path.pop();
1639 }
1640 }
1641 layout
1642 .map_from_window(point)
1643 .is_some_and(|point| layout.bounds.contains(point))
1644}
1645
1646pub(crate) fn valid(target: &Target, scene: &Node, layout: &LayoutNode) -> bool {
1647 let Some(node) = target.node_in(scene) else {
1648 return false;
1649 };
1650 let Some(item) = layout.at_path(&target.path) else {
1651 return false;
1652 };
1653 if let Some(link) = &target.text_link {
1654 return item.enabled
1655 && node.styled_text("text") == Some(&link.document)
1656 && item
1657 .text_link_regions()
1658 .any(|(index, _)| index == link.index);
1659 }
1660 target.focusable == focusable(node) && eligible(node, item)
1661}
1662
1663fn context_menu_area<'a>(
1664 scene: &'a Node,
1665 path: &'a [usize],
1666 scope: &[usize],
1667) -> Option<(&'a [usize], &'a Node, usize)> {
1668 (scope.len()..=path.len()).rev().find_map(|depth| {
1669 let path = &path[..depth];
1670 let area = scene
1671 .interactive_at_path(path)
1672 .filter(|node| node.kind == "ContextMenuArea")?;
1673 let menu = area
1674 .children
1675 .iter()
1676 .position(|child| child.kind == "Menu" && child.is_visible())?;
1677 Some((path, area, menu))
1678 })
1679}
1680
1681fn split_target<'a, 'b>(
1682 target: &'a Target,
1683 scene: &Node,
1684 layout: &'b LayoutNode,
1685) -> Option<(&'a [usize], &'b SplitGeometry, &'b SplitHandle)> {
1686 if scene.at_path(&target.path)?.kind != "SplitHandle" || !valid(target, scene, layout) {
1687 return None;
1688 }
1689 let (&slot, path) = target.path.split_last()?;
1690 let geometry = layout.at_path(path)?.split.as_deref()?;
1691 Some((path, geometry, geometry.handle(slot)?))
1692}
1693
1694fn pending_scroll_offset(
1695 item: &LayoutNode,
1696 offsets: &BTreeMap<Vec<usize>, f32>,
1697 path: &[usize],
1698 axis: Orientation,
1699) -> Option<f32> {
1700 if let Some(renderer) = &item.nested_list {
1701 item.bound_offset(axis).or_else(|| renderer.offset(axis))
1702 } else {
1703 offsets.get(path).copied()
1704 }
1705}
1706
1707fn store_scroll_offset(
1708 item: &LayoutNode,
1709 offsets: &mut BTreeMap<Vec<usize>, f32>,
1710 path: &[usize],
1711 axis: Orientation,
1712 offset: f32,
1713) {
1714 if let Some(renderer) = &item.nested_list {
1715 renderer.set_offset(axis, offset);
1716 } else {
1717 offsets.insert(path.to_vec(), offset);
1718 }
1719}
1720
1721pub(crate) fn moved_row_target(
1722 target: &Target,
1723 scene: &Node,
1724 layout: &LayoutNode,
1725) -> Option<Target> {
1726 let key = target.row_key?;
1727 if key.has_view_scope() {
1728 fn find(node: &Node, target: &Target, path: &mut Vec<usize>) -> Option<Target> {
1729 if matches!(
1730 node.kind,
1731 "ListRow" | "TabButton" | "Tab" | "StackItem" | "SwipePage"
1732 ) && node.routing_row_key() == target.row_key
1733 {
1734 let suffix = target.path.get(path.len()..)?;
1735 let mut moved = target.clone();
1736 moved.path = path.iter().copied().chain(suffix.iter().copied()).collect();
1737 return Some(moved);
1738 }
1739 if path.len() >= target.path.len() {
1740 return None;
1741 }
1742 node.materialized_children().find_map(|(slot, child)| {
1743 path.push(slot);
1744 let found = find(child, target, path);
1745 path.pop();
1746 found
1747 })
1748 }
1749 return find(scene, target, &mut Vec::new()).filter(|moved| valid(moved, scene, layout));
1750 }
1751 for depth in (0..target.path.len()).rev() {
1752 let Some(node) = scene.at_path(&target.path[..depth]) else {
1753 continue;
1754 };
1755 if node.kind == "DynamicContainer" {
1756 let (slot, _) = node
1757 .materialized_children()
1758 .find(|(_, child)| child.dynamic_mount_key() == Some(key))?;
1759 let mut moved = target.clone();
1760 moved.path[depth] = slot;
1761 return valid(&moved, scene, layout).then_some(moved);
1762 }
1763 if !matches!(
1764 node.kind,
1765 "ListView"
1766 | "GridView"
1767 | "StandardListView"
1768 | "TableView"
1769 | "TreeView"
1770 | "TabBar"
1771 | "TabWidget"
1772 | "StackLayout"
1773 | "SwipeView"
1774 ) {
1775 continue;
1776 }
1777 let slot = node
1778 .children
1779 .iter()
1780 .position(|row| row.routing_row_key() == Some(key))?;
1781 let mut moved = target.clone();
1782 moved.path[depth] = slot;
1783 return valid(&moved, scene, layout).then_some(moved);
1784 }
1785 None
1786}
1787
1788fn focus_hitbox(node: &Node, layout: &LayoutNode) -> Option<Rect> {
1789 if node.kind == "PathView"
1790 && layout
1791 .tumbler
1792 .as_ref()
1793 .is_none_or(|view| view.rows.is_empty())
1794 {
1795 return None;
1796 }
1797 if node.kind == "ScrollBar"
1798 && (!node.boolean("interactive", true)
1799 || !layout
1800 .scroll_control_geometry(node)
1801 .is_some_and(ScrollBarGeometry::scrollable))
1802 {
1803 return None;
1804 }
1805 let hitbox = if node.kind == "Tab" {
1806 layout.tab_header
1807 } else if layout.visible && matches!(node.kind, "GroupBox" | "Expander") {
1808 Some(layout.group_header(node))
1809 } else if layout.visible {
1810 Some(layout.bounds)
1811 } else {
1812 None
1813 };
1814 (layout.enabled && interactive(node))
1815 .then_some(hitbox)
1816 .flatten()
1817}
1818
1819pub(crate) fn eligible(node: &Node, layout: &LayoutNode) -> bool {
1820 focus_hitbox(node, layout).is_some_and(|bounds| {
1821 let clipped = layout.clip_rect(bounds);
1822 clipped.width > 0.0 && clipped.height > 0.0
1823 })
1824}
1825
1826pub(crate) fn focus_reachable(
1827 target: &Target,
1828 scene: &Node,
1829 layout: &LayoutNode,
1830 allow_reveal: bool,
1831) -> bool {
1832 valid(target, scene, layout)
1833 || allow_reveal
1834 && target.text_link.is_none()
1835 && target
1836 .node_in(scene)
1837 .zip(layout.at_path(&target.path))
1838 .is_some_and(|(node, item)| {
1839 target.focusable == focusable(node)
1840 && focus_hitbox(node, item).is_some_and(|rect| {
1841 crate::viewport::plan_focus_scroll(scene, layout, &target.path, rect)
1842 .is_some_and(|plan| !plan.is_empty())
1843 })
1844 })
1845}
1846
1847fn scroll_target_visible(item: &LayoutNode) -> bool {
1848 let clip = item.clip_rect(item.bounds);
1849 item.visible && item.enabled && clip.width > 0.0 && clip.height > 0.0
1850}
1851
1852fn first_editable_tree_cell<'a>(
1853 node: &'a Node,
1854 layout: &LayoutNode,
1855 path: &mut Vec<usize>,
1856) -> Option<&'a Node> {
1857 if !layout.enabled || !layout.visible || node.list.is_some() {
1858 return None;
1859 }
1860 if editable_table_cell(node) && eligible(node, layout) {
1861 return Some(node);
1862 }
1863 for (index, child, item) in layout.children_in_scene_order(node) {
1864 path.push(index);
1865 if let Some(cell) = first_editable_tree_cell(child, item, path) {
1866 return Some(cell);
1867 }
1868 path.pop();
1869 }
1870 None
1871}
1872
1873fn group_targets(
1874 node: &Node,
1875 layout: &LayoutNode,
1876 path: &[usize],
1877 include_clipped: bool,
1878) -> impl Iterator<Item = (usize, Target)> {
1879 let scrollable_tabs =
1880 matches!(node.kind, "TabBar" | "TabWidget") && scroll_target_visible(layout);
1881 node.children
1882 .iter()
1883 .zip(&layout.children)
1884 .enumerate()
1885 .filter_map(move |(index, (child, item))| {
1886 let usable = if include_clipped || scrollable_tabs {
1887 focus_hitbox(child, item).is_some_and(|rect| rect.width > 0.0 && rect.height > 0.0)
1888 } else {
1889 eligible(child, item)
1890 };
1891 if group_item(node, index).is_none() || !usable {
1892 return None;
1893 }
1894 let mut child_path = path.to_vec();
1895 child_path.push(index);
1896 Some((index, Target::from_node(child_path, child, true, None)))
1897 })
1898}
1899
1900fn group_focus(node: &Node, layout: &LayoutNode, path: &[usize]) -> Option<Target> {
1901 let selected = group_index(node);
1902 group_targets(node, layout, path, false)
1903 .min_by_key(|(index, _)| Some(*index) != selected)
1904 .map(|(_, target)| target)
1905}
1906
1907pub(crate) fn radio_group_focus(
1908 scene: &Node,
1909 layout: &LayoutNode,
1910 path: &[usize],
1911 allow_reveal: bool,
1912) -> Option<Target> {
1913 let group = scene
1914 .at_path(path)
1915 .filter(|node| node.kind == "RadioGroup")?;
1916 let item = layout.at_path(path)?;
1917 group_targets(group, item, path, allow_reveal)
1918 .filter_map(|(index, mut target)| {
1919 target.row_key = scene.row_key_at(&target.path);
1920 focus_reachable(&target, scene, layout, allow_reveal).then_some((index, target))
1921 })
1922 .min_by_key(|(index, _)| Some(*index) != group_index(group))
1923 .map(|(_, target)| target)
1924}
1925
1926fn attached_radio<'a>(
1927 scene: &'a Node,
1928 path: &'a [usize],
1929) -> Option<(&'a ButtonGroupMembership, &'a [usize])> {
1930 let member = scene
1931 .at_path(path)?
1932 .button_group
1933 .as_ref()
1934 .filter(|member| member.group.exclusive)?;
1935 Some((member, member.component_path(path)?))
1936}
1937
1938fn attached_radio_tab_stop(scene: &Node, path: &[usize], targets: &[Target]) -> Option<usize> {
1939 targets.iter().position(|target| {
1940 attached_radio(scene, &target.path).is_some_and(|(member, component)| {
1941 path.strip_prefix(component)
1942 .is_some_and(|path| member.group.paths().any(|member| member == path))
1943 })
1944 })
1945}
1946
1947pub(crate) fn focus_targets(scene: &Node, layout: &LayoutNode, scope: &[usize]) -> Vec<Target> {
1948 focus_targets_with_reveal(scene, layout, scope, false)
1949}
1950
1951pub(crate) fn focus_targets_with_reveal(
1952 scene: &Node,
1953 layout: &LayoutNode,
1954 scope: &[usize],
1955 allow_reveal: bool,
1956) -> Vec<Target> {
1957 fn collect(
1958 root: (&Node, &LayoutNode),
1959 node: &Node,
1960 layout: &LayoutNode,
1961 path: &mut Vec<usize>,
1962 out: &mut Vec<Target>,
1963 allow_reveal: bool,
1964 clipped_candidates: bool,
1965 ) {
1966 if !layout.visible
1967 || !layout.enabled
1968 || node.kind == "CalendarCells"
1969 || node.is_control_part()
1970 {
1971 return;
1972 }
1973 let clip = layout.clip_rect(layout.bounds);
1974 if !clipped_candidates
1975 && !layout.allows_overflow()
1976 && (clip.width <= 0.0 || clip.height <= 0.0)
1977 {
1978 return;
1979 }
1980 let candidate = |path: &[usize], node: &Node, item: &LayoutNode| {
1981 let target = Target::from_node(path.to_vec(), node, true, root.0.row_key_at(path));
1982 if !clipped_candidates {
1983 return Some(target);
1984 }
1985 (eligible(node, item) || focus_reachable(&target, root.0, root.1, true))
1986 .then_some(target)
1987 };
1988 let before_children = out.len();
1989 if matches!(node.kind, "TabWidget" | "TabBar" | "RadioGroup") {
1990 if clipped_candidates
1991 && !(matches!(node.kind, "TabBar" | "TabWidget") && scroll_target_visible(layout))
1992 {
1993 let selected = group_index(node);
1994 if let Some((_, target)) = group_targets(node, layout, path, true)
1995 .filter_map(|(index, mut target)| {
1996 target.row_key = root.0.row_key_at(&target.path);
1997 focus_reachable(&target, root.0, root.1, true).then_some((index, target))
1998 })
1999 .min_by_key(|(index, _)| Some(*index) != selected)
2000 {
2001 out.push(target);
2002 }
2003 } else if let Some(target) = group_focus(node, layout, path) {
2004 out.push(target);
2005 }
2006 if node.kind != "TabWidget" {
2007 return;
2008 }
2009 } else if !matches!(node.kind, "Tab" | "TreeCell" | "FocusScope" | "Loader")
2010 && !is_window_overlay(node.kind)
2011 && focusable(node)
2012 && (!matches!(node.kind, "GroupBox" | "Expander")
2013 || clipped_candidates
2014 || eligible(node, layout))
2015 {
2016 out.extend(candidate(path, node, layout));
2017 }
2018 if node.kind == "SplitHandle" {
2019 return;
2020 }
2021 if node.kind == "StyledText" {
2022 let indices: BTreeSet<_> = layout.text_link_regions().map(|(index, _)| index).collect();
2023 out.extend(
2024 indices
2025 .into_iter()
2026 .filter_map(|index| Target::for_text_link(node, path, index)),
2027 );
2028 }
2029 let reveal_children =
2030 clipped_candidates || allow_reveal && crate::viewport::reveals_focus(node, layout);
2031 let mut visit = |index: usize| {
2032 if let Some((child, item)) = node.child_at(index).zip(layout.child_at(index))
2033 && !is_window_overlay(child.kind)
2034 {
2035 path.push(index);
2036 collect(root, child, item, path, out, allow_reveal, reveal_children);
2037 path.pop();
2038 }
2039 };
2040 if node.kind == "TreeView" {
2041 if let Some(slot) = current_list_slot(node) {
2042 visit(slot);
2043 }
2044 } else if !node.boolean("__standard-table", false) {
2045 for index in crate::child_reading_order(node) {
2046 visit(index);
2047 }
2048 }
2049 if node.kind == "FocusScope"
2050 && out.len() == before_children
2051 && node.boolean("focus-on-tab-navigation", true)
2052 {
2053 out.extend(candidate(path, node, layout));
2054 }
2055 }
2056 let mut targets = Vec::new();
2057 if let Some((node, item)) = scene.at_path(scope).zip(layout.at_path(scope)) {
2058 let clipped_candidates = allow_reveal
2059 && (0..scope.len())
2060 .rev()
2061 .map(|depth| &scope[..depth])
2062 .map_while(|path| scene.at_path(path).zip(layout.at_path(path)))
2063 .take_while(|(node, _)| !is_window_overlay(node.kind))
2064 .any(|(node, item)| crate::viewport::reveals_focus(node, item));
2065 collect(
2066 (scene, layout),
2067 node,
2068 item,
2069 &mut scope.to_vec(),
2070 &mut targets,
2071 allow_reveal,
2072 clipped_candidates,
2073 );
2074 if targets.is_empty() && is_window_overlay(node.kind) && eligible(node, item) {
2075 targets.push(Target::from_node(scope.to_vec(), node, true, None));
2076 }
2077 }
2078 let mut groups = BTreeMap::new();
2079 let mut stops = Vec::with_capacity(targets.len());
2080 for mut target in targets {
2081 target.row_key = scene.row_key_at(&target.path);
2082 if let Some((member, component)) = attached_radio(scene, &target.path) {
2083 let key = (component.to_vec(), member.group.key.clone());
2084 if let Some(&slot) = groups.get(&key) {
2085 if member.group.selected == Some(member.index) {
2086 stops[slot] = target;
2087 }
2088 continue;
2089 }
2090 groups.insert(key, stops.len());
2091 }
2092 stops.push(target);
2093 }
2094 stops
2095}
2096
2097fn dialog_entry_focus(scene: &Node, layout: &LayoutNode, path: &[usize]) -> Option<Target> {
2098 let node = scene.at_path(path)?;
2099 let targets = focus_targets(scene, layout, path);
2100 let first = targets.iter().find(|target| {
2101 scene
2102 .at_path(&target.path)
2103 .and_then(Node::standard_button_kind)
2104 != Some(StandardButtonKind::Discard)
2105 });
2106 if node.kind == "Dialog"
2107 && first
2108 .and_then(|target| scene.at_path(&target.path))
2109 .and_then(dialog_button_action)
2110 .is_some()
2111 && let Some(primary) = targets.iter().find(|target| {
2112 scene.at_path(&target.path).is_some_and(|button| {
2113 button.boolean("primary", false)
2114 && dialog_button_action(button)
2115 == Some(ControlAction::Dialog(DialogRole::Accept))
2116 })
2117 })
2118 {
2119 return Some(primary.clone());
2120 }
2121 first.cloned().or_else(|| {
2122 eligible(node, layout.at_path(path)?)
2123 .then(|| Target::from_node(path.to_vec(), node, true, scene.row_key_at(path)))
2124 })
2125}
2126
2127fn slider_target<'a, 'b>(
2128 target: &'a Target,
2129 scene: &'b Node,
2130 layout: &LayoutNode,
2131) -> Option<(&'a [usize], &'b Node)> {
2132 let leaf = scene.at_path(&target.path)?;
2133 if matches!(leaf.kind, "Slider" | "RangeSlider" | "Dial" | "ColorPlane") {
2134 return valid(target, scene, layout).then_some((target.path.as_slice(), leaf));
2135 }
2136 if leaf.kind != "RangeThumb" || target.row_key != scene.row_key_at(&target.path) {
2137 return None;
2138 }
2139 let (&index, path) = target.path.split_last()?;
2140 let node = scene.interactive_at_path(path)?;
2141 (index < 2 && node.kind == "RangeSlider" && eligible(node, layout.at_path(path)?))
2142 .then_some((path, node))
2143}
2144
2145fn sibling_menu(
2146 scene: &Node,
2147 layout: &LayoutNode,
2148 target: &Target,
2149 key: MenuKey,
2150) -> Option<Target> {
2151 let (&index, parent) = target.path.split_last()?;
2152 let bar = scene
2153 .at_path(parent)
2154 .filter(|node| node.kind == "MenuBar")?;
2155 let choices: Vec<_> = bar
2156 .children
2157 .iter()
2158 .enumerate()
2159 .filter_map(|(slot, child)| {
2160 if child.kind != "Menu" {
2161 return None;
2162 }
2163 let mut path = parent.to_vec();
2164 path.push(slot);
2165 let row_key = scene.row_key_at(&path);
2166 let sibling = Target::from_node(path, child, true, row_key);
2167 valid(&sibling, scene, layout).then_some((slot, sibling))
2168 })
2169 .collect();
2170 let current = choices.iter().position(|(slot, _)| *slot == index)?;
2171 let rtl = layout.at_path(parent)?.layout_direction == LayoutDirection::RightToLeft;
2172 let previous = (key == MenuKey::Left) != rtl;
2173 let step = if previous { choices.len() - 1 } else { 1 };
2174 Some(choices[(current + step) % choices.len()].1.clone())
2175}
2176
2177impl Interaction {
2178 pub fn begin_pointer_sequence(
2179 &self,
2180 scene: &Node,
2181 layout: &LayoutNode,
2182 point: Point,
2183 event: xrack_runtime::PointerEvent,
2184 now: Instant,
2185 ) -> Option<(crate::PointerSequence, crate::PointerDelivery)> {
2186 if self.menu_open() || self.choice_open() {
2187 return None;
2188 }
2189 let Hit::Target(target) =
2190 self.hit_at_for(scene, layout, point, HitPurpose::Button(event.button))
2191 else {
2192 return None;
2193 };
2194 crate::PointerSequence::begin(target, self, scene, layout, point, event, now)
2195 }
2196
2197 pub(crate) fn touch_area_hover<'a>(
2198 &self,
2199 scene: &'a Node,
2200 layout: &LayoutNode,
2201 point: Point,
2202 ) -> Option<(&'a Node, (Length, Length))> {
2203 if self.menu_open() || self.choice_open() {
2204 return None;
2205 }
2206 let Hit::Target(target) = self.hit_at_for(scene, layout, point, HitPurpose::Hover) else {
2207 return None;
2208 };
2209 let node = scene.interactive_at_path(&target.path)?;
2210 if node.kind != "TouchArea" {
2211 return None;
2212 }
2213 let (_, x, y) =
2214 crate::pointer_events::local_position(layout.at_path(&target.path)?, point)?;
2215 Some((node, (x, y)))
2216 }
2217
2218 pub fn direct_pointer_claimed(&self) -> bool {
2219 self.scroll_table_drag_claimed()
2220 || self.scroll_gesture.as_ref().is_some_and(|gesture| {
2221 gesture.motion.dragging
2222 && (gesture.route.axes.iter().any(Option::is_some)
2223 || gesture.drawer.is_some()
2224 || !gesture.pages.is_empty()
2225 || gesture.tumbler.is_some()
2226 || gesture.switch.is_some()
2227 || gesture.swipe_delegate.is_some()
2228 || matches!(
2229 gesture.swipe,
2230 Some(SwipeRoute::Captured(_) | SwipeRoute::Cancelled)
2231 ))
2232 })
2233 }
2234
2235 pub fn owns_pointer_press(&self, target: &Target) -> bool {
2236 self.pressed.as_ref() == Some(target)
2237 || self.scroll_gesture.as_ref().is_some_and(
2238 |gesture| matches!(&gesture.tap, Some(Hit::Target(tap)) if tap == target),
2239 )
2240 }
2241
2242 pub fn cancel_pointer_activation(&mut self, target: &Target) {
2243 if self.pressed.as_ref() == Some(target) {
2244 self.pressed = None;
2245 self.press_origin = None;
2246 }
2247 if let Some(gesture) = &mut self.scroll_gesture
2248 && matches!(&gesture.tap, Some(Hit::Target(tap)) if tap == target)
2249 {
2250 gesture.tap = None;
2251 }
2252 }
2253
2254 pub(crate) fn hover_entries(
2255 &self,
2256 scene: &Node,
2257 layout: &LayoutNode,
2258 point: Point,
2259 ) -> Vec<HoverEntry> {
2260 if self.menu_open() || self.choice_open() {
2261 return Vec::new();
2262 }
2263 let Some((path, scope_depth)) = self.gesture_hit_path(scene, layout, point, "HoverHandler")
2264 else {
2265 return Vec::new();
2266 };
2267 let mut entries = Vec::new();
2268 for depth in (scope_depth..=path.len()).rev() {
2269 let path = &path[..depth];
2270 let Some((node, item)) = scene.at_path(path).zip(layout.at_path(path)) else {
2271 continue;
2272 };
2273 if !node.boolean("enabled", true) {
2274 continue;
2275 }
2276 let Some((handle, position)) = node
2277 .hover_handle
2278 .as_ref()
2279 .zip(local_handler_position(item, point))
2280 else {
2281 continue;
2282 };
2283 entries.push(HoverEntry {
2284 path: path.to_vec(),
2285 row_key: scene.row_key_at(path),
2286 handle: handle.clone(),
2287 position,
2288 cursor_shape: node.cursor_shape(),
2289 });
2290 if node.boolean("blocking", false) {
2291 break;
2292 }
2293 }
2294 entries
2295 }
2296
2297 pub fn wheel_route(
2298 &self,
2299 scene: &Node,
2300 layout: &LayoutNode,
2301 event: xrack_runtime::WheelEvent,
2302 ) -> Option<WheelRoute> {
2303 if self.menu_open()
2304 || self.choice_open()
2305 || !(event.delta_x.0.is_finite() && event.delta_y.0.is_finite())
2306 || event.delta_x.0 == 0.0 && event.delta_y.0 == 0.0
2307 {
2308 return None;
2309 }
2310 let point = self.pointer?;
2311 let (path, scope_depth) = self.gesture_hit_path(scene, layout, point, "WheelHandler")?;
2312 let mut deliveries = Vec::new();
2313 for depth in (scope_depth..=path.len()).rev() {
2314 let path = &path[..depth];
2315 let node = scene.at_path(path)?;
2316 let item = layout.at_path(path)?;
2317 if !node.handles_wheel() || !item.enabled || !node.boolean("enabled", true) {
2318 continue;
2319 }
2320 let handles_axis = match node.properties.get("orientation") {
2321 Some(Value::Orientation(Orientation::Horizontal)) => event.delta_x.0 != 0.0,
2322 Some(Value::Orientation(Orientation::Vertical)) => event.delta_y.0 != 0.0,
2323 _ => true,
2324 };
2325 if !handles_axis {
2326 continue;
2327 }
2328 if let Some((x, y)) = local_handler_position(item, point) {
2329 deliveries.push((path.to_vec(), xrack_runtime::WheelEvent { x, y, ..event }));
2330 }
2331 }
2332 (!deliveries.is_empty()).then_some(WheelRoute { deliveries })
2333 }
2334
2335 pub fn update_tooltip(&mut self, scene: &Node, layout: &LayoutNode, now: Instant) -> bool {
2336 let scope = self.active_dialog(layout).unwrap_or_default();
2337 let key = match self.tooltip.source {
2338 TooltipSource::Pointer => self.pointer.and_then(|point| {
2339 tooltip::hovered(scene, layout, self.pointer_scope(layout, point), point)
2340 }),
2341 TooltipSource::Focus => self
2342 .focused
2343 .as_ref()
2344 .filter(|target| valid(target, scene, layout))
2345 .and_then(|target| tooltip::focused(scene, &target.path, scope)),
2346 };
2347 let blocked = self.menu_open()
2348 || self.choice_open()
2349 || self.pressed.is_some()
2350 || self.table_drag_selection_claimed()
2351 || self.dialog_backdrop.is_some();
2352 self.tooltip.advance(scene, key, self.pointer, blocked, now)
2353 }
2354
2355 pub fn tooltip_deadline(&self) -> Option<Instant> {
2356 self.tooltip.deadline()
2357 }
2358
2359 pub fn dismiss_tooltip(&mut self) -> bool {
2360 self.tooltip.dismiss()
2361 }
2362
2363 pub fn tooltip_popup<'a>(
2364 &self,
2365 scene: &'a Node,
2366 layout: &LayoutNode,
2367 ) -> Option<crate::TooltipPopup<'a>> {
2368 if self.menu_open() || self.choice_open() {
2369 return None;
2370 }
2371 self.tooltip.popup(
2372 scene,
2373 layout,
2374 self.active_dialog(layout).unwrap_or_default(),
2375 )
2376 }
2377
2378 pub fn overlay_layers<'a>(
2379 &'a self,
2380 layout: &'a LayoutNode,
2381 ) -> impl DoubleEndedIterator<Item = &'a [usize]> + 'a {
2382 self.dialogs
2383 .iter()
2384 .filter(move |dialog| layout.overlay_paths().contains(&dialog.path))
2385 .map(|dialog| dialog.path.as_slice())
2386 .chain(
2387 layout
2388 .overlay_paths()
2389 .iter()
2390 .filter(move |path| !self.dialogs.iter().any(|dialog| &dialog.path == *path))
2391 .map(Vec::as_slice),
2392 )
2393 }
2394
2395 pub fn dialog_layers<'a>(
2396 &'a self,
2397 layout: &'a LayoutNode,
2398 ) -> impl DoubleEndedIterator<Item = &'a [usize]> + 'a {
2399 self.overlay_layers(layout)
2400 .filter(move |path| is_modal_path(layout, path))
2401 }
2402
2403 fn active_dialog<'a>(&'a self, layout: &'a LayoutNode) -> Option<&'a [usize]> {
2404 self.dialog_layers(layout).next_back()
2405 }
2406
2407 pub fn allows_popup(&self, layout: &LayoutNode, path: &[usize]) -> bool {
2408 self.active_dialog(layout)
2409 .is_none_or(|modal| path.starts_with(modal))
2410 }
2411
2412 fn popups<'a>(&'a self, layout: &'a LayoutNode) -> impl Iterator<Item = &'a [usize]> + 'a {
2413 self.overlay_layers(layout)
2414 .rev()
2415 .filter(move |path| !is_modal_path(layout, path) && self.allows_popup(layout, path))
2416 }
2417
2418 fn popup_at<'a>(&'a self, layout: &'a LayoutNode, point: Point) -> Option<&'a [usize]> {
2419 self.popups(layout).find(|path| {
2420 layout
2421 .at_path(path)
2422 .is_some_and(|item| item.bounds.contains(point))
2423 })
2424 }
2425
2426 fn focused_popup<'a>(&'a self, layout: &'a LayoutNode) -> Option<&'a [usize]> {
2427 let target = self.focused.as_ref()?;
2428 self.popups(layout)
2429 .find(|path| target.path.starts_with(path))
2430 }
2431
2432 fn pointer_scope<'a>(&'a self, layout: &'a LayoutNode, point: Point) -> &'a [usize] {
2433 self.popup_at(layout, point)
2434 .or_else(|| self.active_dialog(layout))
2435 .unwrap_or_default()
2436 }
2437
2438 fn drag_context<'a>(
2439 &'a self,
2440 scene: &'a Node,
2441 layout: &'a LayoutNode,
2442 point: Point,
2443 ) -> crate::drag::Context<'a> {
2444 crate::drag::Context {
2445 scene,
2446 layout,
2447 scope: self.pointer_scope(layout, point),
2448 modal: self.active_dialog(layout),
2449 transitions: &self.transitioning_stacks,
2450 blocked: self.menu_open() || self.choice_open(),
2451 }
2452 }
2453
2454 pub fn arm_drag(&mut self, scene: &Node, layout: &LayoutNode, point: Point) {
2455 if self.table_resize.is_some()
2456 || self.table_row_resize.is_some()
2457 || self.table_column_move.is_some()
2458 || self.table_row_move.is_some()
2459 || self.table_drag_selection_claimed()
2460 {
2461 self.drag = None;
2462 return;
2463 }
2464 let competing = match self.hit_at(scene, layout, point) {
2465 Hit::Target(target) => scene.at_path(&target.path).is_some_and(|node| {
2466 is_text_input(node.kind)
2467 || combo_editable(node)
2468 || is_spin_box(node.kind)
2469 || matches!(
2470 node.kind,
2471 "Slider"
2472 | "ColorPlane"
2473 | "Dial"
2474 | "RangeSlider"
2475 | "SplitHandle"
2476 | "TableCell"
2477 | "TreeCell"
2478 | "Tumbler"
2479 | "PathView"
2480 | "SwipeDelegate"
2481 )
2482 }),
2483 Hit::None => false,
2484 _ => true,
2485 };
2486 self.drag = if competing {
2487 None
2488 } else {
2489 crate::drag::DragSession::arm(self.drag_context(scene, layout, point), point)
2490 };
2491 }
2492
2493 pub fn drag_motion(
2494 &mut self,
2495 scene: &Node,
2496 layout: &LayoutNode,
2497 point: Point,
2498 requested: Option<xrack_runtime::DragAction>,
2499 ) -> crate::DragUpdate {
2500 let Some(mut drag) = self.drag.take() else {
2501 return crate::DragUpdate::default();
2502 };
2503 let active = drag.active();
2504 let (update, keep) = drag.motion(self.drag_context(scene, layout, point), point, requested);
2505 self.drag = keep.then_some(drag);
2506 if update.captured && !active {
2507 self.cancel_press();
2508 self.pointer_leave();
2509 }
2510 update
2511 }
2512
2513 pub fn finish_drag(
2514 &mut self,
2515 scene: &Node,
2516 layout: &LayoutNode,
2517 point: Point,
2518 requested: Option<xrack_runtime::DragAction>,
2519 ) -> crate::DragUpdate {
2520 self.drag
2521 .take()
2522 .map_or_else(crate::DragUpdate::default, |drag| {
2523 drag.finish(self.drag_context(scene, layout, point), point, requested)
2524 })
2525 }
2526
2527 pub fn cancel_drag(&mut self) -> crate::DragUpdate {
2528 self.drag
2529 .take()
2530 .map_or_else(crate::DragUpdate::default, |mut drag| drag.cancel())
2531 }
2532
2533 pub fn reconcile_drag(
2534 &mut self,
2535 scene: &Node,
2536 layout: &LayoutNode,
2537 requested: Option<xrack_runtime::DragAction>,
2538 ) -> crate::DragUpdate {
2539 let Some(mut drag) = self.drag.take() else {
2540 return crate::DragUpdate::default();
2541 };
2542 let point = drag.point;
2543 let (update, keep) =
2544 drag.reconcile(self.drag_context(scene, layout, point), point, requested);
2545 self.drag = keep.then_some(drag);
2546 update
2547 }
2548
2549 pub fn drag_position(&self) -> Option<Point> {
2550 self.drag.as_ref().map(|drag| drag.point)
2551 }
2552
2553 pub fn drag_action(&self) -> Option<xrack_runtime::DragAction> {
2554 self.drag
2555 .as_ref()
2556 .and_then(crate::drag::DragSession::action)
2557 }
2558
2559 pub fn is_drop_target(&self, node: &Node, path: &[usize]) -> bool {
2560 self.drag.as_ref().is_some_and(|drag| drag.over(node, path))
2561 || self.file_drag.over(node, path)
2562 }
2563
2564 pub fn file_drop_scope(&self, layout: &LayoutNode) -> crate::FileDropScope {
2565 crate::FileDropScope {
2566 modal: self.active_dialog(layout).map(<[usize]>::to_vec),
2567 popups: self.popups(layout).map(<[usize]>::to_vec).collect(),
2568 transitions: self.transitioning_stacks.clone(),
2569 blocked: self.menu_open() || self.choice_open() || self.drag_action().is_some(),
2570 }
2571 }
2572
2573 pub fn file_drag_event(
2574 &mut self,
2575 scene: &Node,
2576 layout: &LayoutNode,
2577 input: crate::FileDragInput,
2578 ) -> crate::DragUpdate {
2579 let scope = self.file_drop_scope(layout);
2580 self.file_drag.update(&scope, scene, layout, input)
2581 }
2582
2583 pub fn reconcile_file_drag(&mut self, scene: &Node, layout: &LayoutNode) -> crate::DragUpdate {
2584 if !self.file_drag.has_hover() {
2585 return crate::DragUpdate::default();
2586 }
2587 let scope = self.file_drop_scope(layout);
2588 self.file_drag.reconcile(&scope, scene, layout)
2589 }
2590
2591 pub fn clear_file_drag(&mut self) {
2592 self.file_drag = crate::file_drop::FileDrag::default();
2593 }
2594
2595 pub fn popup_outside_press(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
2596 let path = self.popups(layout).next()?;
2597 let point = self.pointer?;
2598 let popup = scene.at_path(path)?;
2599 let (_, anchor) = path.split_last()?;
2600 let anchor_clicked = self
2601 .target_at(scene, layout, point)
2602 .is_some_and(|target| target.path == anchor);
2603 (!anchor_clicked
2604 && !layout.at_path(path)?.bounds.contains(point)
2605 && popup.boolean("close-on-outside", true))
2606 .then(|| ControlInput {
2607 path: path.to_vec(),
2608 action: ControlAction::Popup(false),
2609 })
2610 }
2611
2612 pub fn dialog_button(
2613 &self,
2614 scene: &Node,
2615 layout: &LayoutNode,
2616 target: &Target,
2617 ) -> Option<ControlInput> {
2618 let path = self.active_dialog(layout)?;
2619 let node = scene.at_path(&target.path)?;
2620 if !target.path.starts_with(path)
2621 || scene.at_path(path)?.kind != "Dialog"
2622 || self
2623 .popups(layout)
2624 .any(|popup| target.path.starts_with(popup))
2625 || !valid(target, scene, layout)
2626 {
2627 return None;
2628 }
2629 Some(ControlInput {
2630 path: path.to_vec(),
2631 action: dialog_button_action(node)?,
2632 })
2633 }
2634
2635 pub fn dialog_accept(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
2636 if self.focused_popup(layout).is_some() {
2637 return None;
2638 }
2639 let path = self.active_dialog(layout)?;
2640 focus_targets(scene, layout, path)
2641 .iter()
2642 .filter_map(|target| {
2643 let action = self.dialog_button(scene, layout, target)?;
2644 if action.action != ControlAction::Dialog(DialogRole::Accept) {
2645 return None;
2646 }
2647 let primary = scene.at_path(&target.path)?.boolean("primary", false);
2648 Some((!primary, action))
2649 })
2650 .min_by_key(|(secondary, _)| *secondary)
2651 .map(|(_, action)| action)
2652 }
2653
2654 pub fn dialog_escape(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
2655 let path = self
2656 .popups(layout)
2657 .next()
2658 .or_else(|| self.active_dialog(layout))?;
2659 let node = scene.at_path(path)?;
2660 node.boolean("close-on-escape", true).then(|| ControlInput {
2661 path: path.to_vec(),
2662 action: dismiss_overlay(node),
2663 })
2664 }
2665
2666 pub fn dialog_pointer_press(&mut self, layout: &LayoutNode) -> bool {
2668 self.dialog_backdrop = None;
2669 let Some(path) = self.active_dialog(layout) else {
2670 return false;
2671 };
2672 let Some(point) = self.pointer else {
2673 return false;
2674 };
2675 if self.popup_at(layout, point).is_some() {
2676 return false;
2677 }
2678 let Some(item) = layout.at_path(path) else {
2679 return false;
2680 };
2681 let outside = !item.bounds.contains(point);
2682 if !outside
2683 && self
2684 .hovered
2685 .as_ref()
2686 .is_some_and(|target| target.path.starts_with(path))
2687 {
2688 return false;
2689 }
2690 let backdrop = outside.then(|| path.to_vec());
2691 self.cancel_press();
2692 self.dialog_backdrop = backdrop;
2693 true
2694 }
2695
2696 pub fn dialog_pointer_release(
2697 &mut self,
2698 scene: &Node,
2699 layout: &LayoutNode,
2700 ) -> Option<ControlInput> {
2701 let pressed = self.dialog_backdrop.take()?;
2702 let path = self.active_dialog(layout)?;
2703 let node = scene.at_path(path)?;
2704 if pressed != path
2705 || layout.at_path(path)?.bounds.contains(self.pointer?)
2706 || self.popup_at(layout, self.pointer?).is_some()
2707 || !node.boolean(
2708 "close-on-outside",
2709 matches!(node.kind, "Drawer" | "PopupWindow"),
2710 )
2711 {
2712 return None;
2713 }
2714 Some(ControlInput {
2715 path: pressed,
2716 action: dismiss_overlay(node),
2717 })
2718 }
2719
2720 fn set_focus(&mut self, focus: Option<Target>) {
2721 self.set_focus_with_reason(focus, xrack_runtime::FocusReason::KeyboardNavigation);
2722 }
2723
2724 fn set_focus_with_reason(&mut self, focus: Option<Target>, reason: xrack_runtime::FocusReason) {
2725 if self.focused != focus {
2726 self.calendar_page_focus = None;
2727 self.text_selection_scroll = None;
2728 self.retain_editor_selection();
2729 self.editor_press = None;
2730 self.last_editor_click = None;
2731 self.focus_reason = reason;
2732 self.cancel_shortcut_sequence();
2733 self.cancel_delay();
2734 self.button_hold = None;
2735 self.history.break_group();
2736 self.spin_draft = None;
2737 self.table_edit = None;
2738 self.last_table_click = None;
2739 Self::clear_choice(&mut self.choice);
2740 self.search_query = None;
2741 self.choice_typeahead = Typeahead::default();
2742 self.reset_list_typeahead();
2743 self.list_composition = None;
2744 self.painted_combo_completion = None;
2745 self.dismissed_combo_draft = None;
2746 self.menu = None;
2747 self.range_keys.clear();
2748 self.focused = focus;
2749 }
2750 }
2751
2752 pub fn menu_open(&self) -> bool {
2753 self.menu.is_some()
2754 }
2755
2756 pub fn dismiss_menu(&mut self) {
2757 if self.menu.take().is_some() {
2758 self.cancel_shortcut_sequence();
2759 }
2760 }
2761
2762 pub fn close_menu(&mut self, scene: &Node, layout: &LayoutNode) {
2763 self.dismiss_menu();
2764 if let Some(point) = self.pointer {
2765 self.pointer_move(scene, layout, point);
2766 }
2767 }
2768
2769 pub fn menu_panels<'a>(&'a self, scene: &'a Node, layout: &LayoutNode) -> Vec<MenuPanel<'a>> {
2770 self.menu
2771 .as_ref()
2772 .filter(|menu| self.menu_is_current(menu, scene, layout))
2773 .map_or_else(Vec::new, |menu| menu.panels(scene, layout))
2774 }
2775
2776 pub fn menu_trigger(&self) -> Option<&Target> {
2777 self.menu.as_ref().map(|popup| &popup.trigger)
2778 }
2779
2780 pub fn accessibility_menu_entry(
2781 &mut self,
2782 scene: &Node,
2783 layout: &LayoutNode,
2784 trigger: &Target,
2785 entry: &MenuEntry,
2786 activate: bool,
2787 ) -> Option<ControlInput> {
2788 if !self.reconcile_text_menu(scene, layout) {
2789 return None;
2790 }
2791 let path = self
2792 .menu
2793 .as_mut()?
2794 .accessibility_entry(scene, layout, trigger, entry, activate)?;
2795 self.finish_menu_action(scene, layout, path)
2796 }
2797
2798 pub fn menu_header_open(&self, path: &[usize]) -> bool {
2799 self.menu.as_ref().and_then(MenuPopup::bar_header) == Some(path)
2800 }
2801
2802 pub fn accessibility_close_menu(
2803 &mut self,
2804 scene: &Node,
2805 layout: &LayoutNode,
2806 trigger: &Target,
2807 path: &[usize],
2808 session: u64,
2809 ) {
2810 if self
2811 .menu
2812 .as_mut()
2813 .and_then(|popup| popup.accessibility_close(scene, layout, trigger, path, session))
2814 == Some(true)
2815 {
2816 self.close_menu(scene, layout);
2817 }
2818 }
2819
2820 pub fn menu_shortcut(
2821 &self,
2822 scene: &Node,
2823 layout: &LayoutNode,
2824 key: MenuShortcut,
2825 ) -> Option<ControlInput> {
2826 if self.shortcuts_blocked() {
2827 return None;
2828 }
2829 if let Some(menu) = self.menu.as_ref().filter(|menu| menu.text.is_some()) {
2830 return self
2831 .menu_is_current(menu, scene, layout)
2832 .then(|| menu.text_shortcut(key))
2833 .flatten();
2834 }
2835 let scope = self.shortcut_scope(layout);
2836 shortcut::single_action(
2837 shortcut::bindings(
2838 scene,
2839 layout,
2840 scope,
2841 self.menu.as_ref(),
2842 self.focused.as_ref(),
2843 ),
2844 key,
2845 )
2846 }
2847
2848 pub fn shortcut_press(
2849 &mut self,
2850 scene: &Node,
2851 layout: &LayoutNode,
2852 key: MenuShortcut,
2853 repeat: bool,
2854 now: Instant,
2855 ) -> ShortcutOutcome {
2856 let mut pending = self.pending_shortcut.take();
2857 if key.is_escape() && (self.menu_open() || self.choice_open()) {
2858 return ShortcutOutcome::Unmatched;
2859 }
2860 if self.menu.as_ref().is_some_and(|menu| menu.text.is_some()) {
2861 if repeat || !self.reconcile_text_menu(scene, layout) {
2862 return ShortcutOutcome::Consumed;
2863 }
2864 return self
2865 .menu
2866 .as_ref()
2867 .and_then(|menu| menu.text_shortcut(key))
2868 .map_or(ShortcutOutcome::Consumed, ShortcutOutcome::Activate);
2869 }
2870 if self.shortcuts_blocked() {
2871 return ShortcutOutcome::Unmatched;
2872 }
2873 let scope = self.shortcut_scope(layout);
2874 let bindings = shortcut::bindings(
2875 scene,
2876 layout,
2877 scope,
2878 self.menu.as_ref(),
2879 self.focused.as_ref(),
2880 );
2881 let outcome = shortcut::press(&mut pending, bindings, scope, key, repeat, now);
2882 self.pending_shortcut = pending;
2883 outcome
2884 }
2885
2886 pub fn cancel_shortcut_sequence(&mut self) {
2887 self.pending_shortcut = None;
2888 }
2889
2890 fn shortcuts_blocked(&self) -> bool {
2891 self.choice_open()
2892 || self
2893 .editor
2894 .as_ref()
2895 .is_some_and(|edit| !edit.preedit.is_empty())
2896 }
2897
2898 fn shortcut_scope<'a>(&'a self, layout: &'a LayoutNode) -> &'a [usize] {
2899 self.focused_popup(layout)
2900 .or_else(|| self.active_dialog(layout))
2901 .unwrap_or_default()
2902 }
2903
2904 fn target_at(&self, scene: &Node, layout: &LayoutNode, point: Point) -> Option<Target> {
2905 self.target_at_for(
2906 scene,
2907 layout,
2908 point,
2909 HitPurpose::Button(xrack_runtime::PointerButton::Primary),
2910 )
2911 }
2912
2913 pub fn pointer_hover_target(&self, scene: &Node, layout: &LayoutNode) -> Option<Target> {
2914 self.target_at_for(scene, layout, self.pointer?, HitPurpose::Hover)
2915 }
2916
2917 fn target_at_for(
2918 &self,
2919 scene: &Node,
2920 layout: &LayoutNode,
2921 point: Point,
2922 purpose: HitPurpose<'_>,
2923 ) -> Option<Target> {
2924 match self.hit_at_for(scene, layout, point, purpose) {
2925 Hit::Target(target) | Hit::ControlPart(target, _) | Hit::TableRowGrip(target, _) => {
2926 Some(target)
2927 }
2928 _ => None,
2929 }
2930 }
2931
2932 fn hit_at(&self, scene: &Node, layout: &LayoutNode, point: Point) -> Hit {
2933 self.hit_at_for(
2934 scene,
2935 layout,
2936 point,
2937 HitPurpose::Button(xrack_runtime::PointerButton::Primary),
2938 )
2939 }
2940
2941 #[doc(hidden)]
2943 pub fn inspection_path(
2944 &self,
2945 scene: &Node,
2946 layout: &LayoutNode,
2947 point: Point,
2948 ) -> Option<Vec<usize>> {
2949 let scope = self.pointer_scope(layout, point);
2950 let (node, item) = scene.at_path(scope).zip(layout.at_path(scope))?;
2951 let mut path = scope.to_vec();
2952 inspect_at(node, item, point, &mut path).then_some(path)
2953 }
2954
2955 fn hit_at_for(
2956 &self,
2957 scene: &Node,
2958 layout: &LayoutNode,
2959 point: Point,
2960 purpose: HitPurpose<'_>,
2961 ) -> Hit {
2962 let scope = self.pointer_scope(layout, point);
2963 let Some((node, item)) = scene.at_path(scope).zip(layout.at_path(scope)) else {
2964 return Hit::None;
2965 };
2966 let mut result = hit(
2967 node,
2968 item,
2969 point,
2970 &mut scope.to_vec(),
2971 &self.transitioning_stacks,
2972 purpose,
2973 );
2974 if let Some(motion) = &self.swipe_page_motion {
2975 let moving = &motion.page.target.path;
2976 let hit_path = match &result {
2977 Hit::Target(target)
2978 | Hit::ControlPart(target, _)
2979 | Hit::TableRowGrip(target, _) => Some(target.path.as_slice()),
2980 Hit::ScrollBar(target) => Some(target.path.as_slice()),
2981 Hit::Blocked(path) => Some(path.as_slice()),
2982 _ => None,
2983 };
2984 if hit_path.is_some_and(|path| path.starts_with(moving)) {
2985 return Hit::StackSlide;
2986 }
2987 }
2988 if matches!(result, Hit::None) && node.kind == "PopupWindow" && item.bounds.contains(point)
2989 {
2990 result = Hit::Blocked(scope.to_vec());
2991 }
2992 match &mut result {
2993 Hit::Target(target) => {
2994 target.row_key = scene.row_key_at(&target.path);
2995 target.tab_close = (|| {
2996 let (&index, parent) = target.path.split_last()?;
2997 let item = layout.at_path(&target.path)?;
2998 if !item.tab_close?.contains(item.map_from_window(point)?) {
2999 return None;
3000 }
3001 let request = scene.at_path(parent)?.tab_close(index)?;
3002 let value = scene.at_path(&target.path)?.text("value").unwrap_or("");
3003 Some((request, value.to_owned()))
3004 })();
3005 }
3006 Hit::ControlPart(target, _)
3007 | Hit::TableRowGrip(target, _)
3008 | Hit::WindowMove(target) => target.row_key = scene.row_key_at(&target.path),
3009 Hit::ScrollBar(target) => target.row_key = scene.row_key_at(&target.path),
3010 _ => {}
3011 }
3012 result
3013 }
3014
3015 pub fn scale_rotate_target_at(
3016 &self,
3017 scene: &Node,
3018 layout: &LayoutNode,
3019 point: Point,
3020 ) -> Option<crate::ScaleRotateTarget> {
3021 if self.menu_open()
3022 || self.choice_open()
3023 || self.scroll_bar_captured()
3024 || self.drag_position().is_some()
3025 || self
3026 .scroll_gesture
3027 .as_ref()
3028 .is_some_and(|gesture| gesture.motion.dragging)
3029 {
3030 return None;
3031 }
3032 let (path, scope_len) =
3033 self.gesture_hit_path(scene, layout, point, "ScaleRotateGestureHandler")?;
3034 (scope_len..=path.len()).rev().find_map(|depth| {
3035 let target = crate::ScaleRotateTarget::new(scene, &path[..depth])?;
3036 let item = layout.at_path(&target.path)?;
3037 (item.contains_clip_point(point)
3038 && item.bounds.contains(item.map_from_window(point)?)
3039 && target.is_live(scene, layout, self))
3040 .then_some(target)
3041 })
3042 }
3043
3044 fn gesture_hit_path(
3045 &self,
3046 scene: &Node,
3047 layout: &LayoutNode,
3048 point: Point,
3049 kind: &str,
3050 ) -> Option<(Vec<usize>, usize)> {
3051 let scope = self.pointer_scope(layout, point);
3052 let path = match hit(
3053 scene.at_path(scope)?,
3054 layout.at_path(scope)?,
3055 point,
3056 &mut scope.to_vec(),
3057 &self.transitioning_stacks,
3058 HitPurpose::Gesture(kind),
3059 ) {
3060 Hit::Target(target) | Hit::ControlPart(target, _) => target.path,
3061 Hit::Blocked(path) => path,
3062 _ => return None,
3063 };
3064 Some((path, scope.len()))
3065 }
3066
3067 pub fn window_gestures_allowed(&self, scene: &Node, layout: &LayoutNode) -> bool {
3068 scene.kind == "Window"
3069 && scene.is_visible()
3070 && !self.menu_open()
3071 && !self.choice_open()
3072 && self.active_dialog(layout).is_none()
3073 && self.popups(layout).next().is_none()
3074 && self.drag_position().is_none()
3075 }
3076
3077 pub fn window_resize_edge(
3079 &self,
3080 scene: &Node,
3081 layout: &LayoutNode,
3082 ) -> Option<WindowResizeEdge> {
3083 if !scene.boolean("no-frame", false)
3084 || !scene.boolean("resizable", true)
3085 || !self.window_gestures_allowed(scene, layout)
3086 {
3087 return None;
3088 }
3089 let point = self.pointer?;
3090 let edge =
3091 WindowResizeEdge::at(layout.bounds, point, scene.length("resize-border-width")?)?;
3092 matches!(
3093 self.hit_at(scene, layout, point),
3094 Hit::None | Hit::WindowMove(_)
3095 )
3096 .then_some(edge)
3097 }
3098
3099 pub fn arm_window_move(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
3100 let Some(origin) = self
3101 .pointer
3102 .filter(|_| self.window_gestures_allowed(scene, layout))
3103 else {
3104 return false;
3105 };
3106 let Hit::WindowMove(target) = self.hit_at(scene, layout, origin) else {
3107 return false;
3108 };
3109 self.cancel_press();
3110 self.window_move_press = Some(WindowMovePress { target, origin });
3111 true
3112 }
3113
3114 pub fn take_window_move(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> bool {
3115 let Some(press) = &self.window_move_press else {
3116 return false;
3117 };
3118 if !self.window_gestures_allowed(scene, layout)
3119 || !matches!(self.hit_at(scene, layout, press.origin), Hit::WindowMove(target) if target == press.target)
3120 {
3121 self.window_move_press = None;
3122 return false;
3123 }
3124 const THRESHOLD: f32 = 4.0;
3125 let x = point.x - press.origin.x;
3126 let y = point.y - press.origin.y;
3127 if x * x + y * y < THRESHOLD * THRESHOLD {
3128 return false;
3129 }
3130 self.window_move_press = None;
3131 true
3132 }
3133
3134 pub fn cancel_window_move(&mut self) -> bool {
3135 self.window_move_press.take().is_some()
3136 }
3137
3138 pub fn sync_stack_transitions(&mut self, transitions: &StackTransitions) -> bool {
3140 if self
3141 .transitioning_stacks
3142 .iter()
3143 .map(Vec::as_slice)
3144 .eq(transitions.active_paths())
3145 {
3146 return false;
3147 }
3148 self.transitioning_stacks = transitions.active_paths().map(<[usize]>::to_vec).collect();
3149 true
3150 }
3151
3152 pub fn pointer_on_stack_slide(&self) -> bool {
3153 self.pointer_on_stack_slide
3154 }
3155
3156 pub fn open_menu_bar(&mut self, scene: &Node, layout: &LayoutNode, target: Target) -> bool {
3157 let Some((_, parent)) = target.path.split_last() else {
3158 return false;
3159 };
3160 let scope = self.active_dialog(layout).unwrap_or_default();
3161 if !target.path.starts_with(scope)
3162 || !scene
3163 .at_path(parent)
3164 .is_some_and(|bar| bar.kind == "MenuBar")
3165 || !scene
3166 .at_path(&target.path)
3167 .is_some_and(|node| node.kind == "Menu")
3168 {
3169 return false;
3170 }
3171 let Some(popup) = MenuPopup::open(
3172 target.clone(),
3173 target.path.clone(),
3174 None,
3175 scene,
3176 layout,
3177 None,
3178 ) else {
3179 return false;
3180 };
3181 self.dismiss_choice();
3182 self.set_focus(Some(target));
3183 self.cancel_shortcut_sequence();
3184 self.set_split_hover(None);
3185 self.menu = Some(popup);
3186 true
3187 }
3188
3189 pub fn open_context_menu(&mut self, scene: &Node, layout: &LayoutNode, keyboard: bool) -> bool {
3190 let target = if keyboard {
3191 self.focused.clone()
3192 } else {
3193 self.pointer.and_then(|point| {
3194 self.target_at_for(
3195 scene,
3196 layout,
3197 point,
3198 HitPurpose::Button(xrack_runtime::PointerButton::Secondary),
3199 )
3200 })
3201 };
3202 let Some(target) = target else {
3203 return false;
3204 };
3205 let scope = self.active_dialog(layout).unwrap_or_default();
3206 if !target.path.starts_with(scope) {
3207 return false;
3208 }
3209 let context = context_menu_area(scene, &target.path, scope);
3210 let point = if keyboard {
3211 let Some(item) = layout.at_path(&target.path) else {
3212 return false;
3213 };
3214 let direction = context
3215 .and_then(|(path, area, index)| {
3216 area.child_at(index)
3217 .and_then(Node::layout_direction)
3218 .or_else(|| layout.at_path(path).map(|area| area.layout_direction))
3219 })
3220 .unwrap_or(item.layout_direction);
3221 let anchor = item.visible_window_bounds(item.bounds);
3222 Point {
3223 x: anchor.x
3224 + if direction == LayoutDirection::RightToLeft {
3225 anchor.width
3226 } else {
3227 0.0
3228 },
3229 y: anchor.y + anchor.height,
3230 }
3231 } else if let Some(point) = self.pointer {
3232 point
3233 } else {
3234 return false;
3235 };
3236 let popup = if let Some((path, area, index)) = context {
3237 let trigger = Target::from_node(path.to_vec(), area, true, scene.row_key_at(path));
3238 let mut path = path.to_vec();
3239 path.push(index);
3240 MenuPopup::open(trigger, path, Some(point), scene, layout, None)
3241 } else {
3242 let Some(node) = self.context_editor(scene, layout, &target) else {
3243 return false;
3244 };
3245 if self.focused.as_ref() == Some(&target)
3246 && self.editor.as_ref().is_some_and(TextEdit::is_composing)
3247 {
3248 return false;
3249 }
3250 if !keyboard {
3251 self.set_focus_with_reason(
3252 Some(target.clone()),
3253 xrack_runtime::FocusReason::PointerClick,
3254 );
3255 }
3256 self.sync_editor(scene);
3257 self.break_text_edit_group();
3258 let value = self.editor_value(node);
3259 let Some(editor) = &self.editor else {
3260 return false;
3261 };
3262 let selection = editor.selection_state(&value);
3263 let commands = self.text_command_availability(
3264 scene,
3265 &target,
3266 node,
3267 &value,
3268 !selection.collapsed(),
3269 );
3270 let menu = TextMenu::new(node, value.into_owned(), selection, commands);
3271 MenuPopup::open(
3272 target.clone(),
3273 target.path,
3274 Some(point),
3275 scene,
3276 layout,
3277 Some(menu),
3278 )
3279 };
3280 let Some(popup) = popup else {
3281 return false;
3282 };
3283 self.dismiss_choice();
3284 self.cancel_press();
3285 self.cancel_shortcut_sequence();
3286 self.set_split_hover(None);
3287 self.menu = Some(popup);
3288 true
3289 }
3290
3291 pub fn supports_context_menu(
3292 &self,
3293 scene: &Node,
3294 layout: &LayoutNode,
3295 target: &Target,
3296 ) -> bool {
3297 let scope = self.active_dialog(layout).unwrap_or_default();
3298 target.path.starts_with(scope)
3299 && (context_menu_area(scene, &target.path, scope).is_some()
3300 || self.context_editor(scene, layout, target).is_some())
3301 }
3302
3303 fn context_editor<'a>(
3304 &self,
3305 scene: &'a Node,
3306 layout: &LayoutNode,
3307 target: &Target,
3308 ) -> Option<&'a Node> {
3309 scene.interactive_at_path(&target.path).filter(|node| {
3310 node.boolean("context-menu-enabled", true)
3311 && (self.is_text_editor(node, target) || spin_editable(node))
3312 && self.spin_draft.as_ref().is_none_or(|draft| {
3313 self.focused.as_ref() != Some(target) || draft.mode.is_current(node)
3314 })
3315 && self.table_edit.as_ref().is_none_or(|draft| {
3316 &draft.target != target || node.text("text").unwrap_or("") == draft.original
3317 })
3318 && valid(target, scene, layout)
3319 })
3320 }
3321
3322 fn editor_history(&self, scene: &Node, target: &Target, node: &Node) -> Option<&TextHistory> {
3323 if is_spin_box(node.kind) {
3324 self.spin_draft.as_ref().map(|draft| &draft.history)
3325 } else if let Some(draft) = self
3326 .table_edit
3327 .as_ref()
3328 .filter(|draft| &draft.target == target)
3329 {
3330 Some(&draft.history)
3331 } else {
3332 self.history.get(&EditorKey::new(scene, target))
3333 }
3334 }
3335
3336 pub(crate) fn text_command_availability(
3337 &self,
3338 scene: &Node,
3339 target: &Target,
3340 node: &Node,
3341 value: &str,
3342 selected: bool,
3343 ) -> TextCommandAvailability {
3344 if self.editor.as_ref().is_some_and(TextEdit::is_composing) {
3345 return TextCommandAvailability::default();
3346 }
3347 let writable = !node.text_read_only();
3348 let copy = selected && !node.is_password();
3349 let (undo, redo) = self
3350 .editor_history(scene, target, node)
3351 .filter(|_| writable)
3352 .map_or((false, false), |history| history.availability(value));
3353 TextCommandAvailability {
3354 undo,
3355 redo,
3356 copy,
3357 cut: copy && writable,
3358 }
3359 }
3360
3361 fn menu_is_current(&self, menu: &MenuPopup, scene: &Node, layout: &LayoutNode) -> bool {
3362 let Some(text) = &menu.text else {
3363 return true;
3364 };
3365 self.focused.as_ref() == Some(&menu.trigger)
3366 && menu
3367 .trigger
3368 .path
3369 .starts_with(self.active_dialog(layout).unwrap_or_default())
3370 && self
3371 .context_editor(scene, layout, &menu.trigger)
3372 .is_some_and(|node| {
3373 let value = self.editor_value(node);
3374 text.kind == node.kind
3375 && text.password == node.is_password()
3376 && text.writable == !node.text_read_only()
3377 && text.value == value
3378 && self.editor.as_ref().is_some_and(|editor| {
3379 !editor.is_composing()
3380 && editor.selection_state(&value) == text.selection
3381 })
3382 && text.commands
3383 == self.text_command_availability(
3384 scene,
3385 &menu.trigger,
3386 node,
3387 &value,
3388 !text.selection.collapsed(),
3389 )
3390 })
3391 }
3392
3393 pub fn reconcile_text_menu(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
3394 let current = self
3395 .menu
3396 .as_ref()
3397 .is_none_or(|menu| self.menu_is_current(menu, scene, layout));
3398 if !current {
3399 self.close_menu(scene, layout);
3400 }
3401 current
3402 }
3403
3404 pub fn pointer_context_menu_changes_focus(&self, scene: &Node, layout: &LayoutNode) -> bool {
3405 self.pointer
3406 .and_then(|point| {
3407 self.target_at_for(
3408 scene,
3409 layout,
3410 point,
3411 HitPurpose::Button(xrack_runtime::PointerButton::Secondary),
3412 )
3413 })
3414 .is_some_and(|target| {
3415 let scope = self.active_dialog(layout).unwrap_or_default();
3416 self.focused.as_ref() != Some(&target)
3417 && target.path.starts_with(scope)
3418 && context_menu_area(scene, &target.path, scope).is_none()
3419 && self.context_editor(scene, layout, &target).is_some()
3420 })
3421 }
3422
3423 fn finish_menu_action(
3424 &mut self,
3425 scene: &Node,
3426 layout: &LayoutNode,
3427 path: Vec<usize>,
3428 ) -> Option<ControlInput> {
3429 let action = self.menu.as_ref()?.input(path)?;
3430 self.close_menu(scene, layout);
3431 Some(action)
3432 }
3433
3434 pub fn menu_press(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
3435 if !self.menu_open() {
3436 return false;
3437 }
3438 if !self.reconcile_text_menu(scene, layout) {
3439 return true;
3440 }
3441 self.cancel_press();
3442 if let Some(point) = self.pointer {
3443 if self
3444 .menu
3445 .as_mut()
3446 .is_some_and(|menu| menu.press(scene, layout, point))
3447 {
3448 return true;
3449 }
3450 if let Some(header) = self.target_at(scene, layout, point)
3451 && !self.menu_header_open(&header.path)
3452 && self.open_menu_bar(scene, layout, header)
3453 {
3454 return true;
3455 }
3456 }
3457 self.close_menu(scene, layout);
3458 true
3459 }
3460
3461 pub fn menu_release(&mut self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
3462 if !self.reconcile_text_menu(scene, layout) {
3463 return None;
3464 }
3465 let path = self.menu.as_mut()?.release(scene, layout, self.pointer?)?;
3466 self.finish_menu_action(scene, layout, path)
3467 }
3468
3469 pub fn menu_scroll(&mut self, scene: &Node, layout: &LayoutNode, rows: isize) -> bool {
3470 let Some(popup) = &mut self.menu else {
3471 return false;
3472 };
3473 popup.scroll(scene, layout, self.pointer, rows);
3474 true
3475 }
3476
3477 pub fn menu_key(
3478 &mut self,
3479 scene: &Node,
3480 layout: &LayoutNode,
3481 key: MenuKey,
3482 ) -> Option<ControlInput> {
3483 if !self.reconcile_text_menu(scene, layout) {
3484 return None;
3485 }
3486 let Some(popup) = self.menu.as_mut() else {
3487 let target = self.focused.clone().filter(|target| {
3488 scene
3489 .at_path(&target.path)
3490 .is_some_and(|node| node.kind == "Menu")
3491 })?;
3492 match key {
3493 MenuKey::Up | MenuKey::Down | MenuKey::Accept => {
3494 self.open_menu_bar(scene, layout, target);
3495 }
3496 MenuKey::Left | MenuKey::Right => {
3497 if let Some(next) = sibling_menu(scene, layout, &target, key) {
3498 self.set_focus(Some(next));
3499 }
3500 }
3501 _ => {}
3502 }
3503 return None;
3504 };
3505 if key == MenuKey::Escape && popup.at_root() {
3506 self.close_menu(scene, layout);
3507 return None;
3508 }
3509 if key == popup.forward_key(scene, layout) && popup.enter_submenu(scene, layout) {
3510 return None;
3511 }
3512 if matches!(key, MenuKey::Left | MenuKey::Right)
3513 && popup.at_root()
3514 && popup.bar_header().is_some()
3515 && let Some(next) = sibling_menu(scene, layout, &popup.trigger, key)
3516 {
3517 self.open_menu_bar(scene, layout, next);
3518 return None;
3519 }
3520 let path = popup.key(scene, layout, key)?;
3521 self.finish_menu_action(scene, layout, path)
3522 }
3523
3524 pub fn scroll_offsets(&self) -> &BTreeMap<Vec<usize>, f32> {
3525 &self.scroll_offsets
3526 }
3527
3528 pub(crate) fn tree_root_changed(&self, path: &[usize], node: &Node) -> bool {
3529 node.tree.as_ref().is_some_and(|tree| {
3530 self.tree_scroll_roots
3531 .get(path)
3532 .is_some_and(|root| *root != tree.root_identity())
3533 })
3534 }
3535
3536 pub fn horizontal_scroll_offsets(&self) -> &BTreeMap<Vec<usize>, f32> {
3537 &self.horizontal_scroll_offsets
3538 }
3539
3540 pub(crate) fn scroll_selection_changed(
3541 &self,
3542 node: &Node,
3543 path: &[usize],
3544 columns: usize,
3545 direction: LayoutDirection,
3546 ) -> bool {
3547 self.scroll_selections
3548 .get(path)
3549 .is_some_and(|previous| *previous != ScrollSelection::new(node, columns, direction))
3550 }
3551
3552 pub fn pointer_position(&self) -> Option<Point> {
3553 self.pointer
3554 }
3555
3556 #[doc(hidden)]
3558 pub fn editor_mouse_press(
3559 &mut self,
3560 target: &Target,
3561 point: Point,
3562 now: Instant,
3563 selecting: bool,
3564 ) -> bool {
3565 let previous = self.last_editor_click.take();
3566 self.editor_press = None;
3567 if selecting
3568 || self.pressed.as_ref() != Some(target)
3569 || self.focused.as_ref() != Some(target)
3570 {
3571 return false;
3572 }
3573 let sample = (point, now);
3574 let repeated = previous.is_some_and(|click| {
3575 click.target == *target && crate::pointer_click_follows(click.sample, sample)
3576 });
3577 if !repeated {
3578 self.editor_press = Some(EditorClick {
3579 target: target.clone(),
3580 sample,
3581 });
3582 }
3583 repeated
3584 }
3585
3586 #[doc(hidden)]
3587 pub fn clear_editor_click(&mut self) {
3588 self.editor_press = None;
3589 self.last_editor_click = None;
3590 }
3591
3592 pub fn pointer_press_origin(&self) -> Option<Point> {
3593 self.press_origin
3594 }
3595
3596 #[doc(hidden)]
3597 pub fn schedule_text_selection_scroll(
3598 &mut self,
3599 target: &Target,
3600 point: Option<Point>,
3601 now: Instant,
3602 ) {
3603 self.text_selection_scroll = point
3604 .filter(|_| self.pressed.as_ref() == Some(target) && self.editor_active(&target.path))
3605 .map(|point| TextSelectionScroll {
3606 target: target.clone(),
3607 point,
3608 due: self
3609 .text_selection_scroll
3610 .as_ref()
3611 .filter(|scroll| &scroll.target == target)
3612 .map_or(now + SCROLL_FRAME_INTERVAL, |scroll| scroll.due),
3613 });
3614 }
3615
3616 #[doc(hidden)]
3617 pub fn text_selection_scroll_deadline(&self) -> Option<Instant> {
3618 let scroll = self.text_selection_scroll.as_ref()?;
3619 (self.pressed.as_ref() == Some(&scroll.target) && self.editor_active(&scroll.target.path))
3620 .then_some(scroll.due)
3621 }
3622
3623 #[doc(hidden)]
3624 pub fn take_text_selection_scroll(&mut self, now: Instant) -> Option<(Point, Duration)> {
3625 let Some(due) = self.text_selection_scroll_deadline() else {
3626 self.text_selection_scroll = None;
3627 return None;
3628 };
3629 let elapsed = now.checked_duration_since(due)? + SCROLL_FRAME_INTERVAL;
3630 let scroll = self.text_selection_scroll.take()?;
3631 Some((scroll.point, elapsed.min(3 * SCROLL_FRAME_INTERVAL)))
3632 }
3633
3634 pub fn text_scroll(&self, path: &[usize]) -> Point {
3635 self.text_offsets
3636 .get(path)
3637 .map_or(Point::default(), |(_, offset)| *offset)
3638 }
3639
3640 pub fn set_text_scroll(&mut self, target: &Target, offset: Point) {
3641 if offset == Point::default() {
3642 self.text_offsets.remove(&target.path);
3643 } else {
3644 self.text_offsets
3645 .insert(target.path.clone(), (target.row_key, offset));
3646 }
3647 }
3648
3649 pub fn scroll_y(&mut self, layout: &LayoutNode, delta: f32) -> bool {
3650 self.scroll_axis(layout, delta, Orientation::Vertical)
3651 .unwrap_or(false)
3652 }
3653
3654 pub fn scroll_x(&mut self, layout: &LayoutNode, delta: f32) -> bool {
3655 self.scroll_axis(layout, delta, Orientation::Horizontal)
3656 .unwrap_or(false)
3657 }
3658
3659 pub fn scroll_wheel(&mut self, layout: &LayoutNode, delta: Point, shift: bool) -> bool {
3660 if shift
3661 && delta.x == 0.0
3662 && let Some(moved) = self.scroll_axis(layout, delta.y, Orientation::Horizontal)
3663 {
3664 return moved;
3665 }
3666 let x = self.scroll_x(layout, delta.x);
3667 let y = self.scroll_y(layout, delta.y);
3668 x || y
3669 }
3670
3671 pub fn accessibility_scroll_to(
3673 &mut self,
3674 layout: &LayoutNode,
3675 path: &[usize],
3676 orientation: Orientation,
3677 offset: f32,
3678 ) -> bool {
3679 self.scroll_to_user_offset(layout, path, orientation, offset)
3680 }
3681
3682 fn scroll_to_user_offset(
3683 &mut self,
3684 layout: &LayoutNode,
3685 path: &[usize],
3686 orientation: Orientation,
3687 offset: f32,
3688 ) -> bool {
3689 if !offset.is_finite()
3690 || self
3691 .active_dialog(layout)
3692 .is_some_and(|scope| !path.starts_with(scope))
3693 {
3694 return false;
3695 }
3696 let Some(mut item) = layout
3697 .at_path(path)
3698 .filter(|item| scroll_target_visible(item))
3699 else {
3700 return false;
3701 };
3702 let mut path = path;
3703 if let Some(bar) = &item.attached_scroll_bar {
3704 if bar.geometry.orientation != orientation || !self.allows_popup(layout, &bar.target) {
3705 return false;
3706 }
3707 path = &bar.target;
3708 let Some(viewport) = layout
3709 .at_path(path)
3710 .filter(|viewport| viewport.visible && viewport.enabled)
3711 else {
3712 return false;
3713 };
3714 item = viewport;
3715 }
3716 let Some(scroll) = item.scroll_on(orientation) else {
3717 return false;
3718 };
3719 if !self.set_viewport_offset(path, item, orientation, f64::from(offset)) {
3720 return false;
3721 }
3722 UserScrollChange::record(
3723 &mut self.user_scroll_changes,
3724 item,
3725 orientation,
3726 scroll.offset,
3727 );
3728 true
3729 }
3730
3731 pub(crate) fn scroll_viewport_by(
3732 &mut self,
3733 path: &[usize],
3734 item: &LayoutNode,
3735 axis: Orientation,
3736 delta: f64,
3737 ) -> bool {
3738 delta.is_finite()
3739 && delta != 0.0
3740 && self.update_viewport_offset(path, item, axis, |previous| f64::from(previous) + delta)
3741 }
3742
3743 pub(crate) fn set_viewport_offset(
3744 &mut self,
3745 path: &[usize],
3746 item: &LayoutNode,
3747 axis: Orientation,
3748 offset: f64,
3749 ) -> bool {
3750 offset.is_finite() && self.update_viewport_offset(path, item, axis, |_| offset)
3751 }
3752
3753 pub(crate) fn current_viewport_offset(
3754 &self,
3755 path: &[usize],
3756 item: &LayoutNode,
3757 axis: Orientation,
3758 ) -> Option<f32> {
3759 let scroll = item.scroll_on(axis)?;
3760 let offsets = match axis {
3761 Orientation::Horizontal => &self.horizontal_scroll_offsets,
3762 Orientation::Vertical => &self.scroll_offsets,
3763 };
3764 Some(
3765 item.bound_offset(axis)
3766 .or_else(|| pending_scroll_offset(item, offsets, path, axis))
3767 .unwrap_or(scroll.offset)
3768 .clamp(0.0, scroll.max_offset),
3769 )
3770 }
3771
3772 fn update_viewport_offset(
3773 &mut self,
3774 path: &[usize],
3775 item: &LayoutNode,
3776 axis: Orientation,
3777 next: impl FnOnce(f32) -> f64,
3778 ) -> bool {
3779 let Some(scroll) = item.scroll_on(axis) else {
3780 return false;
3781 };
3782 let had_overscroll = self.overscroll.has_offset();
3783 self.cancel_scroll_gesture();
3784 let previous = self
3785 .current_viewport_offset(path, item, axis)
3786 .unwrap_or(scroll.offset);
3787 let offsets = match axis {
3788 Orientation::Horizontal => &mut self.horizontal_scroll_offsets,
3789 Orientation::Vertical => &mut self.scroll_offsets,
3790 };
3791 let next = next(previous).clamp(0.0, f64::from(scroll.max_offset)) as f32;
3792 if next == previous {
3793 return had_overscroll;
3794 }
3795 store_scroll_offset(item, offsets, path, axis, next);
3796 item.write_bound_offset(axis, next);
3797 true
3798 }
3799
3800 fn scroll_bar_for_target(
3801 &self,
3802 scene: &Node,
3803 layout: &LayoutNode,
3804 target: &ScrollTarget,
3805 ) -> Option<ScrollBarGeometry> {
3806 let path = &target.path;
3807 if !path.starts_with(self.active_dialog(layout).unwrap_or_default()) {
3808 return None;
3809 }
3810 let item = layout.at_path(path)?;
3811 let node = scene.interactive_at_path(path)?;
3812 if !item.visible
3813 || !item.enabled
3814 || !target.matches_node(node)
3815 || scene.row_key_at(path) != target.row_key
3816 {
3817 return None;
3818 }
3819 if node.kind == "ScrollBar" && !node.boolean("interactive", true) {
3820 return None;
3821 }
3822 if let Some(bar) = &item.attached_scroll_bar
3823 && !self.allows_popup(layout, &bar.target)
3824 {
3825 return None;
3826 }
3827 item.scroll_bars(node)
3828 .find(|bar| bar.orientation == target.orientation && bar.scrollable())
3829 }
3830
3831 pub fn scroll_bar_press(
3833 &mut self,
3834 scene: &Node,
3835 layout: &LayoutNode,
3836 ) -> Option<ScrollBarUpdate> {
3837 let target = self.hovered_scroll_bar.clone()?;
3838 self.press_scroll_bar(scene, layout, target, self.pointer?, false)
3839 }
3840
3841 fn press_scroll_bar(
3842 &mut self,
3843 scene: &Node,
3844 layout: &LayoutNode,
3845 target: ScrollTarget,
3846 point: Point,
3847 touch: bool,
3848 ) -> Option<ScrollBarUpdate> {
3849 if self.menu_open() || self.choice_open() {
3850 return None;
3851 }
3852 let item = layout.at_path(&target.path)?;
3853 let start = point;
3854 let point = item.map_from_window(point)?;
3855 let bar = self.scroll_bar_for_target(scene, layout, &target)?;
3856 if !bar.track.contains(point) {
3857 return None;
3858 }
3859 self.cancel_scroll_gesture();
3860 self.cancel_press();
3861 self.tooltip.dismiss();
3862 let node = scene.at_path(&target.path)?;
3863 if node.kind == "ScrollBar" {
3864 self.set_focus_with_reason(
3865 Some(Target::from_node(
3866 target.path.clone(),
3867 node,
3868 true,
3869 target.row_key,
3870 )),
3871 xrack_runtime::FocusReason::PointerClick,
3872 );
3873 self.remember_focus_scope(scene, layout);
3874 }
3875 let grab = bar.grab(point);
3876 let update = if grab.is_none() {
3877 self.move_scroll_bar(node, layout, &target.path, bar, bar.page_toward(point))
3878 } else {
3879 ScrollBarUpdate::Unchanged
3880 };
3881 self.scroll_bar_press = Some(ScrollBarPress {
3882 target,
3883 source: node.kind,
3884 viewport: node.scroll_target.clone(),
3885 reversed: bar.reversed(),
3886 grab,
3887 touch,
3888 cancelled: false,
3889 start,
3890 last: start,
3891 dragged: false,
3892 });
3893 Some(update)
3894 }
3895
3896 pub fn scroll_bar_drag(
3898 &mut self,
3899 scene: &Node,
3900 layout: &LayoutNode,
3901 ) -> Option<ScrollBarUpdate> {
3902 self.update_scroll_bar_capture(scene, layout, self.pointer, false)
3903 }
3904
3905 pub fn release_scroll_bar(
3906 &mut self,
3907 scene: &Node,
3908 layout: &LayoutNode,
3909 ) -> Option<ScrollBarUpdate> {
3910 let point = self
3911 .pointer
3912 .or_else(|| self.scroll_bar_press.as_ref().map(|press| press.last));
3913 self.update_scroll_bar_capture(scene, layout, point, true)
3914 }
3915
3916 fn update_scroll_bar_capture(
3917 &mut self,
3918 scene: &Node,
3919 layout: &LayoutNode,
3920 point: Option<Point>,
3921 released: bool,
3922 ) -> Option<ScrollBarUpdate> {
3923 let mut press = self.scroll_bar_press.take()?;
3924 let update = point.map_or(ScrollBarUpdate::Unchanged, |point| {
3925 self.update_scroll_bar_drag(scene, layout, &mut press, point, released)
3926 });
3927 if !released {
3928 self.scroll_bar_press = Some(press);
3929 }
3930 Some(update)
3931 }
3932
3933 fn update_scroll_bar_drag(
3934 &mut self,
3935 scene: &Node,
3936 layout: &LayoutNode,
3937 press: &mut ScrollBarPress,
3938 point: Point,
3939 released: bool,
3940 ) -> ScrollBarUpdate {
3941 let Some(grab) = press.grab.filter(|_| !press.cancelled) else {
3942 return ScrollBarUpdate::Unchanged;
3943 };
3944 let target = &press.target;
3945 let Some(node) = press.node(scene) else {
3946 press.cancelled = true;
3947 return ScrollBarUpdate::Unchanged;
3948 };
3949 let Some(bar) = self
3950 .scroll_bar_for_target(scene, layout, target)
3951 .filter(|bar| bar.reversed() == press.reversed)
3952 else {
3953 press.cancelled = true;
3954 return ScrollBarUpdate::Unchanged;
3955 };
3956 let mode = match node.properties.get("snap-mode") {
3957 Some(Value::ScrollSnapMode(mode)) => *mode,
3958 _ => ScrollSnapMode::None,
3959 };
3960 if released && mode == ScrollSnapMode::None {
3961 return ScrollBarUpdate::Unchanged;
3962 }
3963 let Some(item) = layout.at_path(&target.path) else {
3964 return ScrollBarUpdate::Unchanged;
3965 };
3966 let window_point = point;
3967 let (Some(point), Some(start)) = (
3968 item.map_from_window(point),
3969 item.map_from_window(press.start),
3970 ) else {
3971 return ScrollBarUpdate::Unchanged;
3972 };
3973 let mut fraction = bar.drag_fraction(point, grab);
3974 if !fraction.is_finite() {
3975 return ScrollBarUpdate::Unchanged;
3976 }
3977 press.last = window_point;
3978 press.dragged |= fraction != bar.drag_fraction(start, grab);
3979 if !press.dragged {
3980 return ScrollBarUpdate::Unchanged;
3981 }
3982 if mode == ScrollSnapMode::Always || released && mode == ScrollSnapMode::OnRelease {
3983 fraction = snap_fraction(fraction, node.number("step-size").unwrap_or(0.0));
3984 }
3985 self.move_scroll_bar_fraction(node, layout, &target.path, bar, fraction)
3986 }
3987
3988 pub fn scroll_bar_key(
3989 &mut self,
3990 scene: &Node,
3991 layout: &LayoutNode,
3992 key: NavigationKey,
3993 ) -> Option<ScrollBarUpdate> {
3994 let target = self.focused.as_ref()?;
3995 let node = scene.interactive_at_path(&target.path)?;
3996 if node.kind != "ScrollBar"
3997 || !valid(target, scene, layout)
3998 || !self.allows_popup(layout, &target.path)
3999 {
4000 return None;
4001 }
4002 let item = layout.at_path(&target.path)?;
4003 let bar = item.scroll_control_geometry(node)?;
4004 let page = if bar.page > 0.0 { bar.page } else { bar.step };
4005 let offset = match (key, bar.orientation) {
4006 (NavigationKey::Home, _) => 0.0,
4007 (NavigationKey::End, _) => bar.scroll.max_offset,
4008 (NavigationKey::PageUp, _) => bar.scroll.offset - page,
4009 (NavigationKey::PageDown, _) => bar.scroll.offset + page,
4010 (NavigationKey::Left, Orientation::Horizontal)
4011 | (NavigationKey::Up, Orientation::Vertical) => {
4012 bar.scroll.offset + bar.logical_delta(-bar.step)
4013 }
4014 (NavigationKey::Right, Orientation::Horizontal)
4015 | (NavigationKey::Down, Orientation::Vertical) => {
4016 bar.scroll.offset + bar.logical_delta(bar.step)
4017 }
4018 _ => return None,
4019 };
4020 let path = target.path.clone();
4021 Some(self.move_scroll_bar(node, layout, &path, bar, offset))
4022 }
4023
4024 fn move_scroll_bar(
4025 &mut self,
4026 node: &Node,
4027 layout: &LayoutNode,
4028 path: &[usize],
4029 bar: ScrollBarGeometry,
4030 offset: f32,
4031 ) -> ScrollBarUpdate {
4032 if !bar.scrollable() {
4033 return ScrollBarUpdate::Unchanged;
4034 }
4035 let fraction =
4036 f64::from(offset.clamp(0.0, bar.scroll.max_offset)) / f64::from(bar.scroll.max_offset);
4037 self.move_scroll_bar_fraction(node, layout, path, bar, fraction)
4038 }
4039
4040 fn move_scroll_bar_fraction(
4041 &mut self,
4042 node: &Node,
4043 layout: &LayoutNode,
4044 path: &[usize],
4045 bar: ScrollBarGeometry,
4046 fraction: f64,
4047 ) -> ScrollBarUpdate {
4048 if node.kind == "ScrollBar" && node.scroll_target.is_none() {
4049 let action = RangeAction::SetFraction(fraction);
4050 if ScrollBarRange::from_node(node).apply(action).is_some() {
4051 return ScrollBarUpdate::Range(RangeInput {
4052 path: path.to_vec(),
4053 action,
4054 });
4055 }
4056 } else if self.scroll_to_user_offset(
4057 layout,
4058 path,
4059 bar.orientation,
4060 (fraction * f64::from(bar.scroll.max_offset)) as f32,
4061 ) {
4062 return ScrollBarUpdate::ViewportMoved;
4063 }
4064 ScrollBarUpdate::Unchanged
4065 }
4066
4067 pub fn finish_scroll_bar(&mut self) -> bool {
4068 self.scroll_bar_press.take().is_some()
4069 }
4070
4071 pub fn scroll_bar_captured(&self) -> bool {
4072 self.scroll_bar_press.is_some()
4073 }
4074
4075 pub fn touch_scroll_bar_press(
4076 &mut self,
4077 scene: &Node,
4078 layout: &LayoutNode,
4079 point: Point,
4080 ) -> Option<ScrollBarUpdate> {
4081 let Hit::ScrollBar(target) = self.hit_at(scene, layout, point) else {
4082 return None;
4083 };
4084 let moved = self.press_scroll_bar(scene, layout, target.clone(), point, true)?;
4085 self.pointer = Some(point);
4086 self.hovered_scroll_bar = Some(target);
4087 Some(moved)
4088 }
4089
4090 pub fn touch_scroll_bar_drag(
4091 &mut self,
4092 scene: &Node,
4093 layout: &LayoutNode,
4094 point: Point,
4095 ) -> ScrollBarUpdate {
4096 self.pointer = Some(point);
4097 self.scroll_bar_drag(scene, layout)
4098 .unwrap_or(ScrollBarUpdate::Unchanged)
4099 }
4100
4101 pub fn finish_touch_scroll_bar(&mut self) -> bool {
4102 if !self.finish_scroll_bar() {
4103 return false;
4104 }
4105 self.hovered_scroll_bar = None;
4106 self.pointer = None;
4107 true
4108 }
4109
4110 pub fn release_touch_scroll_bar(
4111 &mut self,
4112 scene: &Node,
4113 layout: &LayoutNode,
4114 point: Point,
4115 ) -> Option<ScrollBarUpdate> {
4116 let update = self.update_scroll_bar_capture(scene, layout, Some(point), true)?;
4117 self.hovered_scroll_bar = None;
4118 self.pointer = None;
4119 Some(update)
4120 }
4121
4122 pub(crate) fn scroll_bar_interaction(
4123 &self,
4124 scene: &Node,
4125 layout: &LayoutNode,
4126 path: &[usize],
4127 axis: Orientation,
4128 ) -> (bool, bool) {
4129 let matches = |target: &ScrollTarget| target.path == path && target.orientation == axis;
4130 let pressed = self.scroll_bar_press.as_ref().is_some_and(|press| {
4131 !press.cancelled
4132 && matches(&press.target)
4133 && press.node(scene).is_some()
4134 && self
4135 .scroll_bar_for_target(scene, layout, &press.target)
4136 .is_some_and(|bar| bar.reversed() == press.reversed)
4137 });
4138 let hovered = !self
4139 .scroll_bar_press
4140 .as_ref()
4141 .is_some_and(|press| press.touch)
4142 && self.hovered_scroll_bar.as_ref().is_some_and(|target| {
4143 matches(target) && self.scroll_bar_for_target(scene, layout, target).is_some()
4144 });
4145 (pressed, hovered)
4146 }
4147
4148 pub fn scroll_bar_highlighted(&self, path: &[usize], orientation: Orientation) -> bool {
4149 let matches =
4150 |target: &ScrollTarget| target.path == path && target.orientation == orientation;
4151 self.hovered_scroll_bar.as_ref().is_some_and(matches)
4152 || self.scroll_bar_press.as_ref().is_some_and(|press| {
4153 !press.cancelled && press.grab.is_some() && matches(&press.target)
4154 })
4155 }
4156
4157 fn scroll_axis(
4158 &mut self,
4159 layout: &LayoutNode,
4160 delta: f32,
4161 orientation: Orientation,
4162 ) -> Option<bool> {
4163 if self.pointer_on_stack_slide || !delta.is_finite() || delta == 0.0 {
4164 return None;
4165 }
4166 let point = self.pointer?;
4167 let scope = self.pointer_scope(layout, point);
4168 let scope_len = scope.len();
4169 let path = Self::scroll_path(layout, point, scope, |_, item| {
4170 item.scroll_on(orientation)
4171 .is_some_and(|scroll| scroll.max_offset > 0.0)
4172 })?;
4173 Some(
4174 self.consume_scroll(
4175 layout,
4176 &path,
4177 scope_len,
4178 delta,
4179 orientation,
4180 ScrollInput::Wheel,
4181 )
4182 .changed(),
4183 )
4184 }
4185
4186 fn scroll_path(
4187 layout: &LayoutNode,
4188 point: Point,
4189 scope: &[usize],
4190 accepts: impl Fn(&[usize], &LayoutNode) -> bool,
4191 ) -> Option<Vec<usize>> {
4192 fn target(
4193 layout: &LayoutNode,
4194 point: Point,
4195 path: &mut Vec<usize>,
4196 accepts: &impl Fn(&[usize], &LayoutNode) -> bool,
4197 ) -> bool {
4198 if !layout.enabled || !layout.contains_subtree_point(point) {
4199 return false;
4200 }
4201 for (index, child) in layout
4202 .child_paint_order()
4203 .rev()
4204 .filter_map(|index| layout.child_at(index).map(|child| (index, child)))
4205 {
4206 path.push(index);
4207 if target(child, point, path, accepts) {
4208 return true;
4209 }
4210 path.pop();
4211 }
4212 layout
4213 .map_from_window(point)
4214 .is_some_and(|local| layout.tab_viewport().contains(local))
4215 && accepts(path, layout)
4216 }
4217
4218 let mut path = scope.to_vec();
4219 target(layout.at_path(scope)?, point, &mut path, &accepts).then_some(path)
4220 }
4221
4222 fn consume_scroll(
4223 &mut self,
4224 layout: &LayoutNode,
4225 path: &[usize],
4226 scope_len: usize,
4227 delta: f32,
4228 orientation: Orientation,
4229 mut input: ScrollInput<'_>,
4230 ) -> AxisMotion {
4231 let mut result = AxisMotion::default();
4232 let mut delta = f64::from(delta);
4233 if let ScrollInput::Pan {
4234 owners,
4235 flicking: false,
4236 ..
4237 } = &mut input
4238 {
4239 let (remaining, owner) = self.overscroll.unwind(orientation, delta);
4240 delta = remaining;
4241 if let Some(owner) = owner {
4242 record_motion_owner(owners, &owner, orientation);
4243 result.elastic = true;
4244 }
4245 }
4246 let offsets = match orientation {
4247 Orientation::Horizontal => &mut self.horizontal_scroll_offsets,
4248 Orientation::Vertical => &mut self.scroll_offsets,
4249 };
4250 let mut elastic_owner = None;
4251 let last_depth = path.len();
4253 for depth in (scope_len..=last_depth).rev() {
4254 let path = &path[..depth];
4255 let Some(item) = layout.at_path(path) else {
4256 continue;
4257 };
4258 if item.tab_strip.is_some() && depth != last_depth {
4259 continue;
4260 }
4261 if let ScrollInput::Pan { device, .. } = &input
4262 && (!item.visible || !item.enabled || !item.accepts_pan(orientation, *device))
4263 {
4264 continue;
4265 }
4266 let Some(scroll) = item.scroll_on(orientation) else {
4267 continue;
4268 };
4269 let current = pending_scroll_offset(item, offsets, path, orientation)
4270 .unwrap_or(scroll.offset)
4271 .clamp(0.0, scroll.max_offset);
4272 let sign = if item.scroll_axis_reversed(orientation) {
4273 -1.0
4274 } else {
4275 1.0
4276 };
4277 let wanted = f64::from(current) + delta * sign;
4278 let bounded = wanted.clamp(0.0, f64::from(scroll.max_offset));
4279 delta = (wanted - bounded) * sign;
4281 if let ScrollInput::Pan { flicking, .. } = &input
4282 && delta != 0.0
4283 && scroll.max_offset > 0.0
4284 && item.viewport_handle.is_some()
4285 && item
4286 .elastic
4287 .is_some_and(|options| options.behavior.allows_overshoot(*flicking))
4288 {
4289 elastic_owner = Some(item);
4290 }
4291 let next = bounded as f32;
4292 if next != current {
4293 store_scroll_offset(item, offsets, path, orientation, next);
4294 UserScrollChange::commit(
4295 &mut self.user_scroll_changes,
4296 item,
4297 orientation,
4298 scroll.offset,
4299 next,
4300 );
4301 if let ScrollInput::Pan { owners, .. } = &mut input {
4302 record_motion(owners, item, orientation);
4303 }
4304 result.bounded = true;
4305 }
4306 if delta == 0.0 {
4307 break;
4308 }
4309 }
4310 if let Some(item) = elastic_owner
4311 && !self.overscroll.is_rebounding(orientation)
4312 && self.overscroll.pull(item, orientation, delta)
4313 {
4314 result.elastic = true;
4315 if let ScrollInput::Pan {
4316 owners,
4317 flicking: false,
4318 ..
4319 } = &mut input
4320 {
4321 record_motion(owners, item, orientation);
4322 }
4323 }
4324 result
4325 }
4326
4327 pub fn arm_mouse_viewport_pan(
4330 &mut self,
4331 scene: &Node,
4332 layout: &LayoutNode,
4333 point: Point,
4334 now: Instant,
4335 ) -> bool {
4336 if self.press_origin != Some(point)
4337 || self.drag.is_some()
4338 || self.split_resize_active()
4339 || self.scroll_bar_press.is_some()
4340 || self.table_resize.is_some()
4341 || self.table_row_resize.is_some()
4342 || self.table_column_move.is_some()
4343 || self.table_row_move.is_some()
4344 || self.pressed_table_column.is_some()
4345 || self.menu_open()
4346 || self.choice_open()
4347 {
4348 return false;
4349 }
4350 let hit = self.hit_at(scene, layout, point);
4351 let hit_path = match &hit {
4352 Hit::None => None,
4353 Hit::Target(target)
4354 if scene.at_path(&target.path).is_some_and(|node| {
4355 matches!(
4356 node.kind,
4357 "Button"
4358 | "ToolButton"
4359 | "RoundButton"
4360 | "TouchArea"
4361 | "ListRow"
4362 | "ListView"
4363 | "GridView"
4364 | "StandardListView"
4365 | "TableView"
4366 | "TreeView"
4367 ) || is_toggle(node.kind)
4368 }) =>
4369 {
4370 Some(target.path.as_slice())
4371 }
4372 _ => return false,
4373 };
4374 let scope = self.pointer_scope(layout, point).to_vec();
4375 let orientations = [Orientation::Horizontal, Orientation::Vertical];
4376 let can_pan = |item: &LayoutNode, axis| {
4377 item.accepts_pan(axis, PanDevice::LeftMouse)
4378 && item
4379 .scroll_on(axis)
4380 .is_some_and(|scroll| scroll.max_offset > 0.0)
4381 };
4382 let Some(path) = Self::scroll_path(layout, point, &scope, |path, item| {
4383 hit_path.is_none_or(|target| target.starts_with(path))
4384 && orientations.into_iter().any(|axis| can_pan(item, axis))
4385 }) else {
4386 return false;
4387 };
4388 let axes = orientations.map(|orientation| {
4389 (scope.len()..=path.len()).rev().find_map(|depth| {
4390 let path = &path[..depth];
4391 let item = layout.at_path(path)?;
4392 let node = scene.at_path(path)?;
4393 can_pan(item, orientation).then(|| ScrollTarget {
4394 path: path.to_vec(),
4395 orientation,
4396 row_key: scene.row_key_at(path),
4397 id: ElementId::of(node),
4398 })
4399 })
4400 });
4401 self.scroll_gesture = Some(ScrollGesture {
4402 route: ScrollRoute {
4403 scope_row: scene.row_key_at(&scope),
4404 scope_id: scene.at_path(&scope).and_then(ElementId::of),
4405 scope,
4406 axes,
4407 mouse_viewport: true,
4408 pan_device: PanDevice::LeftMouse,
4409 },
4410 motion: DragMotion::new(point, now),
4411 tap: None,
4412 touch_point: None,
4413 popup: (false, false),
4414 drawer: None,
4415 pages: Vec::new(),
4416 tumbler: None,
4417 tab_move: None,
4418 switch: None,
4419 swipe_delegate: None,
4420 swipe: None,
4421 delay_touch: false,
4422 table_gesture: None,
4423 });
4424 true
4425 }
4426
4427 pub fn mouse_viewport_pan_claimed(&self) -> bool {
4428 self.scroll_gesture
4429 .as_ref()
4430 .is_some_and(|gesture| gesture.route.mouse_viewport && gesture.motion.dragging)
4431 }
4432
4433 pub fn begin_scroll_gesture(
4435 &mut self,
4436 scene: &Node,
4437 layout: &LayoutNode,
4438 point: Point,
4439 now: Instant,
4440 kind: ScrollGestureKind,
4441 ) -> bool {
4442 self.begin_scroll_gesture_with_selection(scene, layout, point, now, kind, false)
4443 }
4444
4445 #[doc(hidden)]
4446 pub fn begin_scroll_gesture_with_selection(
4447 &mut self,
4448 scene: &Node,
4449 layout: &LayoutNode,
4450 point: Point,
4451 now: Instant,
4452 kind: ScrollGestureKind,
4453 additive: bool,
4454 ) -> bool {
4455 self.swipe_commit = None;
4456 let tumbler_interrupted = self.interrupt_tumbler_flick();
4457 let interrupted = tumbler_interrupted
4458 || self.scroll_fling.is_some()
4459 || self.overscroll.deadline().is_some();
4460 self.scroll_fling = None;
4461 if interrupted {
4462 self.viewport_motion.clear();
4463 }
4464 if !point.x.is_finite() || !point.y.is_finite() {
4465 return false;
4466 }
4467 let touch = kind == ScrollGestureKind::Touch;
4468 if matches!(
4469 kind,
4470 ScrollGestureKind::Touch | ScrollGestureKind::MouseControl
4471 ) && !interrupted
4472 && self.start_table_selection_handle(scene, layout, point, touch, true)
4473 {
4474 return true;
4475 }
4476 let popup = (self.menu_open(), self.choice_open());
4477 let scope = self.pointer_scope(layout, point).to_vec();
4478 let hit = self.hit_at(scene, layout, point);
4479 if !popup.0 && !popup.1 && matches!(hit, Hit::StackSlide) {
4480 return false;
4481 }
4482 if kind == ScrollGestureKind::MouseControl
4483 && !popup.0
4484 && !popup.1
4485 && let Hit::Target(target) = &hit
4486 && split_target(target, scene, layout).is_some()
4487 {
4488 return false;
4489 }
4490 let tumbler = match &hit {
4491 Hit::Target(target) | Hit::ControlPart(target, _) if !popup.0 && !popup.1 => scene
4492 .at_path(&target.path)
4493 .zip(layout.at_path(&target.path))
4494 .and_then(|(node, item)| {
4495 matches!(node.kind, "Tumbler" | "PathView").then_some(())?;
4496 TumblerDrag::new(target.clone(), node, item, item.map_from_window(point)?)
4497 }),
4498 _ => None,
4499 };
4500 if kind == ScrollGestureKind::MouseTumbler && tumbler.is_none() {
4501 return false;
4502 }
4503 let tab_move = match &hit {
4504 Hit::Target(target)
4505 if popup == (false, false)
4506 && matches!(
4507 kind,
4508 ScrollGestureKind::Touch | ScrollGestureKind::MouseControl
4509 ) =>
4510 {
4511 TabDrag::new(target, scene, layout, point)
4512 }
4513 _ => None,
4514 };
4515 let switch = match &hit {
4516 Hit::Target(target)
4517 if popup == (false, false)
4518 && matches!(
4519 kind,
4520 ScrollGestureKind::Touch | ScrollGestureKind::MouseControl
4521 ) =>
4522 {
4523 scene
4524 .at_path(&target.path)
4525 .zip(layout.at_path(&target.path))
4526 .and_then(|(node, item)| SwitchDrag::new(target.clone(), node, item, point))
4527 }
4528 _ => None,
4529 };
4530 let swipe_delegate = match &hit {
4531 Hit::Target(target)
4532 if !popup.0 && !popup.1 && kind != ScrollGestureKind::MouseTumbler =>
4533 {
4534 scene
4535 .at_path(&target.path)
4536 .zip(layout.at_path(&target.path))
4537 .and_then(|(node, item)| {
4538 SwipeDrag::new(target.clone(), node, item, item.map_from_window(point)?)
4539 })
4540 }
4541 _ => None,
4542 };
4543 let table_gesture = match &hit {
4544 Hit::Target(target)
4545 if !interrupted
4546 && popup == (false, false)
4547 && matches!(
4548 kind,
4549 ScrollGestureKind::Touch | ScrollGestureKind::MouseControl
4550 ) =>
4551 {
4552 self.table_gesture_at(scene, layout, target, point, touch, now, additive)
4553 }
4554 _ => None,
4555 };
4556 let swipe = (!popup.0
4557 && !popup.1
4558 && tumbler.is_none()
4559 && tab_move.is_none()
4560 && swipe_delegate.is_none()
4561 && table_gesture
4562 .as_ref()
4563 .is_none_or(|hold| touch && hold.deadline.is_some())
4564 && matches!(
4565 kind,
4566 ScrollGestureKind::Touch | ScrollGestureKind::MouseControl
4567 ))
4568 .then(|| self.swipe_route(scene, layout, point, &hit))
4569 .flatten();
4570 if kind == ScrollGestureKind::MouseControl
4571 && tumbler.is_none()
4572 && tab_move.is_none()
4573 && switch.is_none()
4574 && swipe_delegate.is_none()
4575 && swipe.is_none()
4576 && table_gesture.is_none()
4577 {
4578 return false;
4579 }
4580 let left_mouse_pan =
4581 kind == ScrollGestureKind::MouseControl && (swipe.is_some() || table_gesture.is_some());
4582 let pan_device = match kind {
4583 ScrollGestureKind::Touch => PanDevice::Touch,
4584 ScrollGestureKind::MouseControl if left_mouse_pan => PanDevice::LeftMouse,
4585 _ => PanDevice::MiddleMouse,
4586 };
4587 let pages = if popup.0 || popup.1 || left_mouse_pan {
4588 Vec::new()
4589 } else {
4590 Self::page_swipes(scene, layout, point, &scope, &hit)
4591 };
4592 let drawer =
4593 if popup.0 || popup.1 || left_mouse_pan || self.popup_at(layout, point).is_some() {
4594 None
4595 } else {
4596 self.drawer_swipe(scene, layout, point)
4597 };
4598 let axes = [Orientation::Horizontal, Orientation::Vertical].map(|orientation| {
4599 if popup.0 || popup.1 {
4600 return None;
4601 }
4602 let path = Self::scroll_path(layout, point, &scope, |_, item| {
4603 item.accepts_pan(orientation, pan_device)
4604 && item
4605 .scroll_on(orientation)
4606 .is_some_and(|scroll| scroll.max_offset > 0.0)
4607 })?;
4608 let row_key = scene.row_key_at(&path);
4609 let id = ElementId::of(scene.at_path(&path)?);
4610 Some(ScrollTarget {
4611 path,
4612 orientation,
4613 row_key,
4614 id,
4615 })
4616 });
4617 if kind == ScrollGestureKind::MousePan
4618 && drawer.is_none()
4619 && pages.is_empty()
4620 && tumbler.is_none()
4621 && tab_move.is_none()
4622 && swipe_delegate.is_none()
4623 && axes.iter().all(Option::is_none)
4624 {
4625 return false;
4626 }
4627 let delay_target = match &hit {
4628 Hit::Target(target) if kind == ScrollGestureKind::Touch && !popup.0 && !popup.1 => {
4629 scene
4630 .at_path(&target.path)
4631 .filter(|node| node.kind == "DelayButton" && !node.boolean("checked", false))
4632 .map(|_| target.clone())
4633 }
4634 _ => None,
4635 };
4636 let repeat_target = match &hit {
4637 Hit::Target(target)
4638 if kind == ScrollGestureKind::Touch && !interrupted && popup == (false, false) =>
4639 {
4640 Some(target.clone())
4641 }
4642 _ => None,
4643 };
4644 let tap = (kind != ScrollGestureKind::MousePan && !interrupted).then_some(hit);
4645 let overscroll = if drawer.is_none()
4646 && pages.is_empty()
4647 && tumbler.is_none()
4648 && tab_move.is_none()
4649 && switch.is_none()
4650 && swipe_delegate.is_none()
4651 && swipe.is_none()
4652 {
4653 self.take_drag_overscroll(layout, &axes, scope.len(), pan_device)
4654 } else {
4655 Overscroll::default()
4656 };
4657 self.cancel_press();
4658 self.overscroll = overscroll;
4659 self.pointer_leave();
4660 let delay_touch = delay_target.is_some_and(|target| {
4661 self.set_focus(Some(target.clone()));
4662 self.begin_delay(scene, layout, target, DelaySource::Touch(point), now)
4663 });
4664 if let Some(target) = repeat_target {
4665 self.begin_button_hold(scene, layout, target, DelaySource::Touch(point), now);
4666 }
4667 if let Some(Hit::Target(target)) = &tap {
4668 self.start_button_contact(scene, target.clone(), ButtonContactSource::Gesture);
4669 }
4670 self.scroll_gesture = Some(ScrollGesture {
4671 route: ScrollRoute {
4672 scope_row: scene.row_key_at(&scope),
4673 scope_id: scene.at_path(&scope).and_then(ElementId::of),
4674 scope,
4675 axes,
4676 mouse_viewport: false,
4677 pan_device,
4678 },
4679 motion: DragMotion::new(point, now),
4680 tap,
4681 touch_point: (kind == ScrollGestureKind::Touch).then_some(point),
4682 popup,
4683 drawer,
4684 pages,
4685 tumbler,
4686 tab_move,
4687 switch,
4688 swipe_delegate,
4689 swipe,
4690 delay_touch,
4691 table_gesture,
4692 });
4693 true
4694 }
4695
4696 fn swipe_route(
4697 &self,
4698 scene: &Node,
4699 layout: &LayoutNode,
4700 point: Point,
4701 hit: &Hit,
4702 ) -> Option<SwipeRoute> {
4703 match hit {
4704 Hit::Target(target)
4705 if scene.at_path(&target.path).is_some_and(|node| {
4706 is_text_input(node.kind)
4707 || is_spin_box(node.kind)
4708 || combo_editable(node)
4709 || matches!(
4710 node.kind,
4711 "Slider"
4712 | "ColorPlane"
4713 | "RangeThumb"
4714 | "RangeSlider"
4715 | "Dial"
4716 | "SplitHandle"
4717 | "DelayButton"
4718 | "TableCell"
4719 | "TreeCell"
4720 | "ComboBox"
4721 )
4722 }) =>
4723 {
4724 return None;
4725 }
4726 Hit::Target(_) | Hit::None | Hit::Blocked(_) => {}
4727 _ => return None,
4728 }
4729 let (path, scope_len) =
4730 self.gesture_hit_path(scene, layout, point, "SwipeGestureHandler")?;
4731 let targets = (scope_len..=path.len())
4732 .rev()
4733 .filter_map(|depth| SwipeTarget::new(scene, layout, &path[..depth], point))
4734 .collect::<Vec<_>>();
4735 if !targets.is_empty()
4736 && crate::drag::DragSession::arm(self.drag_context(scene, layout, point), point)
4737 .is_some()
4738 {
4739 return None;
4740 }
4741 (!targets.is_empty()).then_some(SwipeRoute::Pending(targets))
4742 }
4743
4744 fn page_swipes(
4745 scene: &Node,
4746 layout: &LayoutNode,
4747 point: Point,
4748 scope: &[usize],
4749 hit: &Hit,
4750 ) -> Vec<PageSwipe> {
4751 let hit_path = match hit {
4752 Hit::Target(target) => &target.path,
4753 Hit::Blocked(path) => path,
4754 _ => return Vec::new(),
4755 };
4756 (scope.len()..=hit_path.len())
4757 .rev()
4758 .filter_map(|depth| {
4759 let path = &hit_path[..depth];
4760 let view = scene.interactive_at_path(path)?;
4761 let item = layout.at_path(path)?;
4762 if view.kind != "SwipeView"
4763 || !view.boolean("interactive", true)
4764 || !item.enabled
4765 || !item.visible
4766 || !(item.contains_subtree_point(point))
4767 {
4768 return None;
4769 }
4770 let current = SwipePagePosition::from_view(view, group_index(view)?)?;
4771 let neighbor = |forward| {
4772 let index = swipe_neighbor(view, current.index, forward)?;
4773 SwipePagePosition::from_view(view, index)
4774 };
4775 let previous = neighbor(false);
4776 let next = neighbor(true);
4777 let orientation = view.orientation();
4778 let extent = match orientation {
4779 Orientation::Horizontal => item.bounds.width,
4780 Orientation::Vertical => item.bounds.height,
4781 };
4782 (previous.is_some() || next.is_some()).then(|| PageSwipe {
4783 target: ScrollTarget {
4784 path: path.to_vec(),
4785 row_key: scene.row_key_at(path),
4786 orientation,
4787 id: ElementId::of(view),
4788 },
4789 current,
4790 previous,
4791 next,
4792 mirrored: swipe_view_mirrored(view, item),
4793 start: item.map_from_window(point).unwrap_or(point),
4794 bounds: item.bounds,
4795 threshold: (extent * 0.15).clamp(24.0, 96.0),
4796 })
4797 })
4798 .collect()
4799 }
4800
4801 fn page_scroll_can_move(
4802 &self,
4803 scene: &Node,
4804 layout: &LayoutNode,
4805 route: &ScrollRoute,
4806 page: &PageSwipe,
4807 forward: bool,
4808 ) -> bool {
4809 let (axis, offsets) = match page.target.orientation {
4810 Orientation::Horizontal => (0, &self.horizontal_scroll_offsets),
4811 Orientation::Vertical => (1, &self.scroll_offsets),
4812 };
4813 let Some(target) = &route.axes[axis] else {
4814 return false;
4815 };
4816 if !target.path.starts_with(&page.target.path) || target.resolve(scene, layout).is_none() {
4817 return false;
4818 }
4819 (page.target.path.len() + 1..=target.path.len()).any(|depth| {
4820 let path = &target.path[..depth];
4821 layout.at_path(path).is_some_and(|item| {
4822 item.scroll_on(target.orientation).is_some_and(|scroll| {
4823 let offset = pending_scroll_offset(item, offsets, path, target.orientation)
4824 .unwrap_or(scroll.offset)
4825 .clamp(0.0, scroll.max_offset);
4826 if forward != item.scroll_axis_reversed(target.orientation) {
4827 offset < scroll.max_offset
4828 } else {
4829 offset > 0.0
4830 }
4831 })
4832 })
4833 })
4834 }
4835
4836 fn drawer_swipe(&self, scene: &Node, layout: &LayoutNode, point: Point) -> Option<DrawerSwipe> {
4837 let active = self.active_dialog(layout);
4838 let viewport = layout.bounds;
4839 layout
4840 .drawer_paths()
4841 .iter()
4842 .rev()
4843 .filter_map(|path| {
4844 let node = scene.control_target(path, ControlAction::Drawer(true))?;
4845 let open = node.boolean("open", false);
4846 let panel = if open {
4847 if active != Some(path.as_slice()) {
4848 return None;
4849 }
4850 layout.at_path(path)?.bounds
4851 } else {
4852 if active.is_some() {
4853 return None;
4854 }
4855 modal::drawer_bounds(node, viewport)
4856 };
4857 let edge = node.drawer_edge();
4858 let region = if open { panel } else { viewport };
4859 let span = modal::drawer_extent(edge, panel);
4860 let margin = modal::drawer_margin(node, panel);
4861 let activation_edge = if open { modal::opposite(edge) } else { edge };
4862 let distance = modal::drawer_edge_distance(activation_edge, region, point);
4863 (region.contains(point) && distance < margin).then(|| {
4864 (
4865 distance,
4866 DrawerSwipe {
4867 path: path.clone(),
4868 row_key: scene.row_key_at(path),
4869 id: ElementId::of(node),
4870 edge,
4871 open,
4872 start: point,
4873 threshold: (span * 0.2).clamp(20.0, 80.0),
4874 },
4875 )
4876 })
4877 })
4878 .min_by(|(a, _), (b, _)| a.total_cmp(b))
4879 .map(|(_, swipe)| swipe)
4880 }
4881
4882 fn scroll_route_is_current(
4883 &self,
4884 scene: &Node,
4885 layout: &LayoutNode,
4886 route: &ScrollRoute,
4887 ) -> bool {
4888 (self.active_dialog(layout).unwrap_or_default() == route.scope
4889 || self.popups(layout).any(|path| path == route.scope))
4890 && scene.row_key_at(&route.scope) == route.scope_row
4891 && scene.at_path(&route.scope).and_then(Node::element_id)
4892 == route.scope_id.as_ref().map(ElementId::as_str)
4893 && (!route.mouse_viewport
4894 || route.axes.iter().flatten().any(|target| {
4895 target.resolve(scene, layout).is_some_and(|(_, item)| {
4896 item.accepts_pan(target.orientation, PanDevice::LeftMouse)
4897 })
4898 }))
4899 }
4900
4901 fn scroll_captured(
4902 &mut self,
4903 scene: &Node,
4904 layout: &LayoutNode,
4905 route: &ScrollRoute,
4906 delta: Point,
4907 flicking: bool,
4908 ) -> ([AxisMotion; 2], MotionOwners) {
4909 let mut owners = MotionOwners::new();
4910 if !self.scroll_route_is_current(scene, layout, route) {
4911 return ([AxisMotion::default(); 2], owners);
4912 }
4913 let moved = std::array::from_fn(|index| {
4914 let Some(target) = &route.axes[index] else {
4915 return AxisMotion::default();
4916 };
4917 if flicking && self.overscroll.owns_axis(target.orientation) {
4918 return AxisMotion::default();
4919 }
4920 let Some((_, item)) = target.resolve(scene, layout) else {
4921 return AxisMotion::default();
4922 };
4923 let Some(delta) = item.map_delta_from_window(delta) else {
4924 return AxisMotion::default();
4925 };
4926 let movement = [delta.x, delta.y][index];
4927 if movement == 0.0 {
4928 return AxisMotion::default();
4929 }
4930 let path = &target.path;
4931 self.consume_scroll(
4932 layout,
4933 path,
4934 route.scope.len(),
4935 movement,
4936 target.orientation,
4937 ScrollInput::Pan {
4938 device: route.pan_device,
4939 owners: &mut owners,
4940 flicking,
4941 },
4942 )
4943 });
4944 (moved, owners)
4945 }
4946
4947 fn take_drag_overscroll(
4948 &mut self,
4949 layout: &LayoutNode,
4950 axes: &[Option<ScrollTarget>; 2],
4951 scope_len: usize,
4952 device: PanDevice,
4953 ) -> Overscroll {
4954 let mut overscroll = std::mem::take(&mut self.overscroll);
4955 overscroll.resume_drag(|axis, handle| {
4956 let Some(target) = &axes[usize::from(axis == Orientation::Vertical)] else {
4957 return false;
4958 };
4959 (scope_len..=target.path.len()).rev().any(|depth| {
4960 layout.at_path(&target.path[..depth]).is_some_and(|item| {
4961 item.visible
4962 && item.enabled
4963 && item.accepts_pan(axis, device)
4964 && item.viewport_handle.as_ref() == Some(handle)
4965 && item
4966 .elastic
4967 .is_some_and(|options| options.behavior.allows_overshoot(false))
4968 })
4969 })
4970 });
4971 overscroll
4972 }
4973
4974 pub fn move_scroll_gesture(
4975 &mut self,
4976 scene: &Node,
4977 layout: &LayoutNode,
4978 point: Point,
4979 now: Instant,
4980 ) -> bool {
4981 if !point.x.is_finite() || !point.y.is_finite() {
4982 return false;
4983 }
4984 let claimed = self.advance_table_touch_hold(scene, layout, now);
4985 let wake = self
4986 .table_row_move
4987 .as_mut()
4988 .filter(|drag| drag.touch)
4989 .map(|drag| &mut drag.scroll_wake)
4990 .or_else(|| {
4991 self.table_drag_selection
4992 .as_mut()
4993 .filter(|drag| drag.scroll_capture)
4994 .map(|drag| &mut drag.scroll_wake)
4995 });
4996 if let Some(wake) = wake {
4997 if self.pointer == Some(point) {
4998 return claimed;
4999 }
5000 self.pointer = Some(point);
5001 wake.get_or_insert(now + SCROLL_FRAME_INTERVAL);
5002 return true;
5003 }
5004 let Some(mut gesture) = self.scroll_gesture.take() else {
5005 return false;
5006 };
5007 if gesture.touch_point.is_some() {
5008 gesture.touch_point = Some(point);
5009 }
5010 if !self.scroll_route_is_current(scene, layout, &gesture.route)
5011 || gesture.popup != (self.menu_open(), self.choice_open())
5012 {
5013 self.viewport_motion.clear();
5014 let cleared = self.overscroll.clear() | self.swipe_page_motion.take().is_some();
5015 self.swipe_events
5016 .extend(gesture.swipe.take().and_then(SwipeRoute::cancel));
5017 self.cancel_touch_delay();
5018 self.cancel_touch_button_hold();
5019 let tumbler_cleared = gesture.tumbler.is_some_and(|mut drag| drag.cancel());
5020 return cleared
5021 || tumbler_cleared
5022 || (gesture.motion.dragging && gesture.tab_move.is_some())
5023 || gesture.switch.is_some_and(|drag| drag.position.is_some())
5024 || gesture
5025 .swipe_delegate
5026 .is_some_and(|drag| drag.has_preview());
5027 }
5028 if gesture.delay_touch
5029 && let Some(hold) = &mut self.delay_hold
5030 && matches!(hold.source, DelaySource::Touch(_))
5031 {
5032 hold.source = DelaySource::Touch(point);
5033 if !layout
5034 .at_path(&hold.target.path)
5035 .is_some_and(|item| item.contains_subtree_point(point))
5036 {
5037 self.cancel_delay();
5038 }
5039 }
5040 if let Some(repeat) = &mut self.button_hold
5041 && matches!(repeat.source, DelaySource::Touch(_))
5042 {
5043 repeat.source = DelaySource::Touch(point);
5044 if repeat.moved_too_far(point)
5045 || !layout
5046 .at_path(&repeat.target.path)
5047 .is_some_and(|item| item.contains_subtree_point(point))
5048 {
5049 self.cancel_touch_button_hold();
5050 }
5051 }
5052 let was_dragging = gesture.motion.dragging;
5053 if gesture.route.mouse_viewport && !was_dragging {
5054 let delta = gesture.motion.delta_to(point);
5055 let [x, y] = gesture.route.axes.each_ref().map(|target| {
5056 let Some(target) = target else {
5057 return 0.0;
5058 };
5059 let Some((_, item)) = target.resolve(scene, layout) else {
5060 return 0.0;
5061 };
5062 if !item.accepts_pan(target.orientation, PanDevice::LeftMouse) {
5063 return 0.0;
5064 }
5065 item.map_delta_from_window(delta)
5066 .map_or(0.0, |local| match target.orientation {
5067 Orientation::Horizontal => local.x,
5068 Orientation::Vertical => local.y,
5069 })
5070 });
5071 if x.hypot(y) < DRAG_THRESHOLD {
5072 self.scroll_gesture = Some(gesture);
5073 return false;
5074 }
5075 }
5076 let elastic_frame = self.overscroll.frame();
5077 let scrolled = gesture.motion.update(point, now).is_some_and(|delta| {
5078 let table_gesture = gesture.table_gesture.take();
5079 self.finish_button_contact(ButtonContactSource::Gesture, false);
5080 self.cancel_touch_button_hold();
5081 if let Some(hold) = table_gesture.filter(|hold| hold.deadline.is_none())
5082 && let PendingTableAction::Select(mut drag) = hold.drag
5083 {
5084 drag.claimed = true;
5085 drag.touch = true;
5086 drag.scroll_capture = true;
5087 if self.table_drag_route(scene, layout, &drag, point).is_some() {
5088 self.cancel_touch_delay();
5089 self.overscroll.clear();
5090 self.viewport_motion.clear();
5091 self.capture_table_selection(drag);
5092 self.pointer = Some(point);
5093 return self.move_table_drag_selection(layout, now);
5094 }
5095 }
5096 if gesture.route.mouse_viewport && !was_dragging {
5097 let overscroll = self.take_drag_overscroll(
5098 layout,
5099 &gesture.route.axes,
5100 gesture.route.scope.len(),
5101 gesture.route.pan_device,
5102 );
5103 self.cancel_press();
5104 self.overscroll = overscroll;
5105 self.pointer_leave();
5106 }
5107 if gesture.delay_touch {
5108 self.cancel_touch_delay();
5109 }
5110 if let Some(drag) = &mut gesture.tab_move {
5111 if was_dragging || drag.accepts_direction(scene, layout, point) {
5112 return drag.update(scene, layout, point, now);
5113 }
5114 gesture.tab_move = None;
5115 }
5116 if let Some(drag) = &mut gesture.tumbler {
5117 if let Some(local) = layout
5118 .at_path(&drag.target.path)
5119 .and_then(|item| item.map_from_window(point))
5120 && (was_dragging || drag.accepts_direction(local))
5121 {
5122 return drag.update(scene, layout, local);
5123 }
5124 gesture.tumbler = None;
5125 }
5126 if let Some(drag) = &mut gesture.switch {
5127 if was_dragging || drag.accepts_direction(layout, point) {
5128 return drag.move_thumb(scene, layout, point);
5129 }
5130 gesture.switch = None;
5131 }
5132 if !was_dragging && let Some(swipe) = &gesture.drawer {
5133 let (distance, across) = swipe.movement(point);
5134 if distance <= across {
5135 gesture.drawer = None;
5136 }
5137 }
5138 if gesture.drawer.is_some() {
5139 gesture.swipe_delegate = None;
5140 return false;
5141 }
5142 if !was_dragging
5143 && gesture.swipe_delegate.as_ref().is_some_and(|swipe| {
5144 layout
5145 .at_path(&swipe.target.path)
5146 .and_then(|item| item.map_from_window(point))
5147 .is_none_or(|local| !swipe.accepts_direction(local))
5148 })
5149 {
5150 gesture.swipe_delegate = None;
5151 }
5152 if let Some(swipe) = &mut gesture.swipe_delegate {
5153 return layout
5154 .at_path(&swipe.target.path)
5155 .and_then(|item| item.map_from_window(point))
5156 .is_some_and(|local| swipe.update(scene, layout, local));
5157 }
5158 if self.move_custom_swipe(scene, layout, &mut gesture.swipe, point) {
5159 return false;
5160 }
5161 if !was_dragging {
5162 let selected = gesture.pages.iter().position(|page| {
5163 let Some(local) = layout
5164 .at_path(&page.target.path)
5165 .and_then(|item| item.map_from_window(point))
5166 else {
5167 return false;
5168 };
5169 let (distance, across) = page.movement(local);
5170 let forward = distance > 0.0;
5171 distance.abs() > across
5172 && page.destination(forward).is_some()
5173 && !self.page_scroll_can_move(scene, layout, &gesture.route, page, forward)
5174 });
5175 if let Some(index) = selected {
5176 gesture.pages.swap(0, index);
5177 gesture.pages.truncate(1);
5178 } else {
5179 gesture.pages.clear();
5180 }
5181 }
5182 if let Some(page) = gesture.pages.first() {
5183 return self.update_swipe_page_motion(page, scene, layout, point);
5184 }
5185 let (moved, owners) = self.scroll_captured(scene, layout, &gesture.route, delta, false);
5186 if moved.into_iter().any(AxisMotion::changed) {
5187 self.viewport_motion
5188 .update(owners, ViewportMotion::Dragging);
5189 true
5190 } else {
5191 false
5192 }
5193 });
5194 if !self.scroll_table_selection_claimed() {
5195 self.scroll_gesture = Some(gesture);
5196 }
5197 scrolled || elastic_frame != self.overscroll.frame()
5198 }
5199
5200 fn update_swipe_page_motion(
5201 &mut self,
5202 page: &PageSwipe,
5203 scene: &Node,
5204 layout: &LayoutNode,
5205 point: Point,
5206 ) -> bool {
5207 let preview = (|| {
5208 let (view, item) = page.view(scene, layout)?;
5209 let duration = Duration::from_millis(view.int("transition-duration")?.max(0) as u64);
5210 if duration.is_zero() {
5211 return None;
5212 }
5213 let handle = &view.swipe_preview.as_ref()?.handle;
5214 let (distance, _) = page.movement(item.map_from_window(point)?);
5215 let extent = match page.target.orientation {
5216 Orientation::Horizontal => item.bounds.width,
5217 Orientation::Vertical => item.bounds.height,
5218 };
5219 if extent <= 0.0 || distance == 0.0 {
5220 return None;
5221 }
5222 let destination = page.live_destination(view, distance > 0.0)?;
5223 Some((
5224 handle,
5225 destination,
5226 (distance / extent).clamp(-1.0, 1.0),
5227 duration,
5228 ))
5229 })();
5230 let Some((handle, destination, fraction, duration)) = preview else {
5231 return self.swipe_page_motion.take().is_some();
5232 };
5233 if self
5234 .swipe_page_motion
5235 .as_ref()
5236 .is_some_and(|motion| motion.lease.0 != *handle)
5237 {
5238 self.swipe_page_motion = None;
5239 }
5240 let motion = self
5241 .swipe_page_motion
5242 .get_or_insert_with(|| SwipePageMotion {
5243 page: page.clone(),
5244 lease: Rc::new(SwipePreviewLease(handle.clone())),
5245 fraction: 0.0,
5246 duration,
5247 settling: None,
5248 wake: None,
5249 });
5250 let changed = motion.fraction != fraction || motion.settling.is_some();
5251 motion.page = page.clone();
5252 motion.fraction = fraction;
5253 motion.duration = duration;
5254 motion.settling = None;
5255 motion.wake = None;
5256 handle.request(
5257 (page.current.index, page.current.identity.clone()),
5258 (destination.index, destination.identity.clone()),
5259 );
5260 changed
5261 }
5262
5263 #[doc(hidden)]
5264 pub fn swipe_page_motion(&self, path: &[usize]) -> Option<(usize, f32, Orientation)> {
5265 let motion = self.swipe_page_motion.as_ref()?;
5266 (motion.page.target.path == path).then_some(())?;
5267 let to = motion.page.destination(motion.fraction > 0.0)?;
5268 Some((to.index, motion.fraction, motion.page.target.orientation))
5269 }
5270
5271 pub(crate) fn swipe_commit_fraction(&self, path: &[usize], old: &Node, new: &Node) -> f32 {
5272 let Some((page, fraction)) = &self.swipe_commit else {
5273 return 0.0;
5274 };
5275 let Some((slot, _)) = old
5276 .swipe_preview
5277 .as_ref()
5278 .and_then(|preview| preview.page.as_ref())
5279 else {
5280 return 0.0;
5281 };
5282 if page.target.path != path
5283 || group_index(old) != Some(page.current.index)
5284 || !page.current.matches(old)
5285 {
5286 return 0.0;
5287 }
5288 page.destination(*fraction > 0.0)
5289 .filter(|to| to.index == *slot && group_index(new) == Some(to.index) && to.matches(new))
5290 .map_or(0.0, |_| *fraction)
5291 }
5292
5293 fn move_custom_swipe(
5294 &mut self,
5295 scene: &Node,
5296 layout: &LayoutNode,
5297 swipe: &mut Option<SwipeRoute>,
5298 point: Point,
5299 ) -> bool {
5300 if matches!(swipe, Some(SwipeRoute::Pending(_)))
5301 && let Some(SwipeRoute::Pending(targets)) = swipe.take()
5302 {
5303 *swipe = targets
5304 .into_iter()
5305 .find(|target| target.accepts(scene, layout, self, point))
5306 .map(SwipeRoute::Captured);
5307 }
5308 match swipe {
5309 Some(SwipeRoute::Captured(target))
5310 if target.is_live(scene, layout, self) && !target.cancel_requested() =>
5311 {
5312 self.swipe_events.extend(target.update(point));
5313 true
5314 }
5315 Some(SwipeRoute::Captured(_)) => {
5316 self.swipe_events.extend(
5317 swipe
5318 .replace(SwipeRoute::Cancelled)
5319 .and_then(SwipeRoute::cancel),
5320 );
5321 true
5322 }
5323 Some(SwipeRoute::Cancelled) => true,
5324 _ => false,
5325 }
5326 }
5327
5328 pub fn end_scroll_gesture(
5329 &mut self,
5330 scene: &Node,
5331 layout: &LayoutNode,
5332 point: Point,
5333 now: Instant,
5334 ) -> ScrollGestureEnd {
5335 self.cancel_touch_button_hold();
5336 if !point.x.is_finite() || !point.y.is_finite() {
5337 self.cancel_scroll_gesture();
5338 self.cancel_scroll_table_drag();
5339 return ScrollGestureEnd::default();
5340 }
5341 let scrolled = self.move_scroll_gesture(scene, layout, point, now);
5342 if self.scroll_table_drag_claimed() {
5343 let touch = self.touch_table_drag_claimed();
5344 let control = if self.scroll_table_selection_claimed() {
5345 self.finish_table_drag_selection(scene, layout)
5346 } else {
5347 self.finish_table_row_move(scene, layout)
5348 };
5349 if touch {
5350 self.pointer_leave();
5351 }
5352 return ScrollGestureEnd {
5353 control,
5354 ..ScrollGestureEnd::default()
5355 };
5356 }
5357 let Some(gesture) = self.scroll_gesture.take() else {
5358 return ScrollGestureEnd {
5359 scrolled,
5360 ..ScrollGestureEnd::default()
5361 };
5362 };
5363 let inside = !gesture.motion.dragging
5364 && gesture
5365 .tap
5366 .is_some_and(|hit| hit == self.hit_at(scene, layout, point));
5367 self.finish_button_contact(ButtonContactSource::Gesture, inside);
5368 let tap = inside && !gesture.delay_touch;
5369 match gesture.swipe {
5370 Some(SwipeRoute::Captured(target)) => {
5371 self.swipe_events.push(target.delivery(SwipePhase::Swiped));
5372 return ScrollGestureEnd::default();
5373 }
5374 Some(SwipeRoute::Cancelled) => return ScrollGestureEnd::default(),
5375 _ => {}
5376 }
5377 if gesture.delay_touch && !gesture.motion.dragging {
5378 self.cancel_touch_delay();
5379 return ScrollGestureEnd {
5380 tap: false,
5381 scrolled,
5382 control: None,
5383 };
5384 }
5385 if let Some(drag) = gesture.tab_move {
5386 let control = gesture
5387 .motion
5388 .dragging
5389 .then(|| drag.finish(scene, layout))
5390 .flatten();
5391 return ScrollGestureEnd {
5392 tap,
5393 scrolled: scrolled || gesture.motion.dragging,
5394 control,
5395 };
5396 }
5397 if let Some(mut drag) = gesture.tumbler {
5398 if !gesture.motion.dragging {
5399 return ScrollGestureEnd {
5400 tap,
5401 scrolled,
5402 control: None,
5403 };
5404 }
5405 let target = drag.target.clone();
5406 let velocity = gesture.motion.measured_release_velocity(now);
5407 match drag.settle(scene, layout, velocity, now) {
5408 Ok(flick) => {
5409 self.set_focus(Some(target));
5410 self.tumbler_flick = Some(flick);
5411 return ScrollGestureEnd {
5412 scrolled: true,
5413 ..ScrollGestureEnd::default()
5414 };
5415 }
5416 Err(fallback) => drag = fallback,
5417 }
5418 let control = drag.finish(scene, layout);
5419 if control.is_some() {
5420 self.set_focus(Some(target));
5421 }
5422 return ScrollGestureEnd {
5423 tap,
5424 scrolled: true,
5425 control,
5426 };
5427 }
5428 if let Some(drag) = gesture.switch {
5429 let control = drag.finish(scene, layout);
5430 if control.is_some() {
5431 self.set_focus(Some(drag.target));
5432 }
5433 return ScrollGestureEnd {
5434 tap,
5435 scrolled: scrolled || drag.position.is_some(),
5436 control,
5437 };
5438 }
5439 if let Some(swipe) = gesture.drawer {
5440 let control = gesture
5441 .motion
5442 .dragging
5443 .then(|| swipe.action(scene, layout, point))
5444 .flatten();
5445 return ScrollGestureEnd {
5446 tap,
5447 scrolled,
5448 control,
5449 };
5450 }
5451 if let Some(swipe) = gesture.swipe_delegate {
5452 let control = swipe.finish(scene, layout);
5453 if control.is_some() {
5454 self.set_focus(Some(swipe.target.clone()));
5455 }
5456 return ScrollGestureEnd {
5457 tap,
5458 scrolled: scrolled || swipe.has_preview(),
5459 control,
5460 };
5461 }
5462 if gesture.motion.dragging
5463 && let Some(page) = gesture.pages.into_iter().next()
5464 {
5465 let control = page.action(
5466 scene,
5467 layout,
5468 point,
5469 gesture.motion.measured_release_velocities(now),
5470 );
5471 if let Some(motion) = &mut self.swipe_page_motion {
5472 if control.is_some() {
5473 self.swipe_commit = Some((motion.page.clone(), motion.fraction));
5474 }
5475 motion.settle(now);
5476 }
5477 return ScrollGestureEnd {
5478 tap,
5479 scrolled,
5480 control,
5481 };
5482 }
5483 let transformed = gesture.route.axes.iter().flatten().any(|target| {
5484 layout
5485 .at_path(&target.path)
5486 .is_some_and(|item| item.world_transform() != crate::Affine::IDENTITY)
5487 });
5488 let mut axes = if transformed {
5489 [true, true]
5490 } else {
5491 gesture.route.axes.each_ref().map(|axis| {
5492 axis.as_ref()
5493 .is_some_and(|target| target.resolve(scene, layout).is_some())
5494 })
5495 };
5496 let elastic_axes = [Orientation::Horizontal, Orientation::Vertical]
5497 .map(|axis| self.overscroll.owns_axis(axis));
5498 if transformed && elastic_axes.contains(&true) {
5499 axes = [false; 2];
5500 } else {
5501 for (axis, elastic) in axes.iter_mut().zip(elastic_axes) {
5502 *axis &= !elastic;
5503 }
5504 }
5505 let rebounded = self.overscroll.return_to_bounds(now, None);
5506 self.scroll_fling = gesture.motion.finish(now, axes).map(|motion| ScrollFling {
5507 route: gesture.route,
5508 motion,
5509 transformed,
5510 });
5511 if self.scroll_fling.is_some() {
5512 if !transformed {
5513 self.viewport_motion.retain_axes(axes);
5514 }
5515 self.viewport_motion.set_phase(ViewportMotion::Flicking);
5516 } else {
5517 self.viewport_motion.clear();
5518 }
5519 ScrollGestureEnd {
5520 tap,
5521 scrolled: scrolled || rebounded,
5522 control: None,
5523 }
5524 }
5525
5526 pub fn advance_scroll_motion(
5527 &mut self,
5528 scene: &Node,
5529 layout: &LayoutNode,
5530 now: Instant,
5531 ) -> bool {
5532 let rebounded = self.overscroll.advance(now);
5533 let tab_scroll = self.advance_tab_drag_scroll(scene, layout, now);
5534 let swipe_scroll = self
5535 .swipe_page_motion
5536 .as_mut()
5537 .is_some_and(|motion| motion.advance(now));
5538 if swipe_scroll
5539 && self
5540 .swipe_page_motion
5541 .as_ref()
5542 .is_some_and(|motion| motion.wake.is_none())
5543 {
5544 self.swipe_page_motion = None;
5545 self.swipe_commit = None;
5546 }
5547 self.advance_flick(scene, layout, now) || rebounded || tab_scroll || swipe_scroll
5548 }
5549
5550 fn advance_tab_drag_scroll(&mut self, scene: &Node, layout: &LayoutNode, now: Instant) -> bool {
5551 let Some(drag) = self
5552 .scroll_gesture
5553 .as_mut()
5554 .and_then(|gesture| gesture.tab_move.as_mut())
5555 else {
5556 return false;
5557 };
5558 if !drag.wake.is_some_and(|deadline| deadline <= now) {
5559 return false;
5560 }
5561 let Some((axis, offset)) = drag.scroll_target(scene, layout) else {
5562 drag.wake = None;
5563 return false;
5564 };
5565 drag.wake = Some(now + SCROLL_FRAME_INTERVAL);
5566 let offsets = match axis {
5567 Orientation::Horizontal => &mut self.horizontal_scroll_offsets,
5568 Orientation::Vertical => &mut self.scroll_offsets,
5569 };
5570 offsets.insert(drag.path().to_vec(), offset);
5571 true
5572 }
5573
5574 pub fn tab_move_active(&self) -> bool {
5575 self.scroll_gesture
5576 .as_ref()
5577 .is_some_and(|gesture| gesture.motion.dragging && gesture.tab_move.is_some())
5578 }
5579
5580 pub fn tab_move_marker(&self, bar: &Node, item: &LayoutNode, path: &[usize]) -> Option<Rect> {
5581 let gesture = self.scroll_gesture.as_ref()?;
5582 let drag = gesture.tab_move.as_ref()?;
5583 (gesture.motion.dragging && drag.path() == path).then_some(())?;
5584 drag.marker(bar, item)
5585 }
5586
5587 fn advance_flick(&mut self, scene: &Node, layout: &LayoutNode, now: Instant) -> bool {
5588 let Some(mut fling) = self.scroll_fling.take() else {
5589 return false;
5590 };
5591 if !self.scroll_route_is_current(scene, layout, &fling.route)
5592 || self.menu_open()
5593 || self.choice_open()
5594 {
5595 self.viewport_motion.clear();
5596 return false;
5597 }
5598 let Some(delta) = fling.motion.step(now) else {
5599 self.viewport_motion.clear();
5600 return false;
5601 };
5602 if delta == Point::default() {
5603 self.scroll_fling = Some(fling);
5604 return false;
5605 }
5606 let (moved, mut owners) = self.scroll_captured(scene, layout, &fling.route, delta, true);
5607 self.overscroll.return_to_bounds(now, None);
5608 let continuing = moved.map(|axis| axis.bounded && !axis.elastic);
5609 let axes = if fling.transformed {
5610 [continuing.contains(&true) && !moved.iter().any(|axis| axis.elastic); 2]
5611 } else {
5612 continuing
5613 };
5614 if fling.motion.finish_step(axes) {
5615 self.scroll_fling = Some(fling);
5616 owners.retain_mut(|(_, owner_axes)| {
5617 for (owned, active) in owner_axes.iter_mut().zip(continuing) {
5618 *owned &= active;
5619 }
5620 owner_axes.contains(&true)
5621 });
5622 self.viewport_motion
5623 .update(owners, ViewportMotion::Flicking);
5624 } else {
5625 self.viewport_motion.clear();
5626 }
5627 moved.into_iter().any(AxisMotion::changed)
5628 }
5629
5630 fn interrupt_tumbler_flick(&mut self) -> bool {
5631 self.tumbler_flick
5632 .as_mut()
5633 .is_some_and(TumblerFlick::interrupt)
5634 }
5635
5636 fn tumbler_flick_is_current(
5637 &self,
5638 flick: &TumblerFlick,
5639 scene: &Node,
5640 layout: &LayoutNode,
5641 ) -> bool {
5642 !self.menu_open()
5643 && !self.choice_open()
5644 && self
5645 .active_dialog(layout)
5646 .is_none_or(|scope| flick.drag.target.path.starts_with(scope))
5647 && flick.drag.is_current(scene, layout)
5648 }
5649
5650 pub fn advance_tumbler_motion(
5651 &mut self,
5652 scene: &Node,
5653 layout: &LayoutNode,
5654 now: Instant,
5655 ) -> ScrollGestureEnd {
5656 let Some(mut flick) = self.tumbler_flick.take() else {
5657 return ScrollGestureEnd::default();
5658 };
5659 if !flick.active() || !self.tumbler_flick_is_current(&flick, scene, layout) {
5660 flick.interrupt();
5661 return ScrollGestureEnd {
5662 scrolled: true,
5663 ..ScrollGestureEnd::default()
5664 };
5665 }
5666 if now < flick.wake {
5667 self.tumbler_flick = Some(flick);
5668 return ScrollGestureEnd::default();
5669 }
5670 let control = if flick.advance(now) {
5671 flick.drag.finish(scene, layout)
5672 } else {
5673 self.tumbler_flick = Some(flick);
5674 None
5675 };
5676 ScrollGestureEnd {
5677 scrolled: true,
5678 control,
5679 tap: false,
5680 }
5681 }
5682
5683 pub fn scroll_motion_active(&self) -> bool {
5684 self.scroll_fling.is_some()
5685 || self.overscroll.deadline().is_some()
5686 || self
5687 .swipe_page_motion
5688 .as_ref()
5689 .is_some_and(|motion| motion.wake.is_some())
5690 || self
5691 .tumbler_flick
5692 .as_ref()
5693 .is_some_and(TumblerFlick::active)
5694 }
5695
5696 pub fn scroll_motion_deadline(&self) -> Option<Instant> {
5697 self.scroll_fling
5698 .as_ref()
5699 .map(|fling| fling.motion.deadline())
5700 .into_iter()
5701 .chain(self.overscroll.deadline())
5702 .chain(
5703 self.swipe_page_motion
5704 .as_ref()
5705 .and_then(|motion| motion.wake),
5706 )
5707 .chain(self.tumbler_flick.as_ref().map(|flick| flick.wake))
5708 .chain(
5709 self.scroll_gesture
5710 .as_ref()
5711 .and_then(|gesture| gesture.tab_move.as_ref()?.wake),
5712 )
5713 .min()
5714 }
5715
5716 fn tumbler_drag(&self) -> Option<&TumblerDrag> {
5717 self.scroll_gesture
5718 .as_ref()
5719 .and_then(|gesture| gesture.tumbler.as_ref())
5720 .or_else(|| {
5721 self.tumbler_flick
5722 .as_ref()
5723 .filter(|flick| flick.active())
5724 .map(|flick| &flick.drag)
5725 })
5726 }
5727
5728 pub fn tumbler_preview(&self) -> Option<(&[usize], f32)> {
5729 let drag = self.tumbler_drag()?;
5730 (drag.offset != 0.0).then_some((&drag.target.path, drag.offset))
5731 }
5732
5733 pub fn has_switch_preview(&self) -> bool {
5734 self.scroll_gesture
5735 .as_ref()
5736 .and_then(|gesture| gesture.switch.as_ref())
5737 .is_some_and(|drag| drag.position.is_some())
5738 }
5739
5740 pub(crate) fn contains_switch_preview(&self, path: &[usize]) -> bool {
5741 self.scroll_gesture
5742 .as_ref()
5743 .and_then(|gesture| gesture.switch.as_ref())
5744 .is_some_and(|drag| drag.position.is_some() && drag.target.path.starts_with(path))
5745 }
5746
5747 pub(crate) fn switch_position(
5748 &self,
5749 node: &Node,
5750 bounds: Rect,
5751 direction: LayoutDirection,
5752 path: &[usize],
5753 row: Option<RowKey>,
5754 ) -> Option<f32> {
5755 let drag = self.scroll_gesture.as_ref()?.switch.as_ref()?;
5756 drag.position
5757 .filter(|_| drag.target.path == path && drag.matches(node, bounds, direction, row))
5758 }
5759
5760 pub fn has_swipe_preview(&self) -> bool {
5761 self.swipe_preview().is_some()
5762 }
5763
5764 pub fn swipe_preview(&self) -> Option<(&[usize], Option<RowKey>, f32)> {
5765 self.scroll_gesture
5766 .as_ref()
5767 .and_then(|gesture| gesture.swipe_delegate.as_ref())
5768 .and_then(SwipeDrag::preview_state)
5769 }
5770
5771 pub(crate) fn swipe_preview_offset(
5772 &self,
5773 path: &[usize],
5774 node: &Node,
5775 geometry: &crate::SwipeDelegateGeometry,
5776 row: Option<RowKey>,
5777 ) -> Option<f32> {
5778 self.scroll_gesture
5779 .as_ref()?
5780 .swipe_delegate
5781 .as_ref()?
5782 .preview(path, node, geometry, row)
5783 }
5784
5785 pub(crate) fn tumbler_offset(&self, wheel: &Tumbler<'_>, path: &[usize]) -> f32 {
5786 self.tumbler_drag()
5787 .map_or(0.0, |drag| drag.offset_for(wheel, path))
5788 }
5789
5790 pub fn tumbler_scroll(
5791 &mut self,
5792 scene: &Node,
5793 layout: &LayoutNode,
5794 delta: f32,
5795 lines: bool,
5796 ) -> TumblerScroll {
5797 let target = self.pointer_hover_target(scene, layout);
5798 if let Some(target) = target
5799 && let Some(node) = scene
5800 .at_path(&target.path)
5801 .filter(|node| matches!(node.kind, "Tumbler" | "PathView"))
5802 && let Some(wheel) = layout
5803 .at_path(&target.path)
5804 .and_then(|item| item.tumbler.as_ref())
5805 {
5806 if delta.is_finite() && delta != 0.0 {
5807 self.interrupt_tumbler_flick();
5808 }
5809 return crate::tumbler::scroll(
5810 &mut self.tumbler_wheel,
5811 &target,
5812 &Tumbler::from_node(node),
5813 wheel.step_size(),
5814 delta,
5815 lines,
5816 );
5817 }
5818 self.tumbler_wheel = None;
5819 TumblerScroll::Unhandled
5820 }
5821
5822 pub fn reset_wheel_adjustment(&mut self) {
5823 self.wheel_steps = None;
5824 }
5825
5826 pub fn wheel_adjustment(
5827 &mut self,
5828 scene: &Node,
5829 layout: &LayoutNode,
5830 event: xrack_runtime::WheelEvent,
5831 now: Instant,
5832 ) -> Option<WheelAdjustment> {
5833 let previous = self.wheel_steps.take();
5834 let modifiers = event.modifiers;
5835 if modifiers.shift
5836 || modifiers.control
5837 || modifiers.alt
5838 || modifiers.meta
5839 || self.menu_open()
5840 || self.choice_open()
5841 || self.pressed.is_some()
5842 || !event.delta_x.0.is_finite()
5843 || !event.delta_y.0.is_finite()
5844 {
5845 return None;
5846 }
5847 let point = self.pointer?;
5848 let target = self.pointer_hover_target(scene, layout)?;
5849 let (path, node) = slider_target(&target, scene, layout).or_else(|| {
5850 let node = scene.interactive_at_path(&target.path)?;
5851 valid(&target, scene, layout).then_some((target.path.as_slice(), node))
5852 })?;
5853 if !node.boolean("wheel-enabled", false) {
5854 return None;
5855 }
5856 let horizontal = event.delta_x.0.abs() > event.delta_y.0.abs();
5857 let units = match (horizontal, event.is_line) {
5858 (true, true) => event.lines_x,
5859 (false, true) => -event.lines_y,
5860 (true, false) => event.delta_x.0 / 28.0,
5861 (false, false) => -event.delta_y.0 / 28.0,
5862 };
5863 if !units.is_finite() || units == 0.0 {
5864 return None;
5865 }
5866 let interval = (node.kind == "RangeSlider").then(|| SliderInterval::from_node(node));
5867 let handle = if let Some(interval) = interval {
5868 if target.path.len() > path.len() {
5869 Some(*target.path.last()?)
5870 } else {
5871 let item = layout.at_path(path)?;
5872 let geometry =
5873 SliderGeometry::with_layout_direction(item.bounds, node, item.layout_direction);
5874 let point = item.map_from_window(point)?;
5875 Some(geometry.interval_handle_at(point, geometry.fraction_at(point)?, interval))
5876 }
5877 } else {
5878 None
5879 };
5880 let action_for = |steps| {
5881 if is_spin_box(node.kind) {
5882 if self
5883 .focused
5884 .as_ref()
5885 .is_some_and(|focus| focus.path == path)
5886 && self
5887 .editor
5888 .as_ref()
5889 .is_some_and(|editor| !editor.preedit.is_empty())
5890 {
5891 return None;
5892 }
5893 let action = SpinAction::Step(steps);
5894 if node.kind == "DoubleSpinBox" {
5895 xrack_runtime::decimal_spin_value_after(node, action)?;
5896 } else {
5897 xrack_runtime::spin_value_after(node, action)?;
5898 }
5899 return Some(WheelAdjustment::Spin(ControlInput {
5900 path: path.to_vec(),
5901 action: ControlAction::Spin(action),
5902 }));
5903 }
5904 let action = RangeAction::Step(steps);
5905 let mut path = path.to_vec();
5906 if let Some((interval, handle)) = interval.zip(handle) {
5907 interval.apply(handle, action)?;
5908 path.push(handle);
5909 } else if matches!(node.kind, "Slider" | "Dial") {
5910 SliderRange::from_node(node).apply(action)?;
5911 } else {
5912 return None;
5913 }
5914 Some(WheelAdjustment::Range(RangeInput { path, action }))
5915 };
5916 action_for(units.signum() as i64)?;
5918 let row = scene.row_key_at(path);
5919 let mut total = units;
5920 if let Some(previous) = previous
5921 && previous.path == path
5922 && previous.row == row
5923 && previous.handle == handle
5924 && previous.horizontal == horizontal
5925 && previous.is_line == event.is_line
5926 && previous.remainder.signum() == units.signum()
5927 && now.saturating_duration_since(previous.time) <= Duration::from_millis(300)
5928 {
5929 total += previous.remainder;
5930 }
5931 let steps = total.trunc() as i64;
5932 let adjustment = if steps == 0 {
5933 WheelAdjustment::Pending
5934 } else {
5935 action_for(steps).unwrap_or(WheelAdjustment::Pending)
5936 };
5937 let remainder = total.fract();
5938 self.wheel_steps = (remainder != 0.0).then(|| WheelSteps {
5939 path: path.to_vec(),
5940 row,
5941 handle,
5942 horizontal,
5943 is_line: event.is_line,
5944 remainder,
5945 time: now,
5946 });
5947 Some(adjustment)
5948 }
5949
5950 pub fn tumbler_key(
5951 &mut self,
5952 scene: &Node,
5953 layout: &LayoutNode,
5954 key: NavigationKey,
5955 ) -> Option<ControlInput> {
5956 let target = self.focused.as_ref()?;
5957 if !valid(target, scene, layout) {
5958 return None;
5959 }
5960 let node = scene
5961 .at_path(&target.path)
5962 .filter(|node| matches!(node.kind, "Tumbler" | "PathView"))?;
5963 let wheel = Tumbler::from_node(node);
5964 let (axis, reversed) = layout
5965 .at_path(&target.path)?
5966 .tumbler
5967 .as_ref()?
5968 .navigation_axis();
5969 let index = match key {
5970 NavigationKey::Left if axis == Orientation::Horizontal => {
5971 wheel.step(if reversed { 1 } else { -1 })?
5972 }
5973 NavigationKey::Right if axis == Orientation::Horizontal => {
5974 wheel.step(if reversed { -1 } else { 1 })?
5975 }
5976 NavigationKey::Up => wheel.step(-1)?,
5977 NavigationKey::Down => wheel.step(1)?,
5978 NavigationKey::Home => 0,
5979 NavigationKey::End => wheel.count().checked_sub(1)?,
5980 NavigationKey::PageUp => wheel.step(-(wheel.visible() as i64))?,
5981 NavigationKey::PageDown => wheel.step(wheel.visible() as i64)?,
5982 _ => return None,
5983 };
5984 let input = ControlInput {
5985 path: target.path.clone(),
5986 action: wheel.select(index)?,
5987 };
5988 self.interrupt_tumbler_flick();
5989 Some(input)
5990 }
5991
5992 pub fn cancel_scroll_gesture(&mut self) {
5993 if let Some(motion) = &mut self.swipe_page_motion {
5994 motion.settle(Instant::now());
5995 }
5996 self.finish_button_contact(ButtonContactSource::Gesture, false);
5997 if let Some(drag) = self
5998 .scroll_gesture
5999 .as_mut()
6000 .and_then(|gesture| gesture.tumbler.as_mut())
6001 {
6002 drag.cancel();
6003 }
6004 if let Some(mut flick) = self.tumbler_flick.take() {
6005 flick.interrupt();
6006 }
6007 self.swipe_events.extend(
6008 self.scroll_gesture
6009 .take()
6010 .and_then(|gesture| gesture.swipe)
6011 .and_then(SwipeRoute::cancel),
6012 );
6013 self.scroll_fling = None;
6014 self.viewport_motion.clear();
6015 self.overscroll.clear();
6016 self.cancel_touch_delay();
6017 self.cancel_touch_button_hold();
6018 }
6019
6020 pub fn overscroll_frame(&self) -> crate::OverscrollFrame {
6021 self.overscroll.frame()
6022 }
6023
6024 pub fn has_overscroll(&self) -> bool {
6025 self.overscroll.has_offset()
6026 }
6027
6028 pub(crate) fn visual_overscroll(&self, handle: &ViewportHandle, axis: Orientation) -> f32 {
6029 self.overscroll.visual_offset(handle, axis)
6030 }
6031
6032 pub(crate) fn return_viewport_to_bounds(&mut self, target: &ViewportHandle) -> bool {
6033 self.overscroll
6034 .return_to_bounds(Instant::now(), Some(target))
6035 }
6036
6037 pub(crate) fn cancel_viewport_flick(&mut self, target: &ViewportHandle) -> bool {
6038 if self.viewport_motion.contains(target) && self.scroll_fling.take().is_some() {
6039 self.viewport_motion.clear();
6040 true
6041 } else {
6042 false
6043 }
6044 }
6045
6046 pub fn has_pending_swipe_events(&self) -> bool {
6047 !self.swipe_events.is_empty() || self.scroll_gesture.as_ref().is_some_and(|gesture|
6048 matches!(&gesture.swipe, Some(SwipeRoute::Captured(target)) if target.cancel_requested()))
6049 }
6050
6051 pub fn reconcile_swipe(&mut self, scene: &Node, layout: &LayoutNode) {
6052 let invalid = self.scroll_gesture.as_ref().is_some_and(|gesture| matches!(&gesture.swipe,
6053 Some(SwipeRoute::Captured(target)) if target.cancel_requested() || !target.is_live(scene, layout, self)));
6054 if invalid && let Some(gesture) = &mut self.scroll_gesture {
6055 self.swipe_events.extend(
6056 gesture
6057 .swipe
6058 .replace(SwipeRoute::Cancelled)
6059 .and_then(SwipeRoute::cancel),
6060 );
6061 }
6062 }
6063
6064 pub fn take_swipe_events(&mut self) -> Vec<SwipeDelivery> {
6065 std::mem::take(&mut self.swipe_events)
6066 }
6067
6068 fn begin_delay(
6069 &mut self,
6070 scene: &Node,
6071 layout: &LayoutNode,
6072 target: Target,
6073 source: DelaySource,
6074 now: Instant,
6075 ) -> bool {
6076 let scope = self.active_dialog(layout).unwrap_or_default();
6077 let Some(node) = scene.at_path(&target.path).filter(|node| {
6078 node.kind == "DelayButton"
6079 && !node.boolean("checked", false)
6080 && target.path.starts_with(scope)
6081 && valid(&target, scene, layout)
6082 }) else {
6083 return false;
6084 };
6085 if self.menu_open() || self.choice_open() {
6086 return false;
6087 }
6088 self.delay_hold = Some(DelayHold::new(
6089 target,
6090 source,
6091 scope.to_vec(),
6092 Duration::from_millis(delay_millis(node)),
6093 now,
6094 ));
6095 true
6096 }
6097
6098 pub fn begin_pointer_delay(&mut self, scene: &Node, layout: &LayoutNode, now: Instant) {
6099 if let Some(target) = self.pressed.clone() {
6100 self.pointer_activation_claimed =
6101 self.begin_delay(scene, layout, target, DelaySource::Pointer, now);
6102 }
6103 }
6104
6105 pub fn begin_key_delay(
6106 &mut self,
6107 scene: &Node,
6108 layout: &LayoutNode,
6109 key: ActivationKey,
6110 now: Instant,
6111 ) {
6112 if let Some((pressed, target)) = self.key_pressed.clone()
6113 && pressed == key
6114 && self.begin_delay(scene, layout, target, DelaySource::Key(key), now)
6115 {
6116 self.key_activation_claimed = Some(key);
6117 }
6118 }
6119
6120 fn begin_button_hold(
6121 &mut self,
6122 scene: &Node,
6123 layout: &LayoutNode,
6124 target: Target,
6125 source: DelaySource,
6126 now: Instant,
6127 ) -> bool {
6128 let scope = self.active_dialog(layout).unwrap_or_default();
6129 if !target.path.starts_with(scope)
6130 || !valid(&target, scene, layout)
6131 || self.menu_open()
6132 || self.choice_open()
6133 {
6134 return false;
6135 }
6136 let Some(timing) = target.node_in(scene).and_then(ButtonHoldTiming::from_node) else {
6137 return false;
6138 };
6139 self.button_hold = Some(ButtonHold::new(
6140 target,
6141 source,
6142 scope.to_vec(),
6143 timing,
6144 match source {
6145 DelaySource::Pointer => self.pointer,
6146 DelaySource::Touch(point) => Some(point),
6147 _ => None,
6148 },
6149 now,
6150 ));
6151 true
6152 }
6153
6154 pub fn begin_pointer_button_hold(
6155 &mut self,
6156 scene: &Node,
6157 layout: &LayoutNode,
6158 now: Instant,
6159 ) -> bool {
6160 self.pressed.clone().is_some_and(|target| {
6161 self.begin_button_hold(scene, layout, target, DelaySource::Pointer, now)
6162 })
6163 }
6164
6165 pub fn begin_key_button_hold(
6166 &mut self,
6167 scene: &Node,
6168 layout: &LayoutNode,
6169 key: ActivationKey,
6170 now: Instant,
6171 ) {
6172 if let Some((pressed, target)) = self.key_pressed.clone()
6173 && pressed == key
6174 {
6175 self.begin_button_hold(scene, layout, target, DelaySource::Key(key), now);
6176 }
6177 }
6178
6179 pub fn button_hold_deadline(&self) -> Option<Instant> {
6180 self.button_hold.as_ref().and_then(|hold| hold.deadline)
6181 }
6182
6183 pub fn advance_button_hold(
6184 &mut self,
6185 scene: &Node,
6186 layout: &LayoutNode,
6187 now: Instant,
6188 ) -> Option<(Target, ButtonHoldEvent)> {
6189 let mut repeat = self.button_hold.take()?;
6190 let pointer_matches =
6191 |point| self.target_at(scene, layout, point).as_ref() == Some(&repeat.target);
6192 let pressed = match repeat.source {
6193 DelaySource::Pointer => {
6194 self.pressed.as_ref() == Some(&repeat.target)
6195 && self.pointer.is_some_and(pointer_matches)
6196 }
6197 DelaySource::Key(key) => {
6198 self.focused.as_ref() == Some(&repeat.target)
6199 && self
6200 .key_pressed
6201 .as_ref()
6202 .is_some_and(|(held, target)| *held == key && target == &repeat.target)
6203 }
6204 DelaySource::Touch(point) => {
6205 self.scroll_gesture
6206 .as_ref()
6207 .is_some_and(|gesture| !gesture.motion.dragging)
6208 && pointer_matches(point)
6209 }
6210 DelaySource::Accessibility => false,
6211 };
6212 if !pressed
6213 || self.menu_open()
6214 || self.choice_open()
6215 || self.active_dialog(layout).unwrap_or_default() != repeat.scope
6216 || !valid(&repeat.target, scene, layout)
6217 || repeat
6218 .target
6219 .node_in(scene)
6220 .and_then(ButtonHoldTiming::from_node)
6221 != Some(repeat.timing)
6222 {
6223 return None;
6224 }
6225 let event = repeat.sample(now);
6226 if event.is_some() {
6227 match repeat.source {
6228 DelaySource::Pointer => self.pointer_activation_claimed = true,
6229 DelaySource::Key(key) => self.key_activation_claimed = Some(key),
6230 DelaySource::Touch(_) => {
6231 if let Some(gesture) = &mut self.scroll_gesture {
6232 gesture.delay_touch = true;
6233 }
6234 if repeat.target.focusable
6235 && repeat
6236 .target
6237 .node_in(scene)
6238 .is_some_and(|node| node.boolean("focus-on-click", true))
6239 {
6240 self.set_focus_with_reason(
6241 Some(repeat.target.clone()),
6242 xrack_runtime::FocusReason::PointerClick,
6243 );
6244 }
6245 }
6246 DelaySource::Accessibility => {}
6247 }
6248 }
6249 let delivery = event.map(|event| (repeat.target.clone(), event));
6250 self.button_hold = Some(repeat);
6251 delivery
6252 }
6253
6254 fn cancel_touch_button_hold(&mut self) {
6255 if self
6256 .button_hold
6257 .as_ref()
6258 .is_some_and(|repeat| matches!(repeat.source, DelaySource::Touch(_)))
6259 {
6260 self.button_hold = None;
6261 }
6262 }
6263
6264 fn delay_current(&self, hold: &DelayHold, scene: &Node, layout: &LayoutNode) -> bool {
6265 if self.focused.as_ref() != Some(&hold.target)
6266 || self.menu_open()
6267 || self.choice_open()
6268 || self.active_dialog(layout).unwrap_or_default() != hold.scope
6269 || !valid(&hold.target, scene, layout)
6270 || !scene.at_path(&hold.target.path).is_some_and(|node| {
6271 node.kind == "DelayButton"
6272 && !node.boolean("checked", false)
6273 && Duration::from_millis(delay_millis(node)) == hold.duration
6274 })
6275 {
6276 return false;
6277 }
6278 match hold.source {
6279 DelaySource::Pointer => {
6280 self.pressed.as_ref() == Some(&hold.target)
6281 && self.pointer.is_some_and(|point| {
6282 self.target_at(scene, layout, point).as_ref() == Some(&hold.target)
6283 })
6284 }
6285 DelaySource::Key(key) => self
6286 .key_pressed
6287 .as_ref()
6288 .is_some_and(|(current, target)| *current == key && target == &hold.target),
6289 DelaySource::Touch(point) => {
6290 self.target_at(scene, layout, point).as_ref() == Some(&hold.target)
6291 }
6292 DelaySource::Accessibility => true,
6293 }
6294 }
6295
6296 pub fn advance_delay(
6297 &mut self,
6298 scene: &Node,
6299 layout: &LayoutNode,
6300 now: Instant,
6301 ) -> Option<ControlInput> {
6302 let mut hold = self.delay_hold.take()?;
6303 if !self.delay_current(&hold, scene, layout) {
6304 return None;
6305 }
6306 if hold.sample(now) && !matches!(hold.source, DelaySource::Accessibility) {
6307 return Some(ControlInput {
6308 path: hold.target.path,
6309 action: ControlAction::DelayButton(true),
6310 });
6311 }
6312 self.delay_hold = Some(hold);
6313 None
6314 }
6315
6316 pub fn accessibility_delay_click(
6317 &mut self,
6318 scene: &Node,
6319 layout: &LayoutNode,
6320 target: Target,
6321 now: Instant,
6322 ) -> Option<ControlInput> {
6323 let node = scene
6324 .at_path(&target.path)
6325 .filter(|node| node.kind == "DelayButton")?;
6326 if !valid(&target, scene, layout)
6327 || self.menu_open()
6328 || self.choice_open()
6329 || !target
6330 .path
6331 .starts_with(self.active_dialog(layout).unwrap_or_default())
6332 {
6333 return None;
6334 }
6335 self.accessibility_focus(target.clone());
6336 if node.boolean("checked", false) {
6337 self.cancel_delay();
6338 return Some(ControlInput {
6339 path: target.path,
6340 action: ControlAction::DelayButton(false),
6341 });
6342 }
6343 if let Some(hold) = self.delay_hold.take()
6344 && matches!(hold.source, DelaySource::Accessibility)
6345 && hold.target == target
6346 && self.delay_current(&hold, scene, layout)
6347 {
6348 return (now >= hold.deadline()).then_some(ControlInput {
6349 path: target.path,
6350 action: ControlAction::DelayButton(true),
6351 });
6352 }
6353 self.begin_delay(scene, layout, target, DelaySource::Accessibility, now);
6354 None
6355 }
6356
6357 pub fn cancel_delay(&mut self) -> bool {
6358 self.delay_hold.take().is_some()
6359 }
6360
6361 fn cancel_touch_delay(&mut self) {
6362 if self
6363 .delay_hold
6364 .as_ref()
6365 .is_some_and(|hold| matches!(hold.source, DelaySource::Touch(_)))
6366 {
6367 self.cancel_delay();
6368 }
6369 }
6370
6371 pub fn delay_deadline(&self) -> Option<Instant> {
6372 self.delay_hold
6373 .as_ref()
6374 .filter(|hold| hold.pending())
6375 .map(DelayHold::deadline)
6376 }
6377
6378 pub fn delay_progress(&self, path: &[usize]) -> Option<(f32, bool)> {
6379 let hold = self
6380 .delay_hold
6381 .as_ref()
6382 .filter(|hold| hold.target.path == path)?;
6383 Some((hold.fraction, hold.pending()))
6384 }
6385
6386 pub fn delay_accessibility(&self) -> Option<(&Target, bool)> {
6387 let hold = self
6388 .delay_hold
6389 .as_ref()
6390 .filter(|hold| matches!(hold.source, DelaySource::Accessibility))?;
6391 Some((&hold.target, !hold.pending()))
6392 }
6393
6394 pub fn editor_value<'a>(&'a self, node: &'a Node) -> Cow<'a, str> {
6395 if is_spin_box(node.kind) {
6396 match &self.spin_draft {
6397 Some(draft) => Cow::Borrowed(&draft.text),
6398 None => Cow::Owned(spin_text(node)),
6399 }
6400 } else if matches!(node.kind, "TableCell" | "TreeCell")
6401 && let Some(edit) = &self.table_edit
6402 {
6403 Cow::Borrowed(&edit.draft)
6404 } else {
6405 Cow::Borrowed(text_input_value(node))
6406 }
6407 }
6408
6409 pub fn table_cell_editing(&self, path: &[usize]) -> bool {
6410 self.table_edit
6411 .as_ref()
6412 .is_some_and(|edit| edit.target.path == path)
6413 }
6414
6415 pub fn table_cell_edit_invalid(&self, node: &Node, path: &[usize]) -> bool {
6416 self.table_edit.as_ref().is_some_and(|edit| {
6417 edit.target.path == path
6418 && node
6419 .table_cell_editor
6420 .is_some_and(|editor| !editor.accepts(&edit.draft))
6421 })
6422 }
6423
6424 pub fn is_text_editor(&self, node: &Node, target: &Target) -> bool {
6425 is_text_input(node.kind)
6426 || combo_editable(node)
6427 || node.selectable_styled_text()
6428 || editable_table_cell(node)
6429 && self
6430 .table_edit
6431 .as_ref()
6432 .is_some_and(|edit| &edit.target == target)
6433 }
6434
6435 pub fn table_cell_click(
6436 &mut self,
6437 scene: &Node,
6438 layout: &LayoutNode,
6439 target: Option<&Target>,
6440 now: Instant,
6441 ) -> bool {
6442 let previous = self.last_table_click.take();
6443 let Some(target) =
6444 target.filter(|target| scene.at_path(&target.path).is_some_and(editable_table_cell))
6445 else {
6446 return false;
6447 };
6448 let double_click = previous.is_some_and(|(prior, when)| {
6449 prior == *target && now.saturating_duration_since(when) <= Duration::from_millis(450)
6450 });
6451 let table = table_cell_row(scene, &target.path)
6452 .and_then(|(path, slot)| scene.at_path(path).map(|table| (table, slot)));
6453 let double_enabled =
6454 table.is_none_or(|(table, _)| table.boolean("edit-on-double-click", true));
6455 let start = double_enabled && double_click
6456 || table.is_some_and(|(table, slot)| {
6457 table.boolean("edit-on-click", false)
6458 || table.boolean("edit-on-selected-click", false)
6459 && table
6460 .children
6461 .get(slot)
6462 .and_then(|row| row.row_key)
6463 .is_some_and(|key| {
6464 let column = target.path.last().copied().unwrap_or_default();
6465 table.table_selection.as_ref().map_or_else(
6466 || current_list_slot(table) == Some(slot),
6467 |selection| selection.contains_cell(key, column),
6468 )
6469 })
6470 });
6471 if start {
6472 return self.begin_cell_edit(scene, layout, target.clone(), self.focus_reason);
6473 }
6474 if double_enabled {
6475 self.last_table_click = Some((target.clone(), now));
6476 }
6477 false
6478 }
6479
6480 pub fn begin_table_edit(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
6481 self.begin_focused_cell_edit(scene, layout, "edit-on-key", true)
6482 }
6483
6484 pub fn begin_table_typing(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
6485 self.begin_focused_cell_edit(scene, layout, "edit-on-typing", false)
6486 }
6487
6488 fn begin_focused_cell_edit(
6489 &mut self,
6490 scene: &Node,
6491 layout: &LayoutNode,
6492 property: &str,
6493 default: bool,
6494 ) -> bool {
6495 let Some(target) = self.focused_edit_target(scene, layout) else {
6496 return false;
6497 };
6498 let enabled = table_cell_row(scene, &target.path)
6499 .and_then(|(path, _)| scene.at_path(path))
6500 .map_or(default, |table| table.boolean(property, default));
6501 enabled
6502 && self.begin_cell_edit(
6503 scene,
6504 layout,
6505 target,
6506 xrack_runtime::FocusReason::KeyboardNavigation,
6507 )
6508 }
6509
6510 fn focused_edit_target(&self, scene: &Node, layout: &LayoutNode) -> Option<Target> {
6511 let focused = self.focused.as_ref()?;
6512 let node = scene.interactive_at_path(&focused.path)?;
6513 let mut target = focused.clone();
6514 if matches!(node.kind, "TableView" | "TreeView") {
6515 let slot = current_list_slot(node)?;
6516 let row = node.children.get(slot)?.children.first()?;
6517 target.path.extend([slot, 0]);
6518 let cell = if node.kind == "TreeView" {
6519 layout
6520 .at_path(&target.path)
6521 .and_then(|item| first_editable_tree_cell(row, item, &mut target.path))
6522 } else {
6523 let current_column = node
6524 .table_selection
6525 .as_ref()
6526 .and_then(|view| view.current_column());
6527 let column_index = target.path.len();
6528 target.path.push(0);
6529 row.materialized_children().find_map(|(column, cell)| {
6530 target.path[column_index] = column;
6531 (current_column.is_none_or(|current| current == column)
6532 && editable_table_cell(cell)
6533 && layout
6534 .at_path(&target.path)
6535 .is_some_and(|item| eligible(cell, item)))
6536 .then_some(cell)
6537 })
6538 };
6539 let cell = cell?;
6540 target.set_element_id(ElementId::of(cell));
6541 target.row_key = scene.row_key_at(&target.path);
6542 }
6543 Some(target)
6544 }
6545
6546 fn begin_cell_edit(
6547 &mut self,
6548 scene: &Node,
6549 layout: &LayoutNode,
6550 target: Target,
6551 reason: xrack_runtime::FocusReason,
6552 ) -> bool {
6553 if self
6554 .table_edit
6555 .as_ref()
6556 .is_some_and(|edit| edit.target == target)
6557 {
6558 return false;
6559 }
6560 let Some(cell) = scene.interactive_at_path(&target.path).filter(|cell| {
6561 target.row_key.is_some() && editable_table_cell(cell) && valid(&target, scene, layout)
6562 }) else {
6563 return false;
6564 };
6565 let original = cell.text("text").unwrap_or("").to_owned();
6566 self.set_focus_with_reason(Some(target.clone()), reason);
6567 let mut editor = TextEdit::at_end(&original);
6568 editor.apply(&original, EditAction::SelectAll);
6569 self.editor = Some(editor);
6570 self.table_edit = Some(TableEdit {
6571 target,
6572 draft: original.clone(),
6573 original,
6574 history: TextHistory::default(),
6575 });
6576 true
6577 }
6578
6579 pub fn cancel_table_edit(&mut self) -> bool {
6580 if self.table_edit.take().is_none() {
6581 return false;
6582 }
6583 self.editor = None;
6584 self.last_table_click = None;
6585 true
6586 }
6587
6588 pub fn commit_table_edit(&mut self, component: &mut impl Component, scene: &Node) -> bool {
6589 self.finish_table_edit(component, scene) == TableEditCommit::Changed
6590 }
6591
6592 pub fn finish_table_edit(
6593 &mut self,
6594 component: &mut impl Component,
6595 scene: &Node,
6596 ) -> TableEditCommit {
6597 let Some(edit) = self.table_edit.as_ref() else {
6598 return TableEditCommit::Rejected;
6599 };
6600 if self
6601 .editor
6602 .as_ref()
6603 .is_some_and(|editor| !editor.preedit.is_empty())
6604 {
6605 return TableEditCommit::Kept;
6606 }
6607 let current = scene
6608 .table_cell_commit_target(&edit.target.path, &edit.original)
6609 .filter(|_| scene.row_key_at(&edit.target.path) == edit.target.row_key);
6610 let Some(cell) = current else {
6611 self.cancel_table_edit();
6612 return TableEditCommit::Rejected;
6613 };
6614 let mut unchanged = edit.draft == edit.original;
6615 if !unchanged
6616 && let Some(editor) = cell.table_cell_editor
6617 && editor != xrack_runtime::TableCellEditor::String
6618 {
6619 let Some(draft) = editor.parse(&edit.draft) else {
6620 return TableEditCommit::Kept;
6621 };
6622 unchanged = editor.parse(&edit.original) == Some(draft);
6623 }
6624 let Some(edit) = self.table_edit.take() else {
6625 return TableEditCommit::Rejected;
6626 };
6627 self.editor = None;
6628 self.last_table_click = None;
6629 if unchanged {
6630 TableEditCommit::Unchanged
6631 } else if component.commit_table_cell(scene, &edit.target.path, &edit.original, edit.draft)
6632 {
6633 TableEditCommit::Changed
6634 } else {
6635 TableEditCommit::Rejected
6636 }
6637 }
6638
6639 pub fn tab_edit_origin(&self, scene: &Node) -> Option<TableEditTarget> {
6640 let edit = self.table_edit.as_ref()?;
6641 let (table, slot) = table_cell_row(scene, &edit.target.path)?;
6642 let view = scene.interactive_at_path(table)?;
6643 if !view.boolean("edit-on-tab", false) || self.focused.as_ref() != Some(&edit.target) {
6644 return None;
6645 }
6646 Some(TableEditTarget {
6647 table: table.to_vec(),
6648 viewport: view.viewport_handle.clone()?,
6649 position: TableEditPosition {
6650 row: view.list?.first_row.checked_add(slot)?,
6651 column: *edit.target.path.last()?,
6652 key: view.children.get(slot)?.row_key?,
6653 },
6654 })
6655 }
6656
6657 pub fn next_table_edit_target(
6658 &self,
6659 component: &impl Component,
6660 scene: &Node,
6661 layout: &LayoutNode,
6662 origin: &TableEditTarget,
6663 backward: bool,
6664 ) -> Option<TableEditTarget> {
6665 let view = scene.interactive_at_path(&origin.table)?;
6666 if view.viewport_handle.as_ref() != Some(&origin.viewport)
6667 || !self.allows_popup(layout, &origin.table)
6668 {
6669 return None;
6670 }
6671 let geometry = layout.at_path(&origin.table)?.table.as_ref()?;
6672 let columns: Vec<_> = geometry
6673 .visual_columns()
6674 .filter(|column| geometry.columns[*column].width > 0.0)
6675 .collect();
6676 let position = component.next_table_edit_cell(
6677 scene,
6678 &origin.table,
6679 origin.position,
6680 &columns,
6681 backward,
6682 )?;
6683 Some(TableEditTarget {
6684 table: origin.table.clone(),
6685 viewport: origin.viewport.clone(),
6686 position,
6687 })
6688 }
6689
6690 pub fn begin_table_edit_target(
6691 &mut self,
6692 scene: &Node,
6693 layout: &LayoutNode,
6694 target: &TableEditTarget,
6695 ) -> bool {
6696 let Some(view) = scene.interactive_at_path(&target.table) else {
6697 return false;
6698 };
6699 if view.viewport_handle.as_ref() != Some(&target.viewport)
6700 || !view.boolean("edit-on-tab", false)
6701 || !self.allows_popup(layout, &target.table)
6702 {
6703 return false;
6704 }
6705 let position = target.position;
6706 if view
6707 .list
6708 .and_then(|list| position.row.checked_sub(list.first_row))
6709 .and_then(|slot| view.children.get(slot))
6710 .and_then(|row| row.row_key)
6711 != Some(position.key)
6712 {
6713 return false;
6714 }
6715 let cell = table_cell_target(scene, layout, &target.table, position.row, position.column);
6716 cell.is_some_and(|cell| {
6717 self.begin_cell_edit(
6718 scene,
6719 layout,
6720 cell,
6721 xrack_runtime::FocusReason::KeyboardNavigation,
6722 )
6723 })
6724 }
6725
6726 pub fn sync_editor(&mut self, scene: &Node) {
6727 let target_node = self
6728 .focused
6729 .as_ref()
6730 .and_then(|target| Some((target, target.node_in(scene)?)));
6731 if let Some((target, node)) = target_node
6732 .filter(|(target, node)| self.is_text_editor(node, target) || spin_editable(node))
6733 {
6734 let persistent = node.boolean("persistent-selection", false)
6735 && (is_text_input(node.kind)
6736 || combo_editable(node)
6737 || node.selectable_styled_text());
6738 if persistent {
6739 if let Some(source) = &mut self.persistent_editor {
6740 if !source.matches(node) {
6741 self.editor = None;
6742 if let Some(handle) = &source.handle {
6743 handle.clear_text_state();
6744 }
6745 *source = PersistentEditor::new(target, node);
6746 } else {
6747 source.target.path.clone_from(&target.path);
6748 }
6749 } else {
6750 if self.editor.is_none()
6751 && let Some(index) = self.retained_selections.iter().position(|selection| {
6752 selection.source.same_target(target) && selection.source.matches(node)
6753 })
6754 {
6755 self.editor = Some(self.retained_selections.remove(index).editor);
6756 }
6757 self.persistent_editor = Some(PersistentEditor::new(target, node));
6758 }
6759 } else {
6760 self.persistent_editor = None;
6761 }
6762 if self.editor.is_none() {
6763 self.editor = Some(TextEdit::at_end(&self.editor_value(node)));
6764 }
6765 if let Some(editor) = &mut self.editor
6766 && editor
6767 .password_echo
6768 .as_ref()
6769 .is_some_and(|echo| !echo.matches(node, text_input_value(node)))
6770 {
6771 editor.password_echo = None;
6772 }
6773 if (is_text_input(node.kind) || combo_editable(node))
6774 && let Some(target) = &self.focused
6775 && let Some(history) = self.history.get_mut(&EditorKey::new(scene, target))
6776 {
6777 history.observe(text_input_value(node));
6778 }
6779 } else {
6780 self.persistent_editor = None;
6781 self.editor = None;
6782 self.spin_draft = None;
6783 }
6784 self.reconcile_text_composition(scene);
6785 }
6786
6787 fn retain_editor_selection(&mut self) {
6788 let old = self.editor.take();
6789 let Some(source) = self.persistent_editor.take() else {
6790 return;
6791 };
6792 let Some(editor) = old else { return };
6793 let state = editor.selection_state(&source.text);
6794 if state.collapsed() {
6795 return;
6796 }
6797 let mut saved = TextEdit::default();
6798 saved.restore_selection(&source.text, state);
6799 saved.set_horizontal_drag_scroll(editor.horizontal_drag_scroll());
6800 if let Some(handle) = &source.handle {
6801 let range = saved.selection(&source.text);
6802 let text = if source.password {
6803 ""
6804 } else {
6805 &source.text[range.clone()]
6806 };
6807 handle.publish_text_selection(saved.caret(&source.text), range, text);
6808 handle.publish_text_commands(Default::default());
6809 }
6810 self.retained_selections.push(RetainedSelection {
6811 source,
6812 editor: saved,
6813 });
6814 }
6815
6816 #[doc(hidden)]
6817 pub fn set_editor_window_active(&mut self, active: bool) {
6818 self.editor_window_inactive = !active;
6819 if !active && let Some(editor) = &mut self.editor {
6820 editor.password_echo = None;
6821 }
6822 }
6823
6824 #[doc(hidden)]
6825 pub fn password_echo_deadline(&self) -> Option<Instant> {
6826 Some(self.editor.as_ref()?.password_echo.as_ref()?.deadline)
6827 }
6828
6829 #[doc(hidden)]
6830 pub fn expire_password_echo(&mut self, now: Instant) -> bool {
6831 if let Some(editor) = &mut self.editor
6832 && editor
6833 .password_echo
6834 .as_ref()
6835 .is_some_and(|echo| now >= echo.deadline)
6836 {
6837 editor.password_echo = None;
6838 return true;
6839 }
6840 false
6841 }
6842
6843 #[doc(hidden)]
6844 pub fn editor_active(&self, path: &[usize]) -> bool {
6845 !self.editor_window_inactive && self.is_focused(path)
6846 }
6847
6848 #[doc(hidden)]
6849 pub fn displayed_editor(&self, node: &Node, path: &[usize]) -> Option<&TextEdit> {
6850 if self.is_focused(path) {
6851 return self.editor.as_ref().filter(|_| {
6852 !self.editor_window_inactive
6853 || self
6854 .persistent_editor
6855 .as_ref()
6856 .is_some_and(|source| source.matches(node))
6857 });
6858 }
6859 self.retained_selections.iter().find_map(|selection| {
6860 (selection.source.target.path == path && selection.source.matches(node))
6861 .then_some(&selection.editor)
6862 })
6863 }
6864
6865 pub(crate) fn retained_editor_for<'a>(
6866 &'a self,
6867 scene: &'a Node,
6868 target: &Target,
6869 handle: &FocusHandle,
6870 ) -> Option<(&'a TextEdit, &'a Node)> {
6871 for selection in &self.retained_selections {
6872 let source = &selection.source;
6873 if source.handle.as_ref() == Some(handle)
6874 && source.target.row_key == target.row_key
6875 && let Some(node) = source
6876 .target
6877 .node_in(scene)
6878 .filter(|node| source.matches(node))
6879 {
6880 return Some((&selection.editor, node));
6881 }
6882 }
6883 let source = self.persistent_editor.as_ref()?;
6884 if !self.editor_window_inactive
6885 || !source.same_target(target)
6886 || source.handle.as_ref() != Some(handle)
6887 {
6888 return None;
6889 }
6890 let node = source
6891 .target
6892 .node_in(scene)
6893 .filter(|node| source.matches(node))?;
6894 Some((self.editor.as_ref()?, node))
6895 }
6896
6897 pub fn break_text_edit_group(&mut self) {
6898 self.history.break_group();
6899 if let Some(draft) = &mut self.spin_draft {
6900 draft.history.break_group();
6901 }
6902 if let Some(edit) = &mut self.table_edit {
6903 edit.history.break_group();
6904 }
6905 }
6906
6907 pub fn edit_text(
6908 &mut self,
6909 component: &mut impl Component,
6910 scene: &Node,
6911 action: EditAction<'_>,
6912 source: EditSource,
6913 now: Instant,
6914 ) -> bool {
6915 self.apply_text_edit(scene, action, source, now, |target, text| {
6916 component.edit_at(scene, &target.path, text)
6917 })
6918 }
6919
6920 fn apply_text_edit(
6921 &mut self,
6922 scene: &Node,
6923 action: EditAction<'_>,
6924 source: EditSource,
6925 now: Instant,
6926 commit: impl FnOnce(&Target, String) -> bool,
6927 ) -> bool {
6928 let Some(target) = self.focused.clone() else {
6929 return false;
6930 };
6931 self.apply_text_edit_at(scene, &target, action, source, now, commit)
6932 }
6933
6934 #[doc(hidden)]
6935 pub fn apply_text_replacement(
6936 &mut self,
6937 component: &mut impl Component,
6938 scene: &Node,
6939 layout: &LayoutNode,
6940 handle: &FocusHandle,
6941 replacement: &xrack_runtime::TextReplacement,
6942 now: Instant,
6943 ) -> Option<Target> {
6944 let modal = self.active_dialog(layout).unwrap_or_default();
6945 let target = crate::focus_scope::handle_target(scene, layout, modal, handle, true)?;
6946 let focused = self.focused.as_ref() == Some(&target);
6947 if focused {
6948 if self.editor.as_ref().is_some_and(TextEdit::is_composing) {
6949 return None;
6950 }
6951 self.sync_editor(scene);
6952 }
6953 let action = EditAction::ReplaceRange {
6954 start: replacement.start,
6955 end: replacement.end,
6956 text: &replacement.text,
6957 };
6958 let changed = self.apply_text_edit_at(
6959 scene,
6960 &target,
6961 action,
6962 EditSource::Atomic,
6963 now,
6964 |target, text| component.edit_at(scene, &target.path, text),
6965 );
6966 if changed && !focused {
6967 handle.discard_editor_changes();
6968 }
6969 changed.then_some(target)
6970 }
6971
6972 fn apply_text_edit_at(
6973 &mut self,
6974 scene: &Node,
6975 target: &Target,
6976 action: EditAction<'_>,
6977 source: EditSource,
6978 now: Instant,
6979 commit: impl FnOnce(&Target, String) -> bool,
6980 ) -> bool {
6981 let Some(node) = scene.interactive_at_path(&target.path).filter(|node| {
6982 self.is_text_editor(node, target) && scene.row_key_at(&target.path) == target.row_key
6983 }) else {
6984 return false;
6985 };
6986 if node.text_read_only() && action.changes_text() {
6987 return false;
6988 }
6989
6990 let active = self.focused.as_ref() == Some(target);
6991 let explicit = matches!(action, EditAction::ReplaceRange { .. });
6992 let mut inactive = (!active).then(|| {
6993 self.displayed_editor(node, &target.path)
6994 .cloned()
6995 .unwrap_or_else(|| TextEdit::at_end(text_input_value(node)))
6996 });
6997 let draft = self
6998 .table_edit
6999 .as_mut()
7000 .filter(|edit| &edit.target == target);
7001 let text = draft
7002 .as_ref()
7003 .map_or_else(|| text_input_value(node), |edit| &edit.draft);
7004 let editor = inactive
7005 .as_mut()
7006 .unwrap_or_else(|| self.editor.get_or_insert_with(|| TextEdit::at_end(text)));
7007 editor.password_echo = None;
7008 let previous = editor.clone();
7009 let before = editor.selection_state(text);
7010 let mask = node.text("input-mask").filter(|mask| !mask.is_empty());
7011 let overwrite = node.boolean("overwrite-mode", false)
7012 && matches!(source, EditSource::Keyboard | EditSource::Ime)
7013 && matches!(action, EditAction::Insert(_))
7014 && before.collapsed();
7015 let Some(mut edit) = editor.apply_mode(
7016 text,
7017 action,
7018 is_multiline_text_input(node.kind),
7019 overwrite && mask.is_none(),
7020 ) else {
7021 if explicit {
7022 *editor = previous;
7023 } else if active {
7024 self.break_text_edit_group();
7025 }
7026 return false;
7027 };
7028 if let Some(mask) = mask {
7029 let delete = match action {
7030 EditAction::Backspace | EditAction::BackspaceWord if before.collapsed() => {
7031 Some(xrack_runtime::MaskDelete::Backward)
7032 }
7033 EditAction::Delete | EditAction::DeleteWord if before.collapsed() => {
7034 Some(xrack_runtime::MaskDelete::Forward)
7035 }
7036 _ => None,
7037 };
7038 let range = edit.start..edit.start + edit.removed.len();
7039 let Some(formatted) = xrack_runtime::InputMask::parse(mask).and_then(|mask| {
7040 if overwrite {
7041 mask.overwrite(text, range.start, &edit.inserted)
7042 } else {
7043 mask.edit(text, range, &edit.inserted, delete)
7044 }
7045 }) else {
7046 *editor = previous;
7047 if !explicit {
7048 editor.set_preedit(String::new(), None);
7049 }
7050 return false;
7051 };
7052 editor.place_caret(
7053 &formatted.text,
7054 TextPosition {
7055 offset: formatted.caret,
7056 trailing: !edit.inserted.is_empty(),
7057 },
7058 false,
7059 );
7060 edit = edit.replace_text(text, formatted.text);
7061 }
7062 if edit.text == text {
7063 if explicit {
7064 *editor = previous;
7065 } else if active {
7066 self.break_text_edit_group();
7067 }
7068 return false;
7069 }
7070 if draft.is_none()
7071 && (!node.allows_text_edit(&edit.text) || !commit(target, edit.text.clone()))
7072 {
7073 *editor = previous;
7074 if !explicit {
7075 editor.set_preedit(String::new(), None);
7076 }
7077 return false;
7078 }
7079 let group = Group::for_edit(source, action, before, &edit);
7080 let after = editor.selection_state(&edit.text);
7081 if active
7082 && !self.editor_window_inactive
7083 && source == EditSource::Keyboard
7084 && let EditAction::Insert(typed) = action
7085 {
7086 editor.password_echo = crate::password::PasswordEcho::new(
7087 node,
7088 &edit.text,
7089 typed,
7090 editor.caret(&edit.text),
7091 now,
7092 );
7093 }
7094 let (next, record) = Record::new(edit, before, after);
7095 if active {
7096 self.painted_combo_completion = None;
7097 self.dismissed_combo_draft = None;
7098 if let Some(source) = &mut self.persistent_editor {
7099 source.text.clone_from(&next);
7100 }
7101 if node.kind == "SearchField" {
7102 self.search_query = (!next.is_empty()).then(|| next.clone());
7103 Self::clear_choice(&mut self.choice);
7104 }
7105 }
7106 if let Some(draft) = draft {
7107 draft.history.observe(&draft.draft);
7108 draft.draft = next.clone();
7109 draft.history.push(next, record, group, now);
7110 } else {
7111 let history = self.history.entry(EditorKey::new(scene, target));
7112 history.observe(text);
7113 history.push(next, record, group, now);
7114 }
7115 true
7116 }
7117
7118 pub fn clear_search(
7119 &mut self,
7120 component: &mut impl Component,
7121 scene: &Node,
7122 path: &[usize],
7123 now: Instant,
7124 ) -> bool {
7125 if self
7126 .focused
7127 .as_ref()
7128 .is_none_or(|target| target.path != path)
7129 || scene
7130 .at_path(path)
7131 .is_none_or(|node| node.kind != "SearchField")
7132 {
7133 return false;
7134 }
7135 self.apply_text_edit(
7136 scene,
7137 EditAction::ReplaceAll(""),
7138 EditSource::Atomic,
7139 now,
7140 |target, _| component.control_at(scene, &target.path, ControlAction::ClearSearch),
7141 )
7142 }
7143
7144 pub fn select_search_suggestion(
7145 &mut self,
7146 component: &mut impl Component,
7147 scene: &Node,
7148 index: usize,
7149 now: Instant,
7150 ) -> bool {
7151 let Some(target) = self
7152 .focused
7153 .as_ref()
7154 .filter(|target| scene.row_key_at(&target.path) == target.row_key)
7155 else {
7156 return false;
7157 };
7158 let Some(node) = scene.interactive_at_path(&target.path) else {
7159 return false;
7160 };
7161 let Some(value) = search_suggestion(node, index) else {
7162 return false;
7163 };
7164 let action = ControlAction::Select(index);
7165 let changed = if value == text_input_value(node) {
7166 component.control_at(scene, &target.path, action)
7167 } else {
7168 self.apply_text_edit(
7169 scene,
7170 EditAction::ReplaceAll(value),
7171 EditSource::Atomic,
7172 now,
7173 |target, _| component.control_at(scene, &target.path, action),
7174 )
7175 };
7176 self.dismiss_choice();
7177 changed
7178 }
7179
7180 pub fn replay_text_edit(
7181 &mut self,
7182 component: &mut impl Component,
7183 scene: &Node,
7184 redo: bool,
7185 ) -> bool {
7186 if self.editor.as_ref().is_some_and(TextEdit::is_composing) {
7187 return false;
7188 }
7189 let Some(target) = &self.focused else {
7190 return false;
7191 };
7192 let Some(node) = scene.interactive_at_path(&target.path).filter(|node| {
7193 (self.is_text_editor(node, target) || spin_editable(node))
7194 && !node.text_read_only()
7195 && scene.row_key_at(&target.path) == target.row_key
7196 }) else {
7197 return false;
7198 };
7199 if is_spin_box(node.kind) {
7200 let Some(draft) = self
7201 .spin_draft
7202 .as_mut()
7203 .filter(|draft| draft.mode.is_current(node))
7204 else {
7205 return false;
7206 };
7207 let Some((next, selection)) = draft.history.replay(redo) else {
7208 return false;
7209 };
7210 self.editor
7211 .get_or_insert_with(|| TextEdit::at_end(&draft.text))
7212 .restore_selection(&next, selection);
7213 draft.text = next.clone();
7214 draft.history.commit_replay(next, redo);
7215 return true;
7216 }
7217 if let Some(edit) = self
7218 .table_edit
7219 .as_mut()
7220 .filter(|edit| &edit.target == target)
7221 {
7222 let Some((next, selection)) = edit.history.replay(redo) else {
7223 return false;
7224 };
7225 self.editor
7226 .get_or_insert_with(|| TextEdit::at_end(&edit.draft))
7227 .restore_selection(&next, selection);
7228 edit.draft = next.clone();
7229 edit.history.commit_replay(next, redo);
7230 return true;
7231 }
7232 let text = text_input_value(node);
7233 let Some(history) = self.history.get_mut(&EditorKey::new(scene, target)) else {
7234 return false;
7235 };
7236 history.observe(text);
7237 let Some((next, selection)) = history.replay(redo) else {
7238 return false;
7239 };
7240 if !node.allows_text_edit(&next) || !component.edit_at(scene, &target.path, next.clone()) {
7241 return false;
7242 }
7243 self.editor
7244 .get_or_insert_with(|| TextEdit::at_end(text))
7245 .restore_selection(&next, selection);
7246 if let Some(source) = &mut self.persistent_editor {
7247 source.text.clone_from(&next);
7248 }
7249 if node.kind == "SearchField" {
7250 self.search_query = (!next.is_empty()).then(|| next.clone());
7251 Self::clear_choice(&mut self.choice);
7252 }
7253 history.commit_replay(next, redo);
7254 self.painted_combo_completion = None;
7255 self.dismissed_combo_draft = None;
7256 true
7257 }
7258
7259 pub fn edit_spin(&mut self, node: &Node, action: EditAction<'_>) {
7260 self.edit_spin_from(node, action, EditSource::Keyboard, Instant::now());
7261 }
7262
7263 pub fn edit_spin_from(
7264 &mut self,
7265 node: &Node,
7266 action: EditAction<'_>,
7267 source: EditSource,
7268 now: Instant,
7269 ) {
7270 if !spin_editable(node) {
7271 return;
7272 }
7273 let text = self.editor_value(node).into_owned();
7274 let edit = self.editor.get_or_insert_with(|| TextEdit::at_end(&text));
7275 let previous = edit.clone();
7276 let Some(change) = edit
7277 .apply_mode(&text, action, false, false)
7278 .filter(|change| change.text != text)
7279 else {
7280 self.break_text_edit_group();
7281 return;
7282 };
7283 let mode = self
7284 .spin_draft
7285 .as_ref()
7286 .map_or_else(|| SpinDraftMode::for_node(node), |draft| draft.mode);
7287 if !spin_text_is_valid(&change.text, mode.separator()) {
7288 *edit = previous;
7289 return;
7290 }
7291 let before = previous.selection_state(&text);
7292 let group = Group::for_edit(source, action, before, &change);
7293 let after = edit.selection_state(&change.text);
7294 let (next, record) = Record::new(change, before, after);
7295 let draft = self.spin_draft.get_or_insert_with(|| SpinDraft {
7296 text: text.clone(),
7297 mode,
7298 history: TextHistory::default(),
7299 });
7300 draft.history.observe(&text);
7301 draft.text = next.clone();
7302 draft.history.push(next, record, group, now);
7303 }
7304
7305 pub fn discard_spin_draft(&mut self) {
7306 self.spin_draft = None;
7307 self.editor = None;
7308 }
7309
7310 pub fn commit_spin_draft(&mut self) -> Option<ControlInput> {
7311 let draft = self.spin_draft.take()?;
7312 self.editor = None;
7313 let path = self.focused.as_ref()?.path.clone();
7314 let action = draft.mode.commit(&draft.text)?;
7315 Some(ControlInput {
7316 path,
7317 action: ControlAction::Spin(action),
7318 })
7319 }
7320
7321 pub fn spin_press(&mut self, scene: &Node, layout: &LayoutNode) {
7322 self.spin_pressed = (|| {
7323 let target = self.pressed.as_ref()?;
7324 let node = scene.at_path(&target.path)?;
7325 if !valid(target, scene, layout) || !is_spin_box(node.kind) {
7326 return None;
7327 }
7328 let item = layout.at_path(&target.path)?;
7329 SpinGeometry::for_layout(item, node).action_at(item.map_from_window(self.pointer?)?)
7330 })();
7331 }
7332
7333 pub fn spin_release(&mut self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
7334 let pressed = self.spin_pressed.take()?;
7335 let target = self.pointer_release_target()?;
7336 let node = scene.at_path(&target.path)?;
7337 if !valid(&target, scene, layout) || !is_spin_box(node.kind) {
7338 return None;
7339 }
7340 let item = layout.at_path(&target.path)?;
7341 let action =
7342 SpinGeometry::for_layout(item, node).action_at(item.map_from_window(self.pointer?)?)?;
7343 (action == pressed).then_some(ControlInput {
7344 path: target.path,
7345 action: ControlAction::Spin(action),
7346 })
7347 }
7348
7349 pub fn combo_completion(&self, node: &Node, path: &[usize]) -> Option<ComboCompletion> {
7350 let target = self
7351 .focused
7352 .as_ref()
7353 .filter(|target| target.path == path && target.matches_node(node))?;
7354 if !combo_editable(node)
7355 || node.is_password()
7356 || !node.boolean("auto-complete", false)
7357 || self.choice_open()
7358 || self.menu_open()
7359 || self
7360 .transitioning_stacks
7361 .iter()
7362 .any(|stack| path.starts_with(stack))
7363 {
7364 return None;
7365 }
7366 let draft = text_input_value(node);
7367 let editor = self.editor.as_ref()?;
7368 if !editor.preedit.is_empty()
7369 || editor.caret(draft) != draft.len()
7370 || !editor.selection(draft).is_empty()
7371 || self.dismissed_combo_draft.as_deref() == Some(draft)
7372 {
7373 return None;
7374 }
7375 let value = crate::choice::completion_value(node, draft)?;
7376 Some(ComboCompletion {
7377 target: target.clone(),
7378 value: value.into_owned(),
7379 draft_len: draft.len(),
7380 })
7381 }
7382
7383 pub fn set_painted_combo_completion(&mut self, completion: Option<ComboCompletion>) {
7384 self.painted_combo_completion = completion;
7385 }
7386
7387 pub fn painted_combo_completion_for(
7388 &self,
7389 node: &Node,
7390 path: &[usize],
7391 ) -> Option<&ComboCompletion> {
7392 let painted = self.painted_combo_completion.as_ref()?;
7393 (self.combo_completion(node, path).as_ref() == Some(painted)).then_some(painted)
7394 }
7395
7396 pub fn combo_completion_accepts(&self, key: NavigationKey) -> bool {
7397 matches!(key, NavigationKey::Left | NavigationKey::Right)
7398 && self
7399 .painted_combo_completion
7400 .as_ref()
7401 .is_some_and(|completion| {
7402 (key == NavigationKey::Left) == completion.continues_left()
7403 })
7404 }
7405
7406 fn take_current_combo_completion(&mut self, scene: &Node) -> Option<ComboCompletion> {
7407 let painted = self.painted_combo_completion.take()?;
7408 let path = &painted.target.path;
7409 let node = scene.interactive_at_path(path)?;
7410 if !painted.target.matches_node(node) || scene.row_key_at(path) != painted.target.row_key {
7411 return None;
7412 }
7413 (self.combo_completion(node, path)? == painted).then_some(painted)
7414 }
7415
7416 pub fn accept_combo_completion(
7417 &mut self,
7418 component: &mut impl Component,
7419 scene: &Node,
7420 now: Instant,
7421 ) -> bool {
7422 let Some(completion) = self.take_current_combo_completion(scene) else {
7423 return false;
7424 };
7425 self.edit_text(
7426 component,
7427 scene,
7428 EditAction::Insert(completion.suffix()),
7429 EditSource::Atomic,
7430 now,
7431 )
7432 }
7433
7434 pub fn dismiss_combo_completion(&mut self, scene: &Node) -> bool {
7435 let Some(completion) = self.take_current_combo_completion(scene) else {
7436 return false;
7437 };
7438 self.dismissed_combo_draft = Some(completion.value[..completion.draft_len].to_owned());
7439 true
7440 }
7441
7442 pub fn open_choice(&mut self, scene: &Node, layout: &LayoutNode, target: Target) -> bool {
7443 if scene.at_path(&target.path).is_some_and(combo_editable)
7444 && self
7445 .editor
7446 .as_ref()
7447 .is_some_and(|edit| !edit.preedit.is_empty())
7448 {
7449 return false;
7450 }
7451 let Some(mut popup) = ChoicePopup::open(target.clone(), scene, layout) else {
7452 return false;
7453 };
7454 self.set_focus(Some(target));
7455 self.cancel_shortcut_sequence();
7456 Self::clear_choice(&mut self.choice);
7457 popup.mounted(scene);
7458 self.choice = Some(popup);
7459 self.choice_typeahead = Typeahead::default();
7460 self.pressed = None;
7461 self.pressed_radio = None;
7462 self.hovered = None;
7463 self.set_split_hover(None);
7464 self.hovered_radio = None;
7465 true
7466 }
7467
7468 pub fn open_choice_at_pointer(
7469 &mut self,
7470 scene: &Node,
7471 layout: &LayoutNode,
7472 target: Target,
7473 ) -> bool {
7474 let origin = self.press_origin.take();
7475 let Some(node) = scene
7476 .at_path(&target.path)
7477 .filter(|node| node.kind == "ComboBox")
7478 else {
7479 return false;
7480 };
7481 if combo_editable(node) {
7482 let Some(item) = layout.at_path(&target.path) else {
7483 return false;
7484 };
7485 let trigger =
7486 ComboGeometry::for_control(node, item.bounds, item.layout_direction).trigger;
7487 if !origin.zip(self.pointer).is_some_and(|(start, end)| {
7488 [start, end].into_iter().all(|point| {
7489 item.map_from_window(point)
7490 .is_some_and(|point| trigger.contains(point))
7491 })
7492 }) {
7493 return false;
7494 }
7495 }
7496 self.open_choice(scene, layout, target)
7497 }
7498
7499 pub fn choice_open(&self) -> bool {
7500 self.choice.is_some()
7501 }
7502
7503 pub fn choice_is_open_for(&self, path: &[usize]) -> bool {
7504 self.choice
7505 .as_ref()
7506 .is_some_and(|popup| popup.target.path == path)
7507 }
7508
7509 #[doc(hidden)]
7510 pub fn choice_artwork_dirty(&self, scene: &Node, layout: &LayoutNode) -> bool {
7511 self.choice
7512 .as_ref()
7513 .is_some_and(|popup| popup.artwork_dirty(scene, layout))
7514 }
7515
7516 pub fn dismiss_choice(&mut self) {
7517 Self::clear_choice(&mut self.choice);
7518 self.search_query = None;
7519 self.choice_typeahead = Typeahead::default();
7520 }
7521
7522 fn clear_choice(choice: &mut Option<ChoicePopup>) {
7523 if let Some(popup) = choice.take() {
7524 popup.closed();
7525 }
7526 }
7527
7528 fn reconcile_search_choice(&mut self, scene: &Node, layout: &LayoutNode) {
7529 let Some(query) = &self.search_query else {
7530 return;
7531 };
7532 let Some(target) = self
7533 .focused
7534 .as_ref()
7535 .filter(|target| valid(target, scene, layout))
7536 else {
7537 self.dismiss_choice();
7538 return;
7539 };
7540 if !scene
7541 .at_path(&target.path)
7542 .is_some_and(|node| node.kind == "SearchField" && text_input_value(node) == query)
7543 || self.menu_open()
7544 || !target
7545 .path
7546 .starts_with(self.active_dialog(layout).unwrap_or_default())
7547 {
7548 self.dismiss_choice();
7549 return;
7550 }
7551 if self.choice.is_none() {
7552 self.choice = ChoicePopup::open(target.clone(), scene, layout);
7553 }
7554 }
7555
7556 pub fn choice_menu<'a>(&self, scene: &'a Node, layout: &LayoutNode) -> Option<ChoiceMenu<'a>> {
7557 self.choice.as_ref()?.view(scene, layout)
7558 }
7559
7560 pub fn choice_press(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
7561 let Some(popup) = &mut self.choice else {
7562 return false;
7563 };
7564 if let Some(point) = self.pointer {
7565 if popup.press(scene, layout, point) {
7566 return true;
7567 }
7568 let within_search = scene
7569 .at_path(&popup.target.path)
7570 .is_some_and(|node| node.kind == "SearchField")
7571 && layout
7572 .at_path(&popup.target.path)
7573 .is_some_and(|item| item.contains_subtree_point(point));
7574 self.dismiss_choice();
7575 if within_search {
7576 self.pointer_move(scene, layout, point);
7577 return false;
7578 }
7579 } else {
7580 self.dismiss_choice();
7581 }
7582 true
7583 }
7584
7585 pub fn choice_release(&mut self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
7586 let popup = self.choice.as_mut()?;
7587 let index = popup.release(scene, layout, self.pointer?)?;
7588 let path = popup.target.path.clone();
7589 self.dismiss_choice();
7590 if scene.at_path(&path).is_some_and(combo_editable) {
7591 self.editor = None;
7592 }
7593 Some(ControlInput {
7594 path,
7595 action: ControlAction::Select(index),
7596 })
7597 }
7598
7599 pub fn choice_scroll(&mut self, scene: &Node, layout: &LayoutNode, rows: isize) -> bool {
7600 if let Some(popup) = &mut self.choice {
7601 popup.scroll(scene, layout, rows);
7602 true
7603 } else {
7604 false
7605 }
7606 }
7607
7608 pub fn choice_key(
7609 &mut self,
7610 scene: &Node,
7611 layout: &LayoutNode,
7612 key: ChoiceKey,
7613 ) -> Option<ControlInput> {
7614 self.choice_typeahead = Typeahead::default();
7615 if let Some(popup) = &mut self.choice {
7616 return match key {
7617 ChoiceKey::Escape | ChoiceKey::Open => {
7618 self.dismiss_choice();
7619 None
7620 }
7621 ChoiceKey::Accept => {
7622 let path = popup.target.path.clone();
7623 let action = if let Some(index) = popup.selected(scene, layout) {
7624 ControlAction::Select(index)
7625 } else if scene
7626 .at_path(&path)
7627 .is_some_and(|node| node.kind == "SearchField")
7628 {
7629 ControlAction::SubmitSearch
7630 } else {
7631 return None;
7632 };
7633 self.dismiss_choice();
7634 if scene.at_path(&path).is_some_and(combo_editable) {
7635 self.editor = None;
7636 }
7637 Some(ControlInput { path, action })
7638 }
7639 _ => {
7640 popup.move_highlight(scene, layout, key);
7641 None
7642 }
7643 };
7644 }
7645 let target = self.focused.as_ref()?;
7646 if !valid(target, scene, layout) {
7647 return None;
7648 }
7649 let node = scene.at_path(&target.path)?;
7650 if node.kind == "SearchField" {
7651 return match key {
7652 ChoiceKey::Accept => {
7653 let path = target.path.clone();
7654 self.dismiss_choice();
7655 Some(ControlInput {
7656 path,
7657 action: ControlAction::SubmitSearch,
7658 })
7659 }
7660 ChoiceKey::Open | ChoiceKey::Down | ChoiceKey::Up => {
7661 let text = text_input_value(node);
7662 self.search_query = (!text.is_empty()).then(|| text.to_owned());
7663 self.reconcile_search_choice(scene, layout);
7664 if let Some(popup) = &mut self.choice {
7665 popup.move_highlight(scene, layout, key);
7666 }
7667 None
7668 }
7669 ChoiceKey::Escape => {
7670 self.dismiss_choice();
7671 None
7672 }
7673 _ => None,
7674 };
7675 }
7676 if node.kind != "ComboBox" {
7677 return None;
7678 }
7679 if key == ChoiceKey::Open
7680 || combo_editable(node) && matches!(key, ChoiceKey::Up | ChoiceKey::Down)
7681 {
7682 self.open_choice(scene, layout, target.clone());
7683 return None;
7684 }
7685 if combo_editable(node) {
7686 return (key == ChoiceKey::Accept
7687 && self
7688 .editor
7689 .as_ref()
7690 .is_none_or(|edit| edit.preedit.is_empty()))
7691 .then(|| ControlInput {
7692 path: target.path.clone(),
7693 action: ControlAction::AcceptComboText,
7694 });
7695 }
7696 let current = combo_index(node);
7697 let index = next_choice(node, current, key, CHOICE_PAGE)?;
7698 (current != Some(index)).then(|| ControlInput {
7699 path: target.path.clone(),
7700 action: ControlAction::Select(index),
7701 })
7702 }
7703
7704 pub fn choice_typeahead(
7705 &mut self,
7706 scene: &Node,
7707 layout: &LayoutNode,
7708 text: &str,
7709 now: Instant,
7710 ) -> Option<ControlInput> {
7711 let target = self
7712 .focused
7713 .as_ref()
7714 .filter(|target| valid(target, scene, layout))?;
7715 let node = scene.at_path(&target.path)?;
7716 if node.kind != "ComboBox" || combo_editable(node) {
7717 return None;
7718 }
7719 if let Some(popup) = &mut self.choice {
7720 popup.typeahead(scene, layout, &mut self.choice_typeahead, text, now);
7721 return None;
7722 }
7723 let current = combo_index(node);
7724 let index = self.choice_typeahead.find(node, text, now, current)?;
7725 (current != Some(index)).then(|| ControlInput {
7726 path: target.path.clone(),
7727 action: ControlAction::Select(index),
7728 })
7729 }
7730
7731 fn typeahead_view<'a>(&self, scene: &Node, focus: &'a Target) -> &'a [usize] {
7732 list_item_delegate_row(scene, &focus.path).map_or(focus.path.as_slice(), |(view, _)| view)
7733 }
7734
7735 pub fn list_typeahead_focus(&self, scene: &Node) -> Option<&Target> {
7736 if self.editor.is_some() || self.menu_open() || self.choice_open() {
7737 return None;
7738 }
7739 let focus = self.focused.as_ref()?;
7740 let view = self.typeahead_view(scene, focus);
7741 scene.interactive_at_path(view)?.list_text_search.as_ref()?;
7742 Some(focus)
7743 }
7744
7745 pub fn list_typeahead_ime_area(&self, scene: &Node, layout: &LayoutNode) -> Option<Rect> {
7746 let focus = self
7747 .list_typeahead_focus(scene)
7748 .filter(|focus| valid(focus, scene, layout))?;
7749 let item = layout.at_path(self.typeahead_view(scene, focus))?;
7750 let bounds = item.visible_window_bounds(item.bounds);
7751 (bounds.width > 0.0 && bounds.height > 0.0).then(|| {
7752 let offset = if item.layout_direction == LayoutDirection::RightToLeft {
7753 (bounds.width - 6.0).max(0.0)
7754 } else {
7755 6.0_f32.min(bounds.width)
7756 };
7757 Rect::new(bounds.x + offset, bounds.y, 1.0, bounds.height.min(28.0))
7758 })
7759 }
7760
7761 pub fn reset_list_typeahead(&mut self) {
7762 self.list_typeahead = Typeahead::default();
7763 }
7764
7765 pub fn list_typeahead(
7766 &mut self,
7767 scene: &Node,
7768 layout: &LayoutNode,
7769 text: &str,
7770 now: Instant,
7771 ) -> Option<ControlInput> {
7772 if text.trim().is_empty() {
7773 return None;
7774 }
7775 let focus = self
7776 .list_typeahead_focus(scene)
7777 .filter(|focus| valid(focus, scene, layout))?;
7778 let path = self.typeahead_view(scene, focus).to_vec();
7779 let from_delegate = focus.path != path;
7780 let node = scene.interactive_at_path(&path)?;
7781 let search = node.list_text_search.as_ref()?;
7782 let item = layout.at_path(&path)?;
7783 let current = ListMetrics::selection(node)
7784 .and_then(|index| usize::try_from(index).ok())
7785 .filter(|&index| node.list.is_some_and(|list| index < list.row_count));
7786 let index = self
7787 .list_typeahead
7788 .find_with(text, now, current, |start, prefix| {
7789 search.find(start, |label| matches_prefix(label, prefix))
7790 })?;
7791 self.reveal_row(&path, node, item, index);
7792 if from_delegate {
7793 let saved = std::mem::take(&mut self.list_typeahead);
7794 self.set_focus(Some(Target::from_node(
7795 path.clone(),
7796 node,
7797 true,
7798 scene.row_key_at(&path),
7799 )));
7800 self.list_typeahead = saved;
7801 }
7802 Some(ControlInput {
7803 path,
7804 action: ControlAction::Select(index),
7805 })
7806 }
7807
7808 pub fn pointer_move(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> bool {
7809 if self.pointer != Some(point) {
7810 self.tooltip.source = TooltipSource::Pointer;
7811 }
7812 if self.editor_press.as_ref().is_some_and(|press| {
7813 let start = press.sample.0;
7814 (point.x - start.x).hypot(point.y - start.y)
7815 > crate::pointer_events::PRESS_AND_HOLD_SLOP
7816 }) {
7817 self.editor_press = None;
7818 }
7819 if let Some((start, target)) = self.press_origin.zip(self.pressed.as_ref())
7820 && target.text_link_index().is_some()
7821 && target
7822 .node_in(scene)
7823 .is_some_and(Node::selectable_styled_text)
7824 && (point.x - start.x).hypot(point.y - start.y)
7825 > crate::pointer_events::PRESS_AND_HOLD_SLOP
7826 {
7827 self.pointer_activation_claimed = true;
7828 }
7829 self.pointer = Some(point);
7830 if self.wheel_steps.as_ref().is_some_and(|steps| {
7831 self.pointer_hover_target(scene, layout)
7832 .is_none_or(|target| {
7833 !target.path.starts_with(&steps.path) || target.row_key != steps.row
7834 })
7835 }) {
7836 self.reset_wheel_adjustment();
7837 }
7838 let hit = self.hit_at(scene, layout, point);
7839 let cancelled_delay = self.delay_hold.as_ref().is_some_and(|hold| {
7840 matches!(hold.source, DelaySource::Pointer)
7841 && !matches!(&hit, Hit::Target(target) if *target == hold.target)
7842 });
7843 if cancelled_delay {
7844 self.cancel_delay();
7845 }
7846 if self.button_hold.as_ref().is_some_and(|repeat| {
7847 matches!(repeat.source, DelaySource::Pointer)
7848 && (repeat.moved_too_far(point)
7849 || !matches!(&hit, Hit::Target(target) if *target == repeat.target))
7850 }) {
7851 self.button_hold = None;
7852 }
7853 self.pointer_on_stack_slide = matches!(hit, Hit::StackSlide);
7854 if self.menu.is_some() || self.choice.is_some() {
7855 self.set_split_hover(None);
7856 }
7857 if let Some(popup) = &mut self.menu {
7858 return popup.hover(scene, layout, point);
7859 }
7860 if let Some(popup) = &mut self.choice {
7861 return popup.hover(scene, layout, point);
7862 }
7863 let (next, scroll_bar, control_part, row_grip) = match hit {
7864 Hit::Target(target) => (Some(target), None, None, None),
7865 Hit::ScrollBar(target) => (None, Some(target), None, None),
7866 Hit::ControlPart(target, action) => (Some(target), None, Some(action), None),
7867 Hit::TableRowGrip(target, slot) => {
7868 let grip = scene
7869 .at_path(&target.path)
7870 .zip(layout.at_path(&target.path))
7871 .and_then(|(node, item)| {
7872 Some((
7873 node.children.get(slot)?.row_key?,
7874 item.children.get(slot)?.bounds.height,
7875 ))
7876 });
7877 (Some(target), None, None, grip)
7878 }
7879 _ => (None, None, None, None),
7880 };
7881 let radio = next
7882 .as_ref()
7883 .and_then(|target| scene.at_path(&target.path))
7884 .filter(|node| node.kind == "RadioButton")
7885 .map(|node| (node.text("text").unwrap_or(""), radio_value(node)));
7886 let previous_radio = self
7887 .hovered_radio
7888 .as_ref()
7889 .map(|(label, value)| (label.as_str(), value.as_str()));
7890 let list_row = next.as_ref().and_then(|target| list_row(scene, target));
7891 let standard_button = next
7892 .as_ref()
7893 .and_then(|target| scene.at_path(&target.path))
7894 .and_then(Node::standard_button_kind);
7895 let tree_indicator = next.as_ref().is_some_and(|target| {
7896 scene
7897 .at_path(&target.path)
7898 .zip(layout.at_path(&target.path))
7899 .is_some_and(|(node, item)| tree_indicator_hit(node, item, point))
7900 });
7901 let body_column = next.as_ref().and_then(|target| {
7902 let (path, _) = table_hit_row(scene, &target.path)?;
7903 if scene.at_path(path)?.selection_target() == SelectionTarget::Rows {
7904 return None;
7905 }
7906 let item = layout.at_path(path)?;
7907 item.table
7908 .as_ref()?
7909 .body_column_at(item.map_from_window(point)?)
7910 });
7911 let mut table_grip = None;
7912 let mut table_column = None;
7913 if let Some(target) = &next
7914 && let Some(node) = scene.at_path(&target.path)
7915 && let Some(item) = layout.at_path(&target.path)
7916 && let Some(table) = &item.table
7917 && let Some(point) = item.map_from_window(point)
7918 {
7919 if let Some(index) = table.resize_at(node, item.clip, point) {
7920 let bounds = table.columns[index];
7921 table_grip = Some((index, bounds.width, table.mirrored()));
7922 } else if let Some(index) = table.column_at(point)
7923 && (node.selection_target() == SelectionTarget::Columns
7924 || node
7925 .table_header
7926 .as_ref()
7927 .is_some_and(|header| header.next_sort(index).is_some()))
7928 {
7929 table_column = Some(index);
7930 }
7931 }
7932 let changed = cancelled_delay
7933 || next != self.hovered
7934 || scroll_bar != self.hovered_scroll_bar
7935 || control_part != self.hovered_control_part
7936 || standard_button != self.hovered_standard_button
7937 || radio != previous_radio
7938 || list_row != self.hovered_list_row
7939 || tree_indicator != self.hovered_tree_indicator
7940 || table_column != self.hovered_table_column
7941 || table_grip != self.hovered_table_grip
7942 || row_grip != self.hovered_table_row_grip
7943 || body_column != self.hovered_body_column;
7944 if radio != previous_radio {
7945 self.hovered_radio = radio.map(|(label, value)| (label.to_owned(), value.to_owned()));
7946 }
7947 let split_hover = next.as_ref().and_then(|target| {
7948 let (path, _, handle) = split_target(target, scene, layout)?;
7949 if scene.at_path(&target.path)?.children.is_empty() {
7950 return None;
7951 }
7952 let state = scene.at_path(path)?.split_resize_handle.clone()?;
7953 Some((state, handle.slot))
7954 });
7955 self.set_split_hover(split_hover);
7956 self.hovered = next;
7957 self.hovered_scroll_bar = scroll_bar;
7958 self.hovered_control_part = control_part;
7959 self.hovered_standard_button = standard_button;
7960 self.hovered_list_row = list_row;
7961 self.hovered_tree_indicator = tree_indicator;
7962 self.hovered_table_column = table_column;
7963 self.hovered_table_grip = table_grip;
7964 self.hovered_table_row_grip = row_grip;
7965 self.hovered_body_column = body_column;
7966 changed
7967 }
7968 pub fn pointer_leave(&mut self) -> bool {
7969 let cancelled_table_selection = self.cancel_table_drag_selection();
7970 let cancelled_row_move = self.cancel_table_row_move();
7971 self.cancel_window_move();
7972 let cancelled_delay = self
7973 .delay_hold
7974 .as_ref()
7975 .is_some_and(|hold| matches!(hold.source, DelaySource::Pointer));
7976 if cancelled_delay {
7977 self.cancel_delay();
7978 }
7979 let cancelled_repeat = self
7980 .button_hold
7981 .as_ref()
7982 .is_some_and(|repeat| matches!(repeat.source, DelaySource::Pointer));
7983 if cancelled_repeat {
7984 self.button_hold = None;
7985 }
7986 self.pointer = None;
7987 self.set_split_hover(None);
7988 self.tumbler_wheel = None;
7989 self.reset_wheel_adjustment();
7990 self.pointer_on_stack_slide = false;
7991 let tooltip_was_visible = self.tooltip.pointer_left();
7992 self.hovered_radio = None;
7993 self.hovered_list_row = None;
7994 self.hovered_tree_indicator = false;
7995 self.hovered_table_column = None;
7996 self.hovered_table_grip = None;
7997 self.hovered_table_row_grip = None;
7998 self.hovered_body_column = None;
7999 self.hovered_control_part = None;
8000 self.hovered_standard_button = None;
8001 let bar = self.hovered_scroll_bar.take().is_some();
8002 self.hovered.take().is_some()
8003 || bar
8004 || tooltip_was_visible
8005 || cancelled_delay
8006 || cancelled_repeat
8007 || cancelled_table_selection
8008 || cancelled_row_move
8009 }
8010 pub fn pointer_press(&mut self) {
8011 self.press(None, None, false);
8012 }
8013
8014 pub fn pointer_press_in_scene(&mut self, scene: &Node, layout: &LayoutNode) {
8015 self.replay_tap_in_scene(scene, layout);
8016 if let Some(target) = self.pressed.clone() {
8017 self.start_button_contact(scene, target, ButtonContactSource::Pointer);
8018 }
8019 }
8020
8021 pub fn replay_tap_in_scene(&mut self, scene: &Node, layout: &LayoutNode) {
8023 self.remember_focus_scope(scene, layout);
8024 let proxy = self
8025 .hovered
8026 .as_ref()
8027 .filter(|target| {
8028 scene
8029 .at_path(&target.path)
8030 .is_some_and(|node| node.kind == "FocusScope")
8031 && valid(target, scene, layout)
8032 })
8033 .map(|target| {
8034 self.scope_focus
8035 .choose(scene, layout, target.clone(), false, false)
8036 });
8037
8038 let preserve_focus = self.hovered.as_ref().is_some_and(|target| {
8039 target.tab_close.is_some()
8040 || scene.at_path(&target.path).is_some_and(|node| {
8041 matches!(node.kind, "Button" | "ToolButton" | "RoundButton")
8042 && !node.boolean("focus-on-click", true)
8043 })
8044 });
8045 self.press(proxy, Some(layout), preserve_focus);
8046 if self.table_resize.is_none() && self.table_row_resize.is_none() {
8047 self.table_column_move =
8048 self.pressed
8049 .as_ref()
8050 .zip(self.pointer)
8051 .and_then(|(target, point)| {
8052 Self::table_column_move_at(scene, layout, target, point)
8053 });
8054 }
8055 if self.table_row_resize.is_none() && self.table_column_move.is_none() {
8056 self.table_row_move =
8057 self.pressed
8058 .as_ref()
8059 .zip(self.pointer)
8060 .and_then(|(pressed, point)| {
8061 Self::table_row_move_at(scene, layout, pressed, point)
8062 });
8063 }
8064 self.remember_focus_scope(scene, layout);
8065 }
8066
8067 fn press(&mut self, proxy: Option<Target>, layout: Option<&LayoutNode>, preserve_focus: bool) {
8068 self.text_selection_scroll = None;
8069 self.editor_press = None;
8070 self.cancel_shortcut_sequence();
8071 self.reset_list_typeahead();
8072 self.reset_wheel_adjustment();
8073 self.cancel_delay();
8074 self.button_hold = None;
8075 self.pointer_activation_claimed = false;
8076 if self.pointer_on_stack_slide {
8077 return;
8078 }
8079 self.press_origin = self.pointer;
8080 self.tooltip.source = TooltipSource::Pointer;
8081 self.tooltip.dismiss();
8082 self.pressed = self.hovered.clone();
8083 self.pressed_radio.clone_from(&self.hovered_radio);
8084 self.pressed_list_row = self.hovered_list_row.clone();
8085 self.pressed_tree_indicator = self.hovered_tree_indicator;
8086 self.pressed_table_column = self.hovered_table_column;
8087 self.table_column_move = None;
8088 self.table_row_move = None;
8089 self.table_drag_selection = None;
8090 self.pressed_body_column = self.hovered_body_column;
8091 self.pressed_control_part = self.hovered_control_part;
8092 self.pressed_standard_button = self.hovered_standard_button;
8093 self.table_resize = (|| {
8094 let (column, width, mirrored) = self.hovered_table_grip?;
8095 let target = self.pressed.clone()?;
8096 let pointer = self.pointer?;
8097 let point = match layout {
8098 Some(layout) => layout.at_path(&target.path)?.map_from_window(pointer)?,
8099 None => pointer,
8100 };
8101 Some(TableResize {
8102 target,
8103 column,
8104 pointer_x: point.x,
8105 width,
8106 mirrored,
8107 })
8108 })();
8109 self.table_row_resize = (|| {
8110 let (key, height) = self.hovered_table_row_grip?;
8111 let target = self.pressed.clone()?;
8112 let pointer = self.pointer?;
8113 let point = match layout {
8114 Some(layout) => layout.at_path(&target.path)?.map_from_window(pointer)?,
8115 None => pointer,
8116 };
8117 Some(TableRowResize {
8118 target,
8119 key,
8120 pointer_y: point.y,
8121 height,
8122 })
8123 })();
8124 self.slider_offset = 0.0;
8125 self.slider_anchor = None;
8126 self.slider_fraction = None;
8127 self.clear_range_preview();
8128 self.dial_pointer = None;
8129 self.spin_pressed = None;
8130 let focus = self.hovered.clone().and_then(|mut target| {
8131 if let Some((_, id)) = &self.hovered_list_row {
8132 target.path.pop();
8133 target.set_element_id(id.clone());
8134 target.focusable = true;
8135 target.row_key = None;
8136 }
8137 target.focusable.then_some(target)
8138 });
8139 if self.table_row_resize.is_none() && !preserve_focus {
8140 self.set_focus_with_reason(proxy.or(focus), xrack_runtime::FocusReason::PointerClick);
8141 }
8142 self.key_pressed = None;
8143 }
8144
8145 pub fn split_press(&mut self, scene: &Node, layout: &LayoutNode) {
8146 self.clear_split_drag();
8147 self.split_drag = (|| {
8148 let target = self.pressed.as_ref()?;
8149 let (path, geometry, handle) = split_target(target, scene, layout)?;
8150 let orientation = geometry.orientation;
8151 let point = layout.at_path(path)?.map_from_window(self.pointer?)?;
8152 let position = axis_point(orientation, point);
8153 let state = scene.at_path(path)?.split_resize_handle.clone();
8154 if let Some(state) = &state {
8155 state.publish_pressed(Some((handle.slot, handle.after_pane())));
8156 }
8157 Some(SplitDrag {
8158 target: target.clone(),
8159 orientation,
8160 mirrored: geometry.mirrored,
8161 after_pane: handle.after_pane(),
8162 grab_offset: position - handle.center(orientation),
8163 state,
8164 })
8165 })();
8166 }
8167
8168 pub fn split_resize_active(&self) -> bool {
8169 self.split_drag.is_some()
8170 }
8171
8172 fn set_split_hover(&mut self, next: Option<(xrack_runtime::SplitResizeHandle, usize)>) {
8173 if next == self.split_hover {
8174 return;
8175 }
8176 if let Some((state, _)) = self.split_hover.take()
8177 && next.as_ref().is_none_or(|(next, _)| *next != state)
8178 {
8179 state.publish_hovered(None);
8180 }
8181 if let Some((state, slot)) = &next {
8182 state.publish_hovered(Some(*slot));
8183 }
8184 self.split_hover = next;
8185 }
8186
8187 pub fn touch_split_press(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> bool {
8188 if self.menu.is_some() || self.choice.is_some() {
8189 return false;
8190 }
8191 let Hit::Target(target) = self.hit_at(scene, layout, point) else {
8192 return false;
8193 };
8194 if split_target(&target, scene, layout).is_none() {
8195 return false;
8196 }
8197 self.pointer_move(scene, layout, point);
8198 self.pointer_press_in_scene(scene, layout);
8199 self.split_press(scene, layout);
8200 self.split_resize_active()
8201 }
8202
8203 fn clear_split_drag(&mut self) -> bool {
8204 let Some(drag) = self.split_drag.take() else {
8205 return false;
8206 };
8207 if let Some(state) = drag.state {
8208 state.publish_pressed(None);
8209 }
8210 true
8211 }
8212
8213 pub fn split_orientation(&self, scene: &Node) -> Option<Orientation> {
8214 if let Some(drag) = &self.split_drag {
8215 return Some(drag.orientation);
8216 }
8217 let handle = scene.at_path(&self.hovered.as_ref()?.path)?;
8218 (handle.kind == "SplitHandle").then(|| handle.orientation())
8219 }
8220
8221 pub fn split_drag(&self, scene: &Node, layout: &LayoutNode) -> Option<SplitResize> {
8222 let drag = self.split_drag.as_ref()?;
8223 let (path, geometry, handle) = split_target(&drag.target, scene, layout)?;
8224 if !drag.matches(geometry, handle) {
8225 return None;
8226 }
8227 let point = layout.at_path(path)?.map_from_window(self.pointer?)?;
8228 let position = axis_point(drag.orientation, point) - drag.grab_offset;
8229 geometry.resize(
8230 path.to_vec(),
8231 handle,
8232 geometry.logical_delta(position - handle.center(drag.orientation)),
8233 )
8234 }
8235
8236 pub fn finish_split_resize(&mut self) -> bool {
8237 if !self.clear_split_drag() {
8238 return false;
8239 }
8240 self.cancel_press();
8241 true
8242 }
8243
8244 pub fn split_key(
8245 &self,
8246 scene: &Node,
8247 layout: &LayoutNode,
8248 key: NavigationKey,
8249 ) -> Option<SplitResize> {
8250 let (path, geometry, handle) = split_target(self.focused.as_ref()?, scene, layout)?;
8251 let step = SplitHandleRange::STEP as f32;
8252 let delta = match (geometry.orientation, key) {
8253 (Orientation::Horizontal, NavigationKey::Left)
8254 | (Orientation::Vertical, NavigationKey::Up) => geometry.logical_delta(-step),
8255 (Orientation::Horizontal, NavigationKey::Right)
8256 | (Orientation::Vertical, NavigationKey::Down) => geometry.logical_delta(step),
8257 (_, NavigationKey::Home) => handle.minimum,
8258 (_, NavigationKey::End) => handle.maximum,
8259 _ => return None,
8260 };
8261 geometry.resize(path.to_vec(), handle, delta)
8262 }
8263
8264 pub fn split_set_value(
8266 &self,
8267 scene: &Node,
8268 layout: &LayoutNode,
8269 target: &Target,
8270 value: f64,
8271 ) -> Option<SplitResize> {
8272 if !value.is_finite() {
8273 return None;
8274 }
8275 let (path, geometry, handle) = split_target(target, scene, layout)?;
8276 let range = geometry.handle_range(handle);
8277 let delta = value.clamp(range.minimum, range.maximum) - range.value;
8278 geometry.resize(path.to_vec(), handle, delta as f32)
8279 }
8280
8281 pub fn range_pointer_press(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> bool {
8282 if self.menu.is_some() || self.choice.is_some() {
8283 return false;
8284 }
8285 let Hit::Target(target) = self.hit_at(scene, layout, point) else {
8286 return false;
8287 };
8288 if slider_target(&target, scene, layout).is_none() {
8289 return false;
8290 }
8291 self.pointer_move(scene, layout, point);
8292 self.pointer_press_in_scene(scene, layout);
8293 true
8294 }
8295
8296 pub fn touch_range_press(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> bool {
8297 if !self.range_pointer_press(scene, layout, point) {
8298 return false;
8299 }
8300 self.touch_range = true;
8301 true
8302 }
8303
8304 pub fn touch_range_captured(&self) -> bool {
8305 self.touch_range
8306 }
8307
8308 pub fn finish_touch_range(&mut self) {
8309 if std::mem::take(&mut self.touch_range) {
8310 self.cancel_press();
8311 self.pointer_leave();
8312 }
8313 }
8314
8315 pub fn slider_press(&mut self, scene: &Node, layout: &LayoutNode) -> Option<RangeInput> {
8316 let target = self.pressed.as_ref()?;
8317 let (path, node) = slider_target(target, scene, layout)?;
8318 let item = layout.at_path(path)?;
8319 let bounds = item.bounds;
8320 let point = item.map_from_window(self.pointer?)?;
8321 if node.kind == "ColorPlane" {
8322 return Some(RangeInput {
8323 path: target.path.clone(),
8324 action: ColorPlaneGeometry::new(bounds).action_at(point)?,
8325 });
8326 }
8327 if node.kind == "Dial" {
8328 self.dial_pointer = Some(point);
8329 let geometry = DialGeometry::new(bounds, node);
8330 let current = SliderRange::from_node(node).fraction();
8331 if node.dial_input_mode() != DialInputMode::Circular
8332 || geometry.contains_thumb(current, point)
8333 {
8334 return None;
8335 }
8336 return Some(RangeInput {
8337 path: path.to_vec(),
8338 action: RangeAction::SetFraction(geometry.fraction_at(point)?),
8339 });
8340 }
8341 let geometry = SliderGeometry::with_layout_direction(bounds, node, item.layout_direction);
8342 let fraction = geometry.fraction_at(point)?;
8343 let mut path = path.to_vec();
8344 let current = if node.kind == "RangeSlider" {
8345 let interval = SliderInterval::from_node(node);
8346 let [lower, upper] = interval.fractions();
8347 let handle = geometry.interval_handle_at(point, fraction, interval);
8348 path.push(handle);
8349 self.focus_slider_thumb(scene, &path);
8350 let current = [lower, upper][handle];
8351 if lower == upper && geometry.thumb_bounds(handle, current).contains(point) {
8352 self.slider_anchor = Some(fraction);
8353 }
8354 current
8355 } else {
8356 SliderRange::from_node(node).fraction()
8357 };
8358 let handle = if node.kind == "RangeSlider" {
8359 *path.last()?
8360 } else {
8361 0
8362 };
8363 if geometry.thumb_bounds(handle, current).contains(point) {
8364 self.slider_offset = current - fraction;
8365 None
8366 } else {
8367 self.slider_pointer_action(node, path, fraction)
8368 }
8369 }
8370
8371 fn focus_slider_thumb(&mut self, scene: &Node, path: &[usize]) {
8372 let target = Target::from_element_id(path.to_vec(), None, true, scene.row_key_at(path));
8373 self.set_focus(Some(target.clone()));
8374 self.pressed = Some(target);
8375 }
8376
8377 #[doc(hidden)]
8379 pub fn interval_preview(&self, node: &Node, path: &[usize]) -> Option<(usize, f64)> {
8380 if node.boolean("live", true) {
8381 return None;
8382 }
8383 let (pressed, fraction) = self.slider_preview_position()?;
8384 let (&index, parent) = pressed.split_last()?;
8385 (parent == path && index < Node::RANGE_THUMBS).then_some((index, fraction))
8386 }
8387
8388 #[doc(hidden)]
8389 pub fn slider_preview_position(&self) -> Option<(&[usize], f64)> {
8390 Some((
8391 self.pressed.as_ref()?.path.as_slice(),
8392 self.slider_fraction?,
8393 ))
8394 }
8395
8396 pub fn slider_drag(&mut self, scene: &Node, layout: &LayoutNode) -> Option<RangeInput> {
8397 let target = self.pressed.as_ref()?;
8398 let (owner, node) = slider_target(target, scene, layout)?;
8399 let item = layout.at_path(owner)?;
8400 let bounds = item.bounds;
8401 let point = item.map_from_window(self.pointer?)?;
8402 if node.kind == "ColorPlane" {
8403 return Some(RangeInput {
8404 path: target.path.clone(),
8405 action: ColorPlaneGeometry::new(bounds).action_at(point)?,
8406 });
8407 }
8408 if node.kind == "Dial" {
8409 let previous = self.dial_pointer.replace(point)?;
8410 let delta = DialGeometry::new(bounds, node).drag_delta(
8411 node.dial_input_mode(),
8412 previous,
8413 point,
8414 )?;
8415 let current = SliderRange::from_node(node).fraction();
8416 let next = current + delta;
8417 let next = if node.boolean("wrap", false) && !(0.0..=1.0).contains(&next) {
8418 next.rem_euclid(1.0)
8419 } else {
8420 next.clamp(0.0, 1.0)
8421 };
8422 return (next != current).then(|| RangeInput {
8423 path: target.path.clone(),
8424 action: RangeAction::SetFraction(next),
8425 });
8426 }
8427 let fraction = SliderGeometry::with_layout_direction(bounds, node, item.layout_direction)
8428 .fraction_at(point)?;
8429 let mut path = target.path.clone();
8430 if let Some(anchor) = self.slider_anchor {
8431 if fraction == anchor {
8432 return None;
8433 }
8434 path.truncate(owner.len());
8435 path.push(usize::from(fraction > anchor));
8436 self.focus_slider_thumb(scene, &path);
8437 self.slider_anchor = None;
8438 }
8439 self.slider_pointer_action(node, path, fraction + self.slider_offset)
8440 }
8441
8442 fn slider_pointer_action(
8443 &mut self,
8444 node: &Node,
8445 path: Vec<usize>,
8446 fraction: f64,
8447 ) -> Option<RangeInput> {
8448 let live = node.boolean("live", true);
8449 if !live || SliderRange::from_node(node).snap_mode() == ScrollSnapMode::OnRelease {
8450 self.slider_fraction = Some(fraction);
8451 if self.range_position_handle.as_ref() != node.range_position_handle.as_ref() {
8452 self.clear_range_preview();
8453 self.range_position_handle = node.range_position_handle.clone();
8454 }
8455 if let Some(handle) = &self.range_position_handle {
8456 let index = if node.kind == "RangeSlider" {
8457 path.last().copied().unwrap_or_default()
8458 } else {
8459 0
8460 };
8461 handle.publish_preview(Some((index, fraction)));
8462 }
8463 } else {
8464 self.slider_fraction = None;
8465 self.clear_range_preview();
8466 }
8467 live.then_some(RangeInput {
8468 path,
8469 action: RangeAction::SetFraction(fraction),
8470 })
8471 }
8472
8473 pub fn slider_preview(&self, path: &[usize]) -> Option<f64> {
8474 self.slider_fraction.filter(|_| self.is_pressed(path))
8475 }
8476
8477 pub fn has_slider_preview(&self) -> bool {
8478 self.slider_fraction.is_some() && self.pressed.is_some()
8479 }
8480
8481 pub fn cancel_slider_preview(&mut self) -> bool {
8482 if !self.has_slider_preview() {
8483 return false;
8484 }
8485 self.cancel_press();
8486 true
8487 }
8488
8489 pub fn slider_release(&mut self, scene: &Node, layout: &LayoutNode) -> Option<RangeInput> {
8490 let fraction = self.slider_fraction.take();
8491 self.clear_range_preview();
8492 slider_target(self.pressed.as_ref()?, scene, layout)?;
8493 self.slider_offset = 0.0;
8494 self.slider_anchor = None;
8495 self.dial_pointer = None;
8496 let path = self.pressed.take()?.path;
8497 Some(RangeInput {
8498 path,
8499 action: fraction.map_or(RangeAction::Release, RangeAction::CommitFraction),
8500 })
8501 }
8502
8503 fn clear_range_preview(&mut self) {
8504 if let Some(handle) = self.range_position_handle.take() {
8505 handle.publish_preview(None);
8506 }
8507 }
8508
8509 pub fn slider_key(
8510 &mut self,
8511 scene: &Node,
8512 layout: &LayoutNode,
8513 key: SliderKey,
8514 pressed: bool,
8515 ) -> Option<RangeInput> {
8516 if !pressed {
8517 let target = self.range_keys.remove(&key)?;
8518 if self.focused.as_ref() != Some(&target) {
8519 return None;
8520 }
8521 slider_target(&target, scene, layout)?;
8522 return Some(RangeInput {
8523 path: target.path,
8524 action: RangeAction::Release,
8525 });
8526 }
8527 let target = self.focused.as_ref()?;
8528 if !valid(target, scene, layout) {
8529 return None;
8530 }
8531 let (path, node) = slider_target(target, scene, layout)?;
8532 let action = if node.kind == "ColorPlane" {
8533 let saturation = node.number("saturation").unwrap_or_default();
8534 let brightness = node.number("brightness").unwrap_or_default();
8535 let step = 0.01;
8536 let (x, y) = match key {
8537 SliderKey::Left => (saturation - step, brightness),
8538 SliderKey::Right => (saturation + step, brightness),
8539 SliderKey::Up => (saturation, brightness + step),
8540 SliderKey::Down => (saturation, brightness - step),
8541 _ => return None,
8542 };
8543 RangeAction::SetPoint {
8544 x: x.clamp(0.0, 1.0),
8545 y: y.clamp(0.0, 1.0),
8546 }
8547 } else {
8548 let horizontal = node.kind == "Dial" || node.orientation() == Orientation::Horizontal;
8549 let vertical = node.kind == "Dial" || node.orientation() == Orientation::Vertical;
8550 let mirrored = node.kind != "Dial"
8551 && layout.at_path(path)?.layout_direction == LayoutDirection::RightToLeft;
8552 match key {
8553 SliderKey::Left if horizontal && mirrored => RangeAction::Increase,
8554 SliderKey::Right if horizontal && mirrored => RangeAction::Decrease,
8555 SliderKey::Left if horizontal => RangeAction::Decrease,
8556 SliderKey::Right if horizontal => RangeAction::Increase,
8557 SliderKey::Down if vertical => RangeAction::Decrease,
8558 SliderKey::Up if vertical => RangeAction::Increase,
8559 SliderKey::Home => RangeAction::Minimum,
8560 SliderKey::End => RangeAction::Maximum,
8561 _ => return None,
8562 }
8563 };
8564 self.range_keys.entry(key).or_insert_with(|| target.clone());
8565 Some(RangeInput {
8566 path: target.path.clone(),
8567 action,
8568 })
8569 }
8570
8571 pub fn tab_close_action(
8573 &self,
8574 scene: &Node,
8575 layout: &LayoutNode,
8576 target: &Target,
8577 ) -> Option<ControlInput> {
8578 if !valid(target, scene, layout)
8579 || self.menu_open()
8580 || self.choice_open()
8581 || self
8582 .active_dialog(layout)
8583 .is_some_and(|scope| !target.path.starts_with(scope))
8584 {
8585 return None;
8586 }
8587 let (&index, parent) = target.path.split_last()?;
8588 let item = layout.at_path(&target.path)?;
8589 let rect = item.clip_rect(item.tab_close?);
8590 if rect.width <= 0.0 || rect.height <= 0.0 {
8591 return None;
8592 }
8593 let request = scene.at_path(parent)?.tab_close(index)?;
8594 if let Some((captured, value)) = &target.tab_close
8595 && (*captured != request
8596 || value != scene.at_path(&target.path)?.text("value").unwrap_or(""))
8597 {
8598 return None;
8599 }
8600 Some(ControlInput {
8601 path: parent.to_vec(),
8602 action: ControlAction::CloseTab(request),
8603 })
8604 }
8605
8606 pub fn focused_tab_close(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
8607 self.tab_close_action(scene, layout, self.focused.as_ref()?)
8608 }
8609
8610 pub fn tab_close_hovered(&self, path: &[usize]) -> bool {
8611 self.hovered
8612 .as_ref()
8613 .is_some_and(|target| target.tab_close.is_some() && target.path == path)
8614 }
8615
8616 pub fn select_group_option(
8617 &self,
8618 scene: &Node,
8619 layout: &LayoutNode,
8620 target: &Target,
8621 ) -> Option<ControlInput> {
8622 if target.tab_close.is_some() {
8623 return self.tab_close_action(scene, layout, target);
8624 }
8625 if !valid(target, scene, layout) {
8626 return None;
8627 }
8628 if attached_radio(scene, &target.path).is_some()
8629 && scene.at_path(&target.path)?.kind == "RadioButton"
8630 {
8631 return Some(ControlInput {
8632 path: target.path.clone(),
8633 action: ControlAction::ActivateRadioOption,
8634 });
8635 }
8636 if let Some((view, slot)) =
8637 table_cell_row(scene, &target.path).or_else(|| tree_cell_row(scene, &target.path))
8638 {
8639 if scene.at_path(&target.path)?.boolean("table-editor", false) {
8640 return None;
8641 }
8642 let index = scene.at_path(view)?.list?.first_row.checked_add(slot)?;
8643 return Some(ControlInput {
8644 path: view.to_vec(),
8645 action: ControlAction::Select(index),
8646 });
8647 }
8648 let (&index, path) = target.path.split_last()?;
8649 let index = if let Some((index, _)) = list_row(scene, target) {
8650 index
8651 } else {
8652 group_item(scene.at_path(path)?, index)?;
8653 index
8654 };
8655 Some(ControlInput {
8656 path: path.to_vec(),
8657 action: ControlAction::Select(index),
8658 })
8659 }
8660
8661 pub fn tree_pointer_action(
8662 &self,
8663 scene: &Node,
8664 layout: &LayoutNode,
8665 target: &Target,
8666 ) -> Option<ControlInput> {
8667 let point = self.pointer?;
8668 let node = scene.at_path(&target.path)?;
8669 let item = layout.at_path(&target.path)?;
8670 if !self.hovered_tree_indicator || !tree_indicator_hit(node, item, point) {
8671 return None;
8672 }
8673 self.tree_row_expansion(scene, layout, target, !node.boolean("tree-expanded", false))
8674 }
8675
8676 #[doc(hidden)]
8677 pub fn tree_row_expansion(
8678 &self,
8679 scene: &Node,
8680 layout: &LayoutNode,
8681 target: &Target,
8682 expanded: bool,
8683 ) -> Option<ControlInput> {
8684 if !valid(target, scene, layout) {
8685 return None;
8686 }
8687 let (&slot, path) = target.path.split_last()?;
8688 let node = scene.at_path(path)?;
8689 let index = node.list?.first_row.checked_add(slot)?;
8690 let tree = node.tree.as_ref()?;
8691 if tree.is_filtering() {
8692 return None;
8693 }
8694 let item = tree.rows().get(index)?;
8695 (item.has_children
8696 && item.expanded != expanded
8697 && node.children.get(slot)?.row_key == Some(item.row))
8698 .then_some(ControlInput {
8699 path: path.to_vec(),
8700 action: ControlAction::Tree(TreeAction::SetExpanded {
8701 key: item.key,
8702 row: item.row,
8703 expanded,
8704 }),
8705 })
8706 }
8707
8708 pub fn tree_has_focus(&self, scene: &Node, layout: &LayoutNode) -> bool {
8709 self.focused_tree(scene, layout).is_some()
8710 }
8711
8712 fn focused_tree<'a>(&'a self, scene: &Node, layout: &LayoutNode) -> Option<&'a [usize]> {
8713 let target = self.focused.as_ref()?;
8714 if self.table_edit.is_some()
8715 || !valid(target, scene, layout)
8716 || scene.at_path(&target.path)?.boolean("table-editor", false)
8717 {
8718 return None;
8719 }
8720 let path =
8721 tree_cell_row(scene, &target.path).map_or(target.path.as_slice(), |(path, _)| path);
8722 (scene.at_path(path)?.kind == "TreeView").then_some(path)
8723 }
8724
8725 pub fn tree_toggle(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
8726 let path = self.focused_tree(scene, layout)?;
8727 let node = scene.at_path(path)?;
8728 let tree = node.tree.as_ref()?;
8729 if tree.is_filtering() {
8730 return None;
8731 }
8732 let index = tree.visible_index(node.int("current-key")?)?;
8733 let item = tree.rows().get(index)?;
8734 item.has_children.then_some(ControlInput {
8735 path: path.to_vec(),
8736 action: ControlAction::Tree(TreeAction::SetExpanded {
8737 key: item.key,
8738 row: item.row,
8739 expanded: !item.expanded,
8740 }),
8741 })
8742 }
8743
8744 pub fn tree_key(
8745 &mut self,
8746 scene: &Node,
8747 layout: &LayoutNode,
8748 key: NavigationKey,
8749 ) -> Option<ControlInput> {
8750 if !matches!(key, NavigationKey::Left | NavigationKey::Right) {
8751 return None;
8752 }
8753 let path = self.focused_tree(scene, layout)?.to_vec();
8754 let node = scene.at_path(&path)?;
8755 let view = layout.at_path(&path)?;
8756 let forward = (key == NavigationKey::Right)
8757 != (view.layout_direction == LayoutDirection::RightToLeft);
8758 let tree = node.tree.as_ref()?;
8759 let index = tree.visible_index(node.int("current-key")?)?;
8760 let item = tree.rows().get(index)?;
8761 if !tree.is_filtering() && item.has_children && forward != item.expanded {
8762 return self.tree_toggle(scene, layout);
8763 }
8764 let next = if !forward {
8765 tree.visible_index(item.parent?)?
8766 } else {
8767 index.checked_add(1).filter(|&next| {
8768 tree.rows()
8769 .get(next)
8770 .is_some_and(|next| next.parent == Some(item.key))
8771 })?
8772 };
8773 self.reveal_row(&path, node, view, next);
8774 self.set_focus(Some(Target::from_node(
8775 path.clone(),
8776 node,
8777 true,
8778 scene.row_key_at(&path),
8779 )));
8780 Some(ControlInput {
8781 path,
8782 action: ControlAction::Select(next),
8783 })
8784 }
8785
8786 pub fn tree_key_with_selection(
8787 &mut self,
8788 scene: &Node,
8789 layout: &LayoutNode,
8790 key: NavigationKey,
8791 operation: RowSelection,
8792 ) -> Option<ControlInput> {
8793 Some(
8794 self.tree_key(scene, layout, key)?
8795 .with_row_selection(scene, operation),
8796 )
8797 }
8798
8799 pub fn select_group_option_with_selection(
8800 &self,
8801 scene: &Node,
8802 layout: &LayoutNode,
8803 target: &Target,
8804 operation: RowSelection,
8805 ) -> Option<ControlInput> {
8806 let mut input = self.select_group_option(scene, layout, target)?;
8807 let node = scene.at_path(&input.path)?;
8808 let ControlAction::Select(row) = input.action else {
8809 return Some(input);
8810 };
8811 if let Some(selection) = &node.table_selection {
8812 if self.pointer.is_some_and(|point| {
8813 layout.at_path(&input.path).is_some_and(|item| {
8814 item.table
8815 .as_ref()
8816 .zip(item.map_from_window(point))
8817 .is_some_and(|(table, point)| table.row_header.contains(point))
8818 })
8819 }) && let Some(action) =
8820 self.table_row_header_selection(scene, layout, target, operation)
8821 {
8822 return Some(action);
8823 }
8824 let column = if table_cell_row(scene, &target.path).is_some() {
8825 target.path.last().copied()
8826 } else {
8827 self.hovered_body_column
8828 };
8829 let action = match selection.target() {
8830 SelectionTarget::Rows => TableSelectionAction::Row {
8831 index: row,
8832 operation,
8833 },
8834 SelectionTarget::Cells => TableSelectionAction::Cell {
8835 row,
8836 column: column?,
8837 operation,
8838 },
8839 SelectionTarget::Columns => TableSelectionAction::Column {
8840 column: column?,
8841 operation,
8842 },
8843 };
8844 input.action = ControlAction::TableSelection(action);
8845 } else if let Some(action) = tree_row_action(node, row, operation) {
8846 input.action = action;
8847 }
8848 Some(input)
8849 }
8850
8851 pub fn list_item_delegate_selection(
8852 &self,
8853 scene: &Node,
8854 layout: &LayoutNode,
8855 target: &Target,
8856 ) -> Option<ControlInput> {
8857 if !valid(target, scene, layout) {
8858 return None;
8859 }
8860 target.row_key?;
8861 let (path, slot) = list_item_delegate_row(scene, &target.path)?;
8862 let view = scene.interactive_at_path(path)?;
8863 let row = view.list?.first_row.checked_add(slot)?;
8864 (view.table_selection.is_some() || view.int("current-index") != Some(row as i64)).then_some(
8865 ControlInput {
8866 path: path.to_vec(),
8867 action: ControlAction::Select(row),
8868 },
8869 )
8870 }
8871
8872 pub fn current_item_delegate(
8873 &self,
8874 scene: &Node,
8875 layout: &LayoutNode,
8876 view: &Target,
8877 ) -> Option<Target> {
8878 let node = scene.at_path(&view.path)?;
8879 if !matches!(node.kind, "ListView" | "GridView") {
8880 return None;
8881 }
8882 let slot = current_list_slot(node)?;
8883 self.item_delegate_at_slot(scene, layout, &view.path, slot)
8884 }
8885
8886 pub fn resolve_item_delegate(
8887 &self,
8888 scene: &Node,
8889 layout: &LayoutNode,
8890 view: &[usize],
8891 row: RowKey,
8892 ) -> Option<Target> {
8893 let node = scene.at_path(view)?;
8894 let slot = node
8895 .children
8896 .iter()
8897 .position(|candidate| candidate.routing_row_key() == Some(row))?;
8898 self.item_delegate_at_slot(scene, layout, view, slot)
8899 }
8900
8901 fn item_delegate_at_slot(
8902 &self,
8903 scene: &Node,
8904 layout: &LayoutNode,
8905 view: &[usize],
8906 slot: usize,
8907 ) -> Option<Target> {
8908 let mut path = view.to_vec();
8909 path.extend([slot, 0]);
8910 list_item_delegate_row(scene, &path)?;
8911 self.accessibility_target(scene, layout, &path)
8912 }
8913
8914 pub fn table_row_header_selection(
8915 &self,
8916 scene: &Node,
8917 layout: &LayoutNode,
8918 target: &Target,
8919 operation: RowSelection,
8920 ) -> Option<ControlInput> {
8921 let (path, slot) = Self::visible_table_row_header(scene, layout, target)?;
8922 let table = scene.at_path(path)?;
8923 let index = table.list?.first_row.checked_add(slot)?;
8924 let action =
8925 table
8926 .table_selection
8927 .as_ref()
8928 .map_or(ControlAction::Select(index), |selection| {
8929 ControlAction::TableSelection(selection.row_header_action(index, operation))
8930 });
8931 Some(ControlInput {
8932 path: path.to_vec(),
8933 action,
8934 })
8935 }
8936
8937 fn visible_table_row_header<'a>(
8938 scene: &Node,
8939 layout: &LayoutNode,
8940 target: &'a Target,
8941 ) -> Option<(&'a [usize], usize)> {
8942 if scene.at_path(&target.path)?.kind != "ListRow" || !valid(target, scene, layout) {
8943 return None;
8944 }
8945 let (path, slot) = table_hit_row(scene, &target.path)?;
8946 let item = layout.at_path(path)?;
8947 let table = item.table.as_ref()?;
8948 let row = table
8949 .row_header_cell(item.children.get(slot)?.bounds)
8950 .intersect(table.row_header);
8951 let visible = item.clip_rect(row);
8952 (visible.width > 0.0 && visible.height > 0.0).then_some((path, slot))
8953 }
8954
8955 fn table_column_move_at(
8956 scene: &Node,
8957 layout: &LayoutNode,
8958 target: &Target,
8959 start: Point,
8960 ) -> Option<TableColumnMove> {
8961 let node = target.node_in(scene)?;
8962 if !node.boolean("movable-columns", false) {
8963 return None;
8964 }
8965 let item = layout.at_path(&target.path)?;
8966 let table = item.table.as_ref()?;
8967 let column = table.column_at(item.map_from_window(start)?)?;
8968 Some(TableColumnMove {
8969 target: target.clone(),
8970 column,
8971 start,
8972 order: node.table_column_order.clone(),
8973 mirrored: table.mirrored(),
8974 claimed: false,
8975 scroll_wake: None,
8976 })
8977 }
8978
8979 pub fn press_table_reorder(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
8981 if self.menu_open()
8982 || self.choice_open()
8983 || self.hovered_table_grip.is_some()
8984 || self.hovered_table_row_grip.is_some()
8985 {
8986 return false;
8987 }
8988 let Some((target, point)) = self.hovered.as_ref().zip(self.pointer) else {
8989 return false;
8990 };
8991 if Self::table_column_move_at(scene, layout, target, point).is_none()
8992 && Self::table_row_move_at(scene, layout, target, point).is_none()
8993 {
8994 return false;
8995 }
8996 self.pointer_press_in_scene(scene, layout);
8997 self.table_row_move.is_some() || self.table_column_move.is_some()
8998 }
8999
9000 fn table_row_move_at(
9001 scene: &Node,
9002 layout: &LayoutNode,
9003 target: &Target,
9004 start: Point,
9005 ) -> Option<TableRowMove> {
9006 let (path, slot) = Self::visible_table_row_header(scene, layout, target)?;
9007 let node = scene.at_path(path)?;
9008 let item = layout.at_path(path)?;
9009 if !node.boolean("movable-rows", false)
9010 || !item
9011 .table
9012 .as_ref()?
9013 .row_header
9014 .contains(item.map_from_window(start)?)
9015 {
9016 return None;
9017 }
9018 Some(TableRowMove {
9019 table: Target::from_node(path.to_vec(), node, true, scene.row_key_at(path)),
9020 from: node.list?.first_row.checked_add(slot)?,
9021 row: node.children.get(slot)?.row_key?,
9022 stamp: node.standard_list_stamp?,
9023 start,
9024 claimed: false,
9025 touch: false,
9026 scroll_wake: None,
9027 })
9028 }
9029
9030 pub fn table_row_header_move(
9032 &self,
9033 scene: &Node,
9034 layout: &LayoutNode,
9035 target: &Target,
9036 direction: NavigationKey,
9037 ) -> Option<ControlInput> {
9038 let (path, slot) = Self::visible_table_row_header(scene, layout, target)?;
9039 let node = scene.interactive_at_path(path)?;
9040 let from = node.list?.first_row.checked_add(slot)?;
9041 let row = node.children.get(slot)?.row_key?;
9042 self.adjacent_table_row_move(layout, node, path, from, row, direction)
9043 }
9044
9045 pub fn table_row_move_key(
9046 &self,
9047 scene: &Node,
9048 layout: &LayoutNode,
9049 direction: NavigationKey,
9050 ) -> Option<ControlInput> {
9051 let focused = self.focused.as_ref()?;
9052 let focus_node = scene.at_path(&focused.path)?;
9053 if !valid(focused, scene, layout)
9054 || self.is_text_editor(focus_node, focused)
9055 || spin_editable(focus_node)
9056 || self.table_edit.is_some()
9057 {
9058 return None;
9059 }
9060 let path =
9061 table_cell_row(scene, &focused.path).map_or(focused.path.as_slice(), |(path, _)| path);
9062 let node = scene.interactive_at_path(path)?;
9063 let list = node.list?;
9064 let from = usize::try_from(node.int("current-row")?).ok()?;
9065 let row = from
9066 .checked_sub(list.first_row)
9067 .and_then(|slot| node.children.get(slot)?.row_key)
9068 .or_else(|| node.row_locator.as_ref()?.key_at(from))?;
9069 self.adjacent_table_row_move(layout, node, path, from, row, direction)
9070 }
9071
9072 fn adjacent_table_row_move(
9073 &self,
9074 layout: &LayoutNode,
9075 node: &Node,
9076 path: &[usize],
9077 from: usize,
9078 row: RowKey,
9079 direction: NavigationKey,
9080 ) -> Option<ControlInput> {
9081 if node.kind != "TableView"
9082 || !node.boolean("movable-rows", false)
9083 || self.menu_open()
9084 || self.choice_open()
9085 || self
9086 .active_dialog(layout)
9087 .is_some_and(|scope| !path.starts_with(scope))
9088 {
9089 return None;
9090 }
9091 let to = match direction {
9092 NavigationKey::Up => from.checked_sub(1)?,
9093 NavigationKey::Down => from.checked_add(1)?,
9094 _ => return None,
9095 };
9096 let count = node.list?.row_count;
9097 (from < count && to < count).then_some(ControlInput {
9098 path: path.to_vec(),
9099 action: ControlAction::MoveRow {
9100 from,
9101 to,
9102 row,
9103 stamp: node.standard_list_stamp?,
9104 },
9105 })
9106 }
9107
9108 pub fn table_delegate_selection(
9110 &self,
9111 scene: &Node,
9112 layout: &LayoutNode,
9113 target: &Target,
9114 operation: RowSelection,
9115 ) -> Option<ControlInput> {
9116 if !valid(target, scene, layout) {
9117 return None;
9118 }
9119 let mut node = scene;
9120 for (depth, &index) in target.path.iter().enumerate() {
9121 if node.kind == "TableView" {
9122 let [slot, 0, column, ..] = &target.path[depth..] else {
9123 return None;
9124 };
9125 let cell = scene.at_path(&target.path[..depth + 3])?;
9126 if !cell.boolean("table-delegate-cell", false) {
9127 return None;
9128 }
9129 let row = node.list?.first_row.checked_add(*slot)?;
9130 let action = match node.selection_target() {
9131 SelectionTarget::Rows => TableSelectionAction::Row {
9132 index: row,
9133 operation,
9134 },
9135 SelectionTarget::Cells => TableSelectionAction::Cell {
9136 row,
9137 column: *column,
9138 operation,
9139 },
9140 SelectionTarget::Columns => TableSelectionAction::Column {
9141 column: *column,
9142 operation,
9143 },
9144 };
9145 return Some(ControlInput {
9146 path: target.path[..depth].to_vec(),
9147 action: ControlAction::TableSelection(action),
9148 });
9149 }
9150 node = node.child_at(index)?;
9151 }
9152 None
9153 }
9154
9155 pub fn selection_key_action(
9157 &self,
9158 scene: &Node,
9159 layout: &LayoutNode,
9160 key: &str,
9161 modifiers: xrack_runtime::KeyModifiers,
9162 ) -> Option<ControlInput> {
9163 let additive = modifiers.control || modifiers.meta;
9164 let key = match key {
9165 " " | "Space" => TableSelectionKey::Toggle,
9166 "Escape" => TableSelectionKey::Clear,
9167 key if key.eq_ignore_ascii_case("a")
9168 && additive
9169 && !modifiers.alt
9170 && !modifiers.shift =>
9171 {
9172 TableSelectionKey::All
9173 }
9174 _ => return None,
9175 };
9176 self.table_selection_key(scene, key).or_else(|| {
9177 if key == TableSelectionKey::Toggle && !additive {
9178 return None;
9179 }
9180 self.tree_selection_key(scene, layout, key)
9181 .or_else(|| self.list_selection_key(scene, layout, key))
9182 })
9183 }
9184
9185 fn list_selection_key(
9186 &self,
9187 scene: &Node,
9188 layout: &LayoutNode,
9189 key: TableSelectionKey,
9190 ) -> Option<ControlInput> {
9191 let focused = self.focused.as_ref()?;
9192 if self.editor.is_some()
9193 || self.menu_open()
9194 || self.choice_open()
9195 || !valid(focused, scene, layout)
9196 {
9197 return None;
9198 }
9199 let path = list_item_delegate_row(scene, &focused.path)
9200 .map_or(focused.path.as_slice(), |(view, _)| view);
9201 let node = scene.interactive_at_path(path)?;
9202 if !matches!(node.kind, "ListView" | "GridView" | "StandardListView") {
9203 return None;
9204 }
9205 let selection = node.table_selection.as_ref()?;
9206 let count = node.list?.row_count;
9207 let action = match key {
9208 TableSelectionKey::All if count > 0 => TableSelectionAction::All,
9209 TableSelectionKey::Clear if !selection.is_empty() => TableSelectionAction::Clear,
9210 TableSelectionKey::Toggle => {
9211 let index = usize::try_from(ListMetrics::selection(node)?).ok()?;
9212 if index >= count {
9213 return None;
9214 }
9215 TableSelectionAction::Row {
9216 index,
9217 operation: RowSelection::Toggle,
9218 }
9219 }
9220 _ => return None,
9221 };
9222 Some(ControlInput {
9223 path: path.to_vec(),
9224 action: ControlAction::TableSelection(action),
9225 })
9226 }
9227
9228 pub fn tree_selection_key(
9229 &self,
9230 scene: &Node,
9231 layout: &LayoutNode,
9232 key: TableSelectionKey,
9233 ) -> Option<ControlInput> {
9234 let path = self.focused_tree(scene, layout)?;
9235 let node = scene.at_path(path)?;
9236 let selection = node.tree_selection.as_ref()?;
9237 let tree = node.tree.as_ref()?;
9238 let action = match key {
9239 TableSelectionKey::All if !tree.rows().is_empty() => {
9240 ControlAction::Tree(TreeAction::Selection(TreeSelectionAction::All))
9241 }
9242 TableSelectionKey::Clear if !selection.is_empty() => {
9243 ControlAction::Tree(TreeAction::Selection(TreeSelectionAction::Clear))
9244 }
9245 TableSelectionKey::Toggle => {
9246 let index = tree.visible_index(node.int("current-key")?)?;
9247 tree_row_action(node, index, RowSelection::Toggle)?
9248 }
9249 _ => return None,
9250 };
9251 Some(ControlInput {
9252 path: path.to_vec(),
9253 action,
9254 })
9255 }
9256
9257 pub fn table_selection_key(
9258 &self,
9259 scene: &Node,
9260 key: TableSelectionKey,
9261 ) -> Option<ControlInput> {
9262 if self.editor.is_some() {
9263 return None;
9264 }
9265 let target = self.focused.as_ref()?;
9266 if key == TableSelectionKey::Toggle
9267 && scene
9268 .at_path(&target.path)
9269 .is_some_and(|node| node.boolean("table-editor", false) && is_toggle(node.kind))
9270 {
9271 return None;
9272 }
9273 if scene.row_key_at(&target.path) != target.row_key {
9274 return None;
9275 }
9276 let cell_row = table_cell_row(scene, &target.path);
9277 let path = cell_row.map_or(target.path.as_slice(), |(path, _)| path);
9278 let node = scene.interactive_at_path(path)?;
9279 let selection = node.table_selection.as_ref()?;
9280 node.table_header.as_ref()?;
9281 let list = node.list?;
9282 let action = match key {
9283 TableSelectionKey::All
9284 if selection.multiple()
9285 && (list.row_count > 0 || selection.target() == SelectionTarget::Columns) =>
9286 {
9287 TableSelectionAction::All
9288 }
9289 TableSelectionKey::Clear if !selection.is_empty() => TableSelectionAction::Clear,
9290 TableSelectionKey::Toggle => {
9291 let operation = RowSelection::Toggle;
9292 let header = node.table_header.as_ref()?;
9293 let visible =
9294 |&column: &usize| header.columns.get(column).is_some_and(Node::is_visible);
9295 let column = cell_row
9296 .and_then(|_| target.path.last().copied())
9297 .or(selection.current_column())
9298 .filter(visible)
9299 .or_else(|| {
9300 node.table_column_order
9301 .iter(header.columns.len())
9302 .find(visible)
9303 });
9304 if selection.target() == SelectionTarget::Columns {
9305 TableSelectionAction::Column {
9306 column: column?,
9307 operation,
9308 }
9309 } else {
9310 let row = if let Some((_, slot)) = cell_row {
9311 list.first_row.checked_add(slot)?
9312 } else {
9313 usize::try_from(node.int("current-row")?).ok()?
9314 };
9315 if row >= list.row_count {
9316 return None;
9317 }
9318 if selection.target() == SelectionTarget::Cells {
9319 TableSelectionAction::Cell {
9320 row,
9321 column: column?,
9322 operation,
9323 }
9324 } else {
9325 TableSelectionAction::Row {
9326 index: row,
9327 operation,
9328 }
9329 }
9330 }
9331 }
9332 _ => return None,
9333 };
9334 Some(ControlInput {
9335 path: path.to_vec(),
9336 action: ControlAction::TableSelection(action),
9337 })
9338 }
9339
9340 fn focused_clipboard_table<'a>(
9341 &'a self,
9342 scene: &Node,
9343 layout: &LayoutNode,
9344 ) -> Option<&'a [usize]> {
9345 let focused = self.focused.as_ref()?;
9346 if self.editor.is_some()
9347 || self.menu_open()
9348 || self.choice_open()
9349 || !valid(focused, scene, layout)
9350 {
9351 return None;
9352 }
9353 let path = (0..=focused.path.len())
9354 .rev()
9355 .map(|depth| &focused.path[..depth])
9356 .find(|path| {
9357 scene
9358 .at_path(path)
9359 .is_some_and(|node| node.kind == "TableView")
9360 })?;
9361 scene.interactive_at_path(path)?;
9362 self.allows_popup(layout, path).then_some(path)
9363 }
9364
9365 fn table_clipboard_target(
9366 &self,
9367 scene: &Node,
9368 layout: &LayoutNode,
9369 ) -> Option<(Vec<usize>, Vec<usize>)> {
9370 let path = self.focused_clipboard_table(scene, layout)?;
9371 let geometry = layout.at_path(path)?.table.as_ref()?;
9372 let columns = geometry.visible_columns().collect();
9373 Some((path.to_vec(), columns))
9374 }
9375
9376 pub fn table_edit_history_target<'a>(
9377 &'a self,
9378 scene: &Node,
9379 layout: &LayoutNode,
9380 ) -> Option<&'a [usize]> {
9381 let path = self.focused_clipboard_table(scene, layout)?;
9382 scene
9383 .at_path(path)?
9384 .table_edit_history_enabled()
9385 .then_some(path)
9386 }
9387
9388 #[doc(hidden)]
9389 pub fn table_paste_history_target<'a>(
9390 &'a self,
9391 scene: &Node,
9392 layout: &LayoutNode,
9393 ) -> Option<&'a [usize]> {
9394 self.table_edit_history_target(scene, layout)
9395 }
9396
9397 pub fn table_copy_target(
9398 &self,
9399 scene: &Node,
9400 layout: &LayoutNode,
9401 ) -> Option<(Vec<usize>, Vec<usize>)> {
9402 let (path, columns) = self.table_clipboard_target(scene, layout)?;
9403 scene
9404 .at_path(&path)?
9405 .boolean("copyable", false)
9406 .then_some((path, columns))
9407 }
9408
9409 pub fn table_paste_target(
9410 &self,
9411 scene: &Node,
9412 layout: &LayoutNode,
9413 ) -> Option<TablePasteDestination> {
9414 let (path, mut columns) = self.table_clipboard_target(scene, layout)?;
9415 let table = scene.at_path(&path)?;
9416 let row = usize::try_from(table.int("current-row")?).ok()?;
9417 if !table.boolean("pasteable", false) || row >= table.list?.row_count || columns.is_empty()
9418 {
9419 return None;
9420 }
9421 if let Some(column) = table.table_selection.as_ref().and_then(|selection| {
9422 (selection.target() != SelectionTarget::Rows)
9423 .then(|| selection.current_column())
9424 .flatten()
9425 }) {
9426 let start = columns.iter().position(|&candidate| candidate == column)?;
9427 columns.drain(..start);
9428 }
9429 Some(TablePasteDestination {
9430 path,
9431 row,
9432 columns,
9433 focus: self.focused.clone()?,
9434 })
9435 }
9436
9437 pub fn list_key_with_selection(
9438 &mut self,
9439 scene: &Node,
9440 layout: &LayoutNode,
9441 key: NavigationKey,
9442 operation: RowSelection,
9443 ) -> Option<ControlInput> {
9444 if let Some(input) = self.table_grid_key(scene, layout, key, operation) {
9445 return Some(input);
9446 }
9447 Some(
9448 self.list_key(scene, layout, key)?
9449 .with_row_selection(scene, operation),
9450 )
9451 }
9452
9453 fn table_grid_key(
9454 &mut self,
9455 scene: &Node,
9456 layout: &LayoutNode,
9457 key: NavigationKey,
9458 operation: RowSelection,
9459 ) -> Option<ControlInput> {
9460 let focused = self.focused.as_ref()?;
9461 let cell = table_cell_row(scene, &focused.path);
9462 let path = cell
9463 .map_or(focused.path.as_slice(), |(path, _)| path)
9464 .to_vec();
9465 let node = scene.interactive_at_path(&path)?;
9466 let view = node.table_selection.as_ref()?;
9467 if view.target() == SelectionTarget::Rows {
9468 return None;
9469 }
9470 let item = layout.at_path(&path)?;
9471 let table = item.table.as_ref()?;
9472 let current = view
9473 .current_column()
9474 .or_else(|| cell.and_then(|_| focused.path.last().copied()))
9475 .filter(|&column| column < table.columns.len());
9476 let current_visual = current.and_then(|column| table.visual_index(column));
9477 let visible = |&column: &usize| table.is_column_visible(column);
9478 let visible_current = current.filter(visible);
9479 let (previous, following) = navigation_axis(false, item.layout_direction);
9480 let next = match key {
9481 key if key == previous => table
9482 .visual_columns()
9483 .take(current_visual.unwrap_or(table.columns.len()))
9484 .rev()
9485 .find(visible)
9486 .or(visible_current)
9487 .or_else(|| table.visible_columns().next()),
9488 key if key == following => table
9489 .visual_columns()
9490 .skip(current_visual.map_or(0, |column| column + 1))
9491 .find(visible)
9492 .or(visible_current)
9493 .or_else(|| table.visible_columns().next_back()),
9494 NavigationKey::Home if view.target() == SelectionTarget::Columns => {
9495 table.visible_columns().next()
9496 }
9497 NavigationKey::End if view.target() == SelectionTarget::Columns => {
9498 table.visible_columns().next_back()
9499 }
9500 _ => None,
9501 };
9502 let action = if let Some(column) = next {
9503 if view.target() == SelectionTarget::Columns {
9504 TableSelectionAction::Column { column, operation }
9505 } else {
9506 let list = node.list?;
9507 if list.row_count == 0 {
9508 return None;
9509 }
9510 let row = ListMetrics::selection(node)
9511 .and_then(|value| usize::try_from(value).ok())
9512 .filter(|&row| row < list.row_count)
9513 .unwrap_or(list.first_row);
9514 self.reveal_row(&path, node, item, row);
9515 TableSelectionAction::Cell {
9516 row,
9517 column,
9518 operation,
9519 }
9520 }
9521 } else {
9522 let input = self.list_key(scene, layout, key)?;
9523 let ControlAction::Select(row) = input.action else {
9524 return None;
9525 };
9526 if view.target() == SelectionTarget::Columns {
9527 return Some(ControlInput {
9528 path,
9529 action: ControlAction::TableSelection(TableSelectionAction::Row {
9530 index: row,
9531 operation: RowSelection::Move,
9532 }),
9533 });
9534 }
9535 let column = visible_current.or_else(|| table.visible_columns().next())?;
9536 TableSelectionAction::Cell {
9537 row,
9538 column,
9539 operation,
9540 }
9541 };
9542 let column = match action {
9543 TableSelectionAction::Cell { column, .. }
9544 | TableSelectionAction::Column { column, .. } => column,
9545 _ => unreachable!(),
9546 };
9547 let scroll = table.horizontal;
9548 let offset = table.reveal_column(column);
9549 if offset != scroll.offset {
9550 store_scroll_offset(
9551 item,
9552 &mut self.horizontal_scroll_offsets,
9553 &path,
9554 Orientation::Horizontal,
9555 offset,
9556 );
9557 UserScrollChange::commit(
9558 &mut self.user_scroll_changes,
9559 item,
9560 Orientation::Horizontal,
9561 scroll.offset,
9562 offset,
9563 );
9564 }
9565 self.set_focus(Some(Target::from_node(
9566 path.clone(),
9567 node,
9568 true,
9569 scene.row_key_at(&path),
9570 )));
9571 Some(ControlInput {
9572 path,
9573 action: ControlAction::TableSelection(action),
9574 })
9575 }
9576
9577 fn reveal_row(&mut self, path: &[usize], node: &Node, item: &LayoutNode, row: usize) {
9578 let Some(scroll) = item.scroll else {
9579 return;
9580 };
9581 let viewport = item.table.as_ref().map_or(item.bounds, |table| table.body);
9582 let cells = ViewCells::new(node, viewport.width);
9583 let offset = cells.reveal(scroll, row, viewport.height).offset;
9584 if offset != scroll.offset {
9585 store_scroll_offset(
9586 item,
9587 &mut self.scroll_offsets,
9588 path,
9589 Orientation::Vertical,
9590 offset,
9591 );
9592 UserScrollChange::commit(
9593 &mut self.user_scroll_changes,
9594 item,
9595 Orientation::Vertical,
9596 scroll.offset,
9597 offset,
9598 );
9599 }
9600 }
9601
9602 pub fn list_key(
9603 &mut self,
9604 scene: &Node,
9605 layout: &LayoutNode,
9606 key: NavigationKey,
9607 ) -> Option<ControlInput> {
9608 let target = self.focused.as_ref()?;
9609 let cell_view = table_cell_row(scene, &target.path)
9610 .or_else(|| tree_cell_row(scene, &target.path))
9611 .or_else(|| list_item_delegate_row(scene, &target.path))
9612 .map(|(view, _)| view);
9613 let focused_cell = cell_view.is_some();
9614 let path = cell_view.unwrap_or(&target.path);
9615 let node = scene.at_path(path)?;
9616 let list = node.list?;
9617 let last = list.row_count.checked_sub(1)?;
9618 let layout = layout.at_path(path)?;
9619 layout.scroll?;
9620 let viewport = layout
9621 .table
9622 .as_ref()
9623 .map_or(layout.bounds, |table| table.body);
9624 let cells = ViewCells::new(node, viewport.width);
9625 let columns = cells.columns;
9626 let current = ListMetrics::selection(node)
9627 .and_then(|value| usize::try_from(value).ok())
9628 .filter(|&row| row <= last);
9629 let key = if node.kind == "GridView"
9630 && layout.layout_direction == xrack_runtime::LayoutDirection::RightToLeft
9631 {
9632 match key {
9633 NavigationKey::Left => NavigationKey::Right,
9634 NavigationKey::Right => NavigationKey::Left,
9635 key => key,
9636 }
9637 } else {
9638 key
9639 };
9640 let index = match key {
9641 NavigationKey::Left if node.kind == "GridView" => current.map_or(0, |index| {
9642 if index.is_multiple_of(columns) {
9643 index
9644 } else {
9645 index - 1
9646 }
9647 }),
9648 NavigationKey::Right if node.kind == "GridView" => current.map_or(0, |index| {
9649 if (index + 1).is_multiple_of(columns) {
9650 index
9651 } else {
9652 (index + 1).min(last)
9653 }
9654 }),
9655 NavigationKey::Up => {
9656 current.map_or(0, |index| index.checked_sub(columns).unwrap_or(index))
9657 }
9658 NavigationKey::Down => current.map_or(0, |index| {
9659 if index / columns == last / columns {
9660 index
9661 } else {
9662 index.saturating_add(columns).min(last)
9663 }
9664 }),
9665 NavigationKey::Home => 0,
9666 NavigationKey::End => last,
9667 NavigationKey::PageUp => current.map_or(0, |row| {
9668 cells.page(row, viewport.height, list.row_count, false)
9669 }),
9670 NavigationKey::PageDown => current.map_or(0, |row| {
9671 cells.page(row, viewport.height, list.row_count, true)
9672 }),
9673 _ => return None,
9674 };
9675 let action = ControlInput {
9676 path: path.to_vec(),
9677 action: ControlAction::Select(index),
9678 };
9679 self.reset_list_typeahead();
9680 self.reveal_row(&action.path, node, layout, index);
9681 if focused_cell {
9682 self.set_focus(Some(Target::from_node(
9683 action.path.clone(),
9684 node,
9685 true,
9686 scene.row_key_at(&action.path),
9687 )));
9688 }
9689 Some(action)
9690 }
9691
9692 pub fn tab_move_key(
9694 &self,
9695 scene: &Node,
9696 layout: &LayoutNode,
9697 key: NavigationKey,
9698 ) -> Option<Option<ControlInput>> {
9699 let focused = self.focused.as_ref()?;
9700 let (&from, path) = focused.path.split_last()?;
9701 let bar = scene.at_path(path)?;
9702 let item = layout.at_path(path)?;
9703 if !matches!(bar.kind, "TabBar" | "TabWidget")
9704 || !bar.boolean("reorderable", false)
9705 || !valid(focused, scene, layout)
9706 {
9707 return None;
9708 }
9709 let (previous, following) = navigation_axis(
9710 bar.orientation() == Orientation::Vertical,
9711 item.layout_direction,
9712 );
9713 let available = |slot| group_item(bar, slot).is_some();
9714 let to = if key == previous {
9715 (0..from).rev().find(|&slot| available(slot))
9716 } else if key == following {
9717 (from + 1..bar.children.len()).find(|&slot| available(slot))
9718 } else {
9719 return None;
9720 };
9721 Some(to.and_then(|to| {
9722 Some(ControlInput {
9723 path: path.to_vec(),
9724 action: ControlAction::MoveTab(bar.tab_move(from, to)?),
9725 })
9726 }))
9727 }
9728
9729 pub fn group_key(
9730 &mut self,
9731 scene: &Node,
9732 layout: &LayoutNode,
9733 key: NavigationKey,
9734 ) -> Option<ControlInput> {
9735 let target = self.focused.as_ref()?;
9736 if let Some((member, component)) = attached_radio(scene, &target.path) {
9737 let scope = self
9738 .focused_popup(layout)
9739 .or_else(|| self.active_dialog(layout))
9740 .unwrap_or_default();
9741 let choices: Vec<_> = member
9742 .group
9743 .paths()
9744 .filter_map(|path| {
9745 let path = [component, path].concat();
9746 if !path.starts_with(scope) {
9747 return None;
9748 }
9749 let node = scene.interactive_at_path(&path)?;
9750 let item = layout.at_path(&path)?;
9751 let row_key = scene.row_key_at(&path);
9752 eligible(node, item).then(|| Target::from_node(path, node, true, row_key))
9753 })
9754 .collect();
9755 let position = choices.iter().position(|choice| choice == target)?;
9756 let len = choices.len();
9757 let index = match key {
9758 NavigationKey::Home => 0,
9759 NavigationKey::End => len - 1,
9760 NavigationKey::Up | NavigationKey::Left => (position + len - 1) % len,
9761 NavigationKey::Down | NavigationKey::Right => (position + 1) % len,
9762 _ => return None,
9763 };
9764 let next = choices[index].clone();
9765 let action = ControlInput {
9766 path: next.path.clone(),
9767 action: ControlAction::ActivateRadioOption,
9768 };
9769 self.set_focus(Some(next));
9770 return Some(action);
9771 }
9772 let (¤t, path) = target.path.split_last()?;
9773 let group = scene.at_path(path)?;
9774 group_item(group, current)?;
9775 let vertical =
9776 if group.kind == "RadioGroup" && !group.properties.contains_key("orientation") {
9777 true
9778 } else {
9779 group.orientation() == Orientation::Vertical
9780 };
9781 let group_layout = layout.at_path(path)?;
9782 let choices: Vec<_> = group_targets(group, group_layout, path, false).collect();
9783 let position = choices.iter().position(|(index, _)| *index == current)?;
9784 let len = choices.len();
9785 let (previous, next) = navigation_axis(vertical, group_layout.layout_direction);
9786 let next = match key {
9787 NavigationKey::Home => 0,
9788 NavigationKey::End => len - 1,
9789 key if key == previous => (position + len - 1) % len,
9790 key if key == next => (position + 1) % len,
9791 _ => return None,
9792 };
9793 let (index, next) = &choices[next];
9794 let action = ControlInput {
9795 path: path.to_vec(),
9796 action: ControlAction::Select(*index),
9797 };
9798 let mut next = next.clone();
9799 next.row_key = scene.row_key_at(&next.path);
9800 self.reveal_tab(group, group_layout, &action.path, *index);
9801 self.set_focus(Some(next));
9802 Some(action)
9803 }
9804
9805 fn reveal_tab(
9806 &mut self,
9807 group: &Node,
9808 item: &LayoutNode,
9809 path: &[usize],
9810 index: usize,
9811 ) -> bool {
9812 if !matches!(group.kind, "TabBar" | "TabWidget") {
9813 return false;
9814 }
9815 let orientation = group.orientation();
9816 let Some(scroll) = item.scroll_on(orientation) else {
9817 return false;
9818 };
9819 let Some(header) = item.tab_item_rect(index) else {
9820 return false;
9821 };
9822 let offset = crate::selection::tab_reveal_offset(
9823 item.tab_viewport(),
9824 header,
9825 orientation,
9826 item.layout_direction,
9827 scroll.offset,
9828 )
9829 .clamp(0.0, scroll.max_offset);
9830 if offset == scroll.offset {
9831 return false;
9832 }
9833 let offsets = match orientation {
9834 Orientation::Horizontal => &mut self.horizontal_scroll_offsets,
9835 Orientation::Vertical => &mut self.scroll_offsets,
9836 };
9837 offsets.insert(path.to_vec(), offset);
9838 true
9839 }
9840
9841 pub fn swipe_key(
9842 &mut self,
9843 scene: &Node,
9844 layout: &LayoutNode,
9845 key: NavigationKey,
9846 ) -> Option<ControlInput> {
9847 let target = self.focused.as_ref()?;
9848 if !valid(target, scene, layout) {
9849 return None;
9850 }
9851 let (path, view) = (0..=target.path.len()).rev().find_map(|depth| {
9852 let path = &target.path[..depth];
9853 let view = scene.interactive_at_path(path)?;
9854 (view.kind == "SwipeView" && view.boolean("interactive", true)).then_some((path, view))
9855 })?;
9856 let current = group_index(view)?;
9857 let eligible = |&index: &usize| group_item(view, index).is_some();
9858 let vertical = view.orientation() == Orientation::Vertical;
9859 let mirrored = swipe_view_mirrored(view, layout.at_path(path)?);
9860 let index = match key {
9861 NavigationKey::Home => (0..view.children.len()).find(eligible),
9862 NavigationKey::End => (0..view.children.len()).rev().find(eligible),
9863 NavigationKey::Left if !vertical => swipe_neighbor(view, current, mirrored),
9864 NavigationKey::Right if !vertical => swipe_neighbor(view, current, !mirrored),
9865 NavigationKey::Up if vertical => swipe_neighbor(view, current, false),
9866 NavigationKey::Down if vertical => swipe_neighbor(view, current, true),
9867 _ => None,
9868 }?;
9869 if index == current {
9870 return None;
9871 }
9872 Some(ControlInput {
9873 path: path.to_vec(),
9874 action: ControlAction::Select(index),
9875 })
9876 }
9877
9878 pub fn swipe_delegate_key(
9879 &self,
9880 scene: &Node,
9881 layout: &LayoutNode,
9882 key: NavigationKey,
9883 ) -> Option<ControlInput> {
9884 let target = self.focused.as_ref()?;
9885 let geometry = layout.at_path(&target.path)?.swipe_delegate.as_deref()?;
9886 let side = match (key, geometry.side) {
9887 (NavigationKey::Left, SwipeSide::Left) | (NavigationKey::Right, SwipeSide::Right) => {
9888 SwipeSide::Closed
9889 }
9890 (NavigationKey::Left, _) => SwipeSide::Right,
9891 (NavigationKey::Right, _) => SwipeSide::Left,
9892 _ => return None,
9893 };
9894 self.swipe_delegate_action(scene, layout, target, side)
9895 }
9896
9897 fn swipe_delegate_action(
9898 &self,
9899 scene: &Node,
9900 layout: &LayoutNode,
9901 target: &Target,
9902 side: SwipeSide,
9903 ) -> Option<ControlInput> {
9904 let geometry = layout.at_path(&target.path)?.swipe_delegate.as_deref()?;
9905 (valid(target, scene, layout) && geometry.side != side && geometry.supports(side)).then(
9906 || ControlInput {
9907 path: target.path.clone(),
9908 action: ControlAction::SwipeDelegate(side),
9909 },
9910 )
9911 }
9912
9913 pub fn swipe_delegate_accessibility(
9914 &self,
9915 scene: &Node,
9916 layout: &LayoutNode,
9917 target: &Target,
9918 expand: bool,
9919 ) -> Option<ControlInput> {
9920 let geometry = layout.at_path(&target.path)?.swipe_delegate.as_deref()?;
9921 if expand == (geometry.side != SwipeSide::Closed) {
9922 return None;
9923 }
9924 let side = if !expand {
9925 SwipeSide::Closed
9926 } else if geometry.supports(SwipeSide::Right) {
9927 SwipeSide::Right
9928 } else {
9929 SwipeSide::Left
9930 };
9931 self.swipe_delegate_action(scene, layout, target, side)
9932 }
9933
9934 pub fn dismiss_focused_swipe(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
9935 let focused = self.focused.as_ref()?;
9936 (0..=focused.path.len()).rev().find_map(|depth| {
9937 let path = &focused.path[..depth];
9938 let geometry = layout.at_path(path)?.swipe_delegate.as_deref()?;
9939 if geometry.side == SwipeSide::Closed {
9940 return None;
9941 }
9942 let target = self.accessibility_target(scene, layout, path)?;
9943 self.swipe_delegate_action(scene, layout, &target, SwipeSide::Closed)
9944 })
9945 }
9946
9947 pub fn stack_back(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
9948 let focused = self.focused.as_ref()?;
9949 let scope = self.active_dialog(layout).unwrap_or_default();
9950 if !focused.path.starts_with(scope) || !valid(focused, scene, layout) {
9951 return None;
9952 }
9953 (scope.len()..=focused.path.len()).rev().find_map(|depth| {
9954 let path = &focused.path[..depth];
9955 let stack = scene.interactive_at_path(path)?.stack.as_ref()?;
9956 (stack.depth() > 1).then(|| ControlInput {
9957 path: path.to_vec(),
9958 action: ControlAction::StackBack {
9959 revision: stack.revision(),
9960 },
9961 })
9962 })
9963 }
9964
9965 pub fn pointer_release(&mut self) -> Option<&'static str> {
9966 self.pointer_release_target().and_then(|target| target.id)
9967 }
9968
9969 pub fn page_marker_release(
9970 &mut self,
9971 scene: &Node,
9972 layout: &LayoutNode,
9973 ) -> Option<ControlInput> {
9974 matches!(self.pressed_control_part, Some(ControlAction::Select(_))).then_some(())?;
9975 self.control_part_release(scene, layout)
9976 }
9977
9978 pub fn control_part_release(
9979 &mut self,
9980 scene: &Node,
9981 layout: &LayoutNode,
9982 ) -> Option<ControlInput> {
9983 let action = self.pressed_control_part?;
9984 let pressed = self.pointer_release_target()?;
9985 let Hit::ControlPart(target, current) = self.hit_at(scene, layout, self.pointer?) else {
9986 return None;
9987 };
9988 (pressed == target && action == current).then_some(ControlInput {
9989 path: target.path,
9990 action,
9991 })
9992 }
9993
9994 pub fn page_marker_hovered(&self, path: &[usize], index: usize) -> bool {
9995 self.hovered_control_part == Some(ControlAction::Select(index)) && self.is_hovered(path)
9996 }
9997
9998 pub fn page_indicator_key(
9999 &self,
10000 scene: &Node,
10001 layout: &LayoutNode,
10002 key: NavigationKey,
10003 ) -> Option<ControlInput> {
10004 let target = self.focused.as_ref()?;
10005 let node = scene.at_path(&target.path)?;
10006 if node.kind != "PageIndicator" || !valid(target, scene, layout) {
10007 return None;
10008 }
10009 let last = page_indicator_count(node).checked_sub(1)?;
10010 let current = page_indicator_index(node);
10011 let vertical = node.orientation() == Orientation::Vertical;
10012 let direction = layout.at_path(&target.path)?.layout_direction;
10013 let (previous, next) = navigation_axis(vertical, direction);
10014 let index = match key {
10015 NavigationKey::Home => 0,
10016 NavigationKey::End => last,
10017 key if key == previous => current.map_or(0, |index| index.saturating_sub(1)),
10018 key if key == next => current.map_or(0, |index| (index + 1).min(last)),
10019 _ => return None,
10020 };
10021 (current != Some(index)).then(|| ControlInput {
10022 path: target.path.clone(),
10023 action: ControlAction::Select(index),
10024 })
10025 }
10026
10027 #[doc(hidden)]
10029 pub fn calendar_page_key(
10030 &mut self,
10031 scene: &Node,
10032 layout: &LayoutNode,
10033 key: NavigationKey,
10034 ) -> bool {
10035 let step = match key {
10036 NavigationKey::PageUp => -1,
10037 NavigationKey::PageDown => 1,
10038 _ => return false,
10039 };
10040 let Some(from) = self
10041 .focused
10042 .as_ref()
10043 .filter(|target| valid(target, scene, layout))
10044 else {
10045 return false;
10046 };
10047 if !from
10048 .node_in(scene)
10049 .is_some_and(|node| node.kind == "MonthGrid" && node.boolean("fixed-month", false))
10050 {
10051 return false;
10052 }
10053 let Some((view, node, item, index, order)) = (0..from.path.len()).rev().find_map(|depth| {
10054 let view = &from.path[..depth];
10055 let node = scene
10056 .interactive_at_path(view)
10057 .filter(|node| node.kind == "ListView")?;
10058 let item = layout
10059 .at_path(view)
10060 .filter(|item| item.enabled && item.scroll.is_some())?;
10061 let list = node.list?;
10062 let slot = from.path[depth];
10063 let row = node
10064 .child_at(slot)
10065 .filter(|child| child.kind == "ListRow")?
10066 .routing_row_key()?;
10067 let index = list
10068 .first_row
10069 .checked_add(slot)
10070 .filter(|&index| index < list.row_count)?;
10071 let order = node.standard_list_stamp?;
10072 (from.row_key == Some(row)).then_some((view, node, item, index, order))
10073 }) else {
10074 return false;
10075 };
10076 if let Some(index) = index
10077 .checked_add_signed(step)
10078 .filter(|&index| node.list.is_some_and(|list| index < list.row_count))
10079 {
10080 let page = CalendarPageFocus {
10081 from: from.clone(),
10082 view: Target::from_node(view.to_vec(), node, true, scene.row_key_at(view)),
10083 viewport: node.viewport_handle.clone(),
10084 order,
10085 index,
10086 };
10087 self.reveal_row(&page.view.path, node, item, index);
10088 self.calendar_page_focus = Some(page);
10089 }
10090 true
10091 }
10092
10093 fn finish_calendar_page_focus(&mut self, scene: &Node, layout: &LayoutNode) {
10094 let Some(page) = self
10095 .calendar_page_focus
10096 .take()
10097 .filter(|page| self.focused.as_ref() == Some(&page.from))
10098 else {
10099 return;
10100 };
10101 let Some(view) = page.view.node_in(scene).filter(|view| {
10104 view.kind == "ListView"
10105 && view.viewport_handle == page.viewport
10106 && view.standard_list_stamp == Some(page.order)
10107 }) else {
10108 return;
10109 };
10110 let Some(slot) = view
10111 .list
10112 .and_then(|list| page.index.checked_sub(list.first_row))
10113 else {
10114 return;
10115 };
10116 let Some(row) = view
10117 .child_at(slot)
10118 .filter(|row| row.kind == "ListRow")
10119 .and_then(Node::routing_row_key)
10120 else {
10121 return;
10122 };
10123 let mut path = page.view.path;
10124 let tail = &page.from.path[path.len() + 1..];
10125 path.push(slot);
10126 path.extend_from_slice(tail);
10127 let Some(target) = self
10128 .accessibility_target(scene, layout, &path)
10129 .filter(|target| {
10130 target.focusable
10131 && target.row_key == Some(row)
10132 && target.element_id() == page.from.element_id()
10133 && target.node_in(scene).is_some_and(|node| {
10134 node.kind == "MonthGrid" && node.boolean("fixed-month", false)
10135 })
10136 })
10137 else {
10138 return;
10139 };
10140 self.set_focus(Some(target));
10141 self.remember_focus_scope(scene, layout);
10142 }
10143
10144 pub fn calendar_key(
10145 &self,
10146 scene: &Node,
10147 layout: &LayoutNode,
10148 key: NavigationKey,
10149 ) -> Option<ControlInput> {
10150 let target = self.focused.as_ref()?;
10151 let node = scene.at_path(&target.path)?;
10152 if !is_calendar_control(node.kind) || !valid(target, scene, layout) {
10153 return None;
10154 }
10155 let item = layout.at_path(&target.path)?;
10156 let geometry = CalendarGeometry::for_layout(node, item);
10157 let calendar = &geometry.state;
10158 let day = |delta| {
10159 let date = geometry
10160 .cursor()?
10161 .add_days(delta)
10162 .unwrap_or(if delta < 0 { Date::MIN } else { Date::MAX })
10163 .clamp(calendar.minimum, calendar.maximum);
10164 calendar.selectable_from(date, delta > 0)
10165 };
10166 let month = |offset| {
10167 if geometry.has_header() {
10168 calendar.adjacent_month(offset)
10169 } else {
10170 calendar.month.add_months(offset)
10171 }
10172 .unwrap_or(calendar.month)
10173 };
10174 let right_step = if item.layout_direction == LayoutDirection::RightToLeft {
10175 -1
10176 } else {
10177 1
10178 };
10179 let action = match key {
10180 NavigationKey::Left => CalendarAction::Select(day(-right_step)?),
10181 NavigationKey::Right => CalendarAction::Select(day(right_step)?),
10182 NavigationKey::Up => CalendarAction::Select(day(-7)?),
10183 NavigationKey::Down => CalendarAction::Select(day(7)?),
10184 NavigationKey::Home | NavigationKey::End => {
10185 let date = if key == NavigationKey::Home {
10186 calendar.month.max(calendar.minimum)
10187 } else {
10188 calendar.month.last_of_month().min(calendar.maximum)
10189 };
10190 let date = calendar.selectable_from(date, key == NavigationKey::Home)?;
10191 if date.first_of_month() != calendar.month {
10192 return None;
10193 }
10194 CalendarAction::Select(date)
10195 }
10196 NavigationKey::PageUp | NavigationKey::PageDown if calendar.fixed_month => return None,
10197 NavigationKey::PageUp => CalendarAction::Browse(month(-1)),
10198 NavigationKey::PageDown => CalendarAction::Browse(month(1)),
10199 };
10200 Some(ControlInput {
10201 path: target.path.clone(),
10202 action: ControlAction::Calendar(action),
10203 })
10204 }
10205
10206 pub fn text_link_target(
10207 &self,
10208 scene: &Node,
10209 layout: &LayoutNode,
10210 path: &[usize],
10211 index: usize,
10212 ) -> Option<Target> {
10213 let node = scene.at_path(path)?;
10214 let mut target = Target::for_text_link(node, path, index)?;
10215 target.row_key = scene.row_key_at(path);
10216 self.text_link_activation(scene, layout, &target)
10217 .map(|_| target)
10218 }
10219
10220 pub fn text_link_activation(
10221 &self,
10222 scene: &Node,
10223 layout: &LayoutNode,
10224 target: &Target,
10225 ) -> Option<ControlInput> {
10226 let index = target.text_link_index()?;
10227 let scope = self
10228 .focused_popup(layout)
10229 .or_else(|| self.active_dialog(layout));
10230 (self.menu.is_none()
10231 && self.choice.is_none()
10232 && scope.is_none_or(|scope| target.path.starts_with(scope))
10233 && valid(target, scene, layout))
10234 .then(|| ControlInput {
10235 path: target.path.clone(),
10236 action: ControlAction::ActivateTextLink(index),
10237 })
10238 }
10239
10240 pub fn calendar_activate(
10241 &self,
10242 scene: &Node,
10243 layout: &LayoutNode,
10244 target: &Target,
10245 ) -> Option<ControlInput> {
10246 let node = scene.at_path(&target.path)?;
10247 if !is_calendar_control(node.kind) || !valid(target, scene, layout) {
10248 return None;
10249 }
10250 let geometry = CalendarGeometry::for_layout(node, layout.at_path(&target.path)?);
10251 let date = geometry.cursor()?;
10252 geometry.state.allows(date).then(|| ControlInput {
10253 path: target.path.clone(),
10254 action: ControlAction::Calendar(geometry.day_action(date)),
10255 })
10256 }
10257
10258 pub fn pointer_release_target(&mut self) -> Option<Target> {
10259 self.text_selection_scroll = None;
10260 if self.pressed.is_some() {
10261 self.last_editor_click = self.editor_press.take().filter(|press| {
10262 self.pressed.as_ref() == Some(&press.target)
10263 && self.hovered.as_ref() == Some(&press.target)
10264 && !self.pointer_activation_claimed
10265 });
10266 }
10267 self.finish_button_contact(
10268 ButtonContactSource::Pointer,
10269 self.pressed.is_some() && self.pressed == self.hovered,
10270 );
10271 if self
10272 .button_hold
10273 .as_ref()
10274 .is_some_and(|repeat| matches!(repeat.source, DelaySource::Pointer))
10275 {
10276 self.button_hold = None;
10277 }
10278 let split_resized = self.clear_split_drag();
10279 self.table_column_move = None;
10280 if self.cancel_table_row_move() {
10281 return None;
10282 }
10283 if self.cancel_table_drag_selection() {
10284 return None;
10285 }
10286 let claimed = std::mem::take(&mut self.pointer_activation_claimed);
10287 if self
10288 .delay_hold
10289 .as_ref()
10290 .is_some_and(|hold| matches!(hold.source, DelaySource::Pointer))
10291 {
10292 self.cancel_delay();
10293 }
10294 if self.finish_scroll_bar() {
10295 return None;
10296 }
10297 let pressed_radio = self.pressed_radio.take();
10298 let pressed_list = self.pressed_list_row.take();
10299 let pressed_column = self.pressed_table_column.take();
10300 let pressed_body_column = self.pressed_body_column.take();
10301 let pressed_control_part = self.pressed_control_part.take();
10302 let pressed_standard_button = self.pressed_standard_button.take();
10303 let resized = self.table_resize.take().is_some() | self.table_row_resize.take().is_some();
10304 let pressed = self.pressed.take()?;
10305 (!claimed
10306 && !resized
10307 && !split_resized
10308 && self.hovered.as_ref() == Some(&pressed)
10309 && pressed_radio == self.hovered_radio
10310 && pressed_list == self.hovered_list_row
10311 && self.pressed_tree_indicator == self.hovered_tree_indicator
10312 && pressed_column == self.hovered_table_column
10313 && pressed_body_column == self.hovered_body_column
10314 && pressed_control_part == self.hovered_control_part
10315 && pressed_standard_button == self.hovered_standard_button)
10316 .then_some(pressed)
10317 }
10318
10319 pub fn table_sort_release(&mut self) -> Option<ControlInput> {
10320 let column = self.pressed_table_column?;
10321 let target = self.pointer_release_target()?;
10322 Some(ControlInput {
10323 path: target.path,
10324 action: ControlAction::SortColumn(column),
10325 })
10326 }
10327
10328 pub fn table_header_release(
10329 &mut self,
10330 scene: &Node,
10331 operation: RowSelection,
10332 sort: bool,
10333 ) -> Option<ControlInput> {
10334 let mut input = self.table_sort_release()?;
10335 let ControlAction::SortColumn(column) = input.action else {
10336 return None;
10337 };
10338 let table = scene.interactive_at_path(&input.path)?;
10339 if table.selection_target() == SelectionTarget::Columns && !sort {
10340 input.action =
10341 ControlAction::TableSelection(TableSelectionAction::Column { column, operation });
10342 } else {
10343 table.table_header.as_ref()?.next_sort(column)?;
10344 }
10345 Some(input)
10346 }
10347
10348 pub fn table_column_hovered(&self, path: &[usize], column: usize) -> bool {
10349 self.is_hovered(path) && self.hovered_table_column == Some(column)
10350 }
10351
10352 pub fn arm_table_drag_selection(
10354 &mut self,
10355 scene: &Node,
10356 layout: &LayoutNode,
10357 additive: bool,
10358 ) -> bool {
10359 self.table_drag_selection = (|| {
10360 if self.drag.is_some() || self.table_row_resize.is_some() || self.table_resize.is_some()
10361 {
10362 return None;
10363 }
10364 self.table_selection_at(
10365 scene,
10366 layout,
10367 self.pressed.as_ref()?,
10368 self.pointer?,
10369 additive,
10370 )
10371 .filter(|drag| !drag.gesture.uses_hold(false))
10372 })();
10373 self.table_drag_selection.is_some()
10374 }
10375
10376 pub fn press_table_drag_selection(
10378 &mut self,
10379 scene: &Node,
10380 layout: &LayoutNode,
10381 additive: bool,
10382 ) -> bool {
10383 if self.drag.is_some()
10384 || self.hovered_table_row_grip.is_some()
10385 || self.hovered_table_grip.is_some()
10386 || self.menu_open()
10387 || self.choice_open()
10388 {
10389 return false;
10390 }
10391 let Some(drag) = self
10392 .hovered
10393 .as_ref()
10394 .zip(self.pointer)
10395 .and_then(|(target, point)| {
10396 self.table_selection_at(scene, layout, target, point, additive)
10397 .filter(|drag| !drag.gesture.uses_hold(false))
10398 })
10399 else {
10400 return false;
10401 };
10402 self.pointer_press_in_scene(scene, layout);
10403 self.table_drag_selection = Some(drag);
10404 true
10405 }
10406
10407 fn table_selection_at(
10408 &self,
10409 scene: &Node,
10410 layout: &LayoutNode,
10411 target: &Target,
10412 point: Point,
10413 additive: bool,
10414 ) -> Option<crate::table_drag_selection::TableDragSelection> {
10415 if self.is_text_editor(scene.at_path(&target.path)?, target) {
10416 return None;
10417 }
10418 let (path, slot) = table_hit_row(scene, &target.path)?;
10419 let table = scene.at_path(path)?;
10420 let item = layout.at_path(path)?;
10421 let column = item
10422 .table
10423 .as_ref()?
10424 .body_column_at(item.map_from_window(point)?)?;
10425 crate::table_drag_selection::TableDragSelection::new(
10426 path.to_vec(),
10427 table,
10428 (table.list?.first_row + slot, column),
10429 point,
10430 additive,
10431 scene.row_key_at(path),
10432 item.scroll_axis_reversed(Orientation::Horizontal),
10433 )
10434 }
10435
10436 fn table_gesture_at(
10437 &self,
10438 scene: &Node,
10439 layout: &LayoutNode,
10440 target: &Target,
10441 point: Point,
10442 touch: bool,
10443 now: Instant,
10444 additive: bool,
10445 ) -> Option<PendingTableGesture> {
10446 if touch && let Some(drag) = Self::table_row_move_at(scene, layout, target, point) {
10447 return Some(PendingTableGesture {
10448 drag: PendingTableAction::Move(drag),
10449 deadline: Some(now + Duration::from_millis(500)),
10450 });
10451 }
10452 let select = self.table_selection_at(scene, layout, target, point, additive)?;
10453 let hold = select.gesture.uses_hold(touch);
10454 if !touch && !hold {
10455 return None;
10456 }
10457 if select.gesture != xrack_runtime::SelectionGesture::Auto
10460 && !matches!(
10461 scene.at_path(&target.path)?.kind,
10462 "TableCell" | "TableRow" | "ListRow"
10463 )
10464 {
10465 return None;
10466 }
10467 let deadline = hold.then(|| now + Duration::from_millis(select.hold_interval));
10468 Some(PendingTableGesture {
10469 drag: PendingTableAction::Select(select),
10470 deadline,
10471 })
10472 }
10473
10474 pub fn advance_table_touch_hold(
10476 &mut self,
10477 scene: &Node,
10478 layout: &LayoutNode,
10479 now: Instant,
10480 ) -> bool {
10481 let Some(gesture) = &mut self.scroll_gesture else {
10482 return false;
10483 };
10484 let Some(hold) = gesture
10485 .table_gesture
10486 .take_if(|hold| hold.deadline.is_some_and(|deadline| now >= deadline))
10487 else {
10488 return false;
10489 };
10490 let touch = gesture.touch_point.is_some();
10491 if self.drag.is_some() || self.menu_open() || self.choice_open() {
10492 return false;
10493 }
10494 match hold.drag {
10495 PendingTableAction::Select(mut drag) => {
10496 drag.claimed = true;
10497 drag.touch = touch;
10498 drag.scroll_capture = true;
10499 if self
10500 .table_drag_route(scene, layout, &drag, drag.start)
10501 .is_none()
10502 {
10503 return false;
10504 }
10505 self.cancel_scroll_gesture();
10506 self.capture_table_selection(drag);
10507 }
10508 PendingTableAction::Move(mut drag) => {
10509 let Hit::Target(target) = self.hit_at(scene, layout, drag.start) else {
10510 return false;
10511 };
10512 if Self::table_row_move_at(scene, layout, &target, drag.start).is_none_or(
10513 |current| {
10514 current.table != drag.table
10515 || current.row != drag.row
10516 || current.stamp != drag.stamp
10517 },
10518 ) {
10519 return false;
10520 }
10521 drag.claimed = true;
10522 drag.touch = true;
10523 self.cancel_scroll_gesture();
10524 self.pointer = Some(drag.start);
10525 self.claim_table_selection(drag.table.clone());
10526 self.table_row_move = Some(drag);
10527 }
10528 }
10529 true
10530 }
10531
10532 pub fn table_touch_hold_deadline(&self) -> Option<Instant> {
10533 self.scroll_gesture
10534 .as_ref()?
10535 .table_gesture
10536 .as_ref()?
10537 .deadline
10538 }
10539
10540 fn capture_table_selection(
10541 &mut self,
10542 mut drag: crate::table_drag_selection::TableDragSelection,
10543 ) {
10544 drag.begin_presentation();
10545 self.pointer = Some(drag.start);
10546 let focus = drag.focus_target();
10547 self.table_drag_selection = Some(drag);
10548 self.claim_table_selection(focus);
10549 }
10550
10551 fn table_selection_handle_geometry(
10552 &self,
10553 path: &[usize],
10554 node: &Node,
10555 item: &LayoutNode,
10556 ) -> Option<[Option<crate::table_drag_selection::TableSelectionHandle>; 2]> {
10557 if !self.is_focused(path)
10558 || self.menu_open()
10559 || self.choice_open()
10560 || self.table_edit.is_some()
10561 || self.table_drag_selection_claimed()
10562 {
10563 return None;
10564 }
10565 crate::table_drag_selection::selection_handles(node, item)
10566 }
10567
10568 pub fn table_selection_handles(
10570 &self,
10571 path: &[usize],
10572 node: &Node,
10573 item: &LayoutNode,
10574 ) -> impl Iterator<Item = Rect> {
10575 self.table_selection_handle_parts(path, node, item)
10576 .map(|(_, bounds)| bounds)
10577 }
10578
10579 pub fn table_selection_handle_parts(
10581 &self,
10582 path: &[usize],
10583 node: &Node,
10584 item: &LayoutNode,
10585 ) -> impl Iterator<Item = (usize, Rect)> {
10586 let custom =
10587 node.table_selection_part(0).is_some() || node.table_selection_part(1).is_some();
10588 let preview = if custom {
10589 self.table_drag_selection
10590 .as_ref()
10591 .filter(|drag| drag.path == path && drag.valid(node, item))
10592 .zip(self.pointer)
10593 .and_then(|(drag, point)| drag.preview_handles(node, item, point))
10594 } else {
10595 None
10596 };
10597 preview
10598 .or_else(|| self.table_selection_handle_geometry(path, node, item))
10599 .into_iter()
10600 .flatten()
10601 .enumerate()
10602 .filter_map(|(index, handle)| Some((index, handle?.bounds)))
10603 }
10604
10605 pub fn press_table_selection_handle(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
10606 self.pointer.is_some_and(|point| {
10607 self.start_table_selection_handle(scene, layout, point, false, false)
10608 })
10609 }
10610
10611 fn start_table_selection_handle(
10612 &mut self,
10613 scene: &Node,
10614 layout: &LayoutNode,
10615 point: Point,
10616 touch: bool,
10617 scroll_capture: bool,
10618 ) -> bool {
10619 let drag = (|| {
10620 let focus = self.focused.as_ref()?;
10621 let node = scene.interactive_at_path(&focus.path)?;
10622 let item = layout.at_path(&focus.path)?;
10623 let local = item.map_from_window(point)?;
10624 let handle = self
10625 .table_selection_handle_geometry(&focus.path, node, item)?
10626 .into_iter()
10627 .flatten()
10628 .find(|handle| handle.bounds.contains(local))?;
10629 match self.hit_at(scene, layout, point) {
10630 Hit::Target(target)
10631 | Hit::ControlPart(target, _)
10632 | Hit::TableRowGrip(target, _)
10633 if target.path.starts_with(&focus.path) => {}
10634 _ => return None,
10635 }
10636 let mut drag = crate::table_drag_selection::TableDragSelection::new(
10637 focus.path.clone(),
10638 node,
10639 handle.opposite,
10640 point,
10641 false,
10642 focus.row_key,
10643 item.scroll_axis_reversed(Orientation::Horizontal),
10644 )?;
10645 drag.adjust_range(node.table_selection.as_ref()?.drag_range()?);
10646 drag.touch = touch;
10647 drag.scroll_capture = scroll_capture;
10648 self.table_drag_route(scene, layout, &drag, point)?;
10649 Some(drag)
10650 })();
10651 let Some(drag) = drag else { return false };
10652 self.cancel_press();
10653 if touch {
10654 self.pointer_leave();
10655 }
10656 self.capture_table_selection(drag);
10657 true
10658 }
10659
10660 pub fn touch_table_selection_claimed(&self) -> bool {
10661 self.table_drag_selection
10662 .as_ref()
10663 .is_some_and(|drag| drag.claimed && drag.touch)
10664 }
10665
10666 pub fn touch_table_drag_claimed(&self) -> bool {
10667 self.touch_table_selection_claimed()
10668 || self.table_row_move.as_ref().is_some_and(|drag| drag.touch)
10669 }
10670
10671 fn scroll_table_selection_claimed(&self) -> bool {
10672 self.table_drag_selection
10673 .as_ref()
10674 .is_some_and(|drag| drag.claimed && drag.scroll_capture)
10675 }
10676
10677 pub fn scroll_table_drag_claimed(&self) -> bool {
10678 self.scroll_table_selection_claimed()
10679 || self.table_row_move.as_ref().is_some_and(|drag| drag.touch)
10680 }
10681
10682 pub fn cancel_scroll_table_drag(&mut self) -> bool {
10683 if self.scroll_table_selection_claimed() {
10684 self.cancel_table_drag_selection()
10685 } else {
10686 self.cancel_table_touch_drag()
10687 }
10688 }
10689
10690 pub fn cancel_table_touch_drag(&mut self) -> bool {
10691 if self.touch_table_selection_claimed() {
10692 self.cancel_table_drag_selection()
10693 } else if self.touch_table_drag_claimed() {
10694 self.cancel_table_row_move()
10695 } else {
10696 false
10697 }
10698 }
10699
10700 pub fn table_drag_selection_armed(&self) -> bool {
10701 self.table_drag_selection.is_some()
10702 }
10703
10704 pub fn move_table_drag_selection(&mut self, layout: &LayoutNode, now: Instant) -> bool {
10705 let Some(drag) = &mut self.table_drag_selection else {
10706 return false;
10707 };
10708 if !drag.claimed
10709 && let Some(point) = self.pointer
10710 && let Some(item) = layout.at_path(&drag.path)
10711 && let Some(delta) = item.map_delta_from_window(Point {
10712 x: point.x - drag.start.x,
10713 y: point.y - drag.start.y,
10714 })
10715 && delta.x.hypot(delta.y) >= DRAG_THRESHOLD
10716 {
10717 drag.claimed = true;
10718 drag.begin_presentation();
10719 drag.scroll_wake = Some(now + SCROLL_FRAME_INTERVAL);
10720 let focus = drag.focus_target();
10721 self.claim_table_selection(focus);
10722 return true;
10723 }
10724 if drag.claimed && self.pointer.is_some_and(|point| point != drag.start) {
10725 drag.scroll_wake.get_or_insert(now + SCROLL_FRAME_INTERVAL);
10726 }
10727 drag.claimed
10728 }
10729
10730 fn claim_table_selection(&mut self, focus: Target) {
10731 self.last_table_click = None;
10732 self.pressed = None;
10733 self.set_focus_with_reason(Some(focus), xrack_runtime::FocusReason::PointerClick);
10734 }
10735
10736 pub fn table_drag_selection_claimed(&self) -> bool {
10737 self.table_drag_selection
10738 .as_ref()
10739 .is_some_and(|drag| drag.claimed)
10740 }
10741
10742 pub fn cancel_table_drag_selection(&mut self) -> bool {
10743 if let Some(drag) = self.table_drag_selection.take().filter(|drag| drag.claimed) {
10744 if drag.touch {
10745 self.pointer = None;
10746 }
10747 self.cancel_press();
10748 true
10749 } else {
10750 false
10751 }
10752 }
10753
10754 pub fn finish_table_drag_selection(
10755 &mut self,
10756 scene: &Node,
10757 layout: &LayoutNode,
10758 ) -> Option<ControlInput> {
10759 let drag = self.table_drag_selection.take()?;
10760 let point = self.pointer;
10761 self.cancel_press();
10762 let (node, item, point) = self.table_drag_route(scene, layout, &drag, point?)?;
10763 Some(ControlInput {
10764 action: ControlAction::TableSelection(drag.action(node, item, point)?),
10765 path: drag.path,
10766 })
10767 }
10768
10769 fn table_drag_route<'a>(
10770 &self,
10771 scene: &'a Node,
10772 layout: &'a LayoutNode,
10773 drag: &crate::table_drag_selection::TableDragSelection,
10774 point: Point,
10775 ) -> Option<(&'a Node, &'a LayoutNode, Point)> {
10776 if self.menu_open()
10777 || self.choice_open()
10778 || !drag.path.starts_with(self.pointer_scope(layout, point))
10779 || scene.row_key_at(&drag.path) != drag.parent_row
10780 {
10781 return None;
10782 }
10783 let node = scene.interactive_at_path(&drag.path)?;
10784 let item = layout.at_path(&drag.path)?;
10785 drag.valid(node, item).then_some((node, item, point))
10786 }
10787
10788 pub fn table_drag_preview(
10789 &self,
10790 path: &[usize],
10791 node: &Node,
10792 layout: &LayoutNode,
10793 ) -> Vec<Rect> {
10794 match (&self.table_drag_selection, self.pointer) {
10795 (Some(drag), Some(point)) if drag.path == path && drag.valid(node, layout) => {
10796 drag.preview(node, layout, point)
10797 }
10798 _ => Vec::new(),
10799 }
10800 }
10801
10802 fn table_drag_scroll_delta(&self, scene: &Node, layout: &LayoutNode) -> Option<Point> {
10803 let drag = self.table_drag_selection.as_ref()?;
10804 let (_, item, point) = self.table_drag_route(scene, layout, drag, self.pointer?)?;
10805 let delta = drag.scroll_delta(item, point);
10806 (delta != Point::default()).then_some(delta)
10807 }
10808
10809 pub fn table_drag_selection_deadline(
10810 &self,
10811 scene: &Node,
10812 layout: &LayoutNode,
10813 ) -> Option<Instant> {
10814 self.table_drag_scroll_delta(scene, layout)?;
10815 self.table_drag_selection.as_ref()?.scroll_wake
10816 }
10817
10818 pub fn advance_table_drag_selection(
10819 &mut self,
10820 scene: &Node,
10821 layout: &LayoutNode,
10822 now: Instant,
10823 ) -> bool {
10824 let Some(delta) = self.table_drag_scroll_delta(scene, layout) else {
10825 return false;
10826 };
10827 let Some(drag) = self
10828 .table_drag_selection
10829 .as_mut()
10830 .filter(|drag| drag.scroll_wake.is_some_and(|wake| now >= wake))
10831 else {
10832 return false;
10833 };
10834 drag.scroll_wake = Some(now + SCROLL_FRAME_INTERVAL);
10835 let path = drag.path.clone();
10836 let Some(item) = layout.at_path(&path) else {
10837 return false;
10838 };
10839 let mut moved = false;
10840 for (axis, delta) in [
10841 (Orientation::Horizontal, delta.x),
10842 (Orientation::Vertical, delta.y),
10843 ] {
10844 if delta != 0.0
10845 && let Some(scroll) = item.scroll_on(axis)
10846 {
10847 moved |= self.scroll_to_user_offset(layout, &path, axis, scroll.offset + delta);
10848 }
10849 }
10850 moved
10851 }
10852
10853 pub fn table_column_move_drag(&mut self, layout: &LayoutNode, now: Instant) -> bool {
10854 let Some(drag) = &mut self.table_column_move else {
10855 return false;
10856 };
10857 if !drag.claimed
10858 && let Some(point) = self.pointer
10859 && let Some(item) = layout.at_path(&drag.target.path)
10860 && let Some(delta) = item.map_delta_from_window(Point {
10861 x: point.x - drag.start.x,
10862 y: point.y - drag.start.y,
10863 })
10864 {
10865 drag.claimed = delta.x.abs() >= 8.0 && delta.x.abs() >= delta.y.abs();
10866 if drag.claimed {
10867 drag.scroll_wake = Some(now + SCROLL_FRAME_INTERVAL);
10868 }
10869 }
10870 drag.claimed
10871 }
10872
10873 pub fn table_row_move_drag(&mut self, layout: &LayoutNode, now: Instant) -> bool {
10874 let Some(drag) = &mut self.table_row_move else {
10875 return false;
10876 };
10877 if !drag.claimed
10878 && let Some(point) = self.pointer
10879 && let Some(item) = layout.at_path(&drag.table.path)
10880 && let Some(delta) = item.map_delta_from_window(Point {
10881 x: point.x - drag.start.x,
10882 y: point.y - drag.start.y,
10883 })
10884 && delta.y.abs() >= DRAG_THRESHOLD
10885 && delta.y.abs() >= delta.x.abs()
10886 {
10887 drag.claimed = true;
10888 drag.scroll_wake = Some(now + SCROLL_FRAME_INTERVAL);
10889 }
10890 drag.claimed
10891 }
10892
10893 pub fn table_row_move_claimed(&self) -> bool {
10894 self.table_row_move
10895 .as_ref()
10896 .is_some_and(|drag| drag.claimed)
10897 }
10898
10899 pub fn cancel_table_row_move(&mut self) -> bool {
10900 if let Some(drag) = self.table_row_move.take().filter(|drag| drag.claimed) {
10901 if drag.touch {
10902 self.pointer = None;
10903 }
10904 self.cancel_press();
10905 true
10906 } else {
10907 false
10908 }
10909 }
10910
10911 fn row_move_position(
10912 drag: &TableRowMove,
10913 node: &Node,
10914 layout: &LayoutNode,
10915 point: Point,
10916 ) -> Option<(Rect, Point)> {
10917 if !drag.claimed
10918 || !drag.table.matches_node(node)
10919 || node.standard_list_stamp != Some(drag.stamp)
10920 || !node.boolean("movable-rows", false)
10921 || !layout.visible
10922 || !layout.enabled
10923 || !layout.contains_clip_point(point)
10924 {
10925 return None;
10926 }
10927 let table = layout.table.as_ref()?;
10928 let local = layout.map_from_window(point)?;
10929 let visible = table.rows_area().intersect(layout.clip);
10930 (table.row_header.width > 0.0 && visible.contains(local)).then_some((visible, local))
10931 }
10932
10933 fn row_drop(
10934 drag: &TableRowMove,
10935 node: &Node,
10936 layout: &LayoutNode,
10937 point: Point,
10938 ) -> Option<(usize, Rect)> {
10939 let (visible, point) = Self::row_move_position(drag, node, layout, point)?;
10940 let list = node.list?;
10941 let rows = node
10942 .children
10943 .iter()
10944 .zip(&layout.children)
10945 .enumerate()
10946 .filter(|(_, (row, item))| {
10947 row.kind == "ListRow" && item.visible && item.bounds.intersect(visible).height > 0.0
10948 });
10949 let mut edge = None;
10950 for (slot, (_, item)) in rows {
10951 let row = item.bounds;
10952 let index = list.first_row + slot;
10953 if point.y < row.y + row.height * 0.5 {
10954 edge = Some((index, row.y));
10955 break;
10956 }
10957 edge = Some((index + 1, row.y + row.height));
10958 }
10959 let (insertion, y) = edge?;
10960 let to = insertion.saturating_sub(usize::from(insertion > drag.from));
10961 (to != drag.from && to < list.row_count).then(|| {
10962 let y = y.clamp(
10963 visible.y + 1.0_f32.min(visible.height * 0.5),
10964 visible.y + visible.height - 1.0_f32.min(visible.height * 0.5),
10965 );
10966 (
10967 to,
10968 Rect::new(visible.x, y - 1.0, visible.width, 2.0).intersect(visible),
10969 )
10970 })
10971 }
10972
10973 pub fn table_row_move_marker(
10974 &self,
10975 path: &[usize],
10976 node: &Node,
10977 layout: &LayoutNode,
10978 ) -> Option<Rect> {
10979 let drag = self
10980 .table_row_move
10981 .as_ref()
10982 .filter(|drag| drag.table.path == path)?;
10983 Self::row_drop(drag, node, layout, self.pointer?).map(|(_, marker)| marker)
10984 }
10985
10986 pub fn table_row_move_source(&self, path: &[usize], node: &Node) -> Option<RowKey> {
10987 let drag = self.table_row_move.as_ref()?;
10988 (drag.claimed
10989 && drag.table.path == path
10990 && node.boolean("movable-rows", false)
10991 && node.standard_list_stamp == Some(drag.stamp))
10992 .then_some(drag.row)
10993 }
10994
10995 fn table_row_move_scroll_delta(&self, scene: &Node, layout: &LayoutNode) -> Option<f32> {
10996 let drag = self.table_row_move.as_ref()?;
10997 let point = self.pointer?;
10998 let path = &drag.table.path;
10999 if !path.starts_with(self.pointer_scope(layout, point))
11000 || scene.row_key_at(path) != drag.table.row_key
11001 {
11002 return None;
11003 }
11004 let item = layout.at_path(path)?;
11005 let (visible, point) = Self::row_move_position(drag, scene.at_path(path)?, item, point)?;
11006 let delta = crate::table_drag_selection::edge_delta(point.y, visible.y, visible.height);
11007 let scroll = item.scroll?;
11008 ((scroll.offset + delta).clamp(0.0, scroll.max_offset) != scroll.offset).then_some(delta)
11009 }
11010
11011 pub fn table_row_move_deadline(&self, scene: &Node, layout: &LayoutNode) -> Option<Instant> {
11012 self.table_row_move_scroll_delta(scene, layout)?;
11013 self.table_row_move.as_ref()?.scroll_wake
11014 }
11015
11016 pub fn advance_table_row_move(
11017 &mut self,
11018 scene: &Node,
11019 layout: &LayoutNode,
11020 now: Instant,
11021 ) -> bool {
11022 let Some(delta) = self.table_row_move_scroll_delta(scene, layout) else {
11023 return false;
11024 };
11025 let Some(drag) = self
11026 .table_row_move
11027 .as_mut()
11028 .filter(|drag| drag.scroll_wake.is_some_and(|wake| now >= wake))
11029 else {
11030 return false;
11031 };
11032 drag.scroll_wake = Some(now + SCROLL_FRAME_INTERVAL);
11033 let path = drag.table.path.clone();
11034 let Some(scroll) = layout.at_path(&path).and_then(|item| item.scroll) else {
11035 return false;
11036 };
11037 self.scroll_to_user_offset(layout, &path, Orientation::Vertical, scroll.offset + delta)
11038 }
11039
11040 pub fn finish_table_row_move(
11041 &mut self,
11042 scene: &Node,
11043 layout: &LayoutNode,
11044 ) -> Option<ControlInput> {
11045 let drag = self.table_row_move.take()?;
11046 let point = self.pointer;
11047 self.cancel_press();
11048 let point = point?;
11049 let path = &drag.table.path;
11050 if !valid(&drag.table, scene, layout)
11051 || !path.starts_with(self.pointer_scope(layout, point))
11052 {
11053 return None;
11054 }
11055 let (to, _) = Self::row_drop(&drag, scene.at_path(path)?, layout.at_path(path)?, point)?;
11056 Some(ControlInput {
11057 path: drag.table.path,
11058 action: ControlAction::MoveRow {
11059 from: drag.from,
11060 to,
11061 row: drag.row,
11062 stamp: drag.stamp,
11063 },
11064 })
11065 }
11066
11067 pub fn table_column_move_claimed(&self) -> bool {
11068 self.table_column_move
11069 .as_ref()
11070 .is_some_and(|drag| drag.claimed)
11071 }
11072
11073 fn column_drop(
11074 drag: &TableColumnMove,
11075 node: &Node,
11076 layout: &LayoutNode,
11077 point: Point,
11078 ) -> Option<(usize, usize, f32)> {
11079 let (table, point) = Self::column_move_position(drag, node, layout, point)?;
11080 let from = table.visual_index(drag.column)?;
11081 let (to, marker) = table.column_drop(from, point)?;
11082 Some((from, to, marker))
11083 }
11084
11085 fn column_move_position<'a>(
11086 drag: &TableColumnMove,
11087 node: &Node,
11088 layout: &'a LayoutNode,
11089 point: Point,
11090 ) -> Option<(&'a crate::TableGeometry, Point)> {
11091 if !drag.claimed
11092 || !drag.target.matches_node(node)
11093 || !layout.visible
11094 || !layout.enabled
11095 || !node.boolean("movable-columns", false)
11096 || drag.order != node.table_column_order
11097 || !layout.contains_clip_point(point)
11098 {
11099 return None;
11100 }
11101 let table = layout.table.as_ref()?;
11102 if !table.is_column_visible(drag.column) || drag.mirrored != table.mirrored() {
11103 return None;
11104 }
11105 let local = layout.map_from_window(point)?;
11106 table.header.contains(local).then_some((table, local))
11107 }
11108
11109 fn table_column_move_scroll_delta(&self, scene: &Node, layout: &LayoutNode) -> Option<f32> {
11110 let drag = self.table_column_move.as_ref()?;
11111 let point = self.pointer?;
11112 let path = &drag.target.path;
11113 if !path.starts_with(self.pointer_scope(layout, point)) {
11114 return None;
11115 }
11116 let item = layout.at_path(path)?;
11117 let (table, point) =
11118 Self::column_move_position(drag, drag.target.node_in(scene)?, item, point)?;
11119 let visible = table.scrollable_header().intersect(item.clip);
11120 if !visible.contains(point) {
11121 return None;
11122 }
11123 let edge = (visible.width * 0.25).min(20.0);
11124 if edge <= 0.0 {
11125 return None;
11126 }
11127 let left = (visible.x + edge - point.x).clamp(0.0, edge);
11128 let right = (point.x - (visible.x + visible.width - edge)).clamp(0.0, edge);
11129 let delta = table.logical_delta((right - left) / edge * 18.0);
11130 let scroll = table.horizontal;
11131 ((scroll.offset + delta).clamp(0.0, scroll.max_offset) != scroll.offset).then_some(delta)
11132 }
11133
11134 pub fn table_column_move_deadline(&self, scene: &Node, layout: &LayoutNode) -> Option<Instant> {
11135 self.table_column_move_scroll_delta(scene, layout)?;
11136 self.table_column_move.as_ref()?.scroll_wake
11137 }
11138
11139 pub fn advance_table_column_move(
11140 &mut self,
11141 scene: &Node,
11142 layout: &LayoutNode,
11143 now: Instant,
11144 ) -> bool {
11145 let Some(delta) = self.table_column_move_scroll_delta(scene, layout) else {
11146 return false;
11147 };
11148 let Some(drag) = self
11149 .table_column_move
11150 .as_mut()
11151 .filter(|drag| drag.scroll_wake.is_some_and(|wake| now >= wake))
11152 else {
11153 return false;
11154 };
11155 drag.scroll_wake = Some(now + SCROLL_FRAME_INTERVAL);
11156 let path = drag.target.path.clone();
11157 let Some(item) = layout.at_path(&path) else {
11158 return false;
11159 };
11160 let Some(scroll) = item.scroll_on(Orientation::Horizontal) else {
11161 return false;
11162 };
11163 if !self.set_viewport_offset(
11164 &path,
11165 item,
11166 Orientation::Horizontal,
11167 f64::from(scroll.offset + delta),
11168 ) {
11169 return false;
11170 }
11171 UserScrollChange::record(
11172 &mut self.user_scroll_changes,
11173 item,
11174 Orientation::Horizontal,
11175 scroll.offset,
11176 );
11177 true
11178 }
11179
11180 pub fn table_column_move_marker(
11181 &self,
11182 path: &[usize],
11183 node: &Node,
11184 layout: &LayoutNode,
11185 ) -> Option<f32> {
11186 let drag = self
11187 .table_column_move
11188 .as_ref()
11189 .filter(|drag| drag.target.path == path)?;
11190 Self::column_drop(drag, node, layout, self.pointer?).map(|(_, _, marker)| marker)
11191 }
11192
11193 pub fn finish_table_column_move(
11194 &mut self,
11195 scene: &Node,
11196 layout: &LayoutNode,
11197 ) -> Option<ControlInput> {
11198 let drag = self.table_column_move.take()?;
11199 let point = self.pointer;
11200 self.cancel_press();
11201 let point = point?;
11202 if !valid(&drag.target, scene, layout)
11203 || !drag
11204 .target
11205 .path
11206 .starts_with(self.pointer_scope(layout, point))
11207 {
11208 return None;
11209 }
11210 let node = scene.at_path(&drag.target.path)?;
11211 let item = layout.at_path(&drag.target.path)?;
11212 let (from, to, _) = Self::column_drop(&drag, node, item, point)?;
11213 Some(ControlInput {
11214 path: drag.target.path,
11215 action: ControlAction::MoveColumn { from, to },
11216 })
11217 }
11218
11219 pub fn table_resize_drag(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
11220 let drag = self.table_resize.as_ref()?;
11221 if !valid(&drag.target, scene, layout) {
11222 return None;
11223 }
11224 let node = scene.at_path(&drag.target.path)?;
11225 let column = resizable_table_column(node, drag.column)?;
11226 let item = layout.at_path(&drag.target.path)?;
11227 let table = item.table.as_ref()?;
11228 if !table.is_column_visible(drag.column) || drag.mirrored != table.mirrored() {
11229 return None;
11230 }
11231 let bounds = table.columns[drag.column];
11232 let (min, max) = crate::table::column_limits(column, table.header.width);
11233 let point = item.map_from_window(self.pointer?)?;
11234 let width = drag.width + table.logical_delta(point.x - drag.pointer_x);
11235 if !width.is_finite() || (width.clamp(min, max) - bounds.width).abs() < 0.5 {
11236 return None;
11237 }
11238 Some(ControlInput {
11239 path: drag.target.path.clone(),
11240 action: ControlAction::ResizeColumn {
11241 column: drag.column,
11242 width: width.clamp(min, max).round() as u32,
11243 },
11244 })
11245 }
11246
11247 pub fn finish_table_resize(&mut self) -> bool {
11248 let resizing = self.table_resize.is_some() || self.table_row_resize.is_some();
11249 if resizing {
11250 self.pointer_release_target();
11251 }
11252 resizing
11253 }
11254
11255 pub fn table_resize_cursor(&self) -> bool {
11256 self.table_resize.is_some() || self.hovered_table_grip.is_some()
11257 }
11258
11259 pub fn table_row_resize_cursor(&self) -> bool {
11260 self.table_row_resize.is_some() || self.hovered_table_row_grip.is_some()
11261 }
11262
11263 pub fn table_resize_row(&self, path: &[usize]) -> Option<RowKey> {
11264 if let Some(drag) = &self.table_row_resize {
11265 (drag.target.path == path).then_some(drag.key)
11266 } else if self.is_hovered(path) {
11267 self.hovered_table_row_grip.map(|(key, _)| key)
11268 } else {
11269 None
11270 }
11271 }
11272
11273 pub fn table_row_resize_drag(&self, scene: &Node, layout: &LayoutNode) -> Option<ControlInput> {
11274 let drag = self.table_row_resize.as_ref()?;
11275 if !valid(&drag.target, scene, layout) {
11276 return None;
11277 }
11278 let node = scene.interactive_at_path(&drag.target.path)?;
11279 if !node.boolean("resizable-rows", false) || !self.allows_popup(layout, &drag.target.path) {
11280 return None;
11281 }
11282 let item = layout.at_path(&drag.target.path)?;
11283 let slot = node
11284 .children
11285 .iter()
11286 .position(|row| row.row_key == Some(drag.key))?;
11287 let row = node.list?.first_row.checked_add(slot)?;
11288 let point = item.map_from_window(self.pointer?)?;
11289 let height = drag.height + point.y - drag.pointer_y;
11290 if !height.is_finite() {
11291 return None;
11292 }
11293 let height = ListMetrics::clamp_row_height(height).round();
11294 if (height - item.children.get(slot)?.bounds.height).abs() < 0.5 {
11295 return None;
11296 }
11297 Some(ControlInput {
11298 path: drag.target.path.clone(),
11299 action: ControlAction::ResizeRow {
11300 row,
11301 key: drag.key,
11302 height: height as u32,
11303 },
11304 })
11305 }
11306
11307 pub fn table_resize_column(&self, path: &[usize]) -> Option<usize> {
11308 if let Some(drag) = &self.table_resize {
11309 (drag.target.path == path).then_some(drag.column)
11310 } else if self.is_hovered(path) {
11311 self.hovered_table_grip.map(|(column, _, _)| column)
11312 } else {
11313 None
11314 }
11315 }
11316 pub fn reconcile(&mut self, scene: &Node, layout: &LayoutNode) {
11317 if self
11318 .swipe_page_motion
11319 .as_ref()
11320 .is_some_and(|motion| !motion.is_current(scene, layout))
11321 {
11322 self.swipe_page_motion = None;
11323 }
11324 if self.table_drag_selection.as_ref().is_some_and(|drag| {
11325 drag.claimed
11326 && self
11327 .pointer
11328 .and_then(|point| self.table_drag_route(scene, layout, drag, point))
11329 .is_none()
11330 }) {
11331 self.cancel_table_drag_selection();
11332 }
11333 if let Some(drag) = self
11334 .scroll_gesture
11335 .as_mut()
11336 .and_then(|gesture| gesture.tumbler.as_mut())
11337 && !drag.is_current(scene, layout)
11338 {
11339 drag.cancel();
11340 }
11341 if self.tumbler_flick.as_ref().is_some_and(|flick| {
11342 flick.active() && !self.tumbler_flick_is_current(flick, scene, layout)
11343 }) {
11344 self.interrupt_tumbler_flick();
11345 }
11346 if let Some(drag) = self
11347 .scroll_gesture
11348 .as_mut()
11349 .and_then(|gesture| gesture.switch.as_mut())
11350 && !drag.is_current(scene, layout)
11351 {
11352 drag.position = None;
11353 drag.cancelled = true;
11354 }
11355 self.scope_focus.reconcile(scene, layout);
11356 self.page_focus.reconcile(scene);
11357 self.remember_focus_scope(scene, layout);
11358 self.reconcile_dialogs(scene, layout);
11359 self.finish_calendar_page_focus(scene, layout);
11360 if self.overscroll.has_offset() {
11361 let scope = self.active_dialog(layout).unwrap_or_default();
11362 self.overscroll.reconcile(layout.at_path(scope));
11363 }
11364 let route = self
11365 .scroll_gesture
11366 .as_ref()
11367 .map(|gesture| &gesture.route)
11368 .or_else(|| self.scroll_fling.as_ref().map(|fling| &fling.route));
11369 if let Some(route) = route
11370 && self.scroll_route_is_current(scene, layout, route)
11371 {
11372 self.viewport_motion.reconcile(layout, route.pan_device);
11373 } else {
11374 self.viewport_motion.clear();
11375 }
11376 self.stack_focus.retain(|key, _| {
11377 scene
11378 .at_path(&key.path)
11379 .is_some_and(|view| view.kind == "StackView")
11380 && scene.row_key_at(&key.path) == key.row
11381 });
11382 if self.scroll_bar_press.as_ref().is_some_and(|press| {
11383 !press.cancelled
11384 && (press.node(scene).is_none()
11385 || self
11386 .scroll_bar_for_target(scene, layout, &press.target)
11387 .is_none_or(|bar| bar.reversed() != press.reversed))
11388 }) && let Some(press) = &mut self.scroll_bar_press
11389 {
11390 press.cancelled = true;
11391 }
11392 if self.split_drag.as_ref().is_some_and(|drag| {
11393 !split_target(&drag.target, scene, layout).is_some_and(|(path, geometry, handle)| {
11394 drag.matches(geometry, handle)
11395 && scene
11396 .at_path(path)
11397 .and_then(|node| node.split_resize_handle.as_ref())
11398 == drag.state.as_ref()
11399 })
11400 }) {
11401 self.clear_split_drag();
11402 self.pressed = None;
11403 }
11404 let unavailable = |target: &Target, column, mirrored| {
11405 layout
11406 .at_path(&target.path)
11407 .and_then(|item| item.table.as_ref())
11408 .is_none_or(|table| {
11409 !table.is_column_visible(column) || table.mirrored() != mirrored
11410 })
11411 };
11412 if self
11413 .table_resize
11414 .as_ref()
11415 .is_some_and(|drag| unavailable(&drag.target, drag.column, drag.mirrored))
11416 || self
11417 .table_column_move
11418 .as_ref()
11419 .is_some_and(|drag| unavailable(&drag.target, drag.column, drag.mirrored))
11420 {
11421 self.cancel_press();
11422 }
11423 self.scroll_offsets.retain(|path, value| {
11424 if let Some(scroll) = layout.at_path(path).and_then(|node| node.scroll) {
11425 *value = scroll.offset;
11426 true
11427 } else {
11428 false
11429 }
11430 });
11431 self.horizontal_scroll_offsets.retain(|path, value| {
11432 if let Some(scroll) = layout
11433 .at_path(path)
11434 .and_then(|node| node.scroll_on(Orientation::Horizontal))
11435 && scroll.max_offset > 0.0
11436 {
11437 *value = scroll.offset;
11438 true
11439 } else {
11440 false
11441 }
11442 });
11443 self.tree_scroll_roots = self
11444 .scroll_offsets
11445 .keys()
11446 .filter_map(|path| {
11447 Some((
11448 path.clone(),
11449 scene.at_path(path)?.tree.as_ref()?.root_identity(),
11450 ))
11451 })
11452 .collect();
11453 self.scroll_anchors = capture_list_anchors(scene, layout, &self.scroll_anchors);
11454 for (path, anchor) in &self.scroll_anchors {
11455 if anchor.scope.is_none()
11456 && anchor.offset > 0.0
11457 && !self.scroll_offsets.contains_key(path)
11458 {
11459 self.scroll_offsets.insert(path.clone(), anchor.offset);
11460 }
11461 }
11462 self.scroll_selections = self
11464 .scroll_offsets
11465 .keys()
11466 .chain(self.horizontal_scroll_offsets.keys())
11467 .filter_map(|path| {
11468 let view = scene.at_path(path).filter(|node| {
11469 matches!(
11470 node.kind,
11471 "TabBar" | "TabWidget" | "StandardListView" | "GridView"
11472 ) || node.kind == "TableView" && node.boolean("follow-current", false)
11473 })?;
11474 let item = layout.at_path(path)?;
11475 let cells = ViewCells::new(view, item.bounds.width);
11476 Some((
11477 path.clone(),
11478 ScrollSelection::new(view, cells.columns, item.layout_direction),
11479 ))
11480 })
11481 .collect();
11482 if self
11483 .pressed
11484 .as_ref()
11485 .is_some_and(|t| !valid(t, scene, layout))
11486 {
11487 self.pressed = None;
11488 self.table_resize = None;
11489 }
11490 if let Some(current) = self
11491 .focused
11492 .as_ref()
11493 .filter(|t| !valid(t, scene, layout))
11494 .cloned()
11495 {
11496 if let Some(next) = self.restore_stack_focus(¤t, scene, layout) {
11497 self.set_focus_with_reason(Some(next), xrack_runtime::FocusReason::LayoutChange);
11498 } else if let Some(moved) = moved_row_target(¤t, scene, layout) {
11499 if let Some(offset) = self.text_offsets.remove(¤t.path) {
11500 self.text_offsets.insert(moved.path.clone(), offset);
11501 }
11502 if let Some(edit) = &mut self.table_edit
11503 && edit.target == current
11504 {
11505 edit.target = moved.clone();
11506 }
11507 self.focused = Some(moved);
11508 self.range_keys.clear();
11509 } else {
11510 let scope = self
11511 .focused_popup(layout)
11512 .or_else(|| self.active_dialog(layout))
11513 .unwrap_or_default();
11514 let page = self.page_focus.restore(¤t, scene, layout, scope);
11515 let fallback = page.or_else(|| {
11516 let stops = focus_targets(scene, layout, scope);
11517 attached_radio_tab_stop(scene, ¤t.path, &stops)
11518 .map(|index| stops[index].clone())
11519 .filter(|target| target.row_key == current.row_key)
11520 });
11521 let fallback = fallback.or_else(|| {
11522 (0..current.path.len()).rev().find_map(|length| {
11523 let path = ¤t.path[..length];
11524 let node = scene.at_path(path)?;
11525 if scene
11526 .row_key_at(path)
11527 .is_some_and(|key| Some(key) != current.row_key)
11528 {
11529 return None;
11530 }
11531 let item = layout.at_path(path)?;
11532 let mut target = match node.kind {
11533 "ListView" | "GridView" | "StandardListView" | "TableView"
11534 | "TreeView" | "SwipeView" | "SwipeDelegate" | "StackView"
11535 | "GroupBox" | "Expander"
11536 if eligible(node, item) =>
11537 {
11538 Target::from_node(path.to_vec(), node, true, None)
11539 }
11540 "TabWidget" | "TabBar" | "RadioGroup" => group_focus(node, item, path)?,
11541 "Dialog" | "Drawer" => dialog_entry_focus(scene, layout, path)?,
11542 "FocusScope" => {
11543 let target = crate::focus_scope::target_at(scene, layout, path)?;
11544 self.scope_focus.choose(scene, layout, target, false, false)
11545 }
11546
11547 _ => return None,
11548 };
11549 target.row_key = scene.row_key_at(&target.path);
11550 Some(target)
11551 })
11552 });
11553 self.set_focus_with_reason(fallback, xrack_runtime::FocusReason::LayoutChange);
11554 }
11555 self.key_pressed = None;
11556 self.remember_focus_scope(scene, layout);
11557 }
11558 if self.table_edit.as_ref().is_some_and(|edit| {
11559 !scene
11560 .interactive_at_path(&edit.target.path)
11561 .is_some_and(|node| {
11562 editable_table_cell(node) && node.text("text").unwrap_or("") == edit.original
11563 })
11564 }) {
11565 self.cancel_table_edit();
11566 }
11567 if let Some(draft) = &self.spin_draft
11568 && !self
11569 .focused
11570 .as_ref()
11571 .and_then(|target| scene.interactive_at_path(&target.path))
11572 .is_some_and(|node| draft.mode.is_current(node))
11573 {
11574 self.discard_spin_draft();
11575 }
11576 self.text_offsets.retain(|path, (key, _)| {
11577 scene
11578 .at_path(path)
11579 .is_some_and(|node| is_multiline_text_input(node.kind))
11580 && scene.row_key_at(path) == *key
11581 });
11582 self.retained_selections.retain_mut(|selection| {
11583 let source = &mut selection.source;
11584 if !valid(&source.target, scene, layout)
11585 && let Some(target) = moved_row_target(&source.target, scene, layout)
11586 {
11587 source.target = target;
11588 }
11589 let keep = valid(&source.target, scene, layout)
11590 && source
11591 .target
11592 .node_in(scene)
11593 .is_some_and(|node| source.matches(node));
11594 if !keep && let Some(handle) = &source.handle {
11595 handle.clear_text_state();
11596 }
11597 keep
11598 });
11599 if self
11600 .choice
11601 .as_mut()
11602 .is_some_and(|popup| !popup.reconcile(scene, layout))
11603 {
11604 Self::clear_choice(&mut self.choice);
11605 }
11606 self.reconcile_search_choice(scene, layout);
11607 self.reconcile_text_menu(scene, layout);
11608 if self
11609 .menu
11610 .as_mut()
11611 .is_some_and(|popup| !popup.reconcile(scene, layout))
11612 {
11613 self.dismiss_menu();
11614 }
11615 if let Some(mut pending) = self.pending_shortcut.take()
11616 && !self.shortcuts_blocked()
11617 {
11618 let scope = self.shortcut_scope(layout);
11619 let active = shortcut::bindings(
11620 scene,
11621 layout,
11622 scope,
11623 self.menu.as_ref(),
11624 self.focused.as_ref(),
11625 );
11626 if pending.retain_active(scope, &active) {
11627 self.pending_shortcut = Some(pending);
11628 }
11629 }
11630 if let Some(point) = self.pointer {
11631 if !self.choice_open() && !self.menu_open() {
11633 self.pointer_move(scene, layout, point);
11634 } else {
11635 self.set_split_hover(None);
11636 }
11637 }
11638 if let Some(handle) = &self.range_position_handle
11639 && self.pressed.as_ref().and_then(|target| {
11640 let (_, node) = slider_target(target, scene, layout)?;
11641 node.range_position_handle.as_ref()
11642 }) != Some(handle)
11643 {
11644 self.slider_fraction = None;
11645 self.clear_range_preview();
11646 }
11647 self.publish_button_presses(scene, layout);
11648 }
11649
11650 fn restore_stack_focus(
11651 &mut self,
11652 outgoing: &Target,
11653 scene: &Node,
11654 layout: &LayoutNode,
11655 ) -> Option<Target> {
11656 let scope = self.active_dialog(layout).unwrap_or_default();
11657 let (path, view) = (scope.len()..outgoing.path.len()).rev().find_map(|depth| {
11658 let path = &outgoing.path[..depth];
11659 let view = scene.interactive_at_path(path)?;
11660 (view.kind == "StackView"
11661 && path.starts_with(scope)
11662 && layout
11663 .at_path(path)
11664 .is_some_and(|item| eligible(view, item)))
11665 .then_some((path, view))
11666 })?;
11667 let from = outgoing.path[path.len()];
11668 let to = view.stack_page_index()?;
11669 if from == to {
11670 return None;
11671 }
11672 let row = scene.row_key_at(path);
11673 let key = |page| StackFocusKey {
11674 path: path.to_vec(),
11675 row,
11676 page,
11677 };
11678 self.stack_focus.insert(key(from), outgoing.clone());
11679 if let Some(target) = self.stack_focus.remove(&key(to))
11680 && valid(&target, scene, layout)
11681 {
11682 return Some(target);
11683 }
11684 let mut page = path.to_vec();
11685 page.push(to);
11686 focus_targets(scene, layout, &page)
11687 .into_iter()
11688 .next()
11689 .or_else(|| Some(Target::from_node(path.to_vec(), view, true, row)))
11690 }
11691
11692 fn reconcile_dialogs(&mut self, scene: &Node, layout: &LayoutNode) {
11693 let key = |entry: &DialogFocus| (entry.path.clone(), entry.row_key, entry.modal);
11694 let previous_top = self.dialogs.last().map(key);
11695 let previous_modal = self.dialogs.iter().rfind(|entry| entry.modal).map(key);
11696 let mut focus = self.focused.clone();
11697 let mut index = 0;
11698 while index < self.dialogs.len() {
11699 let dialog = &mut self.dialogs[index];
11700 if layout.overlay_paths().contains(&dialog.path)
11701 && scene.row_key_at(&dialog.path) == dialog.row_key
11702 {
11703 dialog.modal = is_modal_path(layout, &dialog.path);
11704 index += 1;
11705 continue;
11706 }
11707 let removed = self.dialogs.remove(index);
11708 let falls_inside = |target: &Option<Target>| {
11709 target
11710 .as_ref()
11711 .is_some_and(|target| target.path.starts_with(&removed.path))
11712 };
11713 if falls_inside(&focus) {
11714 focus = removed.return_focus.clone();
11715 }
11716 for dialog in &mut self.dialogs {
11717 if falls_inside(&dialog.return_focus) {
11718 dialog.return_focus = removed.return_focus.clone();
11719 }
11720 }
11721 }
11722 for path in layout.overlay_paths() {
11723 if self.dialogs.iter().any(|dialog| dialog.path == *path) {
11724 continue;
11725 }
11726 let modal = is_modal_path(layout, path);
11727 self.dialogs.push(DialogFocus {
11728 path: path.clone(),
11729 row_key: scene.row_key_at(path),
11730 modal,
11731 return_focus: focus.clone(),
11732 });
11733 if modal
11734 || self.allows_popup(layout, path)
11735 && scene
11736 .at_path(path)
11737 .is_some_and(|node| node.boolean("focus", true))
11738 {
11739 focus = dialog_entry_focus(scene, layout, path);
11740 }
11741 }
11742 if previous_top == self.dialogs.last().map(key)
11743 && previous_modal == self.dialogs.iter().rfind(|entry| entry.modal).map(key)
11744 && focus == self.focused
11745 {
11746 return;
11747 }
11748 let active = self.active_dialog(layout);
11749 let scope = active.unwrap_or_default();
11750 let focus = focus
11751 .filter(|target| target.path.starts_with(scope) && valid(target, scene, layout))
11752 .or_else(|| active.and_then(|path| dialog_entry_focus(scene, layout, path)));
11753 self.dismiss_choice();
11754 self.dismiss_menu();
11755 self.cancel_press();
11756 self.cancel_shortcut_sequence();
11757 self.set_focus_with_reason(focus, xrack_runtime::FocusReason::PopupActivation);
11758 }
11759 pub fn focus_next(&mut self, scene: &Node, layout: &LayoutNode, reverse: bool) -> bool {
11761 self.remember_focus_scope(scene, layout);
11762 self.tooltip.focus_source();
11763 let scope = self
11764 .focused_popup(layout)
11765 .or_else(|| self.active_dialog(layout))
11766 .unwrap_or_default();
11767 let boundary = scope.len();
11768 let targets = focus_targets_with_reveal(scene, layout, scope, true);
11769 self.key_pressed = None;
11770 if targets.is_empty() {
11771 self.set_focus_with_reason(None, xrack_runtime::FocusReason::TabNavigation);
11772 return false;
11773 }
11774 let current = self.focused.as_ref().and_then(|target| {
11775 targets
11776 .iter()
11777 .position(|entry| entry == target)
11778 .or_else(|| attached_radio_tab_stop(scene, &target.path, &targets))
11779 .or_else(|| {
11780 let (&index, path) = target.path.split_last()?;
11781 let group = scene.at_path(path).filter(|node| {
11782 matches!(node.kind, "TabWidget" | "TabBar" | "RadioGroup")
11783 })?;
11784 group_item(group, index)?;
11785 targets.iter().position(|entry| {
11786 entry
11787 .path
11788 .split_last()
11789 .is_some_and(|(_, parent)| parent == path)
11790 })
11791 })
11792 .or_else(|| {
11793 let (view, _) = tree_cell_row(scene, &target.path).or_else(|| {
11794 table_cell_row(scene, &target.path).filter(|(table, _)| {
11795 scene
11796 .at_path(table)
11797 .is_some_and(|node| node.boolean("__standard-table", false))
11798 })
11799 })?;
11800 targets.iter().position(|entry| entry.path == view)
11801 })
11802 });
11803 let index = match current {
11804 Some(i) if reverse => (i + targets.len() - 1) % targets.len(),
11805 Some(i) => (i + 1) % targets.len(),
11806 None if reverse => targets.len() - 1,
11807 None => 0,
11808 };
11809 let next = self
11810 .page_focus
11811 .tab_entry(
11812 scene,
11813 layout,
11814 self.focused.as_ref(),
11815 &targets[index],
11816 boundary,
11817 &targets,
11818 )
11819 .unwrap_or_else(|| targets[index].clone());
11820 let next = self
11821 .scope_focus
11822 .entered_scope(
11823 scene,
11824 layout,
11825 self.focused.as_ref(),
11826 &next,
11827 boundary,
11828 true,
11829 true,
11830 )
11831 .map_or(next, |scope| {
11832 self.scope_focus.choose(scene, layout, scope, reverse, true)
11833 });
11834 let revealed = next.path.split_last().is_some_and(|(&index, path)| {
11835 scene
11836 .at_path(path)
11837 .zip(layout.at_path(path))
11838 .is_some_and(|(group, item)| self.reveal_tab(group, item, path, index))
11839 });
11840 let revealed = self.reveal_focus_target(scene, layout, &next) || revealed;
11841 self.set_focus_with_reason(Some(next), xrack_runtime::FocusReason::TabNavigation);
11842 self.remember_focus_scope(scene, layout);
11843 revealed
11844 }
11845
11846 pub fn accessibility_target(
11848 &self,
11849 scene: &Node,
11850 layout: &LayoutNode,
11851 path: &[usize],
11852 ) -> Option<Target> {
11853 if self
11854 .active_dialog(layout)
11855 .is_some_and(|scope| !path.starts_with(scope))
11856 {
11857 return None;
11858 }
11859 let node = scene.interactive_at_path(path)?;
11860 let item = layout.at_path(path)?;
11861 let scrollable = scroll_target_visible(item)
11862 && [Orientation::Horizontal, Orientation::Vertical]
11863 .into_iter()
11864 .any(|axis| {
11865 item.scroll_on(axis)
11866 .is_some_and(|scroll| scroll.max_offset > 0.0)
11867 });
11868 if !eligible(node, item) && !scrollable {
11869 return None;
11870 }
11871 Some(Target::from_node(
11872 path.to_vec(),
11873 node,
11874 focusable(node),
11875 scene.row_key_at(path),
11876 ))
11877 }
11878
11879 pub(crate) fn focus_reason(&self) -> xrack_runtime::FocusReason {
11880 self.focus_reason
11881 }
11882
11883 pub(crate) fn focus_entries(
11884 &self,
11885 scene: &Node,
11886 layout: &LayoutNode,
11887 ) -> Vec<crate::focus_observers::FocusEntry> {
11888 let Some(focus) = self
11889 .focused
11890 .as_ref()
11891 .filter(|target| valid(target, scene, layout))
11892 else {
11893 return Vec::new();
11894 };
11895 let boundary = self
11896 .focused_popup(layout)
11897 .or_else(|| self.active_dialog(layout))
11898 .unwrap_or_default();
11899 if !focus.path.starts_with(boundary) {
11900 return Vec::new();
11901 }
11902 (boundary.len()..=focus.path.len())
11903 .filter_map(|depth| {
11904 let path = &focus.path[..depth];
11905 let node = scene.at_path(path)?;
11906 Some(crate::focus_observers::FocusEntry {
11907 handle: node.focus_handle.clone()?,
11908 direct: depth == focus.path.len(),
11909 target: Target::from_node(path.to_vec(), node, true, scene.row_key_at(path)),
11910 })
11911 })
11912 .collect()
11913 }
11914
11915 pub fn remember_focus_scope(&mut self, scene: &Node, layout: &LayoutNode) {
11916 self.scope_focus
11917 .remember(scene, layout, self.focused.as_ref());
11918 self.page_focus
11919 .remember(scene, layout, self.focused.as_ref());
11920 }
11921
11922 pub fn key_route(&self, scene: &Node, layout: &LayoutNode) -> Option<crate::KeyRoute> {
11923 if self.menu_open()
11924 || self
11925 .editor
11926 .as_ref()
11927 .is_some_and(|editor| !editor.preedit.is_empty())
11928 {
11929 return None;
11930 }
11931 let focus = self
11932 .focused
11933 .as_ref()
11934 .filter(|target| valid(target, scene, layout))?;
11935 let boundary = self
11936 .focused_popup(layout)
11937 .or_else(|| self.active_dialog(layout))
11938 .unwrap_or_default();
11939 if !focus.path.starts_with(boundary) {
11940 return None;
11941 }
11942 let scopes = (boundary.len()..=focus.path.len())
11943 .filter_map(|depth| {
11944 let path = &focus.path[..depth];
11945 let node = scene.at_path(path)?;
11946 if node.kind != "FocusScope" || node.key_handlers == 0 {
11947 return None;
11948 }
11949 crate::focus_scope::target_at(scene, layout, path)
11950 })
11951 .collect();
11952 crate::KeyRoute::new(focus.clone(), scopes)
11953 }
11954
11955 pub fn discard_range_key(&mut self, key: SliderKey) {
11956 self.range_keys.remove(&key);
11957 }
11958
11959 pub fn focus_target(&mut self, scene: &Node, layout: &LayoutNode, target: Target) {
11961 self.focus_target_with_reason(
11962 scene,
11963 layout,
11964 target,
11965 xrack_runtime::FocusReason::Accessibility,
11966 );
11967 }
11968
11969 fn focus_target_with_reason(
11970 &mut self,
11971 scene: &Node,
11972 layout: &LayoutNode,
11973 target: Target,
11974 reason: xrack_runtime::FocusReason,
11975 ) -> bool {
11976 let reveal = reason == xrack_runtime::FocusReason::Programmatic;
11977 let target = if target
11978 .node_in(scene)
11979 .is_some_and(|node| node.kind == "RadioGroup")
11980 {
11981 let Some(target) = radio_group_focus(scene, layout, &target.path, reveal) else {
11982 return false;
11983 };
11984 target
11985 } else {
11986 target
11987 };
11988 if !focus_reachable(&target, scene, layout, reveal)
11989 || self
11990 .active_dialog(layout)
11991 .is_some_and(|modal| !target.path.starts_with(modal))
11992 {
11993 return false;
11994 }
11995 self.remember_focus_scope(scene, layout);
11996 let target = self
11997 .scope_focus
11998 .choose_with_reveal(scene, layout, target, false, false, reveal);
11999 let scrolled = reveal && self.reveal_focus_target(scene, layout, &target);
12000 self.tooltip.focus_source();
12001 self.set_focus_with_reason(Some(target), reason);
12002 self.remember_focus_scope(scene, layout);
12003 scrolled
12004 }
12005
12006 fn reveal_focus_target(&mut self, scene: &Node, layout: &LayoutNode, target: &Target) -> bool {
12007 if target.text_link.is_some() {
12008 return false;
12009 }
12010 let Some(rect) = scene
12011 .at_path(&target.path)
12012 .zip(layout.at_path(&target.path))
12013 .and_then(|(node, item)| focus_hitbox(node, item))
12014 else {
12015 return false;
12016 };
12017 self.reveal_focus_in_viewports(scene, layout, &target.path, rect)
12018 }
12019
12020 pub fn apply_focus_requests(
12021 &mut self,
12022 scene: &Node,
12023 layout: &LayoutNode,
12024 requests: impl IntoIterator<Item = xrack_runtime::FocusRequest>,
12025 ) {
12026 for request in requests {
12027 if let Some(command) = self.apply_focus_request(scene, layout, request) {
12028 self.apply_text_selection(scene, command);
12029 }
12030 }
12031 }
12032
12033 pub fn apply_focus_request(
12035 &mut self,
12036 scene: &Node,
12037 layout: &LayoutNode,
12038 request: xrack_runtime::FocusRequest,
12039 ) -> Option<TextCommand> {
12040 self.apply_focus_request_with_scroll(scene, layout, request)
12041 .0
12042 }
12043
12044 #[doc(hidden)]
12045 pub fn apply_focus_request_with_scroll(
12046 &mut self,
12047 scene: &Node,
12048 layout: &LayoutNode,
12049 request: xrack_runtime::FocusRequest,
12050 ) -> (Option<TextCommand>, bool) {
12051 let mut scrolled = false;
12052 let command = (|| {
12053 let modal = self.active_dialog(layout).unwrap_or_default();
12054 let reveal = matches!(request.action, xrack_runtime::FocusAction::Focus);
12055 let target =
12056 crate::focus_scope::handle_target(scene, layout, modal, &request.target, reveal)?;
12057 match request.action {
12058 xrack_runtime::FocusAction::Focus => {
12059 scrolled = self.focus_target_with_reason(
12060 scene,
12061 layout,
12062 target,
12063 xrack_runtime::FocusReason::Programmatic,
12064 );
12065 }
12066 xrack_runtime::FocusAction::Clear => {
12067 let scope = scene.at_path(&target.path).is_some_and(|node| {
12068 matches!(node.kind, "FocusScope" | "Loader" | "RadioGroup")
12069 });
12070 if self.focused.as_ref().is_some_and(|focused| {
12071 *focused == target || scope && focused.path.starts_with(&target.path)
12072 }) {
12073 self.remember_focus_scope(scene, layout);
12074 self.set_focus_with_reason(None, xrack_runtime::FocusReason::Programmatic);
12075 }
12076 }
12077 xrack_runtime::FocusAction::OpenChoice => {
12078 if scene
12079 .at_path(&target.path)
12080 .is_some_and(|node| node.kind == "ComboBox")
12081 && !self.choice_is_open_for(&target.path)
12082 && self.open_choice(scene, layout, target)
12083 {
12084 self.dismiss_menu();
12085 }
12086 }
12087 xrack_runtime::FocusAction::CloseChoice => {
12088 if self.choice_is_open_for(&target.path) {
12089 self.dismiss_choice();
12090 }
12091 }
12092 xrack_runtime::FocusAction::Text(command) => {
12093 let node = scene.interactive_at_path(&target.path)?;
12094 let focused = self.focused.as_ref().is_some_and(|current| {
12095 current == &target
12096 || node.selectable_styled_text()
12097 && current.path == target.path
12098 && current.row_key == target.row_key
12099 });
12100 if !focused
12101 || !self.is_text_editor(node, &target)
12102 || self.editor.as_ref().is_some_and(TextEdit::is_composing)
12103 {
12104 return None;
12105 }
12106 self.sync_editor(scene);
12107 return Some(command);
12108 }
12109 xrack_runtime::FocusAction::EditTableCell { row, column } => {
12110 let row = usize::try_from(row).ok()?;
12111 let column = usize::try_from(column).ok()?;
12112 let cell = table_cell_target(scene, layout, &target.path, row, column)?;
12113 self.begin_cell_edit(
12114 scene,
12115 layout,
12116 cell,
12117 xrack_runtime::FocusReason::Programmatic,
12118 );
12119 }
12120 xrack_runtime::FocusAction::CancelTableEdit => {
12121 if self.table_edit.as_ref().is_some_and(|edit| {
12122 table_cell_row(scene, &edit.target.path)
12123 .is_some_and(|(table, _)| table == target.path)
12124 }) {
12125 self.cancel_table_edit();
12126 }
12127 }
12128 }
12129 None
12130 })();
12131 (command, scrolled)
12132 }
12133
12134 pub fn apply_text_selection(&mut self, scene: &Node, command: TextCommand) {
12135 let Some(target) = &self.focused else {
12136 return;
12137 };
12138 let Some(node) = scene.interactive_at_path(&target.path) else {
12139 return;
12140 };
12141 let value = self.editor_value(node);
12142 let Some(mut editor) = self.editor.clone() else {
12143 return;
12144 };
12145 let (anchor, focus) = match command {
12146 TextCommand::SelectAll => (
12147 0,
12148 TextPosition {
12149 offset: value.len(),
12150 trailing: false,
12151 },
12152 ),
12153 TextCommand::SelectWord => {
12154 let word = TextEdit::word_at(&value, editor.position(&value), node.is_password());
12155 (
12156 word.start,
12157 TextPosition {
12158 offset: word.end,
12159 trailing: true,
12160 },
12161 )
12162 }
12163 TextCommand::ClearSelection => {
12164 let caret = editor.position(&value);
12165 (caret.offset, caret)
12166 }
12167 TextCommand::SetSelection { anchor, focus } => {
12168 let offset = |byte: i64| {
12169 usize::try_from(byte.max(0))
12170 .unwrap_or(usize::MAX)
12171 .min(value.len())
12172 };
12173 (
12174 offset(anchor),
12175 TextPosition {
12176 offset: offset(focus),
12177 trailing: false,
12178 },
12179 )
12180 }
12181 _ => return,
12182 };
12183 editor.set_selection(&value, anchor, focus);
12184 self.editor = Some(editor);
12185 self.break_text_edit_group();
12186 self.painted_combo_completion = None;
12187 }
12188
12189 pub fn accessibility_focus(&mut self, target: Target) {
12190 if target.focusable {
12191 self.tooltip.focus_source();
12192 self.set_focus_with_reason(Some(target), xrack_runtime::FocusReason::Accessibility);
12193 }
12194 }
12195 pub fn key_press(&mut self, key: ActivationKey) {
12196 self.cancel_delay();
12197 self.button_hold = None;
12198 self.key_activation_claimed = None;
12199 self.key_pressed = self.focused.clone().map(|t| (key, t));
12200 self.key_standard_button = None;
12201 }
12202
12203 pub fn key_press_with_scene(&mut self, scene: &Node, key: ActivationKey) {
12204 self.key_press(key);
12205 if let Some(target) = self.focused.clone() {
12206 self.start_button_contact(scene, target, ButtonContactSource::Key(key));
12207 }
12208 self.key_standard_button = self
12209 .focused
12210 .as_ref()
12211 .and_then(|target| scene.at_path(&target.path))
12212 .and_then(Node::standard_button_kind);
12213 }
12214 pub fn key_release(&mut self, key: ActivationKey) -> Option<&'static str> {
12215 self.key_release_target(key).and_then(|target| target.id)
12216 }
12217 pub fn key_release_target(&mut self, key: ActivationKey) -> Option<Target> {
12218 if self.key_pressed.as_ref()?.0 != key {
12219 return None;
12220 }
12221 let (_, target) = self.key_pressed.take()?;
12222 self.finish_button_contact(
12223 ButtonContactSource::Key(key),
12224 self.focused.as_ref() == Some(&target),
12225 );
12226 if self.button_hold.as_ref().is_some_and(
12227 |repeat| matches!(repeat.source, DelaySource::Key(pressed) if pressed == key),
12228 ) {
12229 self.button_hold = None;
12230 }
12231 self.key_standard_button = None;
12232 let claimed = self.key_activation_claimed.take() == Some(key);
12233 if self
12234 .delay_hold
12235 .as_ref()
12236 .is_some_and(|hold| matches!(hold.source, DelaySource::Key(pressed) if pressed == key))
12237 {
12238 self.cancel_delay();
12239 }
12240 (!claimed && self.focused.as_ref() == Some(&target)).then_some(target)
12241 }
12242
12243 pub fn key_release_with_scene(&mut self, scene: &Node, key: ActivationKey) -> Option<Target> {
12244 let kind = self.key_standard_button;
12245 let target = self.key_release_target(key)?;
12246 let node = target.node_in(scene)?;
12247 (node.standard_button_kind() == kind).then_some(target)
12248 }
12249 pub fn cancel_press(&mut self) {
12250 self.text_selection_scroll = None;
12251 self.editor_press = None;
12252 self.last_editor_click = None;
12253 self.button_press_events.extend(
12254 self.button_contacts
12255 .drain(..)
12256 .map(|contact| (contact, "canceled")),
12257 );
12258 for handle in self.published_button_presses.drain(..) {
12259 handle.publish(false);
12260 }
12261 if self.touch_table_drag_claimed() {
12262 self.pointer = None;
12263 }
12264 self.cancel_window_move();
12265 self.cancel_scroll_gesture();
12266 self.cancel_delay();
12267 self.button_hold = None;
12268 self.pointer_activation_claimed = false;
12269 self.key_activation_claimed = None;
12270 self.dialog_backdrop = None;
12271 self.pressed = None;
12272 self.press_origin = None;
12273 self.scroll_bar_press = None;
12274 self.pressed_radio = None;
12275 self.pressed_list_row = None;
12276 self.pressed_tree_indicator = false;
12277 self.pressed_table_column = None;
12278 self.pressed_body_column = None;
12279 self.pressed_control_part = None;
12280 self.pressed_standard_button = None;
12281 self.table_resize = None;
12282 self.table_row_resize = None;
12283 self.table_column_move = None;
12284 self.table_row_move = None;
12285 self.table_drag_selection = None;
12286 self.clear_split_drag();
12287 self.slider_offset = 0.0;
12288 self.slider_anchor = None;
12289 self.slider_fraction = None;
12290 self.clear_range_preview();
12291 self.dial_pointer = None;
12292 self.spin_pressed = None;
12293 self.key_pressed = None;
12294 self.range_keys.clear();
12295 }
12296 pub fn is_hovered(&self, path: &[usize]) -> bool {
12297 self.hovered.as_ref().is_some_and(|t| t.path == path)
12298 }
12299 pub fn is_focused(&self, path: &[usize]) -> bool {
12300 self.focused.as_ref().is_some_and(|t| t.path == path)
12301 }
12302 pub fn publish_button_presses(&mut self, scene: &Node, layout: &LayoutNode) {
12304 let mut next = Vec::new();
12305 if !self.menu_open() && !self.choice_open() {
12306 let pointer = self
12307 .pressed
12308 .as_ref()
12309 .filter(|target| self.hovered.as_ref() == Some(*target));
12310 let key = self
12311 .key_pressed
12312 .as_ref()
12313 .map(|(_, target)| target)
12314 .filter(|target| self.focused.as_ref() == Some(*target));
12315 let touch = self.scroll_gesture.as_ref().and_then(|gesture| {
12316 let point = gesture.touch_point?;
12317 let Some(Hit::Target(target)) = &gesture.tap else {
12318 return None;
12319 };
12320 (!gesture.motion.dragging
12321 && self.target_at(scene, layout, point).as_ref() == Some(target))
12322 .then_some(target)
12323 });
12324 let scope = self.active_dialog(layout).unwrap_or_default();
12325 for target in [pointer, key, touch].into_iter().flatten() {
12326 if target.path.starts_with(scope)
12327 && valid(target, scene, layout)
12328 && let Some(handle) = target
12329 .node_in(scene)
12330 .and_then(|node| node.button_press_handle.as_ref())
12331 && !next.contains(handle)
12332 {
12333 next.push(handle.clone());
12334 }
12335 }
12336 }
12337 for old in &self.published_button_presses {
12338 if !next.contains(old) {
12339 old.publish(false);
12340 }
12341 }
12342 for handle in &next {
12343 handle.publish(true);
12344 }
12345 self.published_button_presses = next;
12346 }
12347
12348 fn start_button_contact(&mut self, scene: &Node, target: Target, source: ButtonContactSource) {
12349 let Some(handle) = target
12350 .node_in(scene)
12351 .and_then(|node| node.button_press_handle.clone())
12352 else {
12353 return;
12354 };
12355 self.finish_button_contact(source, false);
12356 if handle.cancel_animation() {
12357 self.button_press_events.push((
12358 ButtonContact {
12359 source,
12360 target: target.clone(),
12361 handle: handle.clone(),
12362 },
12363 "canceled",
12364 ));
12365 }
12366 self.button_press_events.push((
12367 ButtonContact {
12368 source,
12369 target: target.clone(),
12370 handle: handle.clone(),
12371 },
12372 "pressed",
12373 ));
12374 self.button_contacts.push(ButtonContact {
12375 source,
12376 target,
12377 handle,
12378 });
12379 }
12380
12381 fn finish_button_contact(&mut self, source: ButtonContactSource, released: bool) {
12382 if let Some(index) = self
12383 .button_contacts
12384 .iter()
12385 .position(|contact| contact.source == source)
12386 {
12387 self.button_press_events.push((
12388 self.button_contacts.remove(index),
12389 if released { "released" } else { "canceled" },
12390 ));
12391 }
12392 }
12393
12394 pub fn dispatch_button_press_events(
12396 &mut self,
12397 component: &mut impl Component,
12398 scene: &Node,
12399 layout: &LayoutNode,
12400 ) -> bool {
12401 self.publish_button_presses(scene, layout);
12402 if self.button_contacts.is_empty() && self.button_press_events.is_empty() {
12403 return false;
12404 }
12405 let scope = self.active_dialog(layout).unwrap_or_default().to_vec();
12406 let popup = self.menu_open() || self.choice_open();
12407 let focused = self.focused.as_ref();
12408 let pointer = self.pressed.as_ref();
12409 let key_pressed = self.key_pressed.as_ref();
12410 let gesture = self.scroll_gesture.is_some();
12411 self.button_contacts.retain(|contact| {
12412 let current = contact.target.path.starts_with(&scope)
12413 && !popup
12414 && valid(&contact.target, scene, layout)
12415 && contact
12416 .target
12417 .node_in(scene)
12418 .and_then(|node| node.button_press_handle.as_ref())
12419 == Some(&contact.handle)
12420 && match contact.source {
12421 ButtonContactSource::Pointer => pointer == Some(&contact.target),
12422 ButtonContactSource::Gesture => gesture,
12423 ButtonContactSource::Key(key) => {
12424 focused == Some(&contact.target)
12425 && key_pressed.is_some_and(|(pressed, target)| {
12426 key == *pressed && target == &contact.target
12427 })
12428 }
12429 };
12430 if !current {
12431 self.button_press_events.push((
12432 ButtonContact {
12433 source: contact.source,
12434 target: contact.target.clone(),
12435 handle: contact.handle.clone(),
12436 },
12437 "canceled",
12438 ));
12439 }
12440 current
12441 });
12442 let mut handled = false;
12443 for (contact, event) in std::mem::take(&mut self.button_press_events) {
12444 if contact
12445 .target
12446 .node_in(scene)
12447 .and_then(|node| node.button_press_handle.as_ref())
12448 == Some(&contact.handle)
12449 {
12450 handled |= component.dispatch_at(scene, &contact.target.path, event);
12451 }
12452 }
12453 handled
12454 }
12455
12456 pub fn is_pressed(&self, path: &[usize]) -> bool {
12457 (self.pressed.as_ref().is_some_and(|t| t.path == path)
12458 && self.is_hovered(path)
12459 && self.pressed_list_row == self.hovered_list_row
12460 && self.pressed_standard_button == self.hovered_standard_button)
12461 || self
12462 .key_pressed
12463 .as_ref()
12464 .is_some_and(|(_, t)| t.path == path)
12465 || self.button_hold.as_ref().is_some_and(|repeat| {
12466 matches!(repeat.source, DelaySource::Touch(_)) && repeat.target.path == path
12467 })
12468 }
12469}
12470
12471pub struct WheelRoute {
12473 deliveries: Vec<(Vec<usize>, xrack_runtime::WheelEvent)>,
12474}
12475
12476fn local_handler_position(
12477 item: &LayoutNode,
12478 point: Point,
12479) -> Option<(xrack_runtime::Length, xrack_runtime::Length)> {
12480 let local = item.map_from_window(point)?;
12481 (item.enabled && item.bounds.contains(local) && item.contains_clip_point(point)).then(|| {
12482 (
12483 xrack_runtime::Length(f64::from(local.x - item.bounds.x)),
12484 xrack_runtime::Length(f64::from(local.y - item.bounds.y)),
12485 )
12486 })
12487}
12488
12489impl WheelRoute {
12490 pub fn dispatch(
12491 self,
12492 component: &mut impl Component,
12493 scene: &Node,
12494 ) -> xrack_runtime::EventResult {
12495 for (path, event) in self.deliveries {
12496 if component.wheel_event_at(scene, &path, &event) == xrack_runtime::EventResult::Accept
12497 {
12498 return xrack_runtime::EventResult::Accept;
12499 }
12500 }
12501 xrack_runtime::EventResult::Reject
12502 }
12503}