1use std::any::{Any, TypeId};
10use std::cell::{Cell, RefCell};
11use std::panic::{self, AssertUnwindSafe};
12use std::rc::{Rc, Weak};
13use std::sync::OnceLock;
14use std::time::{Duration, Instant};
15
16use crabshell_reactive::{Signal, untrack};
17
18use crate::access::AccessEvent;
19use crate::cx::Cx;
20use crate::dnd::Incoming;
21use crate::geometry::{Point, Rect, Size};
22use crate::keyboard::{Clipboard, KeyHandler};
23use crate::prop::{Prop, PropKind};
24use crate::scrolling::{BarDrag, Flick};
25use crate::select::{TextClick, text_selection};
26use crate::tree::{ButtonNode, Change, Node, NodeId, NodeKind, Tree, add_damage, borrow};
27use crate::window::Window;
28
29pub(crate) const PIXELS_PER_STEP: f32 = 15.0;
31
32const VALUE120_PER_STEP: i32 = 120;
34
35pub(crate) const DRAG_THRESHOLD: f32 = 10.0;
38
39const LONG_PRESS: Duration = Duration::from_millis(800);
42
43pub(crate) const DOUBLE_CLICK_MS: u32 = 400;
46
47pub(crate) const DOUBLE_CLICK_DISTANCE: f32 = 5.0;
50
51pub(crate) struct Handler<F: ?Sized> {
53 disabled: Cell<bool>,
54 f: F,
55}
56
57impl<F> Handler<F> {
58 pub(crate) fn new(f: F) -> Handler<F> {
59 Handler {
60 disabled: Cell::new(false),
61 f,
62 }
63 }
64}
65
66impl<F: ?Sized> Handler<F> {
67 pub(crate) fn disabled(&self) -> bool {
69 self.disabled.get()
70 }
71}
72
73pub(crate) type ClickHandler = Rc<Handler<dyn Fn(&Cx)>>;
74type ScrollHandler = Rc<Handler<dyn Fn(&Cx, i32)>>;
75pub(crate) type WheelHandler = Rc<Handler<dyn Fn(&Cx, Wheel)>>;
76pub(crate) type DragHandler = Rc<Handler<dyn Fn(&Cx, Drag)>>;
77pub(crate) type LinkHandler = Rc<Handler<dyn Fn(&Cx, &str)>>;
78
79pub(crate) type DragValue = Rc<dyn Any>;
83
84pub(crate) struct DropTarget {
86 pub(crate) accepts: TypeId,
87 pub(crate) handler: DropHandler,
88 pub(crate) name: &'static str,
90}
91
92pub(crate) type DropHandler = Rc<Handler<dyn Fn(&Cx, &dyn Any)>>;
94
95#[derive(Default)]
97pub(crate) struct Handlers {
98 pub(crate) click: Option<ClickHandler>,
99 pub(crate) press: Option<ClickHandler>,
100 pub(crate) release: Option<ClickHandler>,
101 pub(crate) double_click: Option<ClickHandler>,
102 pub(crate) long_press: Option<ClickHandler>,
103 pub(crate) right_click: Option<ClickHandler>,
104 pub(crate) middle_click: Option<ClickHandler>,
105 pub(crate) back: Option<ClickHandler>,
106 pub(crate) forward: Option<ClickHandler>,
107 pub(crate) scroll: Option<ScrollHandler>,
108 pub(crate) wheel: Option<WheelHandler>,
109 pub(crate) drag: Option<DragHandler>,
110 pub(crate) drop: Option<DropTarget>,
111 pub(crate) key: Option<KeyHandler>,
112}
113
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
116pub enum PointerButton {
117 Left,
119 Right,
121 Middle,
123 Back,
126 Forward,
129}
130
131#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
133pub enum ScrollSource {
134 #[default]
136 Wheel,
137 Finger,
140 Continuous,
142 WheelTilt,
144}
145
146#[derive(Clone, Copy, Debug, Default, PartialEq)]
148pub struct WheelAxis {
149 pub pixels: f32,
152 pub notches: f32,
156 pub stop: bool,
159}
160
161#[derive(Clone, Copy, Debug, Default, PartialEq)]
164pub struct Wheel {
165 pub source: ScrollSource,
167 pub x: WheelAxis,
169 pub y: WheelAxis,
171}
172
173#[derive(Clone, Copy, Debug, PartialEq, Eq)]
175pub enum DragPhase {
176 Start,
179 Move,
181 End,
184}
185
186#[derive(Clone, Copy, Debug, PartialEq)]
191pub struct Drag {
192 pub phase: DragPhase,
194 pub start: Point,
196 pub position: Point,
199 pub size: Size,
201 pub dropped: bool,
205}
206
207#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
210pub enum CursorShape {
211 #[default]
213 Default,
214 ContextMenu,
216 Help,
218 Pointer,
220 Progress,
222 Wait,
224 Cell,
226 Crosshair,
228 Text,
230 VerticalText,
232 Alias,
234 Copy,
236 Move,
238 NoDrop,
240 NotAllowed,
242 Grab,
244 Grabbing,
246 EResize,
248 NResize,
250 NeResize,
252 NwResize,
254 SResize,
256 SeResize,
258 SwResize,
260 WResize,
262 EwResize,
264 NsResize,
266 NeswResize,
268 NwseResize,
270 ColResize,
272 RowResize,
274 AllScroll,
276 ZoomIn,
278 ZoomOut,
280 DndAsk,
283 AllResize,
286}
287
288#[derive(Clone, Copy)]
290pub(crate) struct Press {
291 pub(crate) id: NodeId,
292 pub(crate) button: PointerButton,
293 at: Point,
296 pub(crate) last: Point,
297 start: Point,
299 pub(crate) dragging: bool,
301 long_pressed: bool,
303 pub(crate) out: bool,
306}
307
308#[derive(Default)]
310pub(crate) struct Pointer {
311 pub(crate) position: Option<Point>,
312 pub(crate) hovered: Option<NodeId>,
314 inside: Vec<(NodeId, Signal<bool>)>,
317 positions: Vec<(NodeId, Signal<Option<Point>>, Point)>,
320 pub(crate) pressed: Option<Press>,
322 link: Option<(NodeId, usize, String)>,
325 link_hover: Option<(NodeId, usize)>,
327 pub(crate) bar: Option<BarDrag>,
329 pub(crate) flick: Option<Flick>,
332 pub(crate) gesture: Option<NodeId>,
334 pub(crate) last_click: Option<(NodeId, u32, Point)>,
337 pub(crate) text_click: Option<TextClick>,
340 wheel: i32,
342 pixels: f32,
343 caused_layout: bool,
345 pub(crate) drop_over: Option<(NodeId, Option<Signal<bool>>)>,
348 pub(crate) incoming: Option<Incoming>,
350}
351
352impl Pointer {
353 pub(crate) fn forget(&mut self, removed: &[NodeId]) {
356 if self.hovered.is_some_and(|id| removed.contains(&id)) {
357 self.hovered = None;
358 }
359 let (gone, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut self.inside)
360 .into_iter()
361 .partition(|(id, _)| removed.contains(id));
362 for (_, signal) in gone {
363 if !kept.iter().any(|(_, other)| *other == signal) {
365 signal.try_set(false);
366 }
367 }
368 self.inside = kept;
369 self.positions.retain(|(id, signal, _)| {
370 let gone = removed.contains(id);
371 if gone {
372 signal.try_set(None);
373 }
374 !gone
375 });
376 let source_gone = self
377 .pressed
378 .is_some_and(|press| removed.contains(&press.id));
379 if source_gone {
380 self.pressed = None;
381 }
382 if source_gone || self.drop_over.is_some_and(|(id, _)| removed.contains(&id)) {
383 self.set_drop_over(None);
384 }
385 self.forget_views(removed);
386 if self
387 .last_click
388 .is_some_and(|(id, _, _)| removed.contains(&id))
389 {
390 self.last_click = None;
391 }
392 if self
393 .text_click
394 .is_some_and(|click| removed.contains(&click.id))
395 {
396 self.text_click = None;
397 }
398 }
399}
400
401impl Pointer {
402 fn set_drop_over(&mut self, over: Option<(NodeId, Option<Signal<bool>>)>) {
405 let old = std::mem::replace(&mut self.drop_over, over);
406 if old.map(|(id, _)| id) == over.map(|(id, _)| id) {
407 return;
408 }
409 let (old, new) = (old.and_then(|(_, s)| s), over.and_then(|(_, s)| s));
410 if old != new {
411 if let Some(old) = old {
412 old.try_set(false);
413 }
414 if let Some(new) = new {
415 new.try_set(true);
416 }
417 }
418 }
419}
420
421impl Tree {
422 pub(crate) fn pointer_hide(&mut self, hidden: &[NodeId]) {
425 let held = [
426 self.pointer.hovered,
427 self.pointer.pressed.map(|press| press.id),
428 ];
429 self.pointer.forget(hidden);
430 for id in held.into_iter().flatten().filter(|id| hidden.contains(id)) {
431 self.update_button_style(id, |button| {
432 button.hovered = false;
433 button.pressed = false;
434 });
435 }
436 }
437}
438
439fn now_ms() -> u32 {
442 static START: OnceLock<Instant> = OnceLock::new();
443 START.get_or_init(Instant::now).elapsed().as_millis() as u32
445}
446
447impl Window {
448 pub fn pointer_motion(&self, position: Point) -> CursorShape {
451 self.pointer_motion_at(position, now_ms())
452 }
453
454 pub fn pointer_motion_at(&self, position: Point, time: u32) -> CursorShape {
459 let calls = {
460 let mut tree = borrow(&self.tree);
461 tree.pointer.position = Some(position);
462 tree.bar_motion(position);
463 let calls = if tree.flick_motion(position, time) {
464 Vec::new()
465 } else {
466 tree.drag_motion(position)
467 };
468 tree.hover_at(position);
469 calls
470 };
471 run_all(calls);
472 self.cursor()
473 }
474
475 pub fn pointer_leave(&self) {
478 let calls = borrow(&self.tree).leave();
479 run_all(calls);
480 }
481
482 pub fn pointer_button(&self, button: PointerButton, pressed: bool) {
485 self.pointer_button_at(button, pressed, now_ms());
486 }
487
488 pub fn pointer_button_at(&self, button: PointerButton, pressed: bool, time: u32) {
496 let calls = borrow(&self.tree).button(button, pressed, time, false);
497 run_all(calls);
498 }
499
500 pub fn touch_at(&self, pressed: bool, time: u32) {
505 let calls = borrow(&self.tree).button(PointerButton::Left, pressed, time, true);
506 run_all(calls);
507 }
508
509 pub fn pointer_scroll(&self, wheel: Wheel) {
518 self.pointer_scroll_at(wheel, now_ms());
519 }
520
521 pub fn pointer_scroll_at(&self, wheel: Wheel, time: u32) {
525 let calls = borrow(&self.tree).scroll(wheel, time);
526 run_all(calls);
527 }
528
529 pub fn take_primary(&self) -> Option<Clipboard> {
535 borrow(&self.tree).primary.take()
536 }
537
538 pub fn cursor(&self) -> CursorShape {
540 self.tree.borrow().cursor()
541 }
542}
543
544pub(crate) fn run_all(calls: Vec<Call>) {
546 for call in calls {
547 call.run();
548 }
549}
550
551pub(crate) fn distance(a: Point, b: Point) -> f32 {
552 (a.x - b.x).hypot(a.y - b.y)
553}
554
555impl Tree {
556 fn hit(
563 &self,
564 id: NodeId,
565 point: Point,
566 path: &mut Vec<NodeId>,
567 skip: Option<NodeId>,
568 ) -> Option<NodeId> {
569 if skip == Some(id) {
570 return None;
571 }
572 let node = self.node(id)?;
573 let point = local(node, point)?;
574 let rect = node.rect?;
575 if !node.inner_bounds.contains(point) {
578 return None;
579 }
580 let style = node.effective_style();
581 let border = style.border.map_or(0.0, |border| border.width.max(0.0));
583 let corners = style.radius.unwrap_or_default();
584 let children = if node.clips() && !corners.contains(rect, border, point) {
585 Vec::new()
586 } else {
587 self.drawn_children(id)
588 };
589 path.push(id);
590 if let Some(hit) = children
591 .into_iter()
592 .rev()
593 .find_map(|child| self.hit(child, point, path, skip))
594 {
595 return Some(hit);
596 }
597 let takes = match &node.kind {
598 NodeKind::Button(button) => button.enabled,
599 NodeKind::Input(_) => true,
600 NodeKind::Text(text) => text.selectable,
601 _ => false,
602 };
603 if rect.contains(point) && takes {
604 return Some(id);
605 }
606 if matches!(&node.kind, NodeKind::Text(text) if text.link_at(point).is_some()) {
608 return Some(id);
609 }
610 path.pop();
611 None
612 }
613
614 pub(crate) fn hover_at(&mut self, point: Point) {
618 let mut path = Vec::new();
619 let hit = match self.pointer.pressed.filter(|press| press.dragging) {
620 Some(press) => {
621 path = self.path_to(press.id);
622 Some(press.id)
623 }
624 None => self.hit(self.root, point, &mut path, None),
625 };
626 self.set_hovered(hit, &path);
627 self.set_positions(&path, Some(point));
628 self.update_drop();
629 self.hover_link();
630 }
631
632 fn hover_link(&mut self) {
634 let now = self.pointer.hovered.zip(self.link_under_pointer());
635 let old = std::mem::replace(&mut self.pointer.link_hover, now);
636 if old == now {
637 return;
638 }
639 if let Some((id, _)) = old {
640 self.light_link(id, false, None);
641 }
642 if let Some((id, index)) = now {
643 self.light_link(id, false, Some(index));
644 }
645 }
646
647 pub(crate) fn light_link(&mut self, id: NodeId, focus: bool, index: Option<usize>) {
651 let Some(node) = self.node_mut(id) else {
652 return;
653 };
654 let laid_out = node.rect.is_some();
655 let NodeKind::Text(text) = &mut node.kind else {
656 return;
657 };
658 let slot = match focus {
659 true => &mut text.focused_link,
660 false => &mut text.hovered_link,
661 };
662 let old = std::mem::replace(slot, index);
663 if old == index || !laid_out {
664 return;
665 }
666 let areas: Vec<Rect> = old
667 .into_iter()
668 .chain(index)
669 .flat_map(|index| text.link_areas(index))
670 .collect();
671 for area in areas {
672 let area = self.window_area(id, area);
673 add_damage(&mut self.damage, area);
674 }
675 }
676
677 fn drag_type(&self, id: NodeId) -> Option<TypeId> {
679 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
680 return None;
681 };
682 let data = button.drag_data?;
683 untrack(|| data.try_with(|data| data.as_ref().map(|value| (**value).type_id()))).flatten()
685 }
686
687 pub(crate) fn drop_target(&self) -> Option<NodeId> {
691 let press = self.pointer.pressed.filter(|press| press.dragging);
692 let (carried, at) = match self.pointer.incoming {
693 Some(incoming) => (incoming.carried, incoming.at),
694 None => (self.drag_type(press?.id)?, self.pointer.position?),
695 };
696 let mut path = Vec::new();
697 self.hit(self.root, at, &mut path, press.map(|press| press.id))?;
698 path.into_iter().rev().find(|&id| {
699 self.enabled(id)
700 && self.has(id, |h| {
701 h.drop
703 .as_ref()
704 .is_some_and(|target| target.accepts == carried && !target.handler.disabled.get())
705 })
706 })
707 }
708
709 pub(crate) fn update_drop(&mut self) {
712 let over = self.drop_target().map(|id| {
713 let signal = match self.node(id).map(|node| &node.kind) {
714 Some(NodeKind::Button(button)) => button.drop_hovered,
715 _ => None,
716 };
717 (id, signal)
718 });
719 self.pointer.set_drop_over(over);
720 }
721
722 pub(crate) fn drop_after_place(&mut self) {
725 if self.pointer.incoming.is_some() || self.pointer.pressed.is_some_and(|press| press.dragging) {
726 self.update_drop();
727 }
728 }
729
730 fn drags(&self, id: NodeId) -> bool {
733 self.selects(id) || self.drag_type(id).is_some() || self.has(id, |h| h.drag.is_some())
734 }
735
736 pub(crate) fn path_to(&self, id: NodeId) -> Vec<NodeId> {
738 let mut path = vec![id];
739 while let Some(parent) = path.last().and_then(|&id| self.taffy.parent(id)) {
740 path.push(parent);
741 }
742 path.reverse();
743 path
744 }
745
746 fn cursor(&self) -> CursorShape {
747 let dragged = self
750 .pointer
751 .pressed
752 .filter(|press| press.dragging)
753 .and_then(|press| match self.node(press.id).map(|node| &node.kind) {
754 Some(NodeKind::Button(button)) => Some(button.cursor),
755 _ => None,
756 });
757 if let Some(shape) = dragged {
758 return match shape {
759 CursorShape::Pointer | CursorShape::Grab => CursorShape::Grabbing,
760 shape => shape,
761 };
762 }
763 match self
764 .pointer
765 .hovered
766 .and_then(|id| self.node(id))
767 .map(|node| &node.kind)
768 {
769 Some(NodeKind::Text(_)) if self.link_under_pointer().is_some() => CursorShape::Pointer,
770 Some(NodeKind::Input(_) | NodeKind::Text(_)) => CursorShape::Text,
771 Some(NodeKind::Button(button)) => button.cursor,
772 _ => CursorShape::Default,
773 }
774 }
775
776 pub(crate) fn pointer_after_layout(&mut self) {
781 if std::mem::take(&mut self.pointer.caused_layout) {
782 return;
783 }
784 if let Some(position) = self.pointer.position {
785 self.hover_at(position);
786 }
787 }
788
789 fn set_hovered(&mut self, hovered: Option<NodeId>, path: &[NodeId]) {
792 self.set_inside(path);
793 let old = self.pointer.hovered;
794 if old == hovered {
795 return;
796 }
797 self.pointer.hovered = hovered;
798 self.pointer.wheel = 0;
799 self.pointer.pixels = 0.0;
800 if let Some(old) = old {
801 self.set_button_state(old, |button| button.hovered = false);
802 }
803 if let Some(new) = hovered {
804 self.set_button_state(new, |button| button.hovered = true);
805 }
806 }
807
808 fn path_buttons<T>(
810 &self,
811 path: &[NodeId],
812 pick: impl Fn(&ButtonNode) -> Option<T>,
813 ) -> Vec<(NodeId, T)> {
814 path
815 .iter()
816 .filter_map(|&id| match &self.node(id)?.kind {
817 NodeKind::Button(button) if button.enabled => Some((id, pick(button)?)),
818 _ => None,
819 })
820 .collect()
821 }
822
823 fn set_inside(&mut self, path: &[NodeId]) {
826 let inside = self.path_buttons(path, |button| button.hover_signal);
827 let holds = |list: &[(NodeId, Signal<bool>)], signal| list.iter().any(|(_, s)| *s == signal);
830 let mut seen = Vec::new();
831 for &(_, signal) in self.pointer.inside.iter().chain(&inside) {
832 if seen.contains(&signal) {
833 continue;
834 }
835 seen.push(signal);
836 let now = holds(&inside, signal);
837 if holds(&self.pointer.inside, signal) != now {
838 signal.try_set(now);
839 }
840 }
841 self.pointer.inside = inside;
842 }
843
844 fn set_positions(&mut self, path: &[NodeId], at: Option<Point>) {
848 let now: Vec<(NodeId, Signal<Option<Point>>, Point)> = match at {
849 Some(at) => self
850 .path_buttons(path, |button| button.position_signal)
851 .into_iter()
852 .filter_map(|(id, signal)| Some((id, signal, self.button_local(id, at)?)))
853 .collect(),
854 None => Vec::new(),
855 };
856 for (id, signal, _) in &self.pointer.positions {
857 if !now.iter().any(|(other, ..)| other == id) {
858 signal.try_set(None);
859 }
860 }
861 for &(id, signal, point) in &now {
862 let same = |&(other, _, was): &(NodeId, _, Point)| other == id && was == point;
863 if !self.pointer.positions.iter().any(same) {
864 signal.try_set(Some(point));
865 }
866 }
867 self.pointer.positions = now;
868 }
869
870 fn button_local(&self, id: NodeId, point: Point) -> Option<Point> {
873 let rect = self.node(id)?.rect?;
874 let point = self.local_point(id, point)?;
875 Some(Point::new(point.x - rect.x, point.y - rect.y))
876 }
877
878 fn set_pressed(&mut self, pressed: Option<Press>) {
879 let old = std::mem::replace(&mut self.pointer.pressed, pressed);
880 if let Some(old) = old {
881 self.set_button_state(old.id, |button| button.pressed = false);
882 }
883 if let Some(new) = pressed {
884 self.set_button_state(new.id, |button| button.pressed = true);
885 }
886 }
887
888 fn set_button_state(&mut self, id: NodeId, f: impl FnOnce(&mut ButtonNode)) {
891 if self.update_button_style(id, f) == Change::Layout {
892 self.pointer.caused_layout = true;
893 }
894 }
895
896 fn button(&mut self, button: PointerButton, pressed: bool, time: u32, touch: bool) -> Vec<Call> {
897 if pressed {
898 self.press(button, time, touch)
899 } else {
900 self.release(button, time)
901 }
902 }
903
904 fn press(&mut self, button: PointerButton, time: u32, touch: bool) -> Vec<Call> {
905 if button == PointerButton::Left {
906 self.press_away(self.pointer.hovered);
907 }
908 if let (PointerButton::Left, None, Some(at)) =
910 (button, self.pointer.pressed, self.pointer.position)
911 && self.press_bar(at)
912 {
913 return Vec::new();
914 }
915 if let (PointerButton::Left, None, Some(at)) =
916 (button, self.pointer.pressed, self.pointer.position)
917 {
918 let drags = self.pointer.hovered.is_some_and(|id| self.drags(id));
919 self.press_views(at, drags, touch);
920 }
921 let (None, Some(id), Some(at)) = (
922 self.pointer.pressed,
923 self.pointer.hovered,
924 self.pointer.position,
925 ) else {
926 return Vec::new();
927 };
928 let start = self.button_local(id, at).unwrap_or_default();
929 self.set_pressed(Some(Press {
930 id,
931 button,
932 at,
933 last: at,
934 start,
935 dragging: false,
936 long_pressed: false,
937 out: false,
938 }));
939 if button == PointerButton::Middle && self.press_middle(id, at) {
940 self.primary = Some(Clipboard::Paste);
941 }
942 if button != PointerButton::Left {
943 return Vec::new();
944 }
945 self.pointer.link = self.link_under(id, at);
946 if self.selects(id) {
947 self.press_text(id, at, time);
948 }
949 let mut calls: Vec<Call> = self.call(id, Action::Press).into_iter().collect();
950 if self.has(id, |h| h.long_press.is_some()) {
951 self.arm_long_press(id);
952 }
953 let waits =
955 |h: &Handlers| h.click.is_some() || h.double_click.is_some() || h.long_press.is_some();
956 if self.drags(id) && !self.has(id, waits) {
957 calls.extend(self.start_drag(at));
958 }
959 calls
960 }
961
962 fn release(&mut self, button: PointerButton, time: u32) -> Vec<Call> {
963 if button == PointerButton::Left {
964 self.release_bar();
965 self.flick_release(Some(time));
966 }
967 let Some(press) = self.pointer.pressed.filter(|press| press.button == button) else {
968 return Vec::new();
969 };
970 let mut calls = Vec::new();
971 if button == PointerButton::Left {
972 calls.extend(self.call(press.id, Action::Release));
973 let link = self.pointer.link.take();
974 calls.extend(link.and_then(|link| self.link_click(press, link)));
975 if let Some(text) = self.selected_text(press.id) {
977 self.primary = Some(Clipboard::Copy(text));
978 }
979 }
980 let landed = Rc::new(Cell::new(false));
982 calls.extend(self.drop_call(&landed));
983 calls.extend(self.end_press(Some(landed)));
984 if press.dragging {
985 if let Some(at) = self.pointer.position {
987 self.hover_at(at);
988 }
989 return calls;
990 }
991 if press.long_pressed || self.pointer.hovered != Some(press.id) {
992 return calls;
993 }
994 let action = match button {
995 PointerButton::Left => self.left_click(press.id, time, press.at),
996 PointerButton::Right => Action::RightClick,
997 PointerButton::Middle => Action::MiddleClick,
998 PointerButton::Back => Action::Back,
999 PointerButton::Forward => Action::Forward,
1000 };
1001 calls.extend(self.call(press.id, action));
1002 calls
1003 }
1004
1005 fn link_under_pointer(&self) -> Option<usize> {
1007 let id = self.pointer.hovered?;
1008 let NodeKind::Text(text) = &self.node(id)?.kind else {
1009 return None;
1010 };
1011 text.link_at(self.local_point(id, self.pointer.position?)?)
1012 }
1013
1014 fn link_under(&self, id: NodeId, at: Point) -> Option<(NodeId, usize, String)> {
1017 let NodeKind::Text(text) = &self.node(id)?.kind else {
1018 return None;
1019 };
1020 let index = text.link_at(self.local_point(id, at)?)?;
1021 Some((id, index, text.spans[index].link.clone()?))
1022 }
1023
1024 fn link_click(&self, press: Press, pressed: (NodeId, usize, String)) -> Option<Call> {
1029 let node = self.node(press.id)?;
1030 let NodeKind::Text(text) = &node.kind else {
1031 return None;
1032 };
1033 if text_selection(text).is_some() {
1034 return None;
1035 }
1036 let released = self.link_under(press.id, self.pointer.position?)?;
1037 if pressed != released {
1038 return None;
1039 }
1040 self.link_call(press.id, released.1)
1041 }
1042
1043 pub(crate) fn link_call(&self, id: NodeId, index: usize) -> Option<Call> {
1046 let node = self.node(id)?;
1047 let NodeKind::Text(text) = &node.kind else {
1048 return None;
1049 };
1050 let handler = text.on_link.clone().filter(|handler| !handler.disabled())?;
1051 let url = text.spans.get(index)?.link.clone()?;
1052 Some(Call {
1053 cx: node.cx.clone(),
1054 path: Rc::clone(&node.path),
1055 handlers: None,
1056 action: Action::Link(handler, url, self.this.clone(), id),
1057 })
1058 }
1059
1060 fn left_click(&mut self, id: NodeId, time: u32, at: Point) -> Action {
1064 let close = self.pointer.last_click.is_some_and(|(last, then, place)| {
1065 last == id
1066 && time.wrapping_sub(then) <= DOUBLE_CLICK_MS
1067 && distance(place, at) <= DOUBLE_CLICK_DISTANCE
1068 });
1069 if close && self.has(id, |h| h.double_click.is_some()) {
1070 self.pointer.last_click = None;
1071 Action::DoubleClick
1072 } else {
1073 self.pointer.last_click = Some((id, time, at));
1074 Action::Click
1075 }
1076 }
1077
1078 fn drop_call(&self, landed: &Rc<Cell<bool>>) -> Option<Call> {
1081 let target = self.drop_target()?;
1082 let value = self.drag_value(self.pointer.pressed?.id)?;
1083 self.call(target, Action::Drop(value, Rc::clone(landed)))
1084 }
1085
1086 pub(crate) fn drag_value(&self, id: NodeId) -> Option<DragValue> {
1088 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
1089 return None;
1090 };
1091 untrack(|| button.drag_data?.try_get().flatten())
1092 }
1093
1094 pub(crate) fn end_press(&mut self, landed: Option<Rc<Cell<bool>>>) -> Option<Call> {
1098 let press = self.pointer.pressed?;
1099 self.set_pressed(None);
1100 self.update_drop();
1101 self.stop_long_press(press.id);
1102 if press.dragging {
1103 self.drag_call(press, DragPhase::End, press.last, landed)
1104 } else {
1105 None
1106 }
1107 }
1108
1109 fn drag_motion(&mut self, at: Point) -> Vec<Call> {
1112 let Some(press) = self.pointer.pressed.as_mut() else {
1113 return Vec::new();
1114 };
1115 press.last = at;
1116 let press = *press;
1117 if press.button != PointerButton::Left {
1118 return Vec::new();
1119 }
1120 if press.dragging && self.selects(press.id) {
1121 self.drag_text(press.id, at);
1122 return Vec::new();
1123 }
1124 if press.dragging {
1125 return self
1126 .drag_call(press, DragPhase::Move, at, None)
1127 .into_iter()
1128 .collect();
1129 }
1130 if distance(press.at, at) <= DRAG_THRESHOLD {
1131 return Vec::new();
1132 }
1133 self.stop_long_press(press.id);
1134 if self.drags(press.id) {
1135 self.start_drag(at)
1136 } else {
1137 Vec::new()
1138 }
1139 }
1140
1141 fn start_drag(&mut self, at: Point) -> Vec<Call> {
1143 let Some(press) = self.pointer.pressed.as_mut() else {
1144 return Vec::new();
1145 };
1146 press.dragging = true;
1147 let press = *press;
1148 self.stop_long_press(press.id);
1149 self.update_drop();
1150 self
1151 .drag_call(press, DragPhase::Start, at, None)
1152 .into_iter()
1153 .collect()
1154 }
1155
1156 pub(crate) fn drag_call(
1157 &self,
1158 press: Press,
1159 phase: DragPhase,
1160 at: Point,
1161 landed: Option<Rc<Cell<bool>>>,
1162 ) -> Option<Call> {
1163 let rect = self.node(press.id)?.rect?;
1164 let drag = Drag {
1165 phase,
1166 start: press.start,
1167 position: self.button_local(press.id, at).unwrap_or(press.start),
1170 size: Size::new(rect.width, rect.height),
1171 dropped: false,
1172 };
1173 self.call(press.id, Action::Drag(drag, landed))
1174 }
1175
1176 fn arm_long_press(&mut self, id: NodeId) {
1179 let tree = self.this.clone();
1180 let Some(Node { cx, kind, .. }) = self.node_mut(id) else {
1181 return;
1182 };
1183 let NodeKind::Button(button) = kind else {
1184 return;
1185 };
1186 match button.long_press {
1187 Some(timer) => timer.restart(),
1188 None => {
1189 let timer = cx.after(LONG_PRESS, move || long_press_fired(&tree, id));
1190 button.long_press = Some(timer);
1191 }
1192 }
1193 }
1194
1195 fn stop_long_press(&self, id: NodeId) {
1196 if let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind)
1197 && let Some(timer) = button.long_press
1198 {
1199 timer.stop();
1200 }
1201 }
1202
1203 fn long_press(&mut self, id: NodeId) -> Option<Call> {
1205 let press = self.pointer.pressed.as_mut().filter(|press| {
1206 press.id == id
1207 && press.button == PointerButton::Left
1208 && !press.dragging
1209 && !press.long_pressed
1210 })?;
1211 press.long_pressed = true;
1212 self.call(id, Action::LongPress)
1213 }
1214
1215 pub(crate) fn leave(&mut self) -> Vec<Call> {
1218 self.pointer.position = None;
1219 self.release_bar();
1220 self.flick_release(None);
1221 if let Some(id) = self.pointer.gesture.take() {
1222 self.release_view(id, None);
1223 }
1224 let out = self.pointer.pressed.is_some_and(|press| press.out);
1226 let calls = match out {
1227 true => Vec::new(),
1228 false => self.end_press(None).into_iter().collect(),
1229 };
1230 self.set_hovered(None, &[]);
1231 self.set_positions(&[], None);
1232 self.hover_link();
1233 calls
1234 }
1235
1236 pub(crate) fn set_enabled(&mut self, id: NodeId, enabled: bool) -> Vec<Call> {
1240 let Some(NodeKind::Button(button)) = self.node_mut(id).map(|node| &mut node.kind) else {
1241 return Vec::new();
1242 };
1243 if std::mem::replace(&mut button.enabled, enabled) == enabled {
1244 return Vec::new();
1245 }
1246 self.node_event(id, |id| AccessEvent::Enabled(id, enabled));
1247 let mut calls = Vec::new();
1248 if !enabled {
1249 if self.pointer.pressed.is_some_and(|press| press.id == id) {
1250 calls.extend(self.end_press(None));
1251 }
1252 if self.keyboard.focused == Some(id) {
1253 self.focus(None);
1254 }
1255 }
1256 if let Some(at) = self.pointer.position {
1257 self.hover_at(at);
1258 }
1259 calls
1260 }
1261
1262 pub(crate) fn bind_enabled(&mut self, id: NodeId, prop: Prop<bool>) {
1265 let mut compute = match prop.0 {
1266 PropKind::Value(enabled) => {
1268 self.set_enabled(id, enabled);
1269 return;
1270 }
1271 PropKind::Binding(compute) => compute,
1272 };
1273 let Some(node) = self.node(id) else {
1274 return;
1275 };
1276 let label = format!("{}.enabled", node.path);
1277 let tree = self.this.clone();
1278 node
1279 .cx
1280 .effect(move || {
1281 let enabled = compute();
1282 let Some(tree) = tree.upgrade() else {
1283 return;
1284 };
1285 let calls = borrow(&tree).set_enabled(id, enabled);
1286 untrack(|| run_all(calls));
1288 })
1289 .named(label);
1290 }
1291
1292 pub(crate) fn enabled(&self, id: NodeId) -> bool {
1294 match self.node(id).map(|node| &node.kind) {
1295 Some(NodeKind::Button(button)) => button.enabled,
1296 _ => true,
1297 }
1298 }
1299
1300 fn scroll(&mut self, wheel: Wheel, time: u32) -> Vec<Call> {
1301 let wants = |h: &Handlers| h.scroll.is_some() || h.wheel.is_some();
1302 let target = self.pointer.hovered.filter(|&id| self.has(id, wants));
1303 let calls = match target {
1304 None => {
1305 self.scroll_view(wheel, time);
1306 Vec::new()
1307 }
1308 Some(target) => {
1309 let mut calls = Vec::new();
1310 if self.has(target, |h| h.wheel.is_some()) {
1311 calls.extend(self.call(target, Action::Wheel(wheel)));
1312 }
1313 if self.has(target, |h| h.scroll.is_some()) {
1314 let down = self.steps(wheel.y);
1315 if down != 0 {
1317 calls.extend(self.call(target, Action::Scroll(down.saturating_neg())));
1318 }
1319 }
1320 calls
1321 }
1322 };
1323 if wheel.y.stop {
1324 self.pointer.pixels = 0.0;
1325 }
1326 if wheel.source == ScrollSource::Finger
1330 && (wheel.x.stop || wheel.y.stop)
1331 && let Some(id) = self.pointer.gesture.take()
1332 {
1333 self.release_view(id, Some(time));
1334 }
1335 calls
1336 }
1337
1338 fn steps(&mut self, axis: WheelAxis) -> i32 {
1341 if axis.notches != 0.0 && axis.notches.is_finite() {
1342 let value120 = (axis.notches * VALUE120_PER_STEP as f32).round() as i32;
1344 self.pointer.wheel = self.pointer.wheel.saturating_add(value120);
1345 let steps = self.pointer.wheel / VALUE120_PER_STEP;
1346 self.pointer.wheel -= steps * VALUE120_PER_STEP;
1347 steps
1348 } else if axis.pixels.is_finite() {
1349 self.pointer.pixels += axis.pixels;
1350 let steps = (self.pointer.pixels / PIXELS_PER_STEP).trunc();
1351 self.pointer.pixels -= steps * PIXELS_PER_STEP;
1352 steps as i32
1353 } else {
1354 0
1355 }
1356 }
1357
1358 pub(crate) fn cancel_press(&mut self) {
1361 if let Some(press) = self.pointer.pressed.filter(|press| !press.dragging) {
1362 self.set_pressed(None);
1363 self.stop_long_press(press.id);
1364 }
1365 }
1366
1367 pub(crate) fn has(&self, id: NodeId, f: impl FnOnce(&Handlers) -> bool) -> bool {
1369 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
1370 return false;
1371 };
1372 untrack(|| button.handlers.try_with(f)).unwrap_or(false)
1373 }
1374
1375 pub(crate) fn local_point(&self, id: NodeId, point: Point) -> Option<Point> {
1379 self
1380 .path_to(id)
1381 .iter()
1382 .try_fold(point, |point, &id| local(self.node(id)?, point))
1383 }
1384
1385 pub(crate) fn window_rect(&self, id: NodeId, rect: Rect) -> Rect {
1389 let mut rect = rect;
1390 let mut at = Some(id);
1391 while let Some(current) = at {
1392 if let Some(transform) = self.node(current).and_then(|node| node.transform) {
1393 rect = transform.map_rect(rect);
1394 }
1395 at = self.taffy.parent(current);
1396 }
1397 rect
1398 }
1399
1400 pub(crate) fn click(&self, id: NodeId) -> Option<Call> {
1402 self.call(id, Action::Click)
1403 }
1404
1405 pub(crate) fn call(&self, id: NodeId, action: Action) -> Option<Call> {
1406 let node = self.node(id)?;
1407 let NodeKind::Button(button) = &node.kind else {
1408 return None;
1409 };
1410 Some(Call {
1411 cx: node.cx.clone(),
1412 path: Rc::clone(&node.path),
1413 handlers: Some(button.handlers),
1414 action,
1415 })
1416 }
1417}
1418
1419fn long_press_fired(tree: &Weak<RefCell<Tree>>, id: NodeId) {
1421 let Some(tree) = tree.upgrade() else {
1422 return;
1423 };
1424 let Ok(mut borrowed) = tree.try_borrow_mut() else {
1426 return;
1427 };
1428 let call = borrowed.long_press(id);
1429 drop(borrowed);
1430 if let Some(call) = call {
1431 call.run();
1432 }
1433}
1434
1435pub(crate) fn local(node: &Node, point: Point) -> Option<Point> {
1439 match node.transform {
1440 Some(transform) => Some(transform.invert()?.map(point)),
1441 None => Some(point),
1442 }
1443}
1444
1445#[derive(Clone)]
1446pub(crate) enum Action {
1447 Click,
1448 Press,
1449 Release,
1450 DoubleClick,
1451 LongPress,
1452 RightClick,
1453 MiddleClick,
1454 Back,
1455 Forward,
1456 Scroll(i32),
1457 Wheel(Wheel),
1458 Drag(Drag, Option<Rc<Cell<bool>>>),
1460 Drop(DragValue, Rc<Cell<bool>>),
1462 Link(LinkHandler, String, Weak<RefCell<Tree>>, NodeId),
1465}
1466
1467pub(crate) struct Call {
1469 cx: Cx,
1470 path: Rc<str>,
1471 handlers: Option<Signal<Handlers>>,
1473 action: Action,
1474}
1475
1476enum Picked {
1478 Plain(ClickHandler, &'static str),
1479 Scroll(ScrollHandler, i32),
1480 Wheel(WheelHandler, Wheel),
1481 Drag(DragHandler, Drag),
1482 Drop(DropHandler, &'static str, DragValue, Rc<Cell<bool>>),
1483}
1484
1485impl Call {
1486 pub(crate) fn run(self) {
1487 let (path, cx) = (&self.path, &self.cx);
1488 if let Action::Link(handler, url, tree, id) = &self.action {
1489 run_isolated(path, "on_link", Rc::clone(handler), |f| f(cx, url));
1490 if handler.disabled()
1492 && let Some(tree) = tree.upgrade()
1493 && let Ok(mut tree) = tree.try_borrow_mut()
1494 {
1495 tree.light_link(*id, false, None);
1496 tree.light_link(*id, true, None);
1497 }
1498 return;
1499 }
1500 let Some(handlers) = self.handlers else {
1501 return;
1502 };
1503 let picked = untrack(|| {
1505 handlers.try_with(|h| {
1506 let plain = |handler: &Option<ClickHandler>, name| {
1507 handler.clone().map(|handler| Picked::Plain(handler, name))
1508 };
1509 match &self.action {
1510 Action::Click => plain(&h.click, "on_click"),
1511 Action::Press => plain(&h.press, "on_press"),
1512 Action::Release => plain(&h.release, "on_release"),
1513 Action::DoubleClick => plain(&h.double_click, "on_double_click"),
1514 Action::LongPress => plain(&h.long_press, "on_long_press"),
1515 Action::RightClick => plain(&h.right_click, "on_right_click"),
1516 Action::MiddleClick => plain(&h.middle_click, "on_middle_click"),
1517 Action::Back => plain(&h.back, "on_back"),
1518 Action::Forward => plain(&h.forward, "on_forward"),
1519 Action::Scroll(steps) => h.scroll.clone().map(|f| Picked::Scroll(f, *steps)),
1520 Action::Wheel(wheel) => h.wheel.clone().map(|f| Picked::Wheel(f, *wheel)),
1521 Action::Drag(drag, landed) => {
1522 let drag = Drag {
1523 dropped: landed.as_ref().is_some_and(|landed| landed.get()),
1524 ..*drag
1525 };
1526 h.drag.clone().map(|f| Picked::Drag(f, drag))
1527 }
1528 Action::Drop(value, landed) => {
1529 let target = h.drop.as_ref()?;
1530 Some(Picked::Drop(
1531 target.handler.clone(),
1532 target.name,
1533 Rc::clone(value),
1534 Rc::clone(landed),
1535 ))
1536 }
1537 Action::Link(..) => None,
1538 }
1539 })
1540 });
1541 let Some(Some(picked)) = picked else {
1542 return;
1543 };
1544 match picked {
1545 Picked::Plain(handler, name) => {
1546 run_isolated(path, name, handler, |f| f(cx));
1547 }
1548 Picked::Scroll(handler, steps) => {
1549 run_isolated(path, "on_scroll", handler, |f| f(cx, steps));
1550 }
1551 Picked::Wheel(handler, wheel) => {
1552 run_isolated(path, "on_wheel", handler, |f| f(cx, wheel));
1553 }
1554 Picked::Drag(handler, drag) => {
1555 run_isolated(path, "on_drag", handler, |f| f(cx, drag));
1556 }
1557 Picked::Drop(handler, name, value, landed) => {
1559 let ran = run_isolated(path, name, handler, move |f| f(cx, &*value));
1560 landed.set(ran.is_some());
1561 }
1562 }
1563 }
1564}
1565
1566pub(crate) fn run_isolated<F: ?Sized, R>(
1571 path: &str,
1572 name: &str,
1573 handler: Rc<Handler<F>>,
1574 call: impl FnOnce(&F) -> R,
1575) -> Option<R> {
1576 if handler.disabled.get() {
1577 return None;
1578 }
1579 let result = match panic::catch_unwind(AssertUnwindSafe(|| call(&handler.f))) {
1580 Ok(result) => Some(result),
1581 Err(payload) => {
1582 handler.disabled.set(true);
1583 tracing::error!(
1584 "handler {path}.{name} panicked and is disabled: {}",
1585 panic_message(payload.as_ref())
1586 );
1587 None
1588 }
1589 };
1590 if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(move || drop(handler))) {
1591 tracing::error!(
1592 "dropping handler {path}.{name} panicked: {}",
1593 panic_message(payload.as_ref())
1594 );
1595 }
1596 result
1597}
1598
1599pub(crate) fn panic_message(payload: &(dyn Any + Send)) -> &str {
1600 if let Some(message) = payload.downcast_ref::<&str>() {
1601 message
1602 } else if let Some(message) = payload.downcast_ref::<String>() {
1603 message
1604 } else {
1605 "(panic payload is not a string)"
1606 }
1607}