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::dnd::Incoming;
20use crate::geometry::{Point, Rect, Size};
21use crate::keyboard::{Clipboard, KeyHandler};
22use crate::prop::{Prop, PropKind};
23use crate::scrolling::{BarDrag, Flick};
24use crate::select::{TextClick, text_selection};
25use crate::tree::{ButtonNode, Change, Node, NodeId, NodeKind, Tree, add_damage, borrow};
26use crate::window::Window;
27
28pub(crate) const PIXELS_PER_STEP: f32 = 15.0;
30
31const VALUE120_PER_STEP: i32 = 120;
33
34pub(crate) const DRAG_THRESHOLD: f32 = 10.0;
37
38const LONG_PRESS: Duration = Duration::from_millis(800);
41
42pub(crate) const DOUBLE_CLICK_MS: u32 = 400;
45
46pub(crate) const DOUBLE_CLICK_DISTANCE: f32 = 5.0;
49
50pub(crate) struct Handler<F: ?Sized> {
52 disabled: Cell<bool>,
53 f: F,
54}
55
56impl<F> Handler<F> {
57 pub(crate) fn new(f: F) -> Handler<F> {
58 Handler {
59 disabled: Cell::new(false),
60 f,
61 }
62 }
63}
64
65impl<F: ?Sized> Handler<F> {
66 pub(crate) fn disabled(&self) -> bool {
68 self.disabled.get()
69 }
70}
71
72pub(crate) type ClickHandler = Rc<Handler<dyn Fn(&Cx)>>;
73type ScrollHandler = Rc<Handler<dyn Fn(&Cx, i32)>>;
74pub(crate) type WheelHandler = Rc<Handler<dyn Fn(&Cx, Wheel)>>;
75pub(crate) type DragHandler = Rc<Handler<dyn Fn(&Cx, Drag)>>;
76pub(crate) type LinkHandler = Rc<Handler<dyn Fn(&Cx, &str)>>;
77
78pub(crate) type DragValue = Rc<dyn Any>;
82
83pub(crate) struct DropTarget {
85 pub(crate) accepts: TypeId,
86 pub(crate) handler: DropHandler,
87 pub(crate) name: &'static str,
89}
90
91pub(crate) type DropHandler = Rc<Handler<dyn Fn(&Cx, &dyn Any)>>;
93
94#[derive(Default)]
96pub(crate) struct Handlers {
97 pub(crate) click: Option<ClickHandler>,
98 pub(crate) press: Option<ClickHandler>,
99 pub(crate) release: Option<ClickHandler>,
100 pub(crate) double_click: Option<ClickHandler>,
101 pub(crate) long_press: Option<ClickHandler>,
102 pub(crate) right_click: Option<ClickHandler>,
103 pub(crate) middle_click: Option<ClickHandler>,
104 pub(crate) back: Option<ClickHandler>,
105 pub(crate) forward: Option<ClickHandler>,
106 pub(crate) scroll: Option<ScrollHandler>,
107 pub(crate) wheel: Option<WheelHandler>,
108 pub(crate) drag: Option<DragHandler>,
109 pub(crate) drop: Option<DropTarget>,
110 pub(crate) key: Option<KeyHandler>,
111}
112
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub enum PointerButton {
116 Left,
118 Right,
120 Middle,
122 Back,
125 Forward,
128}
129
130#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
132pub enum ScrollSource {
133 #[default]
135 Wheel,
136 Finger,
139 Continuous,
141 WheelTilt,
143}
144
145#[derive(Clone, Copy, Debug, Default, PartialEq)]
147pub struct WheelAxis {
148 pub pixels: f32,
151 pub notches: f32,
155 pub stop: bool,
158}
159
160#[derive(Clone, Copy, Debug, Default, PartialEq)]
163pub struct Wheel {
164 pub source: ScrollSource,
166 pub x: WheelAxis,
168 pub y: WheelAxis,
170}
171
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
174pub enum DragPhase {
175 Start,
178 Move,
180 End,
183}
184
185#[derive(Clone, Copy, Debug, PartialEq)]
190pub struct Drag {
191 pub phase: DragPhase,
193 pub start: Point,
195 pub position: Point,
198 pub size: Size,
200 pub dropped: bool,
204}
205
206#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
209pub enum CursorShape {
210 #[default]
212 Default,
213 ContextMenu,
215 Help,
217 Pointer,
219 Progress,
221 Wait,
223 Cell,
225 Crosshair,
227 Text,
229 VerticalText,
231 Alias,
233 Copy,
235 Move,
237 NoDrop,
239 NotAllowed,
241 Grab,
243 Grabbing,
245 EResize,
247 NResize,
249 NeResize,
251 NwResize,
253 SResize,
255 SeResize,
257 SwResize,
259 WResize,
261 EwResize,
263 NsResize,
265 NeswResize,
267 NwseResize,
269 ColResize,
271 RowResize,
273 AllScroll,
275 ZoomIn,
277 ZoomOut,
279 DndAsk,
282 AllResize,
285}
286
287#[derive(Clone, Copy)]
289pub(crate) struct Press {
290 pub(crate) id: NodeId,
291 pub(crate) button: PointerButton,
292 at: Point,
295 pub(crate) last: Point,
296 start: Point,
298 pub(crate) dragging: bool,
300 long_pressed: bool,
302 pub(crate) out: bool,
305}
306
307#[derive(Default)]
309pub(crate) struct Pointer {
310 pub(crate) position: Option<Point>,
311 pub(crate) hovered: Option<NodeId>,
313 inside: Vec<(NodeId, Signal<bool>)>,
316 positions: Vec<(NodeId, Signal<Option<Point>>, Point)>,
319 pub(crate) pressed: Option<Press>,
321 link: Option<(NodeId, usize, String)>,
324 link_hover: Option<(NodeId, usize)>,
326 pub(crate) bar: Option<BarDrag>,
328 pub(crate) flick: Option<Flick>,
331 pub(crate) gesture: Option<NodeId>,
333 pub(crate) last_click: Option<(NodeId, u32, Point)>,
336 pub(crate) text_click: Option<TextClick>,
339 wheel: i32,
341 pixels: f32,
342 caused_layout: bool,
344 pub(crate) drop_over: Option<(NodeId, Option<Signal<bool>>)>,
347 pub(crate) incoming: Option<Incoming>,
349}
350
351impl Pointer {
352 pub(crate) fn forget(&mut self, removed: &[NodeId]) {
355 if self.hovered.is_some_and(|id| removed.contains(&id)) {
356 self.hovered = None;
357 }
358 let (gone, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut self.inside)
359 .into_iter()
360 .partition(|(id, _)| removed.contains(id));
361 for (_, signal) in gone {
362 if !kept.iter().any(|(_, other)| *other == signal) {
364 signal.try_set(false);
365 }
366 }
367 self.inside = kept;
368 self.positions.retain(|(id, signal, _)| {
369 let gone = removed.contains(id);
370 if gone {
371 signal.try_set(None);
372 }
373 !gone
374 });
375 let source_gone = self
376 .pressed
377 .is_some_and(|press| removed.contains(&press.id));
378 if source_gone {
379 self.pressed = None;
380 }
381 if source_gone || self.drop_over.is_some_and(|(id, _)| removed.contains(&id)) {
382 self.set_drop_over(None);
383 }
384 self.forget_views(removed);
385 if self
386 .last_click
387 .is_some_and(|(id, _, _)| removed.contains(&id))
388 {
389 self.last_click = None;
390 }
391 if self
392 .text_click
393 .is_some_and(|click| removed.contains(&click.id))
394 {
395 self.text_click = None;
396 }
397 }
398}
399
400impl Pointer {
401 fn set_drop_over(&mut self, over: Option<(NodeId, Option<Signal<bool>>)>) {
404 let old = std::mem::replace(&mut self.drop_over, over);
405 if old.map(|(id, _)| id) == over.map(|(id, _)| id) {
406 return;
407 }
408 let (old, new) = (old.and_then(|(_, s)| s), over.and_then(|(_, s)| s));
409 if old != new {
410 if let Some(old) = old {
411 old.try_set(false);
412 }
413 if let Some(new) = new {
414 new.try_set(true);
415 }
416 }
417 }
418}
419
420impl Tree {
421 pub(crate) fn pointer_hide(&mut self, hidden: &[NodeId]) {
424 let held = [
425 self.pointer.hovered,
426 self.pointer.pressed.map(|press| press.id),
427 ];
428 self.pointer.forget(hidden);
429 for id in held.into_iter().flatten().filter(|id| hidden.contains(id)) {
430 self.update_button_style(id, |button| {
431 button.hovered = false;
432 button.pressed = false;
433 });
434 }
435 }
436}
437
438fn now_ms() -> u32 {
441 static START: OnceLock<Instant> = OnceLock::new();
442 START.get_or_init(Instant::now).elapsed().as_millis() as u32
444}
445
446impl Window {
447 pub fn pointer_motion(&self, position: Point) -> CursorShape {
450 self.pointer_motion_at(position, now_ms())
451 }
452
453 pub fn pointer_motion_at(&self, position: Point, time: u32) -> CursorShape {
458 let calls = {
459 let mut tree = borrow(&self.tree);
460 tree.pointer.position = Some(position);
461 tree.bar_motion(position);
462 let calls = if tree.flick_motion(position, time) {
463 Vec::new()
464 } else {
465 tree.drag_motion(position)
466 };
467 tree.hover_at(position);
468 calls
469 };
470 run_all(calls);
471 self.cursor()
472 }
473
474 pub fn pointer_leave(&self) {
477 let calls = borrow(&self.tree).leave();
478 run_all(calls);
479 }
480
481 pub fn pointer_button(&self, button: PointerButton, pressed: bool) {
484 self.pointer_button_at(button, pressed, now_ms());
485 }
486
487 pub fn pointer_button_at(&self, button: PointerButton, pressed: bool, time: u32) {
495 let calls = borrow(&self.tree).button(button, pressed, time, false);
496 run_all(calls);
497 }
498
499 pub fn touch_at(&self, pressed: bool, time: u32) {
504 let calls = borrow(&self.tree).button(PointerButton::Left, pressed, time, true);
505 run_all(calls);
506 }
507
508 pub fn pointer_scroll(&self, wheel: Wheel) {
517 self.pointer_scroll_at(wheel, now_ms());
518 }
519
520 pub fn pointer_scroll_at(&self, wheel: Wheel, time: u32) {
524 let calls = borrow(&self.tree).scroll(wheel, time);
525 run_all(calls);
526 }
527
528 pub fn take_primary(&self) -> Option<Clipboard> {
534 borrow(&self.tree).primary.take()
535 }
536
537 pub fn cursor(&self) -> CursorShape {
539 self.tree.borrow().cursor()
540 }
541}
542
543pub(crate) fn run_all(calls: Vec<Call>) {
545 for call in calls {
546 call.run();
547 }
548}
549
550pub(crate) fn distance(a: Point, b: Point) -> f32 {
551 (a.x - b.x).hypot(a.y - b.y)
552}
553
554impl Tree {
555 fn hit(
562 &self,
563 id: NodeId,
564 point: Point,
565 path: &mut Vec<NodeId>,
566 skip: Option<NodeId>,
567 ) -> Option<NodeId> {
568 if skip == Some(id) {
569 return None;
570 }
571 let node = self.node(id)?;
572 let point = local(node, point)?;
573 let rect = node.rect?;
574 if !node.inner_bounds.contains(point) {
577 return None;
578 }
579 let style = node.effective_style();
580 let border = style.border.map_or(0.0, |border| border.width.max(0.0));
582 let corners = style.radius.unwrap_or_default();
583 let children = if node.clips() && !corners.contains(rect, border, point) {
584 Vec::new()
585 } else {
586 self.drawn_children(id)
587 };
588 path.push(id);
589 if let Some(hit) = children
590 .into_iter()
591 .rev()
592 .find_map(|child| self.hit(child, point, path, skip))
593 {
594 return Some(hit);
595 }
596 let takes = match &node.kind {
597 NodeKind::Button(button) => button.enabled,
598 NodeKind::Input(_) => true,
599 NodeKind::Text(text) => text.selectable,
600 _ => false,
601 };
602 if rect.contains(point) && takes {
603 return Some(id);
604 }
605 if matches!(&node.kind, NodeKind::Text(text) if text.link_at(point).is_some()) {
607 return Some(id);
608 }
609 path.pop();
610 None
611 }
612
613 pub(crate) fn hover_at(&mut self, point: Point) {
617 let mut path = Vec::new();
618 let hit = match self.pointer.pressed.filter(|press| press.dragging) {
619 Some(press) => {
620 path = self.path_to(press.id);
621 Some(press.id)
622 }
623 None => self.hit(self.root, point, &mut path, None),
624 };
625 self.set_hovered(hit, &path);
626 self.set_positions(&path, Some(point));
627 self.update_drop();
628 self.hover_link();
629 }
630
631 fn hover_link(&mut self) {
633 let now = self.pointer.hovered.zip(self.link_under_pointer());
634 let old = std::mem::replace(&mut self.pointer.link_hover, now);
635 if old == now {
636 return;
637 }
638 if let Some((id, _)) = old {
639 self.light_link(id, false, None);
640 }
641 if let Some((id, index)) = now {
642 self.light_link(id, false, Some(index));
643 }
644 }
645
646 pub(crate) fn light_link(&mut self, id: NodeId, focus: bool, index: Option<usize>) {
650 let Some(node) = self.node_mut(id) else {
651 return;
652 };
653 let laid_out = node.rect.is_some();
654 let NodeKind::Text(text) = &mut node.kind else {
655 return;
656 };
657 let slot = match focus {
658 true => &mut text.focused_link,
659 false => &mut text.hovered_link,
660 };
661 let old = std::mem::replace(slot, index);
662 if old == index || !laid_out {
663 return;
664 }
665 let areas: Vec<Rect> = old
666 .into_iter()
667 .chain(index)
668 .flat_map(|index| text.link_areas(index))
669 .collect();
670 for area in areas {
671 let area = self.window_area(id, area);
672 add_damage(&mut self.damage, area);
673 }
674 }
675
676 fn drag_type(&self, id: NodeId) -> Option<TypeId> {
678 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
679 return None;
680 };
681 let data = button.drag_data?;
682 untrack(|| data.try_with(|data| data.as_ref().map(|value| (**value).type_id()))).flatten()
684 }
685
686 pub(crate) fn drop_target(&self) -> Option<NodeId> {
690 let press = self.pointer.pressed.filter(|press| press.dragging);
691 let (carried, at) = match self.pointer.incoming {
692 Some(incoming) => (incoming.carried, incoming.at),
693 None => (self.drag_type(press?.id)?, self.pointer.position?),
694 };
695 let mut path = Vec::new();
696 self.hit(self.root, at, &mut path, press.map(|press| press.id))?;
697 path.into_iter().rev().find(|&id| {
698 self.enabled(id)
699 && self.has(id, |h| {
700 h.drop
702 .as_ref()
703 .is_some_and(|target| target.accepts == carried && !target.handler.disabled.get())
704 })
705 })
706 }
707
708 pub(crate) fn update_drop(&mut self) {
711 let over = self.drop_target().map(|id| {
712 let signal = match self.node(id).map(|node| &node.kind) {
713 Some(NodeKind::Button(button)) => button.drop_hovered,
714 _ => None,
715 };
716 (id, signal)
717 });
718 self.pointer.set_drop_over(over);
719 }
720
721 pub(crate) fn drop_after_place(&mut self) {
724 if self.pointer.incoming.is_some() || self.pointer.pressed.is_some_and(|press| press.dragging) {
725 self.update_drop();
726 }
727 }
728
729 fn drags(&self, id: NodeId) -> bool {
732 self.selects(id) || self.drag_type(id).is_some() || self.has(id, |h| h.drag.is_some())
733 }
734
735 pub(crate) fn path_to(&self, id: NodeId) -> Vec<NodeId> {
737 let mut path = vec![id];
738 while let Some(parent) = path.last().and_then(|&id| self.taffy.parent(id)) {
739 path.push(parent);
740 }
741 path.reverse();
742 path
743 }
744
745 fn cursor(&self) -> CursorShape {
746 let dragged = self
749 .pointer
750 .pressed
751 .filter(|press| press.dragging)
752 .and_then(|press| match self.node(press.id).map(|node| &node.kind) {
753 Some(NodeKind::Button(button)) => Some(button.cursor),
754 _ => None,
755 });
756 if let Some(shape) = dragged {
757 return match shape {
758 CursorShape::Pointer | CursorShape::Grab => CursorShape::Grabbing,
759 shape => shape,
760 };
761 }
762 match self
763 .pointer
764 .hovered
765 .and_then(|id| self.node(id))
766 .map(|node| &node.kind)
767 {
768 Some(NodeKind::Text(_)) if self.link_under_pointer().is_some() => CursorShape::Pointer,
769 Some(NodeKind::Input(_) | NodeKind::Text(_)) => CursorShape::Text,
770 Some(NodeKind::Button(button)) => button.cursor,
771 _ => CursorShape::Default,
772 }
773 }
774
775 pub(crate) fn pointer_after_layout(&mut self) {
780 if std::mem::take(&mut self.pointer.caused_layout) {
781 return;
782 }
783 if let Some(position) = self.pointer.position {
784 self.hover_at(position);
785 }
786 }
787
788 fn set_hovered(&mut self, hovered: Option<NodeId>, path: &[NodeId]) {
791 self.set_inside(path);
792 let old = self.pointer.hovered;
793 if old == hovered {
794 return;
795 }
796 self.pointer.hovered = hovered;
797 self.pointer.wheel = 0;
798 self.pointer.pixels = 0.0;
799 if let Some(old) = old {
800 self.set_button_state(old, |button| button.hovered = false);
801 }
802 if let Some(new) = hovered {
803 self.set_button_state(new, |button| button.hovered = true);
804 }
805 }
806
807 fn path_buttons<T>(
809 &self,
810 path: &[NodeId],
811 pick: impl Fn(&ButtonNode) -> Option<T>,
812 ) -> Vec<(NodeId, T)> {
813 path
814 .iter()
815 .filter_map(|&id| match &self.node(id)?.kind {
816 NodeKind::Button(button) if button.enabled => Some((id, pick(button)?)),
817 _ => None,
818 })
819 .collect()
820 }
821
822 fn set_inside(&mut self, path: &[NodeId]) {
825 let inside = self.path_buttons(path, |button| button.hover_signal);
826 let holds = |list: &[(NodeId, Signal<bool>)], signal| list.iter().any(|(_, s)| *s == signal);
829 let mut seen = Vec::new();
830 for &(_, signal) in self.pointer.inside.iter().chain(&inside) {
831 if seen.contains(&signal) {
832 continue;
833 }
834 seen.push(signal);
835 let now = holds(&inside, signal);
836 if holds(&self.pointer.inside, signal) != now {
837 signal.try_set(now);
838 }
839 }
840 self.pointer.inside = inside;
841 }
842
843 fn set_positions(&mut self, path: &[NodeId], at: Option<Point>) {
847 let now: Vec<(NodeId, Signal<Option<Point>>, Point)> = match at {
848 Some(at) => self
849 .path_buttons(path, |button| button.position_signal)
850 .into_iter()
851 .filter_map(|(id, signal)| Some((id, signal, self.button_local(id, at)?)))
852 .collect(),
853 None => Vec::new(),
854 };
855 for (id, signal, _) in &self.pointer.positions {
856 if !now.iter().any(|(other, ..)| other == id) {
857 signal.try_set(None);
858 }
859 }
860 for &(id, signal, point) in &now {
861 let same = |&(other, _, was): &(NodeId, _, Point)| other == id && was == point;
862 if !self.pointer.positions.iter().any(same) {
863 signal.try_set(Some(point));
864 }
865 }
866 self.pointer.positions = now;
867 }
868
869 fn button_local(&self, id: NodeId, point: Point) -> Option<Point> {
872 let rect = self.node(id)?.rect?;
873 let point = self.local_point(id, point)?;
874 Some(Point::new(point.x - rect.x, point.y - rect.y))
875 }
876
877 fn set_pressed(&mut self, pressed: Option<Press>) {
878 let old = std::mem::replace(&mut self.pointer.pressed, pressed);
879 if let Some(old) = old {
880 self.set_button_state(old.id, |button| button.pressed = false);
881 }
882 if let Some(new) = pressed {
883 self.set_button_state(new.id, |button| button.pressed = true);
884 }
885 }
886
887 fn set_button_state(&mut self, id: NodeId, f: impl FnOnce(&mut ButtonNode)) {
890 if self.update_button_style(id, f) == Change::Layout {
891 self.pointer.caused_layout = true;
892 }
893 }
894
895 fn button(&mut self, button: PointerButton, pressed: bool, time: u32, touch: bool) -> Vec<Call> {
896 if pressed {
897 self.press(button, time, touch)
898 } else {
899 self.release(button, time)
900 }
901 }
902
903 fn press(&mut self, button: PointerButton, time: u32, touch: bool) -> Vec<Call> {
904 if button == PointerButton::Left {
905 self.press_away(self.pointer.hovered);
906 }
907 if let (PointerButton::Left, None, Some(at)) =
909 (button, self.pointer.pressed, self.pointer.position)
910 && self.press_bar(at)
911 {
912 return Vec::new();
913 }
914 if let (PointerButton::Left, None, Some(at)) =
915 (button, self.pointer.pressed, self.pointer.position)
916 {
917 let drags = self.pointer.hovered.is_some_and(|id| self.drags(id));
918 self.press_views(at, drags, touch);
919 }
920 let (None, Some(id), Some(at)) = (
921 self.pointer.pressed,
922 self.pointer.hovered,
923 self.pointer.position,
924 ) else {
925 return Vec::new();
926 };
927 let start = self.button_local(id, at).unwrap_or_default();
928 self.set_pressed(Some(Press {
929 id,
930 button,
931 at,
932 last: at,
933 start,
934 dragging: false,
935 long_pressed: false,
936 out: false,
937 }));
938 if button == PointerButton::Middle && self.press_middle(id, at) {
939 self.primary = Some(Clipboard::Paste);
940 }
941 if button != PointerButton::Left {
942 return Vec::new();
943 }
944 self.pointer.link = self.link_under(id, at);
945 if self.selects(id) {
946 self.press_text(id, at, time);
947 }
948 let mut calls: Vec<Call> = self.call(id, Action::Press).into_iter().collect();
949 if self.has(id, |h| h.long_press.is_some()) {
950 self.arm_long_press(id);
951 }
952 let waits =
954 |h: &Handlers| h.click.is_some() || h.double_click.is_some() || h.long_press.is_some();
955 if self.drags(id) && !self.has(id, waits) {
956 calls.extend(self.start_drag(at));
957 }
958 calls
959 }
960
961 fn release(&mut self, button: PointerButton, time: u32) -> Vec<Call> {
962 if button == PointerButton::Left {
963 self.release_bar();
964 self.flick_release(Some(time));
965 }
966 let Some(press) = self.pointer.pressed.filter(|press| press.button == button) else {
967 return Vec::new();
968 };
969 let mut calls = Vec::new();
970 if button == PointerButton::Left {
971 calls.extend(self.call(press.id, Action::Release));
972 let link = self.pointer.link.take();
973 calls.extend(link.and_then(|link| self.link_click(press, link)));
974 if let Some(text) = self.selected_text(press.id) {
976 self.primary = Some(Clipboard::Copy(text));
977 }
978 }
979 let landed = Rc::new(Cell::new(false));
981 calls.extend(self.drop_call(&landed));
982 calls.extend(self.end_press(Some(landed)));
983 if press.dragging {
984 if let Some(at) = self.pointer.position {
986 self.hover_at(at);
987 }
988 return calls;
989 }
990 if press.long_pressed || self.pointer.hovered != Some(press.id) {
991 return calls;
992 }
993 let action = match button {
994 PointerButton::Left => self.left_click(press.id, time, press.at),
995 PointerButton::Right => Action::RightClick,
996 PointerButton::Middle => Action::MiddleClick,
997 PointerButton::Back => Action::Back,
998 PointerButton::Forward => Action::Forward,
999 };
1000 calls.extend(self.call(press.id, action));
1001 calls
1002 }
1003
1004 fn link_under_pointer(&self) -> Option<usize> {
1006 let id = self.pointer.hovered?;
1007 let NodeKind::Text(text) = &self.node(id)?.kind else {
1008 return None;
1009 };
1010 text.link_at(self.local_point(id, self.pointer.position?)?)
1011 }
1012
1013 fn link_under(&self, id: NodeId, at: Point) -> Option<(NodeId, usize, String)> {
1016 let NodeKind::Text(text) = &self.node(id)?.kind else {
1017 return None;
1018 };
1019 let index = text.link_at(self.local_point(id, at)?)?;
1020 Some((id, index, text.spans[index].link.clone()?))
1021 }
1022
1023 fn link_click(&self, press: Press, pressed: (NodeId, usize, String)) -> Option<Call> {
1028 let node = self.node(press.id)?;
1029 let NodeKind::Text(text) = &node.kind else {
1030 return None;
1031 };
1032 if text_selection(text).is_some() {
1033 return None;
1034 }
1035 let released = self.link_under(press.id, self.pointer.position?)?;
1036 if pressed != released {
1037 return None;
1038 }
1039 self.link_call(press.id, released.1)
1040 }
1041
1042 pub(crate) fn link_call(&self, id: NodeId, index: usize) -> Option<Call> {
1045 let node = self.node(id)?;
1046 let NodeKind::Text(text) = &node.kind else {
1047 return None;
1048 };
1049 let handler = text.on_link.clone().filter(|handler| !handler.disabled())?;
1050 let url = text.spans.get(index)?.link.clone()?;
1051 Some(Call {
1052 cx: node.cx.clone(),
1053 path: Rc::clone(&node.path),
1054 handlers: None,
1055 action: Action::Link(handler, url, self.this.clone(), id),
1056 })
1057 }
1058
1059 fn left_click(&mut self, id: NodeId, time: u32, at: Point) -> Action {
1063 let close = self.pointer.last_click.is_some_and(|(last, then, place)| {
1064 last == id
1065 && time.wrapping_sub(then) <= DOUBLE_CLICK_MS
1066 && distance(place, at) <= DOUBLE_CLICK_DISTANCE
1067 });
1068 if close && self.has(id, |h| h.double_click.is_some()) {
1069 self.pointer.last_click = None;
1070 Action::DoubleClick
1071 } else {
1072 self.pointer.last_click = Some((id, time, at));
1073 Action::Click
1074 }
1075 }
1076
1077 fn drop_call(&self, landed: &Rc<Cell<bool>>) -> Option<Call> {
1080 let target = self.drop_target()?;
1081 let value = self.drag_value(self.pointer.pressed?.id)?;
1082 self.call(target, Action::Drop(value, Rc::clone(landed)))
1083 }
1084
1085 pub(crate) fn drag_value(&self, id: NodeId) -> Option<DragValue> {
1087 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
1088 return None;
1089 };
1090 untrack(|| button.drag_data?.try_get().flatten())
1091 }
1092
1093 pub(crate) fn end_press(&mut self, landed: Option<Rc<Cell<bool>>>) -> Option<Call> {
1097 let press = self.pointer.pressed?;
1098 self.set_pressed(None);
1099 self.update_drop();
1100 self.stop_long_press(press.id);
1101 if press.dragging {
1102 self.drag_call(press, DragPhase::End, press.last, landed)
1103 } else {
1104 None
1105 }
1106 }
1107
1108 fn drag_motion(&mut self, at: Point) -> Vec<Call> {
1111 let Some(press) = self.pointer.pressed.as_mut() else {
1112 return Vec::new();
1113 };
1114 press.last = at;
1115 let press = *press;
1116 if press.button != PointerButton::Left {
1117 return Vec::new();
1118 }
1119 if press.dragging && self.selects(press.id) {
1120 self.drag_text(press.id, at);
1121 return Vec::new();
1122 }
1123 if press.dragging {
1124 return self
1125 .drag_call(press, DragPhase::Move, at, None)
1126 .into_iter()
1127 .collect();
1128 }
1129 if distance(press.at, at) <= DRAG_THRESHOLD {
1130 return Vec::new();
1131 }
1132 self.stop_long_press(press.id);
1133 if self.drags(press.id) {
1134 self.start_drag(at)
1135 } else {
1136 Vec::new()
1137 }
1138 }
1139
1140 fn start_drag(&mut self, at: Point) -> Vec<Call> {
1142 let Some(press) = self.pointer.pressed.as_mut() else {
1143 return Vec::new();
1144 };
1145 press.dragging = true;
1146 let press = *press;
1147 self.stop_long_press(press.id);
1148 self.update_drop();
1149 self
1150 .drag_call(press, DragPhase::Start, at, None)
1151 .into_iter()
1152 .collect()
1153 }
1154
1155 pub(crate) fn drag_call(
1156 &self,
1157 press: Press,
1158 phase: DragPhase,
1159 at: Point,
1160 landed: Option<Rc<Cell<bool>>>,
1161 ) -> Option<Call> {
1162 let rect = self.node(press.id)?.rect?;
1163 let drag = Drag {
1164 phase,
1165 start: press.start,
1166 position: self.button_local(press.id, at).unwrap_or(press.start),
1169 size: Size::new(rect.width, rect.height),
1170 dropped: false,
1171 };
1172 self.call(press.id, Action::Drag(drag, landed))
1173 }
1174
1175 fn arm_long_press(&mut self, id: NodeId) {
1178 let tree = self.this.clone();
1179 let Some(Node { cx, kind, .. }) = self.node_mut(id) else {
1180 return;
1181 };
1182 let NodeKind::Button(button) = kind else {
1183 return;
1184 };
1185 match button.long_press {
1186 Some(timer) => timer.restart(),
1187 None => {
1188 let timer = cx.after(LONG_PRESS, move || long_press_fired(&tree, id));
1189 button.long_press = Some(timer);
1190 }
1191 }
1192 }
1193
1194 fn stop_long_press(&self, id: NodeId) {
1195 if let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind)
1196 && let Some(timer) = button.long_press
1197 {
1198 timer.stop();
1199 }
1200 }
1201
1202 fn long_press(&mut self, id: NodeId) -> Option<Call> {
1204 let press = self.pointer.pressed.as_mut().filter(|press| {
1205 press.id == id
1206 && press.button == PointerButton::Left
1207 && !press.dragging
1208 && !press.long_pressed
1209 })?;
1210 press.long_pressed = true;
1211 self.call(id, Action::LongPress)
1212 }
1213
1214 pub(crate) fn leave(&mut self) -> Vec<Call> {
1217 self.pointer.position = None;
1218 self.release_bar();
1219 self.flick_release(None);
1220 if let Some(id) = self.pointer.gesture.take() {
1221 self.release_view(id, None);
1222 }
1223 let out = self.pointer.pressed.is_some_and(|press| press.out);
1225 let calls = match out {
1226 true => Vec::new(),
1227 false => self.end_press(None).into_iter().collect(),
1228 };
1229 self.set_hovered(None, &[]);
1230 self.set_positions(&[], None);
1231 self.hover_link();
1232 calls
1233 }
1234
1235 pub(crate) fn set_enabled(&mut self, id: NodeId, enabled: bool) -> Vec<Call> {
1239 let Some(NodeKind::Button(button)) = self.node_mut(id).map(|node| &mut node.kind) else {
1240 return Vec::new();
1241 };
1242 if std::mem::replace(&mut button.enabled, enabled) == enabled {
1243 return Vec::new();
1244 }
1245 let mut calls = Vec::new();
1246 if !enabled {
1247 if self.pointer.pressed.is_some_and(|press| press.id == id) {
1248 calls.extend(self.end_press(None));
1249 }
1250 if self.keyboard.focused == Some(id) {
1251 self.focus(None);
1252 }
1253 }
1254 if let Some(at) = self.pointer.position {
1255 self.hover_at(at);
1256 }
1257 calls
1258 }
1259
1260 pub(crate) fn bind_enabled(&mut self, id: NodeId, prop: Prop<bool>) {
1263 let mut compute = match prop.0 {
1264 PropKind::Value(enabled) => {
1266 self.set_enabled(id, enabled);
1267 return;
1268 }
1269 PropKind::Binding(compute) => compute,
1270 };
1271 let Some(node) = self.node(id) else {
1272 return;
1273 };
1274 let label = format!("{}.enabled", node.path);
1275 let tree = self.this.clone();
1276 node
1277 .cx
1278 .effect(move || {
1279 let enabled = compute();
1280 let Some(tree) = tree.upgrade() else {
1281 return;
1282 };
1283 let calls = borrow(&tree).set_enabled(id, enabled);
1284 untrack(|| run_all(calls));
1286 })
1287 .named(label);
1288 }
1289
1290 pub(crate) fn enabled(&self, id: NodeId) -> bool {
1292 match self.node(id).map(|node| &node.kind) {
1293 Some(NodeKind::Button(button)) => button.enabled,
1294 _ => true,
1295 }
1296 }
1297
1298 fn scroll(&mut self, wheel: Wheel, time: u32) -> Vec<Call> {
1299 let wants = |h: &Handlers| h.scroll.is_some() || h.wheel.is_some();
1300 let target = self.pointer.hovered.filter(|&id| self.has(id, wants));
1301 let calls = match target {
1302 None => {
1303 self.scroll_view(wheel, time);
1304 Vec::new()
1305 }
1306 Some(target) => {
1307 let mut calls = Vec::new();
1308 if self.has(target, |h| h.wheel.is_some()) {
1309 calls.extend(self.call(target, Action::Wheel(wheel)));
1310 }
1311 if self.has(target, |h| h.scroll.is_some()) {
1312 let down = self.steps(wheel.y);
1313 if down != 0 {
1315 calls.extend(self.call(target, Action::Scroll(down.saturating_neg())));
1316 }
1317 }
1318 calls
1319 }
1320 };
1321 if wheel.y.stop {
1322 self.pointer.pixels = 0.0;
1323 }
1324 if wheel.source == ScrollSource::Finger
1328 && (wheel.x.stop || wheel.y.stop)
1329 && let Some(id) = self.pointer.gesture.take()
1330 {
1331 self.release_view(id, Some(time));
1332 }
1333 calls
1334 }
1335
1336 fn steps(&mut self, axis: WheelAxis) -> i32 {
1339 if axis.notches != 0.0 && axis.notches.is_finite() {
1340 let value120 = (axis.notches * VALUE120_PER_STEP as f32).round() as i32;
1342 self.pointer.wheel = self.pointer.wheel.saturating_add(value120);
1343 let steps = self.pointer.wheel / VALUE120_PER_STEP;
1344 self.pointer.wheel -= steps * VALUE120_PER_STEP;
1345 steps
1346 } else if axis.pixels.is_finite() {
1347 self.pointer.pixels += axis.pixels;
1348 let steps = (self.pointer.pixels / PIXELS_PER_STEP).trunc();
1349 self.pointer.pixels -= steps * PIXELS_PER_STEP;
1350 steps as i32
1351 } else {
1352 0
1353 }
1354 }
1355
1356 pub(crate) fn cancel_press(&mut self) {
1359 if let Some(press) = self.pointer.pressed.filter(|press| !press.dragging) {
1360 self.set_pressed(None);
1361 self.stop_long_press(press.id);
1362 }
1363 }
1364
1365 pub(crate) fn has(&self, id: NodeId, f: impl FnOnce(&Handlers) -> bool) -> bool {
1367 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
1368 return false;
1369 };
1370 untrack(|| button.handlers.try_with(f)).unwrap_or(false)
1371 }
1372
1373 pub(crate) fn local_point(&self, id: NodeId, point: Point) -> Option<Point> {
1377 self
1378 .path_to(id)
1379 .iter()
1380 .try_fold(point, |point, &id| local(self.node(id)?, point))
1381 }
1382
1383 pub(crate) fn window_rect(&self, id: NodeId, rect: Rect) -> Rect {
1387 let mut rect = rect;
1388 let mut at = Some(id);
1389 while let Some(current) = at {
1390 if let Some(transform) = self.node(current).and_then(|node| node.transform) {
1391 rect = transform.map_rect(rect);
1392 }
1393 at = self.taffy.parent(current);
1394 }
1395 rect
1396 }
1397
1398 pub(crate) fn click(&self, id: NodeId) -> Option<Call> {
1400 self.call(id, Action::Click)
1401 }
1402
1403 pub(crate) fn call(&self, id: NodeId, action: Action) -> Option<Call> {
1404 let node = self.node(id)?;
1405 let NodeKind::Button(button) = &node.kind else {
1406 return None;
1407 };
1408 Some(Call {
1409 cx: node.cx.clone(),
1410 path: Rc::clone(&node.path),
1411 handlers: Some(button.handlers),
1412 action,
1413 })
1414 }
1415}
1416
1417fn long_press_fired(tree: &Weak<RefCell<Tree>>, id: NodeId) {
1419 let Some(tree) = tree.upgrade() else {
1420 return;
1421 };
1422 let Ok(mut borrowed) = tree.try_borrow_mut() else {
1424 return;
1425 };
1426 let call = borrowed.long_press(id);
1427 drop(borrowed);
1428 if let Some(call) = call {
1429 call.run();
1430 }
1431}
1432
1433pub(crate) fn local(node: &Node, point: Point) -> Option<Point> {
1437 match node.transform {
1438 Some(transform) => Some(transform.invert()?.map(point)),
1439 None => Some(point),
1440 }
1441}
1442
1443#[derive(Clone)]
1444pub(crate) enum Action {
1445 Click,
1446 Press,
1447 Release,
1448 DoubleClick,
1449 LongPress,
1450 RightClick,
1451 MiddleClick,
1452 Back,
1453 Forward,
1454 Scroll(i32),
1455 Wheel(Wheel),
1456 Drag(Drag, Option<Rc<Cell<bool>>>),
1458 Drop(DragValue, Rc<Cell<bool>>),
1460 Link(LinkHandler, String, Weak<RefCell<Tree>>, NodeId),
1463}
1464
1465pub(crate) struct Call {
1467 cx: Cx,
1468 path: Rc<str>,
1469 handlers: Option<Signal<Handlers>>,
1471 action: Action,
1472}
1473
1474enum Picked {
1476 Plain(ClickHandler, &'static str),
1477 Scroll(ScrollHandler, i32),
1478 Wheel(WheelHandler, Wheel),
1479 Drag(DragHandler, Drag),
1480 Drop(DropHandler, &'static str, DragValue, Rc<Cell<bool>>),
1481}
1482
1483impl Call {
1484 pub(crate) fn run(self) {
1485 let (path, cx) = (&self.path, &self.cx);
1486 if let Action::Link(handler, url, tree, id) = &self.action {
1487 run_isolated(path, "on_link", Rc::clone(handler), |f| f(cx, url));
1488 if handler.disabled()
1490 && let Some(tree) = tree.upgrade()
1491 && let Ok(mut tree) = tree.try_borrow_mut()
1492 {
1493 tree.light_link(*id, false, None);
1494 tree.light_link(*id, true, None);
1495 }
1496 return;
1497 }
1498 let Some(handlers) = self.handlers else {
1499 return;
1500 };
1501 let picked = untrack(|| {
1503 handlers.try_with(|h| {
1504 let plain = |handler: &Option<ClickHandler>, name| {
1505 handler.clone().map(|handler| Picked::Plain(handler, name))
1506 };
1507 match &self.action {
1508 Action::Click => plain(&h.click, "on_click"),
1509 Action::Press => plain(&h.press, "on_press"),
1510 Action::Release => plain(&h.release, "on_release"),
1511 Action::DoubleClick => plain(&h.double_click, "on_double_click"),
1512 Action::LongPress => plain(&h.long_press, "on_long_press"),
1513 Action::RightClick => plain(&h.right_click, "on_right_click"),
1514 Action::MiddleClick => plain(&h.middle_click, "on_middle_click"),
1515 Action::Back => plain(&h.back, "on_back"),
1516 Action::Forward => plain(&h.forward, "on_forward"),
1517 Action::Scroll(steps) => h.scroll.clone().map(|f| Picked::Scroll(f, *steps)),
1518 Action::Wheel(wheel) => h.wheel.clone().map(|f| Picked::Wheel(f, *wheel)),
1519 Action::Drag(drag, landed) => {
1520 let drag = Drag {
1521 dropped: landed.as_ref().is_some_and(|landed| landed.get()),
1522 ..*drag
1523 };
1524 h.drag.clone().map(|f| Picked::Drag(f, drag))
1525 }
1526 Action::Drop(value, landed) => {
1527 let target = h.drop.as_ref()?;
1528 Some(Picked::Drop(
1529 target.handler.clone(),
1530 target.name,
1531 Rc::clone(value),
1532 Rc::clone(landed),
1533 ))
1534 }
1535 Action::Link(..) => None,
1536 }
1537 })
1538 });
1539 let Some(Some(picked)) = picked else {
1540 return;
1541 };
1542 match picked {
1543 Picked::Plain(handler, name) => {
1544 run_isolated(path, name, handler, |f| f(cx));
1545 }
1546 Picked::Scroll(handler, steps) => {
1547 run_isolated(path, "on_scroll", handler, |f| f(cx, steps));
1548 }
1549 Picked::Wheel(handler, wheel) => {
1550 run_isolated(path, "on_wheel", handler, |f| f(cx, wheel));
1551 }
1552 Picked::Drag(handler, drag) => {
1553 run_isolated(path, "on_drag", handler, |f| f(cx, drag));
1554 }
1555 Picked::Drop(handler, name, value, landed) => {
1557 let ran = run_isolated(path, name, handler, move |f| f(cx, &*value));
1558 landed.set(ran.is_some());
1559 }
1560 }
1561 }
1562}
1563
1564pub(crate) fn run_isolated<F: ?Sized, R>(
1569 path: &str,
1570 name: &str,
1571 handler: Rc<Handler<F>>,
1572 call: impl FnOnce(&F) -> R,
1573) -> Option<R> {
1574 if handler.disabled.get() {
1575 return None;
1576 }
1577 let result = match panic::catch_unwind(AssertUnwindSafe(|| call(&handler.f))) {
1578 Ok(result) => Some(result),
1579 Err(payload) => {
1580 handler.disabled.set(true);
1581 tracing::error!(
1582 "handler {path}.{name} panicked and is disabled: {}",
1583 panic_message(payload.as_ref())
1584 );
1585 None
1586 }
1587 };
1588 if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(move || drop(handler))) {
1589 tracing::error!(
1590 "dropping handler {path}.{name} panicked: {}",
1591 panic_message(payload.as_ref())
1592 );
1593 }
1594 result
1595}
1596
1597pub(crate) fn panic_message(payload: &(dyn Any + Send)) -> &str {
1598 if let Some(message) = payload.downcast_ref::<&str>() {
1599 message
1600 } else if let Some(message) = payload.downcast_ref::<String>() {
1601 message
1602 } else {
1603 "(panic payload is not a string)"
1604 }
1605}