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::cx::Cx;
19use crate::geometry::{Point, Rect, Size};
20use crate::keyboard::KeyHandler;
21use crate::prop::{Prop, PropKind};
22use crate::scrolling::{BarDrag, Flick};
23use crate::select::{TextClick, text_selection};
24use crate::tree::{ButtonNode, Change, Node, NodeId, NodeKind, Tree, add_damage, borrow};
25use crate::window::Window;
26
27pub(crate) const PIXELS_PER_STEP: f32 = 15.0;
29
30const VALUE120_PER_STEP: i32 = 120;
32
33pub(crate) const DRAG_THRESHOLD: f32 = 10.0;
36
37const LONG_PRESS: Duration = Duration::from_millis(800);
40
41pub(crate) const DOUBLE_CLICK_MS: u32 = 400;
44
45pub(crate) const DOUBLE_CLICK_DISTANCE: f32 = 5.0;
48
49pub(crate) struct Handler<F: ?Sized> {
51 disabled: Cell<bool>,
52 f: F,
53}
54
55impl<F> Handler<F> {
56 pub(crate) fn new(f: F) -> Handler<F> {
57 Handler {
58 disabled: Cell::new(false),
59 f,
60 }
61 }
62}
63
64impl<F: ?Sized> Handler<F> {
65 pub(crate) fn disabled(&self) -> bool {
67 self.disabled.get()
68 }
69}
70
71pub(crate) type ClickHandler = Rc<Handler<dyn Fn(&Cx)>>;
72type ScrollHandler = Rc<Handler<dyn Fn(&Cx, i32)>>;
73pub(crate) type WheelHandler = Rc<Handler<dyn Fn(&Cx, Wheel)>>;
74pub(crate) type DragHandler = Rc<Handler<dyn Fn(&Cx, Drag)>>;
75pub(crate) type LinkHandler = Rc<Handler<dyn Fn(&Cx, &str)>>;
76
77pub(crate) type DragValue = Rc<dyn Any>;
81
82pub(crate) struct DropTarget {
84 pub(crate) accepts: TypeId,
85 pub(crate) handler: DropHandler,
86}
87
88pub(crate) type DropHandler = Rc<Handler<dyn Fn(&Cx, &dyn Any)>>;
90
91#[derive(Default)]
93pub(crate) struct Handlers {
94 pub(crate) click: Option<ClickHandler>,
95 pub(crate) press: Option<ClickHandler>,
96 pub(crate) release: Option<ClickHandler>,
97 pub(crate) double_click: Option<ClickHandler>,
98 pub(crate) long_press: Option<ClickHandler>,
99 pub(crate) right_click: Option<ClickHandler>,
100 pub(crate) middle_click: Option<ClickHandler>,
101 pub(crate) back: Option<ClickHandler>,
102 pub(crate) forward: Option<ClickHandler>,
103 pub(crate) scroll: Option<ScrollHandler>,
104 pub(crate) wheel: Option<WheelHandler>,
105 pub(crate) drag: Option<DragHandler>,
106 pub(crate) drop: Option<DropTarget>,
107 pub(crate) key: Option<KeyHandler>,
108}
109
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub enum PointerButton {
113 Left,
115 Right,
117 Middle,
119 Back,
122 Forward,
125}
126
127#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
129pub enum ScrollSource {
130 #[default]
132 Wheel,
133 Finger,
136 Continuous,
138 WheelTilt,
140}
141
142#[derive(Clone, Copy, Debug, Default, PartialEq)]
144pub struct WheelAxis {
145 pub pixels: f32,
148 pub notches: f32,
152 pub stop: bool,
155}
156
157#[derive(Clone, Copy, Debug, Default, PartialEq)]
160pub struct Wheel {
161 pub source: ScrollSource,
163 pub x: WheelAxis,
165 pub y: WheelAxis,
167}
168
169#[derive(Clone, Copy, Debug, PartialEq, Eq)]
171pub enum DragPhase {
172 Start,
175 Move,
177 End,
180}
181
182#[derive(Clone, Copy, Debug, PartialEq)]
187pub struct Drag {
188 pub phase: DragPhase,
190 pub start: Point,
192 pub position: Point,
195 pub size: Size,
197 pub dropped: bool,
201}
202
203#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
206pub enum CursorShape {
207 #[default]
209 Default,
210 ContextMenu,
212 Help,
214 Pointer,
216 Progress,
218 Wait,
220 Cell,
222 Crosshair,
224 Text,
226 VerticalText,
228 Alias,
230 Copy,
232 Move,
234 NoDrop,
236 NotAllowed,
238 Grab,
240 Grabbing,
242 EResize,
244 NResize,
246 NeResize,
248 NwResize,
250 SResize,
252 SeResize,
254 SwResize,
256 WResize,
258 EwResize,
260 NsResize,
262 NeswResize,
264 NwseResize,
266 ColResize,
268 RowResize,
270 AllScroll,
272 ZoomIn,
274 ZoomOut,
276 DndAsk,
279 AllResize,
282}
283
284#[derive(Clone, Copy)]
286struct Press {
287 id: NodeId,
288 button: PointerButton,
289 at: Point,
292 last: Point,
293 start: Point,
295 dragging: bool,
297 long_pressed: bool,
299}
300
301#[derive(Default)]
303pub(crate) struct Pointer {
304 pub(crate) position: Option<Point>,
305 pub(crate) hovered: Option<NodeId>,
307 inside: Vec<(NodeId, Signal<bool>)>,
310 positions: Vec<(NodeId, Signal<Option<Point>>, Point)>,
313 pressed: Option<Press>,
315 link: Option<(NodeId, usize, String)>,
318 link_hover: Option<(NodeId, usize)>,
320 pub(crate) bar: Option<BarDrag>,
322 pub(crate) flick: Option<Flick>,
325 pub(crate) gesture: Option<NodeId>,
327 pub(crate) last_click: Option<(NodeId, u32, Point)>,
330 pub(crate) text_click: Option<TextClick>,
333 wheel: i32,
335 pixels: f32,
336 caused_layout: bool,
338 drop_over: Option<(NodeId, Option<Signal<bool>>)>,
341}
342
343impl Pointer {
344 pub(crate) fn forget(&mut self, removed: &[NodeId]) {
347 if self.hovered.is_some_and(|id| removed.contains(&id)) {
348 self.hovered = None;
349 }
350 let (gone, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut self.inside)
351 .into_iter()
352 .partition(|(id, _)| removed.contains(id));
353 for (_, signal) in gone {
354 if !kept.iter().any(|(_, other)| *other == signal) {
356 signal.try_set(false);
357 }
358 }
359 self.inside = kept;
360 self.positions.retain(|(id, signal, _)| {
361 let gone = removed.contains(id);
362 if gone {
363 signal.try_set(None);
364 }
365 !gone
366 });
367 let source_gone = self
368 .pressed
369 .is_some_and(|press| removed.contains(&press.id));
370 if source_gone {
371 self.pressed = None;
372 }
373 if source_gone || self.drop_over.is_some_and(|(id, _)| removed.contains(&id)) {
374 self.set_drop_over(None);
375 }
376 self.forget_views(removed);
377 if self
378 .last_click
379 .is_some_and(|(id, _, _)| removed.contains(&id))
380 {
381 self.last_click = None;
382 }
383 if self
384 .text_click
385 .is_some_and(|click| removed.contains(&click.id))
386 {
387 self.text_click = None;
388 }
389 }
390}
391
392impl Pointer {
393 fn set_drop_over(&mut self, over: Option<(NodeId, Option<Signal<bool>>)>) {
396 let old = std::mem::replace(&mut self.drop_over, over);
397 if old.map(|(id, _)| id) == over.map(|(id, _)| id) {
398 return;
399 }
400 let (old, new) = (old.and_then(|(_, s)| s), over.and_then(|(_, s)| s));
401 if old != new {
402 if let Some(old) = old {
403 old.try_set(false);
404 }
405 if let Some(new) = new {
406 new.try_set(true);
407 }
408 }
409 }
410}
411
412impl Tree {
413 pub(crate) fn pointer_hide(&mut self, hidden: &[NodeId]) {
416 let held = [
417 self.pointer.hovered,
418 self.pointer.pressed.map(|press| press.id),
419 ];
420 self.pointer.forget(hidden);
421 for id in held.into_iter().flatten().filter(|id| hidden.contains(id)) {
422 self.update_button_style(id, |button| {
423 button.hovered = false;
424 button.pressed = false;
425 });
426 }
427 }
428}
429
430fn now_ms() -> u32 {
433 static START: OnceLock<Instant> = OnceLock::new();
434 START.get_or_init(Instant::now).elapsed().as_millis() as u32
436}
437
438impl Window {
439 pub fn pointer_motion(&self, position: Point) -> CursorShape {
442 self.pointer_motion_at(position, now_ms())
443 }
444
445 pub fn pointer_motion_at(&self, position: Point, time: u32) -> CursorShape {
450 let calls = {
451 let mut tree = borrow(&self.tree);
452 tree.pointer.position = Some(position);
453 tree.bar_motion(position);
454 let calls = if tree.flick_motion(position, time) {
455 Vec::new()
456 } else {
457 tree.drag_motion(position)
458 };
459 tree.hover_at(position);
460 calls
461 };
462 run_all(calls);
463 self.cursor()
464 }
465
466 pub fn pointer_leave(&self) {
469 let calls = borrow(&self.tree).leave();
470 run_all(calls);
471 }
472
473 pub fn pointer_button(&self, button: PointerButton, pressed: bool) {
476 self.pointer_button_at(button, pressed, now_ms());
477 }
478
479 pub fn pointer_button_at(&self, button: PointerButton, pressed: bool, time: u32) {
487 let calls = borrow(&self.tree).button(button, pressed, time, false);
488 run_all(calls);
489 }
490
491 pub fn touch_at(&self, pressed: bool, time: u32) {
496 let calls = borrow(&self.tree).button(PointerButton::Left, pressed, time, true);
497 run_all(calls);
498 }
499
500 pub fn pointer_scroll(&self, wheel: Wheel) {
509 self.pointer_scroll_at(wheel, now_ms());
510 }
511
512 pub fn pointer_scroll_at(&self, wheel: Wheel, time: u32) {
516 let calls = borrow(&self.tree).scroll(wheel, time);
517 run_all(calls);
518 }
519
520 pub fn cursor(&self) -> CursorShape {
522 self.tree.borrow().cursor()
523 }
524}
525
526fn run_all(calls: Vec<Call>) {
528 for call in calls {
529 call.run();
530 }
531}
532
533pub(crate) fn distance(a: Point, b: Point) -> f32 {
534 (a.x - b.x).hypot(a.y - b.y)
535}
536
537impl Tree {
538 fn hit(
545 &self,
546 id: NodeId,
547 point: Point,
548 path: &mut Vec<NodeId>,
549 skip: Option<NodeId>,
550 ) -> Option<NodeId> {
551 if skip == Some(id) {
552 return None;
553 }
554 let node = self.node(id)?;
555 let point = local(node, point)?;
556 let rect = node.rect?;
557 if !node.inner_bounds.contains(point) {
560 return None;
561 }
562 let style = node.effective_style();
563 let border = style.border.map_or(0.0, |border| border.width.max(0.0));
565 let corners = style.radius.unwrap_or_default();
566 let children = if node.clips() && !corners.contains(rect, border, point) {
567 Vec::new()
568 } else {
569 self.drawn_children(id)
570 };
571 path.push(id);
572 if let Some(hit) = children
573 .into_iter()
574 .rev()
575 .find_map(|child| self.hit(child, point, path, skip))
576 {
577 return Some(hit);
578 }
579 let takes = match &node.kind {
580 NodeKind::Button(button) => button.enabled,
581 NodeKind::Input(_) => true,
582 NodeKind::Text(text) => text.selectable,
583 _ => false,
584 };
585 if rect.contains(point) && takes {
586 return Some(id);
587 }
588 if matches!(&node.kind, NodeKind::Text(text) if text.link_at(point).is_some()) {
590 return Some(id);
591 }
592 path.pop();
593 None
594 }
595
596 pub(crate) fn hover_at(&mut self, point: Point) {
600 let mut path = Vec::new();
601 let hit = match self.pointer.pressed.filter(|press| press.dragging) {
602 Some(press) => {
603 path = self.path_to(press.id);
604 Some(press.id)
605 }
606 None => self.hit(self.root, point, &mut path, None),
607 };
608 self.set_hovered(hit, &path);
609 self.set_positions(&path, Some(point));
610 self.update_drop();
611 self.hover_link();
612 }
613
614 fn hover_link(&mut self) {
616 let now = self.pointer.hovered.zip(self.link_under_pointer());
617 let old = std::mem::replace(&mut self.pointer.link_hover, now);
618 if old == now {
619 return;
620 }
621 if let Some((id, _)) = old {
622 self.light_link(id, false, None);
623 }
624 if let Some((id, index)) = now {
625 self.light_link(id, false, Some(index));
626 }
627 }
628
629 pub(crate) fn light_link(&mut self, id: NodeId, focus: bool, index: Option<usize>) {
633 let Some(node) = self.node_mut(id) else {
634 return;
635 };
636 let laid_out = node.rect.is_some();
637 let NodeKind::Text(text) = &mut node.kind else {
638 return;
639 };
640 let slot = match focus {
641 true => &mut text.focused_link,
642 false => &mut text.hovered_link,
643 };
644 let old = std::mem::replace(slot, index);
645 if old == index || !laid_out {
646 return;
647 }
648 let areas: Vec<Rect> = old
649 .into_iter()
650 .chain(index)
651 .flat_map(|index| text.link_areas(index))
652 .collect();
653 for area in areas {
654 let area = self.window_area(id, area);
655 add_damage(&mut self.damage, area);
656 }
657 }
658
659 fn drag_type(&self, id: NodeId) -> Option<TypeId> {
661 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
662 return None;
663 };
664 let data = button.drag_data?;
665 untrack(|| data.try_with(|data| data.as_ref().map(|value| (**value).type_id()))).flatten()
667 }
668
669 fn drop_target(&self) -> Option<NodeId> {
673 let press = self.pointer.pressed.filter(|press| press.dragging)?;
674 let carried = self.drag_type(press.id)?;
675 let mut path = Vec::new();
676 self.hit(self.root, self.pointer.position?, &mut path, Some(press.id))?;
677 path.into_iter().rev().find(|&id| {
678 self.enabled(id)
679 && self.has(id, |h| {
680 h.drop
682 .as_ref()
683 .is_some_and(|target| target.accepts == carried && !target.handler.disabled.get())
684 })
685 })
686 }
687
688 fn update_drop(&mut self) {
691 let over = self.drop_target().map(|id| {
692 let signal = match self.node(id).map(|node| &node.kind) {
693 Some(NodeKind::Button(button)) => button.drop_hovered,
694 _ => None,
695 };
696 (id, signal)
697 });
698 self.pointer.set_drop_over(over);
699 }
700
701 pub(crate) fn drop_after_place(&mut self) {
704 if self.pointer.pressed.is_some_and(|press| press.dragging) {
705 self.update_drop();
706 }
707 }
708
709 fn drags(&self, id: NodeId) -> bool {
712 self.selects(id) || self.drag_type(id).is_some() || self.has(id, |h| h.drag.is_some())
713 }
714
715 pub(crate) fn path_to(&self, id: NodeId) -> Vec<NodeId> {
717 let mut path = vec![id];
718 while let Some(parent) = path.last().and_then(|&id| self.taffy.parent(id)) {
719 path.push(parent);
720 }
721 path.reverse();
722 path
723 }
724
725 fn cursor(&self) -> CursorShape {
726 let dragged = self
729 .pointer
730 .pressed
731 .filter(|press| press.dragging)
732 .and_then(|press| match self.node(press.id).map(|node| &node.kind) {
733 Some(NodeKind::Button(button)) => Some(button.cursor),
734 _ => None,
735 });
736 if let Some(shape) = dragged {
737 return match shape {
738 CursorShape::Pointer | CursorShape::Grab => CursorShape::Grabbing,
739 shape => shape,
740 };
741 }
742 match self
743 .pointer
744 .hovered
745 .and_then(|id| self.node(id))
746 .map(|node| &node.kind)
747 {
748 Some(NodeKind::Text(_)) if self.link_under_pointer().is_some() => CursorShape::Pointer,
749 Some(NodeKind::Input(_) | NodeKind::Text(_)) => CursorShape::Text,
750 Some(NodeKind::Button(button)) => button.cursor,
751 _ => CursorShape::Default,
752 }
753 }
754
755 pub(crate) fn pointer_after_layout(&mut self) {
760 if std::mem::take(&mut self.pointer.caused_layout) {
761 return;
762 }
763 if let Some(position) = self.pointer.position {
764 self.hover_at(position);
765 }
766 }
767
768 fn set_hovered(&mut self, hovered: Option<NodeId>, path: &[NodeId]) {
771 self.set_inside(path);
772 let old = self.pointer.hovered;
773 if old == hovered {
774 return;
775 }
776 self.pointer.hovered = hovered;
777 self.pointer.wheel = 0;
778 self.pointer.pixels = 0.0;
779 if let Some(old) = old {
780 self.set_button_state(old, |button| button.hovered = false);
781 }
782 if let Some(new) = hovered {
783 self.set_button_state(new, |button| button.hovered = true);
784 }
785 }
786
787 fn path_buttons<T>(
789 &self,
790 path: &[NodeId],
791 pick: impl Fn(&ButtonNode) -> Option<T>,
792 ) -> Vec<(NodeId, T)> {
793 path
794 .iter()
795 .filter_map(|&id| match &self.node(id)?.kind {
796 NodeKind::Button(button) if button.enabled => Some((id, pick(button)?)),
797 _ => None,
798 })
799 .collect()
800 }
801
802 fn set_inside(&mut self, path: &[NodeId]) {
805 let inside = self.path_buttons(path, |button| button.hover_signal);
806 let holds = |list: &[(NodeId, Signal<bool>)], signal| list.iter().any(|(_, s)| *s == signal);
809 let mut seen = Vec::new();
810 for &(_, signal) in self.pointer.inside.iter().chain(&inside) {
811 if seen.contains(&signal) {
812 continue;
813 }
814 seen.push(signal);
815 let now = holds(&inside, signal);
816 if holds(&self.pointer.inside, signal) != now {
817 signal.try_set(now);
818 }
819 }
820 self.pointer.inside = inside;
821 }
822
823 fn set_positions(&mut self, path: &[NodeId], at: Option<Point>) {
827 let now: Vec<(NodeId, Signal<Option<Point>>, Point)> = match at {
828 Some(at) => self
829 .path_buttons(path, |button| button.position_signal)
830 .into_iter()
831 .filter_map(|(id, signal)| Some((id, signal, self.button_local(id, at)?)))
832 .collect(),
833 None => Vec::new(),
834 };
835 for (id, signal, _) in &self.pointer.positions {
836 if !now.iter().any(|(other, ..)| other == id) {
837 signal.try_set(None);
838 }
839 }
840 for &(id, signal, point) in &now {
841 let same = |&(other, _, was): &(NodeId, _, Point)| other == id && was == point;
842 if !self.pointer.positions.iter().any(same) {
843 signal.try_set(Some(point));
844 }
845 }
846 self.pointer.positions = now;
847 }
848
849 fn button_local(&self, id: NodeId, point: Point) -> Option<Point> {
852 let rect = self.node(id)?.rect?;
853 let point = self.local_point(id, point)?;
854 Some(Point::new(point.x - rect.x, point.y - rect.y))
855 }
856
857 fn set_pressed(&mut self, pressed: Option<Press>) {
858 let old = std::mem::replace(&mut self.pointer.pressed, pressed);
859 if let Some(old) = old {
860 self.set_button_state(old.id, |button| button.pressed = false);
861 }
862 if let Some(new) = pressed {
863 self.set_button_state(new.id, |button| button.pressed = true);
864 }
865 }
866
867 fn set_button_state(&mut self, id: NodeId, f: impl FnOnce(&mut ButtonNode)) {
870 if self.update_button_style(id, f) == Change::Layout {
871 self.pointer.caused_layout = true;
872 }
873 }
874
875 fn button(&mut self, button: PointerButton, pressed: bool, time: u32, touch: bool) -> Vec<Call> {
876 if pressed {
877 self.press(button, time, touch)
878 } else {
879 self.release(button, time)
880 }
881 }
882
883 fn press(&mut self, button: PointerButton, time: u32, touch: bool) -> Vec<Call> {
884 if button == PointerButton::Left {
885 self.press_away(self.pointer.hovered);
886 }
887 if let (PointerButton::Left, None, Some(at)) =
889 (button, self.pointer.pressed, self.pointer.position)
890 && self.press_bar(at)
891 {
892 return Vec::new();
893 }
894 if let (PointerButton::Left, None, Some(at)) =
895 (button, self.pointer.pressed, self.pointer.position)
896 {
897 let drags = self.pointer.hovered.is_some_and(|id| self.drags(id));
898 self.press_views(at, drags, touch);
899 }
900 let (None, Some(id), Some(at)) = (
901 self.pointer.pressed,
902 self.pointer.hovered,
903 self.pointer.position,
904 ) else {
905 return Vec::new();
906 };
907 let start = self.button_local(id, at).unwrap_or_default();
908 self.set_pressed(Some(Press {
909 id,
910 button,
911 at,
912 last: at,
913 start,
914 dragging: false,
915 long_pressed: false,
916 }));
917 if button != PointerButton::Left {
918 return Vec::new();
919 }
920 self.pointer.link = self.link_under(id, at);
921 if self.selects(id) {
922 self.press_text(id, at, time);
923 }
924 let mut calls: Vec<Call> = self.call(id, Action::Press).into_iter().collect();
925 if self.has(id, |h| h.long_press.is_some()) {
926 self.arm_long_press(id);
927 }
928 let waits =
930 |h: &Handlers| h.click.is_some() || h.double_click.is_some() || h.long_press.is_some();
931 if self.drags(id) && !self.has(id, waits) {
932 calls.extend(self.start_drag(at));
933 }
934 calls
935 }
936
937 fn release(&mut self, button: PointerButton, time: u32) -> Vec<Call> {
938 if button == PointerButton::Left {
939 self.release_bar();
940 self.flick_release(Some(time));
941 }
942 let Some(press) = self.pointer.pressed.filter(|press| press.button == button) else {
943 return Vec::new();
944 };
945 let mut calls = Vec::new();
946 if button == PointerButton::Left {
947 calls.extend(self.call(press.id, Action::Release));
948 let link = self.pointer.link.take();
949 calls.extend(link.and_then(|link| self.link_click(press, link)));
950 }
951 let landed = Rc::new(Cell::new(false));
953 calls.extend(self.drop_call(&landed));
954 calls.extend(self.end_press(Some(landed)));
955 if press.dragging {
956 if let Some(at) = self.pointer.position {
958 self.hover_at(at);
959 }
960 return calls;
961 }
962 if press.long_pressed || self.pointer.hovered != Some(press.id) {
963 return calls;
964 }
965 let action = match button {
966 PointerButton::Left => self.left_click(press.id, time, press.at),
967 PointerButton::Right => Action::RightClick,
968 PointerButton::Middle => Action::MiddleClick,
969 PointerButton::Back => Action::Back,
970 PointerButton::Forward => Action::Forward,
971 };
972 calls.extend(self.call(press.id, action));
973 calls
974 }
975
976 fn link_under_pointer(&self) -> Option<usize> {
978 let id = self.pointer.hovered?;
979 let NodeKind::Text(text) = &self.node(id)?.kind else {
980 return None;
981 };
982 text.link_at(self.local_point(id, self.pointer.position?)?)
983 }
984
985 fn link_under(&self, id: NodeId, at: Point) -> Option<(NodeId, usize, String)> {
988 let NodeKind::Text(text) = &self.node(id)?.kind else {
989 return None;
990 };
991 let index = text.link_at(self.local_point(id, at)?)?;
992 Some((id, index, text.spans[index].link.clone()?))
993 }
994
995 fn link_click(&self, press: Press, pressed: (NodeId, usize, String)) -> Option<Call> {
1000 let node = self.node(press.id)?;
1001 let NodeKind::Text(text) = &node.kind else {
1002 return None;
1003 };
1004 if text_selection(text).is_some() {
1005 return None;
1006 }
1007 let released = self.link_under(press.id, self.pointer.position?)?;
1008 if pressed != released {
1009 return None;
1010 }
1011 self.link_call(press.id, released.1)
1012 }
1013
1014 pub(crate) fn link_call(&self, id: NodeId, index: usize) -> Option<Call> {
1017 let node = self.node(id)?;
1018 let NodeKind::Text(text) = &node.kind else {
1019 return None;
1020 };
1021 let handler = text.on_link.clone().filter(|handler| !handler.disabled())?;
1022 let url = text.spans.get(index)?.link.clone()?;
1023 Some(Call {
1024 cx: node.cx.clone(),
1025 path: Rc::clone(&node.path),
1026 handlers: None,
1027 action: Action::Link(handler, url, self.this.clone(), id),
1028 })
1029 }
1030
1031 fn left_click(&mut self, id: NodeId, time: u32, at: Point) -> Action {
1035 let close = self.pointer.last_click.is_some_and(|(last, then, place)| {
1036 last == id
1037 && time.wrapping_sub(then) <= DOUBLE_CLICK_MS
1038 && distance(place, at) <= DOUBLE_CLICK_DISTANCE
1039 });
1040 if close && self.has(id, |h| h.double_click.is_some()) {
1041 self.pointer.last_click = None;
1042 Action::DoubleClick
1043 } else {
1044 self.pointer.last_click = Some((id, time, at));
1045 Action::Click
1046 }
1047 }
1048
1049 fn drop_call(&self, landed: &Rc<Cell<bool>>) -> Option<Call> {
1052 let target = self.drop_target()?;
1053 let press = self.pointer.pressed?;
1054 let Some(NodeKind::Button(button)) = self.node(press.id).map(|node| &node.kind) else {
1055 return None;
1056 };
1057 let value = untrack(|| button.drag_data?.try_get().flatten())?;
1058 self.call(target, Action::Drop(value, Rc::clone(landed)))
1059 }
1060
1061 fn end_press(&mut self, landed: Option<Rc<Cell<bool>>>) -> Option<Call> {
1065 let press = self.pointer.pressed?;
1066 self.set_pressed(None);
1067 self.update_drop();
1068 self.stop_long_press(press.id);
1069 if press.dragging {
1070 self.drag_call(press, DragPhase::End, press.last, landed)
1071 } else {
1072 None
1073 }
1074 }
1075
1076 fn drag_motion(&mut self, at: Point) -> Vec<Call> {
1079 let Some(press) = self.pointer.pressed.as_mut() else {
1080 return Vec::new();
1081 };
1082 press.last = at;
1083 let press = *press;
1084 if press.button != PointerButton::Left {
1085 return Vec::new();
1086 }
1087 if press.dragging && self.selects(press.id) {
1088 self.drag_text(press.id, at);
1089 return Vec::new();
1090 }
1091 if press.dragging {
1092 return self
1093 .drag_call(press, DragPhase::Move, at, None)
1094 .into_iter()
1095 .collect();
1096 }
1097 if distance(press.at, at) <= DRAG_THRESHOLD {
1098 return Vec::new();
1099 }
1100 self.stop_long_press(press.id);
1101 if self.drags(press.id) {
1102 self.start_drag(at)
1103 } else {
1104 Vec::new()
1105 }
1106 }
1107
1108 fn start_drag(&mut self, at: Point) -> Vec<Call> {
1110 let Some(press) = self.pointer.pressed.as_mut() else {
1111 return Vec::new();
1112 };
1113 press.dragging = true;
1114 let press = *press;
1115 self.stop_long_press(press.id);
1116 self.update_drop();
1117 self
1118 .drag_call(press, DragPhase::Start, at, None)
1119 .into_iter()
1120 .collect()
1121 }
1122
1123 fn drag_call(
1124 &self,
1125 press: Press,
1126 phase: DragPhase,
1127 at: Point,
1128 landed: Option<Rc<Cell<bool>>>,
1129 ) -> Option<Call> {
1130 let rect = self.node(press.id)?.rect?;
1131 let drag = Drag {
1132 phase,
1133 start: press.start,
1134 position: self.button_local(press.id, at).unwrap_or(press.start),
1137 size: Size::new(rect.width, rect.height),
1138 dropped: false,
1139 };
1140 self.call(press.id, Action::Drag(drag, landed))
1141 }
1142
1143 fn arm_long_press(&mut self, id: NodeId) {
1146 let tree = self.this.clone();
1147 let Some(Node { cx, kind, .. }) = self.node_mut(id) else {
1148 return;
1149 };
1150 let NodeKind::Button(button) = kind else {
1151 return;
1152 };
1153 match button.long_press {
1154 Some(timer) => timer.restart(),
1155 None => {
1156 let timer = cx.after(LONG_PRESS, move || long_press_fired(&tree, id));
1157 button.long_press = Some(timer);
1158 }
1159 }
1160 }
1161
1162 fn stop_long_press(&self, id: NodeId) {
1163 if let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind)
1164 && let Some(timer) = button.long_press
1165 {
1166 timer.stop();
1167 }
1168 }
1169
1170 fn long_press(&mut self, id: NodeId) -> Option<Call> {
1172 let press = self.pointer.pressed.as_mut().filter(|press| {
1173 press.id == id
1174 && press.button == PointerButton::Left
1175 && !press.dragging
1176 && !press.long_pressed
1177 })?;
1178 press.long_pressed = true;
1179 self.call(id, Action::LongPress)
1180 }
1181
1182 pub(crate) fn leave(&mut self) -> Vec<Call> {
1185 self.pointer.position = None;
1186 self.release_bar();
1187 self.flick_release(None);
1188 if let Some(id) = self.pointer.gesture.take() {
1189 self.release_view(id, None);
1190 }
1191 let calls = self.end_press(None).into_iter().collect();
1192 self.set_hovered(None, &[]);
1193 self.set_positions(&[], None);
1194 self.hover_link();
1195 calls
1196 }
1197
1198 pub(crate) fn set_enabled(&mut self, id: NodeId, enabled: bool) -> Vec<Call> {
1202 let Some(NodeKind::Button(button)) = self.node_mut(id).map(|node| &mut node.kind) else {
1203 return Vec::new();
1204 };
1205 if std::mem::replace(&mut button.enabled, enabled) == enabled {
1206 return Vec::new();
1207 }
1208 let mut calls = Vec::new();
1209 if !enabled {
1210 if self.pointer.pressed.is_some_and(|press| press.id == id) {
1211 calls.extend(self.end_press(None));
1212 }
1213 if self.keyboard.focused == Some(id) {
1214 self.focus(None);
1215 }
1216 }
1217 if let Some(at) = self.pointer.position {
1218 self.hover_at(at);
1219 }
1220 calls
1221 }
1222
1223 pub(crate) fn bind_enabled(&mut self, id: NodeId, prop: Prop<bool>) {
1226 let mut compute = match prop.0 {
1227 PropKind::Value(enabled) => {
1229 self.set_enabled(id, enabled);
1230 return;
1231 }
1232 PropKind::Binding(compute) => compute,
1233 };
1234 let Some(node) = self.node(id) else {
1235 return;
1236 };
1237 let label = format!("{}.enabled", node.path);
1238 let tree = self.this.clone();
1239 node
1240 .cx
1241 .effect(move || {
1242 let enabled = compute();
1243 let Some(tree) = tree.upgrade() else {
1244 return;
1245 };
1246 let calls = borrow(&tree).set_enabled(id, enabled);
1247 untrack(|| run_all(calls));
1249 })
1250 .named(label);
1251 }
1252
1253 pub(crate) fn enabled(&self, id: NodeId) -> bool {
1255 match self.node(id).map(|node| &node.kind) {
1256 Some(NodeKind::Button(button)) => button.enabled,
1257 _ => true,
1258 }
1259 }
1260
1261 fn scroll(&mut self, wheel: Wheel, time: u32) -> Vec<Call> {
1262 let wants = |h: &Handlers| h.scroll.is_some() || h.wheel.is_some();
1263 let target = self.pointer.hovered.filter(|&id| self.has(id, wants));
1264 let calls = match target {
1265 None => {
1266 self.scroll_view(wheel, time);
1267 Vec::new()
1268 }
1269 Some(target) => {
1270 let mut calls = Vec::new();
1271 if self.has(target, |h| h.wheel.is_some()) {
1272 calls.extend(self.call(target, Action::Wheel(wheel)));
1273 }
1274 if self.has(target, |h| h.scroll.is_some()) {
1275 let down = self.steps(wheel.y);
1276 if down != 0 {
1278 calls.extend(self.call(target, Action::Scroll(down.saturating_neg())));
1279 }
1280 }
1281 calls
1282 }
1283 };
1284 if wheel.y.stop {
1285 self.pointer.pixels = 0.0;
1286 }
1287 if wheel.source == ScrollSource::Finger
1291 && (wheel.x.stop || wheel.y.stop)
1292 && let Some(id) = self.pointer.gesture.take()
1293 {
1294 self.release_view(id, Some(time));
1295 }
1296 calls
1297 }
1298
1299 fn steps(&mut self, axis: WheelAxis) -> i32 {
1302 if axis.notches != 0.0 && axis.notches.is_finite() {
1303 let value120 = (axis.notches * VALUE120_PER_STEP as f32).round() as i32;
1305 self.pointer.wheel = self.pointer.wheel.saturating_add(value120);
1306 let steps = self.pointer.wheel / VALUE120_PER_STEP;
1307 self.pointer.wheel -= steps * VALUE120_PER_STEP;
1308 steps
1309 } else if axis.pixels.is_finite() {
1310 self.pointer.pixels += axis.pixels;
1311 let steps = (self.pointer.pixels / PIXELS_PER_STEP).trunc();
1312 self.pointer.pixels -= steps * PIXELS_PER_STEP;
1313 steps as i32
1314 } else {
1315 0
1316 }
1317 }
1318
1319 pub(crate) fn cancel_press(&mut self) {
1322 if let Some(press) = self.pointer.pressed.filter(|press| !press.dragging) {
1323 self.set_pressed(None);
1324 self.stop_long_press(press.id);
1325 }
1326 }
1327
1328 fn has(&self, id: NodeId, f: impl FnOnce(&Handlers) -> bool) -> bool {
1330 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
1331 return false;
1332 };
1333 untrack(|| button.handlers.try_with(f)).unwrap_or(false)
1334 }
1335
1336 pub(crate) fn local_point(&self, id: NodeId, point: Point) -> Option<Point> {
1340 self
1341 .path_to(id)
1342 .iter()
1343 .try_fold(point, |point, &id| local(self.node(id)?, point))
1344 }
1345
1346 pub(crate) fn window_rect(&self, id: NodeId, rect: Rect) -> Rect {
1350 let mut rect = rect;
1351 let mut at = Some(id);
1352 while let Some(current) = at {
1353 if let Some(transform) = self.node(current).and_then(|node| node.transform) {
1354 rect = transform.map_rect(rect);
1355 }
1356 at = self.taffy.parent(current);
1357 }
1358 rect
1359 }
1360
1361 pub(crate) fn click(&self, id: NodeId) -> Option<Call> {
1363 self.call(id, Action::Click)
1364 }
1365
1366 fn call(&self, id: NodeId, action: Action) -> Option<Call> {
1367 let node = self.node(id)?;
1368 let NodeKind::Button(button) = &node.kind else {
1369 return None;
1370 };
1371 Some(Call {
1372 cx: node.cx.clone(),
1373 path: Rc::clone(&node.path),
1374 handlers: Some(button.handlers),
1375 action,
1376 })
1377 }
1378}
1379
1380fn long_press_fired(tree: &Weak<RefCell<Tree>>, id: NodeId) {
1382 let Some(tree) = tree.upgrade() else {
1383 return;
1384 };
1385 let Ok(mut borrowed) = tree.try_borrow_mut() else {
1387 return;
1388 };
1389 let call = borrowed.long_press(id);
1390 drop(borrowed);
1391 if let Some(call) = call {
1392 call.run();
1393 }
1394}
1395
1396pub(crate) fn local(node: &Node, point: Point) -> Option<Point> {
1400 match node.transform {
1401 Some(transform) => Some(transform.invert()?.map(point)),
1402 None => Some(point),
1403 }
1404}
1405
1406#[derive(Clone)]
1407enum Action {
1408 Click,
1409 Press,
1410 Release,
1411 DoubleClick,
1412 LongPress,
1413 RightClick,
1414 MiddleClick,
1415 Back,
1416 Forward,
1417 Scroll(i32),
1418 Wheel(Wheel),
1419 Drag(Drag, Option<Rc<Cell<bool>>>),
1421 Drop(DragValue, Rc<Cell<bool>>),
1423 Link(LinkHandler, String, Weak<RefCell<Tree>>, NodeId),
1426}
1427
1428pub(crate) struct Call {
1430 cx: Cx,
1431 path: Rc<str>,
1432 handlers: Option<Signal<Handlers>>,
1434 action: Action,
1435}
1436
1437enum Picked {
1439 Plain(ClickHandler, &'static str),
1440 Scroll(ScrollHandler, i32),
1441 Wheel(WheelHandler, Wheel),
1442 Drag(DragHandler, Drag),
1443 Drop(DropHandler, DragValue, Rc<Cell<bool>>),
1444}
1445
1446impl Call {
1447 pub(crate) fn run(self) {
1448 let (path, cx) = (&self.path, &self.cx);
1449 if let Action::Link(handler, url, tree, id) = &self.action {
1450 run_isolated(path, "on_link", Rc::clone(handler), |f| f(cx, url));
1451 if handler.disabled()
1453 && let Some(tree) = tree.upgrade()
1454 && let Ok(mut tree) = tree.try_borrow_mut()
1455 {
1456 tree.light_link(*id, false, None);
1457 tree.light_link(*id, true, None);
1458 }
1459 return;
1460 }
1461 let Some(handlers) = self.handlers else {
1462 return;
1463 };
1464 let picked = untrack(|| {
1466 handlers.try_with(|h| {
1467 let plain = |handler: &Option<ClickHandler>, name| {
1468 handler.clone().map(|handler| Picked::Plain(handler, name))
1469 };
1470 match &self.action {
1471 Action::Click => plain(&h.click, "on_click"),
1472 Action::Press => plain(&h.press, "on_press"),
1473 Action::Release => plain(&h.release, "on_release"),
1474 Action::DoubleClick => plain(&h.double_click, "on_double_click"),
1475 Action::LongPress => plain(&h.long_press, "on_long_press"),
1476 Action::RightClick => plain(&h.right_click, "on_right_click"),
1477 Action::MiddleClick => plain(&h.middle_click, "on_middle_click"),
1478 Action::Back => plain(&h.back, "on_back"),
1479 Action::Forward => plain(&h.forward, "on_forward"),
1480 Action::Scroll(steps) => h.scroll.clone().map(|f| Picked::Scroll(f, *steps)),
1481 Action::Wheel(wheel) => h.wheel.clone().map(|f| Picked::Wheel(f, *wheel)),
1482 Action::Drag(drag, landed) => {
1483 let drag = Drag {
1484 dropped: landed.as_ref().is_some_and(|landed| landed.get()),
1485 ..*drag
1486 };
1487 h.drag.clone().map(|f| Picked::Drag(f, drag))
1488 }
1489 Action::Drop(value, landed) => {
1490 let target = h.drop.as_ref()?;
1491 Some(Picked::Drop(
1492 target.handler.clone(),
1493 Rc::clone(value),
1494 Rc::clone(landed),
1495 ))
1496 }
1497 Action::Link(..) => None,
1498 }
1499 })
1500 });
1501 let Some(Some(picked)) = picked else {
1502 return;
1503 };
1504 match picked {
1505 Picked::Plain(handler, name) => {
1506 run_isolated(path, name, handler, |f| f(cx));
1507 }
1508 Picked::Scroll(handler, steps) => {
1509 run_isolated(path, "on_scroll", handler, |f| f(cx, steps));
1510 }
1511 Picked::Wheel(handler, wheel) => {
1512 run_isolated(path, "on_wheel", handler, |f| f(cx, wheel));
1513 }
1514 Picked::Drag(handler, drag) => {
1515 run_isolated(path, "on_drag", handler, |f| f(cx, drag));
1516 }
1517 Picked::Drop(handler, value, landed) => {
1519 let ran = run_isolated(path, "on_drop", handler, move |f| f(cx, &*value));
1520 landed.set(ran.is_some());
1521 }
1522 }
1523 }
1524}
1525
1526pub(crate) fn run_isolated<F: ?Sized, R>(
1531 path: &str,
1532 name: &str,
1533 handler: Rc<Handler<F>>,
1534 call: impl FnOnce(&F) -> R,
1535) -> Option<R> {
1536 if handler.disabled.get() {
1537 return None;
1538 }
1539 let result = match panic::catch_unwind(AssertUnwindSafe(|| call(&handler.f))) {
1540 Ok(result) => Some(result),
1541 Err(payload) => {
1542 handler.disabled.set(true);
1543 tracing::error!(
1544 "handler {path}.{name} panicked and is disabled: {}",
1545 panic_message(payload.as_ref())
1546 );
1547 None
1548 }
1549 };
1550 if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(move || drop(handler))) {
1551 tracing::error!(
1552 "dropping handler {path}.{name} panicked: {}",
1553 panic_message(payload.as_ref())
1554 );
1555 }
1556 result
1557}
1558
1559pub(crate) fn panic_message(payload: &(dyn Any + Send)) -> &str {
1560 if let Some(message) = payload.downcast_ref::<&str>() {
1561 message
1562 } else if let Some(message) = payload.downcast_ref::<String>() {
1563 message
1564 } else {
1565 "(panic payload is not a string)"
1566 }
1567}