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 AnyPressHandler = Rc<Handler<dyn Fn(&Cx, PointerButton)>>;
77pub(crate) type DragHandler = Rc<Handler<dyn Fn(&Cx, Drag)>>;
78pub(crate) type LinkHandler = Rc<Handler<dyn Fn(&Cx, &str)>>;
79
80pub(crate) type DragValue = Rc<dyn Any>;
84
85pub(crate) struct DropTarget {
87 pub(crate) accepts: TypeId,
88 pub(crate) handler: DropHandler,
89 pub(crate) name: &'static str,
91}
92
93pub(crate) type DropHandler = Rc<Handler<dyn Fn(&Cx, &dyn Any)>>;
95
96#[derive(Default)]
98pub(crate) struct Handlers {
99 pub(crate) click: Option<ClickHandler>,
100 pub(crate) press: Option<ClickHandler>,
101 pub(crate) any_press: Option<AnyPressHandler>,
102 pub(crate) release: Option<ClickHandler>,
103 pub(crate) double_click: Option<ClickHandler>,
104 pub(crate) long_press: Option<ClickHandler>,
105 pub(crate) right_click: Option<ClickHandler>,
106 pub(crate) middle_click: Option<ClickHandler>,
107 pub(crate) back: Option<ClickHandler>,
108 pub(crate) forward: Option<ClickHandler>,
109 pub(crate) scroll: Option<ScrollHandler>,
110 pub(crate) wheel: Option<WheelHandler>,
111 pub(crate) drag: Option<DragHandler>,
112 pub(crate) drop: Option<DropTarget>,
113 pub(crate) key: Option<KeyHandler>,
114}
115
116#[derive(Clone, Copy, Debug, PartialEq, Eq)]
118pub enum PointerButton {
119 Left,
121 Right,
123 Middle,
125 Back,
128 Forward,
131}
132
133#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
135pub enum ScrollSource {
136 #[default]
138 Wheel,
139 Finger,
142 Continuous,
144 WheelTilt,
146}
147
148#[derive(Clone, Copy, Debug, Default, PartialEq)]
150pub struct WheelAxis {
151 pub pixels: f32,
154 pub notches: f32,
158 pub stop: bool,
161}
162
163#[derive(Clone, Copy, Debug, Default, PartialEq)]
166pub struct Wheel {
167 pub source: ScrollSource,
169 pub x: WheelAxis,
171 pub y: WheelAxis,
173}
174
175#[derive(Clone, Copy, Debug, PartialEq, Eq)]
177pub enum DragPhase {
178 Start,
181 Move,
183 End,
186}
187
188#[derive(Clone, Copy, Debug, PartialEq)]
193pub struct Drag {
194 pub phase: DragPhase,
196 pub start: Point,
198 pub position: Point,
201 pub size: Size,
203 pub dropped: bool,
207}
208
209#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
212pub enum CursorShape {
213 #[default]
215 Default,
216 ContextMenu,
218 Help,
220 Pointer,
222 Progress,
224 Wait,
226 Cell,
228 Crosshair,
230 Text,
232 VerticalText,
234 Alias,
236 Copy,
238 Move,
240 NoDrop,
242 NotAllowed,
244 Grab,
246 Grabbing,
248 EResize,
250 NResize,
252 NeResize,
254 NwResize,
256 SResize,
258 SeResize,
260 SwResize,
262 WResize,
264 EwResize,
266 NsResize,
268 NeswResize,
270 NwseResize,
272 ColResize,
274 RowResize,
276 AllScroll,
278 ZoomIn,
280 ZoomOut,
282 DndAsk,
285 AllResize,
288}
289
290#[derive(Clone, Copy)]
292pub(crate) struct Press {
293 pub(crate) id: NodeId,
294 pub(crate) button: PointerButton,
295 at: Point,
298 pub(crate) last: Point,
299 start: Point,
301 pub(crate) dragging: bool,
303 long_pressed: bool,
305 pub(crate) out: bool,
308 signal: Option<Signal<bool>>,
310}
311
312impl Press {
313 pub(crate) fn write(self, held: bool) {
315 if let Some(signal) = self.signal
316 && untrack(|| signal.try_get()) != Some(held)
317 {
318 signal.try_set(held);
319 }
320 }
321}
322
323#[derive(Default)]
325pub(crate) struct Pointer {
326 pub(crate) position: Option<Point>,
327 pub(crate) hovered: Option<NodeId>,
329 inside: Vec<(NodeId, Signal<bool>)>,
332 positions: Vec<(NodeId, Signal<Option<Point>>, Point)>,
335 pub(crate) pressed: Option<Press>,
337 link: Option<(NodeId, usize, String)>,
340 link_hover: Option<(NodeId, usize)>,
342 pub(crate) bar: Option<BarDrag>,
344 pub(crate) flick: Option<Flick>,
347 pub(crate) gesture: Option<NodeId>,
349 pub(crate) last_click: Option<(NodeId, u32, Point)>,
352 pub(crate) text_click: Option<TextClick>,
355 wheel: i32,
357 pixels: f32,
358 caused_layout: bool,
360 pub(crate) drop_over: Option<(NodeId, Option<Signal<bool>>)>,
363 pub(crate) incoming: Option<Incoming>,
365}
366
367impl Pointer {
368 pub(crate) fn forget(&mut self, removed: &[NodeId]) {
371 if self.hovered.is_some_and(|id| removed.contains(&id)) {
372 self.hovered = None;
373 }
374 let (gone, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut self.inside)
375 .into_iter()
376 .partition(|(id, _)| removed.contains(id));
377 for (_, signal) in gone {
378 if !kept.iter().any(|(_, other)| *other == signal) {
380 signal.try_set(false);
381 }
382 }
383 self.inside = kept;
384 self.positions.retain(|(id, signal, _)| {
385 let gone = removed.contains(id);
386 if gone {
387 signal.try_set(None);
388 }
389 !gone
390 });
391 let source_gone = self
392 .pressed
393 .is_some_and(|press| removed.contains(&press.id));
394 if source_gone && let Some(press) = self.pressed.take() {
395 press.write(false);
396 }
397 if source_gone || self.drop_over.is_some_and(|(id, _)| removed.contains(&id)) {
398 self.set_drop_over(None);
399 }
400 self.forget_views(removed);
401 if self
402 .last_click
403 .is_some_and(|(id, _, _)| removed.contains(&id))
404 {
405 self.last_click = None;
406 }
407 if self
408 .text_click
409 .is_some_and(|click| removed.contains(&click.id))
410 {
411 self.text_click = None;
412 }
413 }
414}
415
416impl Pointer {
417 fn set_drop_over(&mut self, over: Option<(NodeId, Option<Signal<bool>>)>) {
420 let old = std::mem::replace(&mut self.drop_over, over);
421 if old.map(|(id, _)| id) == over.map(|(id, _)| id) {
422 return;
423 }
424 let (old, new) = (old.and_then(|(_, s)| s), over.and_then(|(_, s)| s));
425 if old != new {
426 if let Some(old) = old {
427 old.try_set(false);
428 }
429 if let Some(new) = new {
430 new.try_set(true);
431 }
432 }
433 }
434}
435
436impl Tree {
437 pub(crate) fn pointer_hide(&mut self, hidden: &[NodeId]) {
440 let held = [
441 self.pointer.hovered,
442 self.pointer.pressed.map(|press| press.id),
443 ];
444 self.pointer.forget(hidden);
445 for id in held.into_iter().flatten().filter(|id| hidden.contains(id)) {
446 self.update_button_style(id, |button| {
447 button.hovered = false;
448 button.pressed = false;
449 });
450 }
451 }
452}
453
454fn now_ms() -> u32 {
457 static START: OnceLock<Instant> = OnceLock::new();
458 START.get_or_init(Instant::now).elapsed().as_millis() as u32
460}
461
462impl Window {
463 pub fn pointer_motion(&self, position: Point) -> CursorShape {
466 self.pointer_motion_at(position, now_ms())
467 }
468
469 pub fn pointer_motion_at(&self, position: Point, time: u32) -> CursorShape {
474 let calls = {
475 let mut tree = borrow(&self.tree);
476 tree.pointer.position = Some(position);
477 tree.bar_motion(position);
478 let calls = if tree.flick_motion(position, time) {
479 Vec::new()
480 } else {
481 tree.drag_motion(position)
482 };
483 tree.hover_at(position);
484 calls
485 };
486 run_all(calls);
487 self.cursor()
488 }
489
490 pub fn pointer_leave(&self) {
493 let calls = borrow(&self.tree).leave();
494 run_all(calls);
495 }
496
497 pub fn pointer_button(&self, button: PointerButton, pressed: bool) {
500 self.pointer_button_at(button, pressed, now_ms());
501 }
502
503 pub fn pointer_button_at(&self, button: PointerButton, pressed: bool, time: u32) {
511 let calls = borrow(&self.tree).button(button, pressed, time, false);
512 run_all(calls);
513 }
514
515 pub fn touch_at(&self, pressed: bool, time: u32) {
520 let calls = borrow(&self.tree).button(PointerButton::Left, pressed, time, true);
521 run_all(calls);
522 }
523
524 pub fn pointer_scroll(&self, wheel: Wheel) {
533 self.pointer_scroll_at(wheel, now_ms());
534 }
535
536 pub fn pointer_scroll_at(&self, wheel: Wheel, time: u32) {
540 let calls = borrow(&self.tree).scroll(wheel, time);
541 run_all(calls);
542 }
543
544 pub fn take_primary(&self) -> Option<Clipboard> {
550 borrow(&self.tree).primary.take()
551 }
552
553 pub fn cursor(&self) -> CursorShape {
555 self.tree.borrow().cursor()
556 }
557}
558
559pub(crate) fn run_all(calls: Vec<Call>) {
561 for call in calls {
562 call.run();
563 }
564}
565
566pub(crate) fn distance(a: Point, b: Point) -> f32 {
567 (a.x - b.x).hypot(a.y - b.y)
568}
569
570impl Tree {
571 fn hit(
578 &self,
579 id: NodeId,
580 point: Point,
581 path: &mut Vec<NodeId>,
582 skip: Option<NodeId>,
583 ) -> Option<NodeId> {
584 if skip == Some(id) {
585 return None;
586 }
587 let node = self.node(id)?;
588 let point = local(node, point)?;
589 let rect = node.rect?;
590 if !node.inner_bounds.contains(point) {
593 return None;
594 }
595 let style = node.effective_style();
596 let border = style.border.map_or(0.0, |border| border.width.max(0.0));
598 let corners = style.radius.unwrap_or_default();
599 let children = if node.clips() && !corners.contains(rect, border, point) {
600 Vec::new()
601 } else {
602 self.drawn_children(id)
603 };
604 path.push(id);
605 if let Some(hit) = children
606 .into_iter()
607 .rev()
608 .find_map(|child| self.hit(child, point, path, skip))
609 {
610 return Some(hit);
611 }
612 let takes = match &node.kind {
613 NodeKind::Button(button) => button.enabled,
614 NodeKind::Input(_) => true,
615 NodeKind::Text(text) => text.selectable,
616 _ => false,
617 };
618 if rect.contains(point) && takes {
619 return Some(id);
620 }
621 if matches!(&node.kind, NodeKind::Text(text) if text.link_at(point).is_some()) {
623 return Some(id);
624 }
625 path.pop();
626 None
627 }
628
629 pub(crate) fn hover_at(&mut self, point: Point) {
633 let mut path = Vec::new();
634 let hit = match self.pointer.pressed.filter(|press| press.dragging) {
635 Some(press) => {
636 path = self.path_to(press.id);
637 Some(press.id)
638 }
639 None => self.hit(self.root, point, &mut path, None),
640 };
641 self.set_hovered(hit, &path);
642 self.set_positions(&path, Some(point));
643 self.update_drop();
644 self.hover_link();
645 }
646
647 fn hover_link(&mut self) {
649 let now = self.pointer.hovered.zip(self.link_under_pointer());
650 let old = std::mem::replace(&mut self.pointer.link_hover, now);
651 if old == now {
652 return;
653 }
654 if let Some((id, _)) = old {
655 self.light_link(id, false, None);
656 }
657 if let Some((id, index)) = now {
658 self.light_link(id, false, Some(index));
659 }
660 }
661
662 pub(crate) fn light_link(&mut self, id: NodeId, focus: bool, index: Option<usize>) {
666 let Some(node) = self.node_mut(id) else {
667 return;
668 };
669 let laid_out = node.rect.is_some();
670 let NodeKind::Text(text) = &mut node.kind else {
671 return;
672 };
673 let slot = match focus {
674 true => &mut text.focused_link,
675 false => &mut text.hovered_link,
676 };
677 let old = std::mem::replace(slot, index);
678 if old == index || !laid_out {
679 return;
680 }
681 let areas: Vec<Rect> = old
682 .into_iter()
683 .chain(index)
684 .flat_map(|index| text.link_areas(index))
685 .collect();
686 self.touch(id, true);
687 for area in areas {
688 let area = self.window_area(id, area);
689 add_damage(&mut self.damage, area);
690 }
691 }
692
693 fn drag_type(&self, id: NodeId) -> Option<TypeId> {
695 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
696 return None;
697 };
698 let data = button.drag_data?;
699 untrack(|| data.try_with(|data| data.as_ref().map(|value| (**value).type_id()))).flatten()
701 }
702
703 pub(crate) fn drop_target(&self) -> Option<NodeId> {
707 let press = self.pointer.pressed.filter(|press| press.dragging);
708 let (carried, at) = match self.pointer.incoming {
709 Some(incoming) => (incoming.carried, incoming.at),
710 None => (self.drag_type(press?.id)?, self.pointer.position?),
711 };
712 let mut path = Vec::new();
713 self.hit(self.root, at, &mut path, press.map(|press| press.id))?;
714 path.into_iter().rev().find(|&id| {
715 self.enabled(id)
716 && self.has(id, |h| {
717 h.drop
719 .as_ref()
720 .is_some_and(|target| target.accepts == carried && !target.handler.disabled.get())
721 })
722 })
723 }
724
725 pub(crate) fn update_drop(&mut self) {
728 let over = self.drop_target().map(|id| {
729 let signal = match self.node(id).map(|node| &node.kind) {
730 Some(NodeKind::Button(button)) => button.drop_hovered,
731 _ => None,
732 };
733 (id, signal)
734 });
735 self.pointer.set_drop_over(over);
736 }
737
738 pub(crate) fn drop_after_place(&mut self) {
741 if self.pointer.incoming.is_some() || self.pointer.pressed.is_some_and(|press| press.dragging) {
742 self.update_drop();
743 }
744 }
745
746 fn drags(&self, id: NodeId) -> bool {
749 self.selects(id) || self.drag_type(id).is_some() || self.has(id, |h| h.drag.is_some())
750 }
751
752 pub(crate) fn path_to(&self, id: NodeId) -> Vec<NodeId> {
754 let mut path = vec![id];
755 while let Some(parent) = path.last().and_then(|&id| self.taffy.parent(id)) {
756 path.push(parent);
757 }
758 path.reverse();
759 path
760 }
761
762 fn cursor(&self) -> CursorShape {
763 let dragged = self
766 .pointer
767 .pressed
768 .filter(|press| press.dragging)
769 .and_then(|press| match self.node(press.id).map(|node| &node.kind) {
770 Some(NodeKind::Button(button)) => Some(button.cursor),
771 _ => None,
772 });
773 if let Some(shape) = dragged {
774 return match shape {
775 CursorShape::Pointer | CursorShape::Grab => CursorShape::Grabbing,
776 shape => shape,
777 };
778 }
779 match self
780 .pointer
781 .hovered
782 .and_then(|id| self.node(id))
783 .map(|node| &node.kind)
784 {
785 Some(NodeKind::Text(_)) if self.link_under_pointer().is_some() => CursorShape::Pointer,
786 Some(NodeKind::Input(_) | NodeKind::Text(_)) => CursorShape::Text,
787 Some(NodeKind::Button(button)) => button.cursor,
788 _ => CursorShape::Default,
789 }
790 }
791
792 pub(crate) fn pointer_after_layout(&mut self) {
797 if std::mem::take(&mut self.pointer.caused_layout) {
798 return;
799 }
800 if let Some(position) = self.pointer.position {
801 self.hover_at(position);
802 }
803 }
804
805 fn set_hovered(&mut self, hovered: Option<NodeId>, path: &[NodeId]) {
808 self.set_inside(path);
809 let old = self.pointer.hovered;
810 if old == hovered {
811 return;
812 }
813 self.pointer.hovered = hovered;
814 self.pointer.wheel = 0;
815 self.pointer.pixels = 0.0;
816 if let Some(old) = old {
817 self.set_button_state(old, |button| button.hovered = false);
818 }
819 if let Some(new) = hovered {
820 self.set_button_state(new, |button| button.hovered = true);
821 }
822 }
823
824 fn path_buttons<T>(
826 &self,
827 path: &[NodeId],
828 pick: impl Fn(&ButtonNode) -> Option<T>,
829 ) -> Vec<(NodeId, T)> {
830 path
831 .iter()
832 .filter_map(|&id| match &self.node(id)?.kind {
833 NodeKind::Button(button) if button.enabled => Some((id, pick(button)?)),
834 _ => None,
835 })
836 .collect()
837 }
838
839 fn set_inside(&mut self, path: &[NodeId]) {
842 let inside = self.path_buttons(path, |button| button.hover_signal);
843 let holds = |list: &[(NodeId, Signal<bool>)], signal| list.iter().any(|(_, s)| *s == signal);
846 let mut seen = Vec::new();
847 for &(_, signal) in self.pointer.inside.iter().chain(&inside) {
848 if seen.contains(&signal) {
849 continue;
850 }
851 seen.push(signal);
852 let now = holds(&inside, signal);
853 if holds(&self.pointer.inside, signal) != now {
854 signal.try_set(now);
855 }
856 }
857 self.pointer.inside = inside;
858 }
859
860 fn set_positions(&mut self, path: &[NodeId], at: Option<Point>) {
864 let now: Vec<(NodeId, Signal<Option<Point>>, Point)> = match at {
865 Some(at) => self
866 .path_buttons(path, |button| button.position_signal)
867 .into_iter()
868 .filter_map(|(id, signal)| Some((id, signal, self.button_local(id, at)?)))
869 .collect(),
870 None => Vec::new(),
871 };
872 for (id, signal, _) in &self.pointer.positions {
873 if !now.iter().any(|(other, ..)| other == id) {
874 signal.try_set(None);
875 }
876 }
877 for &(id, signal, point) in &now {
878 let same = |&(other, _, was): &(NodeId, _, Point)| other == id && was == point;
879 if !self.pointer.positions.iter().any(same) {
880 signal.try_set(Some(point));
881 }
882 }
883 self.pointer.positions = now;
884 }
885
886 fn button_local(&self, id: NodeId, point: Point) -> Option<Point> {
889 let rect = self.node(id)?.rect?;
890 let point = self.local_point(id, point)?;
891 Some(Point::new(point.x - rect.x, point.y - rect.y))
892 }
893
894 fn set_pressed(&mut self, pressed: Option<Press>) {
895 let old = std::mem::replace(&mut self.pointer.pressed, pressed);
896 if let Some(old) = old {
897 old.write(false);
898 self.set_button_state(old.id, |button| button.pressed = false);
899 }
900 if let Some(new) = pressed {
901 new.write(true);
902 self.set_button_state(new.id, |button| button.pressed = true);
903 }
904 }
905
906 fn set_button_state(&mut self, id: NodeId, f: impl FnOnce(&mut ButtonNode)) {
909 if self.update_button_style(id, f) == Change::Layout {
910 self.pointer.caused_layout = true;
911 }
912 }
913
914 fn button(&mut self, button: PointerButton, pressed: bool, time: u32, touch: bool) -> Vec<Call> {
915 if pressed {
916 self.press(button, time, touch)
917 } else {
918 self.release(button, time)
919 }
920 }
921
922 fn press(&mut self, button: PointerButton, time: u32, touch: bool) -> Vec<Call> {
923 if button == PointerButton::Left {
924 self.press_away(self.pointer.hovered);
925 }
926 if let (PointerButton::Left, None, Some(at)) =
928 (button, self.pointer.pressed, self.pointer.position)
929 && self.press_bar(at)
930 {
931 return Vec::new();
932 }
933 if let (PointerButton::Left, None, Some(at)) =
934 (button, self.pointer.pressed, self.pointer.position)
935 {
936 let drags = self.pointer.hovered.is_some_and(|id| self.drags(id));
937 self.press_views(at, drags, touch);
938 }
939 let (None, Some(id), Some(at)) = (
940 self.pointer.pressed,
941 self.pointer.hovered,
942 self.pointer.position,
943 ) else {
944 return Vec::new();
945 };
946 let start = self.button_local(id, at).unwrap_or_default();
947 let signal = match &self.node(id).map(|node| &node.kind) {
948 Some(NodeKind::Button(node)) if button == PointerButton::Left => node.pressed_signal,
949 _ => None,
950 };
951 self.set_pressed(Some(Press {
952 id,
953 button,
954 at,
955 last: at,
956 start,
957 dragging: false,
958 long_pressed: false,
959 out: false,
960 signal,
961 }));
962 if button == PointerButton::Middle && self.press_middle(id, at) {
963 self.primary = Some(Clipboard::Paste);
964 }
965 let any = self.call(id, Action::AnyPress(button));
966 if button != PointerButton::Left {
967 return any.into_iter().collect();
968 }
969 self.pointer.link = self.link_under(id, at);
970 if self.selects(id) {
971 self.press_text(id, at, time);
972 }
973 let mut calls: Vec<Call> = self.call(id, Action::Press).into_iter().collect();
974 calls.extend(any);
975 if self.has(id, |h| h.long_press.is_some()) {
976 self.arm_long_press(id);
977 }
978 let waits =
980 |h: &Handlers| h.click.is_some() || h.double_click.is_some() || h.long_press.is_some();
981 if self.drags(id) && !self.has(id, waits) {
982 calls.extend(self.start_drag(at));
983 }
984 calls
985 }
986
987 fn release(&mut self, button: PointerButton, time: u32) -> Vec<Call> {
988 if button == PointerButton::Left {
989 self.release_bar();
990 self.flick_release(Some(time));
991 }
992 let Some(press) = self.pointer.pressed.filter(|press| press.button == button) else {
993 return Vec::new();
994 };
995 let mut calls = Vec::new();
996 if button == PointerButton::Left {
997 calls.extend(self.call(press.id, Action::Release));
998 let link = self.pointer.link.take();
999 calls.extend(link.and_then(|link| self.link_click(press, link)));
1000 if let Some(text) = self.selected_text(press.id) {
1002 self.primary = Some(Clipboard::Copy(text));
1003 }
1004 }
1005 let landed = Rc::new(Cell::new(false));
1007 calls.extend(self.drop_call(&landed));
1008 calls.extend(self.end_press(Some(landed)));
1009 if press.dragging {
1010 if let Some(at) = self.pointer.position {
1012 self.hover_at(at);
1013 }
1014 return calls;
1015 }
1016 if press.long_pressed || self.pointer.hovered != Some(press.id) {
1017 return calls;
1018 }
1019 let action = match button {
1020 PointerButton::Left => self.left_click(press.id, time, press.at),
1021 PointerButton::Right => Action::RightClick,
1022 PointerButton::Middle => Action::MiddleClick,
1023 PointerButton::Back => Action::Back,
1024 PointerButton::Forward => Action::Forward,
1025 };
1026 calls.extend(self.call(press.id, action));
1027 calls
1028 }
1029
1030 fn link_under_pointer(&self) -> Option<usize> {
1032 let id = self.pointer.hovered?;
1033 let NodeKind::Text(text) = &self.node(id)?.kind else {
1034 return None;
1035 };
1036 text.link_at(self.local_point(id, self.pointer.position?)?)
1037 }
1038
1039 fn link_under(&self, id: NodeId, at: Point) -> Option<(NodeId, usize, String)> {
1042 let NodeKind::Text(text) = &self.node(id)?.kind else {
1043 return None;
1044 };
1045 let index = text.link_at(self.local_point(id, at)?)?;
1046 Some((id, index, text.spans[index].link.clone()?))
1047 }
1048
1049 fn link_click(&self, press: Press, pressed: (NodeId, usize, String)) -> Option<Call> {
1054 let node = self.node(press.id)?;
1055 let NodeKind::Text(text) = &node.kind else {
1056 return None;
1057 };
1058 if text_selection(text).is_some() {
1059 return None;
1060 }
1061 let released = self.link_under(press.id, self.pointer.position?)?;
1062 if pressed != released {
1063 return None;
1064 }
1065 self.link_call(press.id, released.1)
1066 }
1067
1068 pub(crate) fn link_call(&self, id: NodeId, index: usize) -> Option<Call> {
1071 let node = self.node(id)?;
1072 let NodeKind::Text(text) = &node.kind else {
1073 return None;
1074 };
1075 let handler = text.on_link.clone().filter(|handler| !handler.disabled())?;
1076 let url = text.spans.get(index)?.link.clone()?;
1077 Some(Call {
1078 cx: node.cx.clone(),
1079 path: Rc::clone(&node.path),
1080 handlers: None,
1081 action: Action::Link(handler, url, self.this.clone(), id),
1082 })
1083 }
1084
1085 fn left_click(&mut self, id: NodeId, time: u32, at: Point) -> Action {
1089 let close = self.pointer.last_click.is_some_and(|(last, then, place)| {
1090 last == id
1091 && time.wrapping_sub(then) <= DOUBLE_CLICK_MS
1092 && distance(place, at) <= DOUBLE_CLICK_DISTANCE
1093 });
1094 if close && self.has(id, |h| h.double_click.is_some()) {
1095 self.pointer.last_click = None;
1096 Action::DoubleClick
1097 } else {
1098 self.pointer.last_click = Some((id, time, at));
1099 Action::Click
1100 }
1101 }
1102
1103 fn drop_call(&self, landed: &Rc<Cell<bool>>) -> Option<Call> {
1106 let target = self.drop_target()?;
1107 let value = self.drag_value(self.pointer.pressed?.id)?;
1108 self.call(target, Action::Drop(value, Rc::clone(landed)))
1109 }
1110
1111 pub(crate) fn drag_value(&self, id: NodeId) -> Option<DragValue> {
1113 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
1114 return None;
1115 };
1116 untrack(|| button.drag_data?.try_get().flatten())
1117 }
1118
1119 pub(crate) fn end_press(&mut self, landed: Option<Rc<Cell<bool>>>) -> Option<Call> {
1123 let press = self.pointer.pressed?;
1124 self.set_pressed(None);
1125 self.update_drop();
1126 self.stop_long_press(press.id);
1127 if press.dragging {
1128 self.drag_call(press, DragPhase::End, press.last, landed)
1129 } else {
1130 None
1131 }
1132 }
1133
1134 fn drag_motion(&mut self, at: Point) -> Vec<Call> {
1137 let Some(press) = self.pointer.pressed.as_mut() else {
1138 return Vec::new();
1139 };
1140 press.last = at;
1141 let press = *press;
1142 if press.button != PointerButton::Left {
1143 return Vec::new();
1144 }
1145 if press.dragging && self.selects(press.id) {
1146 self.drag_text(press.id, at);
1147 return Vec::new();
1148 }
1149 if press.dragging {
1150 return self
1151 .drag_call(press, DragPhase::Move, at, None)
1152 .into_iter()
1153 .collect();
1154 }
1155 if distance(press.at, at) <= DRAG_THRESHOLD {
1156 return Vec::new();
1157 }
1158 self.stop_long_press(press.id);
1159 if self.drags(press.id) {
1160 self.start_drag(at)
1161 } else {
1162 Vec::new()
1163 }
1164 }
1165
1166 fn start_drag(&mut self, at: Point) -> Vec<Call> {
1168 let Some(press) = self.pointer.pressed.as_mut() else {
1169 return Vec::new();
1170 };
1171 press.dragging = true;
1172 let press = *press;
1173 self.stop_long_press(press.id);
1174 self.update_drop();
1175 self
1176 .drag_call(press, DragPhase::Start, at, None)
1177 .into_iter()
1178 .collect()
1179 }
1180
1181 pub(crate) fn drag_call(
1182 &self,
1183 press: Press,
1184 phase: DragPhase,
1185 at: Point,
1186 landed: Option<Rc<Cell<bool>>>,
1187 ) -> Option<Call> {
1188 let rect = self.node(press.id)?.rect?;
1189 let drag = Drag {
1190 phase,
1191 start: press.start,
1192 position: self.button_local(press.id, at).unwrap_or(press.start),
1195 size: Size::new(rect.width, rect.height),
1196 dropped: false,
1197 };
1198 self.call(press.id, Action::Drag(drag, landed))
1199 }
1200
1201 fn arm_long_press(&mut self, id: NodeId) {
1204 let tree = self.this.clone();
1205 let Some(Node { cx, kind, .. }) = self.node_mut(id) else {
1206 return;
1207 };
1208 let NodeKind::Button(button) = kind else {
1209 return;
1210 };
1211 match button.long_press {
1212 Some(timer) => timer.restart(),
1213 None => {
1214 let timer = cx.after(LONG_PRESS, move || long_press_fired(&tree, id));
1215 button.long_press = Some(timer);
1216 }
1217 }
1218 }
1219
1220 fn stop_long_press(&self, id: NodeId) {
1221 if let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind)
1222 && let Some(timer) = button.long_press
1223 {
1224 timer.stop();
1225 }
1226 }
1227
1228 fn long_press(&mut self, id: NodeId) -> Option<Call> {
1230 let press = self.pointer.pressed.as_mut().filter(|press| {
1231 press.id == id
1232 && press.button == PointerButton::Left
1233 && !press.dragging
1234 && !press.long_pressed
1235 })?;
1236 press.long_pressed = true;
1237 self.call(id, Action::LongPress)
1238 }
1239
1240 pub(crate) fn leave(&mut self) -> Vec<Call> {
1243 self.pointer.position = None;
1244 self.release_bar();
1245 self.flick_release(None);
1246 if let Some(id) = self.pointer.gesture.take() {
1247 self.release_view(id, None);
1248 }
1249 let out = self.pointer.pressed.is_some_and(|press| press.out);
1251 let calls = match out {
1252 true => Vec::new(),
1253 false => self.end_press(None).into_iter().collect(),
1254 };
1255 self.set_hovered(None, &[]);
1256 self.set_positions(&[], None);
1257 self.hover_link();
1258 calls
1259 }
1260
1261 pub(crate) fn set_enabled(&mut self, id: NodeId, enabled: bool) -> Vec<Call> {
1265 let Some(NodeKind::Button(button)) = self.node_mut(id).map(|node| &mut node.kind) else {
1266 return Vec::new();
1267 };
1268 if std::mem::replace(&mut button.enabled, enabled) == enabled {
1269 return Vec::new();
1270 }
1271 self.node_event(id, |id| AccessEvent::Enabled(id, enabled));
1272 let mut calls = Vec::new();
1273 if !enabled {
1274 if self.pointer.pressed.is_some_and(|press| press.id == id) {
1275 calls.extend(self.end_press(None));
1276 }
1277 if self.keyboard.focused == Some(id) {
1278 self.focus(None);
1279 }
1280 }
1281 if let Some(at) = self.pointer.position {
1282 self.hover_at(at);
1283 }
1284 calls
1285 }
1286
1287 pub(crate) fn bind_enabled(&mut self, id: NodeId, prop: Prop<bool>) {
1290 let mut compute = match prop.0 {
1291 PropKind::Value(enabled) => {
1293 self.set_enabled(id, enabled);
1294 return;
1295 }
1296 PropKind::Binding(compute) => compute,
1297 };
1298 let Some(node) = self.node(id) else {
1299 return;
1300 };
1301 let label = format!("{}.enabled", node.path);
1302 let tree = self.this.clone();
1303 node
1304 .cx
1305 .effect(move || {
1306 let enabled = compute();
1307 let Some(tree) = tree.upgrade() else {
1308 return;
1309 };
1310 let calls = borrow(&tree).set_enabled(id, enabled);
1311 untrack(|| run_all(calls));
1313 })
1314 .named(label);
1315 }
1316
1317 pub(crate) fn enabled(&self, id: NodeId) -> bool {
1319 match self.node(id).map(|node| &node.kind) {
1320 Some(NodeKind::Button(button)) => button.enabled,
1321 _ => true,
1322 }
1323 }
1324
1325 fn scroll(&mut self, wheel: Wheel, time: u32) -> Vec<Call> {
1326 let wants = |h: &Handlers| h.scroll.is_some() || h.wheel.is_some();
1327 let target = self.pointer.hovered.filter(|&id| self.has(id, wants));
1328 let calls = match target {
1329 None => {
1330 self.scroll_view(wheel, time);
1331 Vec::new()
1332 }
1333 Some(target) => {
1334 let mut calls = Vec::new();
1335 if self.has(target, |h| h.wheel.is_some()) {
1336 calls.extend(self.call(target, Action::Wheel(wheel)));
1337 }
1338 if self.has(target, |h| h.scroll.is_some()) {
1339 let down = self.steps(wheel.y);
1340 if down != 0 {
1342 calls.extend(self.call(target, Action::Scroll(down.saturating_neg())));
1343 }
1344 }
1345 calls
1346 }
1347 };
1348 if wheel.y.stop {
1349 self.pointer.pixels = 0.0;
1350 }
1351 if wheel.source == ScrollSource::Finger
1355 && (wheel.x.stop || wheel.y.stop)
1356 && let Some(id) = self.pointer.gesture.take()
1357 {
1358 self.release_view(id, Some(time));
1359 }
1360 calls
1361 }
1362
1363 fn steps(&mut self, axis: WheelAxis) -> i32 {
1366 if axis.notches != 0.0 && axis.notches.is_finite() {
1367 let value120 = (axis.notches * VALUE120_PER_STEP as f32).round() as i32;
1369 self.pointer.wheel = self.pointer.wheel.saturating_add(value120);
1370 let steps = self.pointer.wheel / VALUE120_PER_STEP;
1371 self.pointer.wheel -= steps * VALUE120_PER_STEP;
1372 steps
1373 } else if axis.pixels.is_finite() {
1374 self.pointer.pixels += axis.pixels;
1375 let steps = (self.pointer.pixels / PIXELS_PER_STEP).trunc();
1376 self.pointer.pixels -= steps * PIXELS_PER_STEP;
1377 steps as i32
1378 } else {
1379 0
1380 }
1381 }
1382
1383 pub(crate) fn cancel_press(&mut self) {
1386 if let Some(press) = self.pointer.pressed.filter(|press| !press.dragging) {
1387 self.set_pressed(None);
1388 self.stop_long_press(press.id);
1389 }
1390 }
1391
1392 pub(crate) fn has(&self, id: NodeId, f: impl FnOnce(&Handlers) -> bool) -> bool {
1394 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
1395 return false;
1396 };
1397 untrack(|| button.handlers.try_with(f)).unwrap_or(false)
1398 }
1399
1400 pub(crate) fn local_point(&self, id: NodeId, point: Point) -> Option<Point> {
1404 self
1405 .path_to(id)
1406 .iter()
1407 .try_fold(point, |point, &id| local(self.node(id)?, point))
1408 }
1409
1410 pub(crate) fn window_rect(&self, id: NodeId, rect: Rect) -> Rect {
1414 let mut rect = rect;
1415 let mut at = Some(id);
1416 while let Some(current) = at {
1417 if let Some(transform) = self.node(current).and_then(|node| node.transform) {
1418 rect = transform.map_rect(rect);
1419 }
1420 at = self.taffy.parent(current);
1421 }
1422 rect
1423 }
1424
1425 pub(crate) fn click(&self, id: NodeId) -> Option<Call> {
1427 self.call(id, Action::Click)
1428 }
1429
1430 pub(crate) fn call(&self, id: NodeId, action: Action) -> Option<Call> {
1431 let node = self.node(id)?;
1432 let NodeKind::Button(button) = &node.kind else {
1433 return None;
1434 };
1435 Some(Call {
1436 cx: node.cx.clone(),
1437 path: Rc::clone(&node.path),
1438 handlers: Some(button.handlers),
1439 action,
1440 })
1441 }
1442}
1443
1444fn long_press_fired(tree: &Weak<RefCell<Tree>>, id: NodeId) {
1446 let Some(tree) = tree.upgrade() else {
1447 return;
1448 };
1449 let Ok(mut borrowed) = tree.try_borrow_mut() else {
1451 return;
1452 };
1453 let call = borrowed.long_press(id);
1454 drop(borrowed);
1455 if let Some(call) = call {
1456 call.run();
1457 }
1458}
1459
1460pub(crate) fn local(node: &Node, point: Point) -> Option<Point> {
1464 match node.transform {
1465 Some(transform) => Some(transform.invert()?.map(point)),
1466 None => Some(point),
1467 }
1468}
1469
1470#[derive(Clone)]
1471pub(crate) enum Action {
1472 Click,
1473 Press,
1474 AnyPress(PointerButton),
1475 Release,
1476 DoubleClick,
1477 LongPress,
1478 RightClick,
1479 MiddleClick,
1480 Back,
1481 Forward,
1482 Scroll(i32),
1483 Wheel(Wheel),
1484 Drag(Drag, Option<Rc<Cell<bool>>>),
1486 Drop(DragValue, Rc<Cell<bool>>),
1488 Link(LinkHandler, String, Weak<RefCell<Tree>>, NodeId),
1491}
1492
1493pub(crate) struct Call {
1495 cx: Cx,
1496 path: Rc<str>,
1497 handlers: Option<Signal<Handlers>>,
1499 action: Action,
1500}
1501
1502enum Picked {
1504 Plain(ClickHandler, &'static str),
1505 AnyPress(AnyPressHandler, PointerButton),
1506 Scroll(ScrollHandler, i32),
1507 Wheel(WheelHandler, Wheel),
1508 Drag(DragHandler, Drag),
1509 Drop(DropHandler, &'static str, DragValue, Rc<Cell<bool>>),
1510}
1511
1512impl Call {
1513 pub(crate) fn run(self) {
1514 let (path, cx) = (&self.path, &self.cx);
1515 if let Action::Link(handler, url, tree, id) = &self.action {
1516 run_isolated(path, "on_link", Rc::clone(handler), |f| f(cx, url));
1517 if handler.disabled()
1519 && let Some(tree) = tree.upgrade()
1520 && let Ok(mut tree) = tree.try_borrow_mut()
1521 {
1522 tree.light_link(*id, false, None);
1523 tree.light_link(*id, true, None);
1524 }
1525 return;
1526 }
1527 let Some(handlers) = self.handlers else {
1528 return;
1529 };
1530 let picked = untrack(|| {
1532 handlers.try_with(|h| {
1533 let plain = |handler: &Option<ClickHandler>, name| {
1534 handler.clone().map(|handler| Picked::Plain(handler, name))
1535 };
1536 match &self.action {
1537 Action::Click => plain(&h.click, "on_click"),
1538 Action::Press => plain(&h.press, "on_press"),
1539 Action::AnyPress(button) => h.any_press.clone().map(|f| Picked::AnyPress(f, *button)),
1540 Action::Release => plain(&h.release, "on_release"),
1541 Action::DoubleClick => plain(&h.double_click, "on_double_click"),
1542 Action::LongPress => plain(&h.long_press, "on_long_press"),
1543 Action::RightClick => plain(&h.right_click, "on_right_click"),
1544 Action::MiddleClick => plain(&h.middle_click, "on_middle_click"),
1545 Action::Back => plain(&h.back, "on_back"),
1546 Action::Forward => plain(&h.forward, "on_forward"),
1547 Action::Scroll(steps) => h.scroll.clone().map(|f| Picked::Scroll(f, *steps)),
1548 Action::Wheel(wheel) => h.wheel.clone().map(|f| Picked::Wheel(f, *wheel)),
1549 Action::Drag(drag, landed) => {
1550 let drag = Drag {
1551 dropped: landed.as_ref().is_some_and(|landed| landed.get()),
1552 ..*drag
1553 };
1554 h.drag.clone().map(|f| Picked::Drag(f, drag))
1555 }
1556 Action::Drop(value, landed) => {
1557 let target = h.drop.as_ref()?;
1558 Some(Picked::Drop(
1559 target.handler.clone(),
1560 target.name,
1561 Rc::clone(value),
1562 Rc::clone(landed),
1563 ))
1564 }
1565 Action::Link(..) => None,
1566 }
1567 })
1568 });
1569 let Some(Some(picked)) = picked else {
1570 return;
1571 };
1572 match picked {
1573 Picked::Plain(handler, name) => {
1574 run_isolated(path, name, handler, |f| f(cx));
1575 }
1576 Picked::AnyPress(handler, button) => {
1577 run_isolated(path, "on_any_press", handler, |f| f(cx, button));
1578 }
1579 Picked::Scroll(handler, steps) => {
1580 run_isolated(path, "on_scroll", handler, |f| f(cx, steps));
1581 }
1582 Picked::Wheel(handler, wheel) => {
1583 run_isolated(path, "on_wheel", handler, |f| f(cx, wheel));
1584 }
1585 Picked::Drag(handler, drag) => {
1586 run_isolated(path, "on_drag", handler, |f| f(cx, drag));
1587 }
1588 Picked::Drop(handler, name, value, landed) => {
1590 let ran = run_isolated(path, name, handler, move |f| f(cx, &*value));
1591 landed.set(ran.is_some());
1592 }
1593 }
1594 }
1595}
1596
1597pub(crate) fn run_isolated<F: ?Sized, R>(
1602 path: &str,
1603 name: &str,
1604 handler: Rc<Handler<F>>,
1605 call: impl FnOnce(&F) -> R,
1606) -> Option<R> {
1607 if handler.disabled.get() {
1608 return None;
1609 }
1610 let result = match panic::catch_unwind(AssertUnwindSafe(|| call(&handler.f))) {
1611 Ok(result) => Some(result),
1612 Err(payload) => {
1613 handler.disabled.set(true);
1614 tracing::error!(
1615 "handler {path}.{name} panicked and is disabled: {}",
1616 panic_message(payload.as_ref())
1617 );
1618 None
1619 }
1620 };
1621 if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(move || drop(handler))) {
1622 tracing::error!(
1623 "dropping handler {path}.{name} panicked: {}",
1624 panic_message(payload.as_ref())
1625 );
1626 }
1627 result
1628}
1629
1630pub(crate) fn panic_message(payload: &(dyn Any + Send)) -> &str {
1631 if let Some(message) = payload.downcast_ref::<&str>() {
1632 message
1633 } else if let Some(message) = payload.downcast_ref::<String>() {
1634 message
1635 } else {
1636 "(panic payload is not a string)"
1637 }
1638}