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 signal: Option<Signal<bool>>,
308}
309
310impl Press {
311 pub(crate) fn write(self, held: bool) {
313 if let Some(signal) = self.signal
314 && untrack(|| signal.try_get()) != Some(held)
315 {
316 signal.try_set(held);
317 }
318 }
319}
320
321#[derive(Default)]
323pub(crate) struct Pointer {
324 pub(crate) position: Option<Point>,
325 pub(crate) hovered: Option<NodeId>,
327 inside: Vec<(NodeId, Signal<bool>)>,
330 positions: Vec<(NodeId, Signal<Option<Point>>, Point)>,
333 pub(crate) pressed: Option<Press>,
335 link: Option<(NodeId, usize, String)>,
338 link_hover: Option<(NodeId, usize)>,
340 pub(crate) bar: Option<BarDrag>,
342 pub(crate) flick: Option<Flick>,
345 pub(crate) gesture: Option<NodeId>,
347 pub(crate) last_click: Option<(NodeId, u32, Point)>,
350 pub(crate) text_click: Option<TextClick>,
353 wheel: i32,
355 pixels: f32,
356 caused_layout: bool,
358 pub(crate) drop_over: Option<(NodeId, Option<Signal<bool>>)>,
361 pub(crate) incoming: Option<Incoming>,
363}
364
365impl Pointer {
366 pub(crate) fn forget(&mut self, removed: &[NodeId]) {
369 if self.hovered.is_some_and(|id| removed.contains(&id)) {
370 self.hovered = None;
371 }
372 let (gone, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut self.inside)
373 .into_iter()
374 .partition(|(id, _)| removed.contains(id));
375 for (_, signal) in gone {
376 if !kept.iter().any(|(_, other)| *other == signal) {
378 signal.try_set(false);
379 }
380 }
381 self.inside = kept;
382 self.positions.retain(|(id, signal, _)| {
383 let gone = removed.contains(id);
384 if gone {
385 signal.try_set(None);
386 }
387 !gone
388 });
389 let source_gone = self
390 .pressed
391 .is_some_and(|press| removed.contains(&press.id));
392 if source_gone && let Some(press) = self.pressed.take() {
393 press.write(false);
394 }
395 if source_gone || self.drop_over.is_some_and(|(id, _)| removed.contains(&id)) {
396 self.set_drop_over(None);
397 }
398 self.forget_views(removed);
399 if self
400 .last_click
401 .is_some_and(|(id, _, _)| removed.contains(&id))
402 {
403 self.last_click = None;
404 }
405 if self
406 .text_click
407 .is_some_and(|click| removed.contains(&click.id))
408 {
409 self.text_click = None;
410 }
411 }
412}
413
414impl Pointer {
415 fn set_drop_over(&mut self, over: Option<(NodeId, Option<Signal<bool>>)>) {
418 let old = std::mem::replace(&mut self.drop_over, over);
419 if old.map(|(id, _)| id) == over.map(|(id, _)| id) {
420 return;
421 }
422 let (old, new) = (old.and_then(|(_, s)| s), over.and_then(|(_, s)| s));
423 if old != new {
424 if let Some(old) = old {
425 old.try_set(false);
426 }
427 if let Some(new) = new {
428 new.try_set(true);
429 }
430 }
431 }
432}
433
434impl Tree {
435 pub(crate) fn pointer_hide(&mut self, hidden: &[NodeId]) {
438 let held = [
439 self.pointer.hovered,
440 self.pointer.pressed.map(|press| press.id),
441 ];
442 self.pointer.forget(hidden);
443 for id in held.into_iter().flatten().filter(|id| hidden.contains(id)) {
444 self.update_button_style(id, |button| {
445 button.hovered = false;
446 button.pressed = false;
447 });
448 }
449 }
450}
451
452fn now_ms() -> u32 {
455 static START: OnceLock<Instant> = OnceLock::new();
456 START.get_or_init(Instant::now).elapsed().as_millis() as u32
458}
459
460impl Window {
461 pub fn pointer_motion(&self, position: Point) -> CursorShape {
464 self.pointer_motion_at(position, now_ms())
465 }
466
467 pub fn pointer_motion_at(&self, position: Point, time: u32) -> CursorShape {
472 let calls = {
473 let mut tree = borrow(&self.tree);
474 tree.pointer.position = Some(position);
475 tree.bar_motion(position);
476 let calls = if tree.flick_motion(position, time) {
477 Vec::new()
478 } else {
479 tree.drag_motion(position)
480 };
481 tree.hover_at(position);
482 calls
483 };
484 run_all(calls);
485 self.cursor()
486 }
487
488 pub fn pointer_leave(&self) {
491 let calls = borrow(&self.tree).leave();
492 run_all(calls);
493 }
494
495 pub fn pointer_button(&self, button: PointerButton, pressed: bool) {
498 self.pointer_button_at(button, pressed, now_ms());
499 }
500
501 pub fn pointer_button_at(&self, button: PointerButton, pressed: bool, time: u32) {
509 let calls = borrow(&self.tree).button(button, pressed, time, false);
510 run_all(calls);
511 }
512
513 pub fn touch_at(&self, pressed: bool, time: u32) {
518 let calls = borrow(&self.tree).button(PointerButton::Left, pressed, time, true);
519 run_all(calls);
520 }
521
522 pub fn pointer_scroll(&self, wheel: Wheel) {
531 self.pointer_scroll_at(wheel, now_ms());
532 }
533
534 pub fn pointer_scroll_at(&self, wheel: Wheel, time: u32) {
538 let calls = borrow(&self.tree).scroll(wheel, time);
539 run_all(calls);
540 }
541
542 pub fn take_primary(&self) -> Option<Clipboard> {
548 borrow(&self.tree).primary.take()
549 }
550
551 pub fn cursor(&self) -> CursorShape {
553 self.tree.borrow().cursor()
554 }
555}
556
557pub(crate) fn run_all(calls: Vec<Call>) {
559 for call in calls {
560 call.run();
561 }
562}
563
564pub(crate) fn distance(a: Point, b: Point) -> f32 {
565 (a.x - b.x).hypot(a.y - b.y)
566}
567
568impl Tree {
569 fn hit(
576 &self,
577 id: NodeId,
578 point: Point,
579 path: &mut Vec<NodeId>,
580 skip: Option<NodeId>,
581 ) -> Option<NodeId> {
582 if skip == Some(id) {
583 return None;
584 }
585 let node = self.node(id)?;
586 let point = local(node, point)?;
587 let rect = node.rect?;
588 if !node.inner_bounds.contains(point) {
591 return None;
592 }
593 let style = node.effective_style();
594 let border = style.border.map_or(0.0, |border| border.width.max(0.0));
596 let corners = style.radius.unwrap_or_default();
597 let children = if node.clips() && !corners.contains(rect, border, point) {
598 Vec::new()
599 } else {
600 self.drawn_children(id)
601 };
602 path.push(id);
603 if let Some(hit) = children
604 .into_iter()
605 .rev()
606 .find_map(|child| self.hit(child, point, path, skip))
607 {
608 return Some(hit);
609 }
610 let takes = match &node.kind {
611 NodeKind::Button(button) => button.enabled,
612 NodeKind::Input(_) => true,
613 NodeKind::Text(text) => text.selectable,
614 _ => false,
615 };
616 if rect.contains(point) && takes {
617 return Some(id);
618 }
619 if matches!(&node.kind, NodeKind::Text(text) if text.link_at(point).is_some()) {
621 return Some(id);
622 }
623 path.pop();
624 None
625 }
626
627 pub(crate) fn hover_at(&mut self, point: Point) {
631 let mut path = Vec::new();
632 let hit = match self.pointer.pressed.filter(|press| press.dragging) {
633 Some(press) => {
634 path = self.path_to(press.id);
635 Some(press.id)
636 }
637 None => self.hit(self.root, point, &mut path, None),
638 };
639 self.set_hovered(hit, &path);
640 self.set_positions(&path, Some(point));
641 self.update_drop();
642 self.hover_link();
643 }
644
645 fn hover_link(&mut self) {
647 let now = self.pointer.hovered.zip(self.link_under_pointer());
648 let old = std::mem::replace(&mut self.pointer.link_hover, now);
649 if old == now {
650 return;
651 }
652 if let Some((id, _)) = old {
653 self.light_link(id, false, None);
654 }
655 if let Some((id, index)) = now {
656 self.light_link(id, false, Some(index));
657 }
658 }
659
660 pub(crate) fn light_link(&mut self, id: NodeId, focus: bool, index: Option<usize>) {
664 let Some(node) = self.node_mut(id) else {
665 return;
666 };
667 let laid_out = node.rect.is_some();
668 let NodeKind::Text(text) = &mut node.kind else {
669 return;
670 };
671 let slot = match focus {
672 true => &mut text.focused_link,
673 false => &mut text.hovered_link,
674 };
675 let old = std::mem::replace(slot, index);
676 if old == index || !laid_out {
677 return;
678 }
679 let areas: Vec<Rect> = old
680 .into_iter()
681 .chain(index)
682 .flat_map(|index| text.link_areas(index))
683 .collect();
684 for area in areas {
685 let area = self.window_area(id, area);
686 add_damage(&mut self.damage, area);
687 }
688 }
689
690 fn drag_type(&self, id: NodeId) -> Option<TypeId> {
692 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
693 return None;
694 };
695 let data = button.drag_data?;
696 untrack(|| data.try_with(|data| data.as_ref().map(|value| (**value).type_id()))).flatten()
698 }
699
700 pub(crate) fn drop_target(&self) -> Option<NodeId> {
704 let press = self.pointer.pressed.filter(|press| press.dragging);
705 let (carried, at) = match self.pointer.incoming {
706 Some(incoming) => (incoming.carried, incoming.at),
707 None => (self.drag_type(press?.id)?, self.pointer.position?),
708 };
709 let mut path = Vec::new();
710 self.hit(self.root, at, &mut path, press.map(|press| press.id))?;
711 path.into_iter().rev().find(|&id| {
712 self.enabled(id)
713 && self.has(id, |h| {
714 h.drop
716 .as_ref()
717 .is_some_and(|target| target.accepts == carried && !target.handler.disabled.get())
718 })
719 })
720 }
721
722 pub(crate) fn update_drop(&mut self) {
725 let over = self.drop_target().map(|id| {
726 let signal = match self.node(id).map(|node| &node.kind) {
727 Some(NodeKind::Button(button)) => button.drop_hovered,
728 _ => None,
729 };
730 (id, signal)
731 });
732 self.pointer.set_drop_over(over);
733 }
734
735 pub(crate) fn drop_after_place(&mut self) {
738 if self.pointer.incoming.is_some() || self.pointer.pressed.is_some_and(|press| press.dragging) {
739 self.update_drop();
740 }
741 }
742
743 fn drags(&self, id: NodeId) -> bool {
746 self.selects(id) || self.drag_type(id).is_some() || self.has(id, |h| h.drag.is_some())
747 }
748
749 pub(crate) fn path_to(&self, id: NodeId) -> Vec<NodeId> {
751 let mut path = vec![id];
752 while let Some(parent) = path.last().and_then(|&id| self.taffy.parent(id)) {
753 path.push(parent);
754 }
755 path.reverse();
756 path
757 }
758
759 fn cursor(&self) -> CursorShape {
760 let dragged = self
763 .pointer
764 .pressed
765 .filter(|press| press.dragging)
766 .and_then(|press| match self.node(press.id).map(|node| &node.kind) {
767 Some(NodeKind::Button(button)) => Some(button.cursor),
768 _ => None,
769 });
770 if let Some(shape) = dragged {
771 return match shape {
772 CursorShape::Pointer | CursorShape::Grab => CursorShape::Grabbing,
773 shape => shape,
774 };
775 }
776 match self
777 .pointer
778 .hovered
779 .and_then(|id| self.node(id))
780 .map(|node| &node.kind)
781 {
782 Some(NodeKind::Text(_)) if self.link_under_pointer().is_some() => CursorShape::Pointer,
783 Some(NodeKind::Input(_) | NodeKind::Text(_)) => CursorShape::Text,
784 Some(NodeKind::Button(button)) => button.cursor,
785 _ => CursorShape::Default,
786 }
787 }
788
789 pub(crate) fn pointer_after_layout(&mut self) {
794 if std::mem::take(&mut self.pointer.caused_layout) {
795 return;
796 }
797 if let Some(position) = self.pointer.position {
798 self.hover_at(position);
799 }
800 }
801
802 fn set_hovered(&mut self, hovered: Option<NodeId>, path: &[NodeId]) {
805 self.set_inside(path);
806 let old = self.pointer.hovered;
807 if old == hovered {
808 return;
809 }
810 self.pointer.hovered = hovered;
811 self.pointer.wheel = 0;
812 self.pointer.pixels = 0.0;
813 if let Some(old) = old {
814 self.set_button_state(old, |button| button.hovered = false);
815 }
816 if let Some(new) = hovered {
817 self.set_button_state(new, |button| button.hovered = true);
818 }
819 }
820
821 fn path_buttons<T>(
823 &self,
824 path: &[NodeId],
825 pick: impl Fn(&ButtonNode) -> Option<T>,
826 ) -> Vec<(NodeId, T)> {
827 path
828 .iter()
829 .filter_map(|&id| match &self.node(id)?.kind {
830 NodeKind::Button(button) if button.enabled => Some((id, pick(button)?)),
831 _ => None,
832 })
833 .collect()
834 }
835
836 fn set_inside(&mut self, path: &[NodeId]) {
839 let inside = self.path_buttons(path, |button| button.hover_signal);
840 let holds = |list: &[(NodeId, Signal<bool>)], signal| list.iter().any(|(_, s)| *s == signal);
843 let mut seen = Vec::new();
844 for &(_, signal) in self.pointer.inside.iter().chain(&inside) {
845 if seen.contains(&signal) {
846 continue;
847 }
848 seen.push(signal);
849 let now = holds(&inside, signal);
850 if holds(&self.pointer.inside, signal) != now {
851 signal.try_set(now);
852 }
853 }
854 self.pointer.inside = inside;
855 }
856
857 fn set_positions(&mut self, path: &[NodeId], at: Option<Point>) {
861 let now: Vec<(NodeId, Signal<Option<Point>>, Point)> = match at {
862 Some(at) => self
863 .path_buttons(path, |button| button.position_signal)
864 .into_iter()
865 .filter_map(|(id, signal)| Some((id, signal, self.button_local(id, at)?)))
866 .collect(),
867 None => Vec::new(),
868 };
869 for (id, signal, _) in &self.pointer.positions {
870 if !now.iter().any(|(other, ..)| other == id) {
871 signal.try_set(None);
872 }
873 }
874 for &(id, signal, point) in &now {
875 let same = |&(other, _, was): &(NodeId, _, Point)| other == id && was == point;
876 if !self.pointer.positions.iter().any(same) {
877 signal.try_set(Some(point));
878 }
879 }
880 self.pointer.positions = now;
881 }
882
883 fn button_local(&self, id: NodeId, point: Point) -> Option<Point> {
886 let rect = self.node(id)?.rect?;
887 let point = self.local_point(id, point)?;
888 Some(Point::new(point.x - rect.x, point.y - rect.y))
889 }
890
891 fn set_pressed(&mut self, pressed: Option<Press>) {
892 let old = std::mem::replace(&mut self.pointer.pressed, pressed);
893 if let Some(old) = old {
894 old.write(false);
895 self.set_button_state(old.id, |button| button.pressed = false);
896 }
897 if let Some(new) = pressed {
898 new.write(true);
899 self.set_button_state(new.id, |button| button.pressed = true);
900 }
901 }
902
903 fn set_button_state(&mut self, id: NodeId, f: impl FnOnce(&mut ButtonNode)) {
906 if self.update_button_style(id, f) == Change::Layout {
907 self.pointer.caused_layout = true;
908 }
909 }
910
911 fn button(&mut self, button: PointerButton, pressed: bool, time: u32, touch: bool) -> Vec<Call> {
912 if pressed {
913 self.press(button, time, touch)
914 } else {
915 self.release(button, time)
916 }
917 }
918
919 fn press(&mut self, button: PointerButton, time: u32, touch: bool) -> Vec<Call> {
920 if button == PointerButton::Left {
921 self.press_away(self.pointer.hovered);
922 }
923 if let (PointerButton::Left, None, Some(at)) =
925 (button, self.pointer.pressed, self.pointer.position)
926 && self.press_bar(at)
927 {
928 return Vec::new();
929 }
930 if let (PointerButton::Left, None, Some(at)) =
931 (button, self.pointer.pressed, self.pointer.position)
932 {
933 let drags = self.pointer.hovered.is_some_and(|id| self.drags(id));
934 self.press_views(at, drags, touch);
935 }
936 let (None, Some(id), Some(at)) = (
937 self.pointer.pressed,
938 self.pointer.hovered,
939 self.pointer.position,
940 ) else {
941 return Vec::new();
942 };
943 let start = self.button_local(id, at).unwrap_or_default();
944 let signal = match &self.node(id).map(|node| &node.kind) {
945 Some(NodeKind::Button(node)) if button == PointerButton::Left => node.pressed_signal,
946 _ => None,
947 };
948 self.set_pressed(Some(Press {
949 id,
950 button,
951 at,
952 last: at,
953 start,
954 dragging: false,
955 long_pressed: false,
956 out: false,
957 signal,
958 }));
959 if button == PointerButton::Middle && self.press_middle(id, at) {
960 self.primary = Some(Clipboard::Paste);
961 }
962 if button != PointerButton::Left {
963 return Vec::new();
964 }
965 self.pointer.link = self.link_under(id, at);
966 if self.selects(id) {
967 self.press_text(id, at, time);
968 }
969 let mut calls: Vec<Call> = self.call(id, Action::Press).into_iter().collect();
970 if self.has(id, |h| h.long_press.is_some()) {
971 self.arm_long_press(id);
972 }
973 let waits =
975 |h: &Handlers| h.click.is_some() || h.double_click.is_some() || h.long_press.is_some();
976 if self.drags(id) && !self.has(id, waits) {
977 calls.extend(self.start_drag(at));
978 }
979 calls
980 }
981
982 fn release(&mut self, button: PointerButton, time: u32) -> Vec<Call> {
983 if button == PointerButton::Left {
984 self.release_bar();
985 self.flick_release(Some(time));
986 }
987 let Some(press) = self.pointer.pressed.filter(|press| press.button == button) else {
988 return Vec::new();
989 };
990 let mut calls = Vec::new();
991 if button == PointerButton::Left {
992 calls.extend(self.call(press.id, Action::Release));
993 let link = self.pointer.link.take();
994 calls.extend(link.and_then(|link| self.link_click(press, link)));
995 if let Some(text) = self.selected_text(press.id) {
997 self.primary = Some(Clipboard::Copy(text));
998 }
999 }
1000 let landed = Rc::new(Cell::new(false));
1002 calls.extend(self.drop_call(&landed));
1003 calls.extend(self.end_press(Some(landed)));
1004 if press.dragging {
1005 if let Some(at) = self.pointer.position {
1007 self.hover_at(at);
1008 }
1009 return calls;
1010 }
1011 if press.long_pressed || self.pointer.hovered != Some(press.id) {
1012 return calls;
1013 }
1014 let action = match button {
1015 PointerButton::Left => self.left_click(press.id, time, press.at),
1016 PointerButton::Right => Action::RightClick,
1017 PointerButton::Middle => Action::MiddleClick,
1018 PointerButton::Back => Action::Back,
1019 PointerButton::Forward => Action::Forward,
1020 };
1021 calls.extend(self.call(press.id, action));
1022 calls
1023 }
1024
1025 fn link_under_pointer(&self) -> Option<usize> {
1027 let id = self.pointer.hovered?;
1028 let NodeKind::Text(text) = &self.node(id)?.kind else {
1029 return None;
1030 };
1031 text.link_at(self.local_point(id, self.pointer.position?)?)
1032 }
1033
1034 fn link_under(&self, id: NodeId, at: Point) -> Option<(NodeId, usize, String)> {
1037 let NodeKind::Text(text) = &self.node(id)?.kind else {
1038 return None;
1039 };
1040 let index = text.link_at(self.local_point(id, at)?)?;
1041 Some((id, index, text.spans[index].link.clone()?))
1042 }
1043
1044 fn link_click(&self, press: Press, pressed: (NodeId, usize, String)) -> Option<Call> {
1049 let node = self.node(press.id)?;
1050 let NodeKind::Text(text) = &node.kind else {
1051 return None;
1052 };
1053 if text_selection(text).is_some() {
1054 return None;
1055 }
1056 let released = self.link_under(press.id, self.pointer.position?)?;
1057 if pressed != released {
1058 return None;
1059 }
1060 self.link_call(press.id, released.1)
1061 }
1062
1063 pub(crate) fn link_call(&self, id: NodeId, index: usize) -> Option<Call> {
1066 let node = self.node(id)?;
1067 let NodeKind::Text(text) = &node.kind else {
1068 return None;
1069 };
1070 let handler = text.on_link.clone().filter(|handler| !handler.disabled())?;
1071 let url = text.spans.get(index)?.link.clone()?;
1072 Some(Call {
1073 cx: node.cx.clone(),
1074 path: Rc::clone(&node.path),
1075 handlers: None,
1076 action: Action::Link(handler, url, self.this.clone(), id),
1077 })
1078 }
1079
1080 fn left_click(&mut self, id: NodeId, time: u32, at: Point) -> Action {
1084 let close = self.pointer.last_click.is_some_and(|(last, then, place)| {
1085 last == id
1086 && time.wrapping_sub(then) <= DOUBLE_CLICK_MS
1087 && distance(place, at) <= DOUBLE_CLICK_DISTANCE
1088 });
1089 if close && self.has(id, |h| h.double_click.is_some()) {
1090 self.pointer.last_click = None;
1091 Action::DoubleClick
1092 } else {
1093 self.pointer.last_click = Some((id, time, at));
1094 Action::Click
1095 }
1096 }
1097
1098 fn drop_call(&self, landed: &Rc<Cell<bool>>) -> Option<Call> {
1101 let target = self.drop_target()?;
1102 let value = self.drag_value(self.pointer.pressed?.id)?;
1103 self.call(target, Action::Drop(value, Rc::clone(landed)))
1104 }
1105
1106 pub(crate) fn drag_value(&self, id: NodeId) -> Option<DragValue> {
1108 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
1109 return None;
1110 };
1111 untrack(|| button.drag_data?.try_get().flatten())
1112 }
1113
1114 pub(crate) fn end_press(&mut self, landed: Option<Rc<Cell<bool>>>) -> Option<Call> {
1118 let press = self.pointer.pressed?;
1119 self.set_pressed(None);
1120 self.update_drop();
1121 self.stop_long_press(press.id);
1122 if press.dragging {
1123 self.drag_call(press, DragPhase::End, press.last, landed)
1124 } else {
1125 None
1126 }
1127 }
1128
1129 fn drag_motion(&mut self, at: Point) -> Vec<Call> {
1132 let Some(press) = self.pointer.pressed.as_mut() else {
1133 return Vec::new();
1134 };
1135 press.last = at;
1136 let press = *press;
1137 if press.button != PointerButton::Left {
1138 return Vec::new();
1139 }
1140 if press.dragging && self.selects(press.id) {
1141 self.drag_text(press.id, at);
1142 return Vec::new();
1143 }
1144 if press.dragging {
1145 return self
1146 .drag_call(press, DragPhase::Move, at, None)
1147 .into_iter()
1148 .collect();
1149 }
1150 if distance(press.at, at) <= DRAG_THRESHOLD {
1151 return Vec::new();
1152 }
1153 self.stop_long_press(press.id);
1154 if self.drags(press.id) {
1155 self.start_drag(at)
1156 } else {
1157 Vec::new()
1158 }
1159 }
1160
1161 fn start_drag(&mut self, at: Point) -> Vec<Call> {
1163 let Some(press) = self.pointer.pressed.as_mut() else {
1164 return Vec::new();
1165 };
1166 press.dragging = true;
1167 let press = *press;
1168 self.stop_long_press(press.id);
1169 self.update_drop();
1170 self
1171 .drag_call(press, DragPhase::Start, at, None)
1172 .into_iter()
1173 .collect()
1174 }
1175
1176 pub(crate) fn drag_call(
1177 &self,
1178 press: Press,
1179 phase: DragPhase,
1180 at: Point,
1181 landed: Option<Rc<Cell<bool>>>,
1182 ) -> Option<Call> {
1183 let rect = self.node(press.id)?.rect?;
1184 let drag = Drag {
1185 phase,
1186 start: press.start,
1187 position: self.button_local(press.id, at).unwrap_or(press.start),
1190 size: Size::new(rect.width, rect.height),
1191 dropped: false,
1192 };
1193 self.call(press.id, Action::Drag(drag, landed))
1194 }
1195
1196 fn arm_long_press(&mut self, id: NodeId) {
1199 let tree = self.this.clone();
1200 let Some(Node { cx, kind, .. }) = self.node_mut(id) else {
1201 return;
1202 };
1203 let NodeKind::Button(button) = kind else {
1204 return;
1205 };
1206 match button.long_press {
1207 Some(timer) => timer.restart(),
1208 None => {
1209 let timer = cx.after(LONG_PRESS, move || long_press_fired(&tree, id));
1210 button.long_press = Some(timer);
1211 }
1212 }
1213 }
1214
1215 fn stop_long_press(&self, id: NodeId) {
1216 if let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind)
1217 && let Some(timer) = button.long_press
1218 {
1219 timer.stop();
1220 }
1221 }
1222
1223 fn long_press(&mut self, id: NodeId) -> Option<Call> {
1225 let press = self.pointer.pressed.as_mut().filter(|press| {
1226 press.id == id
1227 && press.button == PointerButton::Left
1228 && !press.dragging
1229 && !press.long_pressed
1230 })?;
1231 press.long_pressed = true;
1232 self.call(id, Action::LongPress)
1233 }
1234
1235 pub(crate) fn leave(&mut self) -> Vec<Call> {
1238 self.pointer.position = None;
1239 self.release_bar();
1240 self.flick_release(None);
1241 if let Some(id) = self.pointer.gesture.take() {
1242 self.release_view(id, None);
1243 }
1244 let out = self.pointer.pressed.is_some_and(|press| press.out);
1246 let calls = match out {
1247 true => Vec::new(),
1248 false => self.end_press(None).into_iter().collect(),
1249 };
1250 self.set_hovered(None, &[]);
1251 self.set_positions(&[], None);
1252 self.hover_link();
1253 calls
1254 }
1255
1256 pub(crate) fn set_enabled(&mut self, id: NodeId, enabled: bool) -> Vec<Call> {
1260 let Some(NodeKind::Button(button)) = self.node_mut(id).map(|node| &mut node.kind) else {
1261 return Vec::new();
1262 };
1263 if std::mem::replace(&mut button.enabled, enabled) == enabled {
1264 return Vec::new();
1265 }
1266 self.node_event(id, |id| AccessEvent::Enabled(id, enabled));
1267 let mut calls = Vec::new();
1268 if !enabled {
1269 if self.pointer.pressed.is_some_and(|press| press.id == id) {
1270 calls.extend(self.end_press(None));
1271 }
1272 if self.keyboard.focused == Some(id) {
1273 self.focus(None);
1274 }
1275 }
1276 if let Some(at) = self.pointer.position {
1277 self.hover_at(at);
1278 }
1279 calls
1280 }
1281
1282 pub(crate) fn bind_enabled(&mut self, id: NodeId, prop: Prop<bool>) {
1285 let mut compute = match prop.0 {
1286 PropKind::Value(enabled) => {
1288 self.set_enabled(id, enabled);
1289 return;
1290 }
1291 PropKind::Binding(compute) => compute,
1292 };
1293 let Some(node) = self.node(id) else {
1294 return;
1295 };
1296 let label = format!("{}.enabled", node.path);
1297 let tree = self.this.clone();
1298 node
1299 .cx
1300 .effect(move || {
1301 let enabled = compute();
1302 let Some(tree) = tree.upgrade() else {
1303 return;
1304 };
1305 let calls = borrow(&tree).set_enabled(id, enabled);
1306 untrack(|| run_all(calls));
1308 })
1309 .named(label);
1310 }
1311
1312 pub(crate) fn enabled(&self, id: NodeId) -> bool {
1314 match self.node(id).map(|node| &node.kind) {
1315 Some(NodeKind::Button(button)) => button.enabled,
1316 _ => true,
1317 }
1318 }
1319
1320 fn scroll(&mut self, wheel: Wheel, time: u32) -> Vec<Call> {
1321 let wants = |h: &Handlers| h.scroll.is_some() || h.wheel.is_some();
1322 let target = self.pointer.hovered.filter(|&id| self.has(id, wants));
1323 let calls = match target {
1324 None => {
1325 self.scroll_view(wheel, time);
1326 Vec::new()
1327 }
1328 Some(target) => {
1329 let mut calls = Vec::new();
1330 if self.has(target, |h| h.wheel.is_some()) {
1331 calls.extend(self.call(target, Action::Wheel(wheel)));
1332 }
1333 if self.has(target, |h| h.scroll.is_some()) {
1334 let down = self.steps(wheel.y);
1335 if down != 0 {
1337 calls.extend(self.call(target, Action::Scroll(down.saturating_neg())));
1338 }
1339 }
1340 calls
1341 }
1342 };
1343 if wheel.y.stop {
1344 self.pointer.pixels = 0.0;
1345 }
1346 if wheel.source == ScrollSource::Finger
1350 && (wheel.x.stop || wheel.y.stop)
1351 && let Some(id) = self.pointer.gesture.take()
1352 {
1353 self.release_view(id, Some(time));
1354 }
1355 calls
1356 }
1357
1358 fn steps(&mut self, axis: WheelAxis) -> i32 {
1361 if axis.notches != 0.0 && axis.notches.is_finite() {
1362 let value120 = (axis.notches * VALUE120_PER_STEP as f32).round() as i32;
1364 self.pointer.wheel = self.pointer.wheel.saturating_add(value120);
1365 let steps = self.pointer.wheel / VALUE120_PER_STEP;
1366 self.pointer.wheel -= steps * VALUE120_PER_STEP;
1367 steps
1368 } else if axis.pixels.is_finite() {
1369 self.pointer.pixels += axis.pixels;
1370 let steps = (self.pointer.pixels / PIXELS_PER_STEP).trunc();
1371 self.pointer.pixels -= steps * PIXELS_PER_STEP;
1372 steps as i32
1373 } else {
1374 0
1375 }
1376 }
1377
1378 pub(crate) fn cancel_press(&mut self) {
1381 if let Some(press) = self.pointer.pressed.filter(|press| !press.dragging) {
1382 self.set_pressed(None);
1383 self.stop_long_press(press.id);
1384 }
1385 }
1386
1387 pub(crate) fn has(&self, id: NodeId, f: impl FnOnce(&Handlers) -> bool) -> bool {
1389 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
1390 return false;
1391 };
1392 untrack(|| button.handlers.try_with(f)).unwrap_or(false)
1393 }
1394
1395 pub(crate) fn local_point(&self, id: NodeId, point: Point) -> Option<Point> {
1399 self
1400 .path_to(id)
1401 .iter()
1402 .try_fold(point, |point, &id| local(self.node(id)?, point))
1403 }
1404
1405 pub(crate) fn window_rect(&self, id: NodeId, rect: Rect) -> Rect {
1409 let mut rect = rect;
1410 let mut at = Some(id);
1411 while let Some(current) = at {
1412 if let Some(transform) = self.node(current).and_then(|node| node.transform) {
1413 rect = transform.map_rect(rect);
1414 }
1415 at = self.taffy.parent(current);
1416 }
1417 rect
1418 }
1419
1420 pub(crate) fn click(&self, id: NodeId) -> Option<Call> {
1422 self.call(id, Action::Click)
1423 }
1424
1425 pub(crate) fn call(&self, id: NodeId, action: Action) -> Option<Call> {
1426 let node = self.node(id)?;
1427 let NodeKind::Button(button) = &node.kind else {
1428 return None;
1429 };
1430 Some(Call {
1431 cx: node.cx.clone(),
1432 path: Rc::clone(&node.path),
1433 handlers: Some(button.handlers),
1434 action,
1435 })
1436 }
1437}
1438
1439fn long_press_fired(tree: &Weak<RefCell<Tree>>, id: NodeId) {
1441 let Some(tree) = tree.upgrade() else {
1442 return;
1443 };
1444 let Ok(mut borrowed) = tree.try_borrow_mut() else {
1446 return;
1447 };
1448 let call = borrowed.long_press(id);
1449 drop(borrowed);
1450 if let Some(call) = call {
1451 call.run();
1452 }
1453}
1454
1455pub(crate) fn local(node: &Node, point: Point) -> Option<Point> {
1459 match node.transform {
1460 Some(transform) => Some(transform.invert()?.map(point)),
1461 None => Some(point),
1462 }
1463}
1464
1465#[derive(Clone)]
1466pub(crate) enum Action {
1467 Click,
1468 Press,
1469 Release,
1470 DoubleClick,
1471 LongPress,
1472 RightClick,
1473 MiddleClick,
1474 Back,
1475 Forward,
1476 Scroll(i32),
1477 Wheel(Wheel),
1478 Drag(Drag, Option<Rc<Cell<bool>>>),
1480 Drop(DragValue, Rc<Cell<bool>>),
1482 Link(LinkHandler, String, Weak<RefCell<Tree>>, NodeId),
1485}
1486
1487pub(crate) struct Call {
1489 cx: Cx,
1490 path: Rc<str>,
1491 handlers: Option<Signal<Handlers>>,
1493 action: Action,
1494}
1495
1496enum Picked {
1498 Plain(ClickHandler, &'static str),
1499 Scroll(ScrollHandler, i32),
1500 Wheel(WheelHandler, Wheel),
1501 Drag(DragHandler, Drag),
1502 Drop(DropHandler, &'static str, DragValue, Rc<Cell<bool>>),
1503}
1504
1505impl Call {
1506 pub(crate) fn run(self) {
1507 let (path, cx) = (&self.path, &self.cx);
1508 if let Action::Link(handler, url, tree, id) = &self.action {
1509 run_isolated(path, "on_link", Rc::clone(handler), |f| f(cx, url));
1510 if handler.disabled()
1512 && let Some(tree) = tree.upgrade()
1513 && let Ok(mut tree) = tree.try_borrow_mut()
1514 {
1515 tree.light_link(*id, false, None);
1516 tree.light_link(*id, true, None);
1517 }
1518 return;
1519 }
1520 let Some(handlers) = self.handlers else {
1521 return;
1522 };
1523 let picked = untrack(|| {
1525 handlers.try_with(|h| {
1526 let plain = |handler: &Option<ClickHandler>, name| {
1527 handler.clone().map(|handler| Picked::Plain(handler, name))
1528 };
1529 match &self.action {
1530 Action::Click => plain(&h.click, "on_click"),
1531 Action::Press => plain(&h.press, "on_press"),
1532 Action::Release => plain(&h.release, "on_release"),
1533 Action::DoubleClick => plain(&h.double_click, "on_double_click"),
1534 Action::LongPress => plain(&h.long_press, "on_long_press"),
1535 Action::RightClick => plain(&h.right_click, "on_right_click"),
1536 Action::MiddleClick => plain(&h.middle_click, "on_middle_click"),
1537 Action::Back => plain(&h.back, "on_back"),
1538 Action::Forward => plain(&h.forward, "on_forward"),
1539 Action::Scroll(steps) => h.scroll.clone().map(|f| Picked::Scroll(f, *steps)),
1540 Action::Wheel(wheel) => h.wheel.clone().map(|f| Picked::Wheel(f, *wheel)),
1541 Action::Drag(drag, landed) => {
1542 let drag = Drag {
1543 dropped: landed.as_ref().is_some_and(|landed| landed.get()),
1544 ..*drag
1545 };
1546 h.drag.clone().map(|f| Picked::Drag(f, drag))
1547 }
1548 Action::Drop(value, landed) => {
1549 let target = h.drop.as_ref()?;
1550 Some(Picked::Drop(
1551 target.handler.clone(),
1552 target.name,
1553 Rc::clone(value),
1554 Rc::clone(landed),
1555 ))
1556 }
1557 Action::Link(..) => None,
1558 }
1559 })
1560 });
1561 let Some(Some(picked)) = picked else {
1562 return;
1563 };
1564 match picked {
1565 Picked::Plain(handler, name) => {
1566 run_isolated(path, name, handler, |f| f(cx));
1567 }
1568 Picked::Scroll(handler, steps) => {
1569 run_isolated(path, "on_scroll", handler, |f| f(cx, steps));
1570 }
1571 Picked::Wheel(handler, wheel) => {
1572 run_isolated(path, "on_wheel", handler, |f| f(cx, wheel));
1573 }
1574 Picked::Drag(handler, drag) => {
1575 run_isolated(path, "on_drag", handler, |f| f(cx, drag));
1576 }
1577 Picked::Drop(handler, name, value, landed) => {
1579 let ran = run_isolated(path, name, handler, move |f| f(cx, &*value));
1580 landed.set(ran.is_some());
1581 }
1582 }
1583 }
1584}
1585
1586pub(crate) fn run_isolated<F: ?Sized, R>(
1591 path: &str,
1592 name: &str,
1593 handler: Rc<Handler<F>>,
1594 call: impl FnOnce(&F) -> R,
1595) -> Option<R> {
1596 if handler.disabled.get() {
1597 return None;
1598 }
1599 let result = match panic::catch_unwind(AssertUnwindSafe(|| call(&handler.f))) {
1600 Ok(result) => Some(result),
1601 Err(payload) => {
1602 handler.disabled.set(true);
1603 tracing::error!(
1604 "handler {path}.{name} panicked and is disabled: {}",
1605 panic_message(payload.as_ref())
1606 );
1607 None
1608 }
1609 };
1610 if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(move || drop(handler))) {
1611 tracing::error!(
1612 "dropping handler {path}.{name} panicked: {}",
1613 panic_message(payload.as_ref())
1614 );
1615 }
1616 result
1617}
1618
1619pub(crate) fn panic_message(payload: &(dyn Any + Send)) -> &str {
1620 if let Some(message) = payload.downcast_ref::<&str>() {
1621 message
1622 } else if let Some(message) = payload.downcast_ref::<String>() {
1623 message
1624 } else {
1625 "(panic payload is not a string)"
1626 }
1627}