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 for area in areas {
687 let area = self.window_area(id, area);
688 add_damage(&mut self.damage, area);
689 }
690 }
691
692 fn drag_type(&self, id: NodeId) -> Option<TypeId> {
694 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
695 return None;
696 };
697 let data = button.drag_data?;
698 untrack(|| data.try_with(|data| data.as_ref().map(|value| (**value).type_id()))).flatten()
700 }
701
702 pub(crate) fn drop_target(&self) -> Option<NodeId> {
706 let press = self.pointer.pressed.filter(|press| press.dragging);
707 let (carried, at) = match self.pointer.incoming {
708 Some(incoming) => (incoming.carried, incoming.at),
709 None => (self.drag_type(press?.id)?, self.pointer.position?),
710 };
711 let mut path = Vec::new();
712 self.hit(self.root, at, &mut path, press.map(|press| press.id))?;
713 path.into_iter().rev().find(|&id| {
714 self.enabled(id)
715 && self.has(id, |h| {
716 h.drop
718 .as_ref()
719 .is_some_and(|target| target.accepts == carried && !target.handler.disabled.get())
720 })
721 })
722 }
723
724 pub(crate) fn update_drop(&mut self) {
727 let over = self.drop_target().map(|id| {
728 let signal = match self.node(id).map(|node| &node.kind) {
729 Some(NodeKind::Button(button)) => button.drop_hovered,
730 _ => None,
731 };
732 (id, signal)
733 });
734 self.pointer.set_drop_over(over);
735 }
736
737 pub(crate) fn drop_after_place(&mut self) {
740 if self.pointer.incoming.is_some() || self.pointer.pressed.is_some_and(|press| press.dragging) {
741 self.update_drop();
742 }
743 }
744
745 fn drags(&self, id: NodeId) -> bool {
748 self.selects(id) || self.drag_type(id).is_some() || self.has(id, |h| h.drag.is_some())
749 }
750
751 pub(crate) fn path_to(&self, id: NodeId) -> Vec<NodeId> {
753 let mut path = vec![id];
754 while let Some(parent) = path.last().and_then(|&id| self.taffy.parent(id)) {
755 path.push(parent);
756 }
757 path.reverse();
758 path
759 }
760
761 fn cursor(&self) -> CursorShape {
762 let dragged = self
765 .pointer
766 .pressed
767 .filter(|press| press.dragging)
768 .and_then(|press| match self.node(press.id).map(|node| &node.kind) {
769 Some(NodeKind::Button(button)) => Some(button.cursor),
770 _ => None,
771 });
772 if let Some(shape) = dragged {
773 return match shape {
774 CursorShape::Pointer | CursorShape::Grab => CursorShape::Grabbing,
775 shape => shape,
776 };
777 }
778 match self
779 .pointer
780 .hovered
781 .and_then(|id| self.node(id))
782 .map(|node| &node.kind)
783 {
784 Some(NodeKind::Text(_)) if self.link_under_pointer().is_some() => CursorShape::Pointer,
785 Some(NodeKind::Input(_) | NodeKind::Text(_)) => CursorShape::Text,
786 Some(NodeKind::Button(button)) => button.cursor,
787 _ => CursorShape::Default,
788 }
789 }
790
791 pub(crate) fn pointer_after_layout(&mut self) {
796 if std::mem::take(&mut self.pointer.caused_layout) {
797 return;
798 }
799 if let Some(position) = self.pointer.position {
800 self.hover_at(position);
801 }
802 }
803
804 fn set_hovered(&mut self, hovered: Option<NodeId>, path: &[NodeId]) {
807 self.set_inside(path);
808 let old = self.pointer.hovered;
809 if old == hovered {
810 return;
811 }
812 self.pointer.hovered = hovered;
813 self.pointer.wheel = 0;
814 self.pointer.pixels = 0.0;
815 if let Some(old) = old {
816 self.set_button_state(old, |button| button.hovered = false);
817 }
818 if let Some(new) = hovered {
819 self.set_button_state(new, |button| button.hovered = true);
820 }
821 }
822
823 fn path_buttons<T>(
825 &self,
826 path: &[NodeId],
827 pick: impl Fn(&ButtonNode) -> Option<T>,
828 ) -> Vec<(NodeId, T)> {
829 path
830 .iter()
831 .filter_map(|&id| match &self.node(id)?.kind {
832 NodeKind::Button(button) if button.enabled => Some((id, pick(button)?)),
833 _ => None,
834 })
835 .collect()
836 }
837
838 fn set_inside(&mut self, path: &[NodeId]) {
841 let inside = self.path_buttons(path, |button| button.hover_signal);
842 let holds = |list: &[(NodeId, Signal<bool>)], signal| list.iter().any(|(_, s)| *s == signal);
845 let mut seen = Vec::new();
846 for &(_, signal) in self.pointer.inside.iter().chain(&inside) {
847 if seen.contains(&signal) {
848 continue;
849 }
850 seen.push(signal);
851 let now = holds(&inside, signal);
852 if holds(&self.pointer.inside, signal) != now {
853 signal.try_set(now);
854 }
855 }
856 self.pointer.inside = inside;
857 }
858
859 fn set_positions(&mut self, path: &[NodeId], at: Option<Point>) {
863 let now: Vec<(NodeId, Signal<Option<Point>>, Point)> = match at {
864 Some(at) => self
865 .path_buttons(path, |button| button.position_signal)
866 .into_iter()
867 .filter_map(|(id, signal)| Some((id, signal, self.button_local(id, at)?)))
868 .collect(),
869 None => Vec::new(),
870 };
871 for (id, signal, _) in &self.pointer.positions {
872 if !now.iter().any(|(other, ..)| other == id) {
873 signal.try_set(None);
874 }
875 }
876 for &(id, signal, point) in &now {
877 let same = |&(other, _, was): &(NodeId, _, Point)| other == id && was == point;
878 if !self.pointer.positions.iter().any(same) {
879 signal.try_set(Some(point));
880 }
881 }
882 self.pointer.positions = now;
883 }
884
885 fn button_local(&self, id: NodeId, point: Point) -> Option<Point> {
888 let rect = self.node(id)?.rect?;
889 let point = self.local_point(id, point)?;
890 Some(Point::new(point.x - rect.x, point.y - rect.y))
891 }
892
893 fn set_pressed(&mut self, pressed: Option<Press>) {
894 let old = std::mem::replace(&mut self.pointer.pressed, pressed);
895 if let Some(old) = old {
896 old.write(false);
897 self.set_button_state(old.id, |button| button.pressed = false);
898 }
899 if let Some(new) = pressed {
900 new.write(true);
901 self.set_button_state(new.id, |button| button.pressed = true);
902 }
903 }
904
905 fn set_button_state(&mut self, id: NodeId, f: impl FnOnce(&mut ButtonNode)) {
908 if self.update_button_style(id, f) == Change::Layout {
909 self.pointer.caused_layout = true;
910 }
911 }
912
913 fn button(&mut self, button: PointerButton, pressed: bool, time: u32, touch: bool) -> Vec<Call> {
914 if pressed {
915 self.press(button, time, touch)
916 } else {
917 self.release(button, time)
918 }
919 }
920
921 fn press(&mut self, button: PointerButton, time: u32, touch: bool) -> Vec<Call> {
922 if button == PointerButton::Left {
923 self.press_away(self.pointer.hovered);
924 }
925 if let (PointerButton::Left, None, Some(at)) =
927 (button, self.pointer.pressed, self.pointer.position)
928 && self.press_bar(at)
929 {
930 return Vec::new();
931 }
932 if let (PointerButton::Left, None, Some(at)) =
933 (button, self.pointer.pressed, self.pointer.position)
934 {
935 let drags = self.pointer.hovered.is_some_and(|id| self.drags(id));
936 self.press_views(at, drags, touch);
937 }
938 let (None, Some(id), Some(at)) = (
939 self.pointer.pressed,
940 self.pointer.hovered,
941 self.pointer.position,
942 ) else {
943 return Vec::new();
944 };
945 let start = self.button_local(id, at).unwrap_or_default();
946 let signal = match &self.node(id).map(|node| &node.kind) {
947 Some(NodeKind::Button(node)) if button == PointerButton::Left => node.pressed_signal,
948 _ => None,
949 };
950 self.set_pressed(Some(Press {
951 id,
952 button,
953 at,
954 last: at,
955 start,
956 dragging: false,
957 long_pressed: false,
958 out: false,
959 signal,
960 }));
961 if button == PointerButton::Middle && self.press_middle(id, at) {
962 self.primary = Some(Clipboard::Paste);
963 }
964 let any = self.call(id, Action::AnyPress(button));
965 if button != PointerButton::Left {
966 return any.into_iter().collect();
967 }
968 self.pointer.link = self.link_under(id, at);
969 if self.selects(id) {
970 self.press_text(id, at, time);
971 }
972 let mut calls: Vec<Call> = self.call(id, Action::Press).into_iter().collect();
973 calls.extend(any);
974 if self.has(id, |h| h.long_press.is_some()) {
975 self.arm_long_press(id);
976 }
977 let waits =
979 |h: &Handlers| h.click.is_some() || h.double_click.is_some() || h.long_press.is_some();
980 if self.drags(id) && !self.has(id, waits) {
981 calls.extend(self.start_drag(at));
982 }
983 calls
984 }
985
986 fn release(&mut self, button: PointerButton, time: u32) -> Vec<Call> {
987 if button == PointerButton::Left {
988 self.release_bar();
989 self.flick_release(Some(time));
990 }
991 let Some(press) = self.pointer.pressed.filter(|press| press.button == button) else {
992 return Vec::new();
993 };
994 let mut calls = Vec::new();
995 if button == PointerButton::Left {
996 calls.extend(self.call(press.id, Action::Release));
997 let link = self.pointer.link.take();
998 calls.extend(link.and_then(|link| self.link_click(press, link)));
999 if let Some(text) = self.selected_text(press.id) {
1001 self.primary = Some(Clipboard::Copy(text));
1002 }
1003 }
1004 let landed = Rc::new(Cell::new(false));
1006 calls.extend(self.drop_call(&landed));
1007 calls.extend(self.end_press(Some(landed)));
1008 if press.dragging {
1009 if let Some(at) = self.pointer.position {
1011 self.hover_at(at);
1012 }
1013 return calls;
1014 }
1015 if press.long_pressed || self.pointer.hovered != Some(press.id) {
1016 return calls;
1017 }
1018 let action = match button {
1019 PointerButton::Left => self.left_click(press.id, time, press.at),
1020 PointerButton::Right => Action::RightClick,
1021 PointerButton::Middle => Action::MiddleClick,
1022 PointerButton::Back => Action::Back,
1023 PointerButton::Forward => Action::Forward,
1024 };
1025 calls.extend(self.call(press.id, action));
1026 calls
1027 }
1028
1029 fn link_under_pointer(&self) -> Option<usize> {
1031 let id = self.pointer.hovered?;
1032 let NodeKind::Text(text) = &self.node(id)?.kind else {
1033 return None;
1034 };
1035 text.link_at(self.local_point(id, self.pointer.position?)?)
1036 }
1037
1038 fn link_under(&self, id: NodeId, at: Point) -> Option<(NodeId, usize, String)> {
1041 let NodeKind::Text(text) = &self.node(id)?.kind else {
1042 return None;
1043 };
1044 let index = text.link_at(self.local_point(id, at)?)?;
1045 Some((id, index, text.spans[index].link.clone()?))
1046 }
1047
1048 fn link_click(&self, press: Press, pressed: (NodeId, usize, String)) -> Option<Call> {
1053 let node = self.node(press.id)?;
1054 let NodeKind::Text(text) = &node.kind else {
1055 return None;
1056 };
1057 if text_selection(text).is_some() {
1058 return None;
1059 }
1060 let released = self.link_under(press.id, self.pointer.position?)?;
1061 if pressed != released {
1062 return None;
1063 }
1064 self.link_call(press.id, released.1)
1065 }
1066
1067 pub(crate) fn link_call(&self, id: NodeId, index: usize) -> Option<Call> {
1070 let node = self.node(id)?;
1071 let NodeKind::Text(text) = &node.kind else {
1072 return None;
1073 };
1074 let handler = text.on_link.clone().filter(|handler| !handler.disabled())?;
1075 let url = text.spans.get(index)?.link.clone()?;
1076 Some(Call {
1077 cx: node.cx.clone(),
1078 path: Rc::clone(&node.path),
1079 handlers: None,
1080 action: Action::Link(handler, url, self.this.clone(), id),
1081 })
1082 }
1083
1084 fn left_click(&mut self, id: NodeId, time: u32, at: Point) -> Action {
1088 let close = self.pointer.last_click.is_some_and(|(last, then, place)| {
1089 last == id
1090 && time.wrapping_sub(then) <= DOUBLE_CLICK_MS
1091 && distance(place, at) <= DOUBLE_CLICK_DISTANCE
1092 });
1093 if close && self.has(id, |h| h.double_click.is_some()) {
1094 self.pointer.last_click = None;
1095 Action::DoubleClick
1096 } else {
1097 self.pointer.last_click = Some((id, time, at));
1098 Action::Click
1099 }
1100 }
1101
1102 fn drop_call(&self, landed: &Rc<Cell<bool>>) -> Option<Call> {
1105 let target = self.drop_target()?;
1106 let value = self.drag_value(self.pointer.pressed?.id)?;
1107 self.call(target, Action::Drop(value, Rc::clone(landed)))
1108 }
1109
1110 pub(crate) fn drag_value(&self, id: NodeId) -> Option<DragValue> {
1112 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
1113 return None;
1114 };
1115 untrack(|| button.drag_data?.try_get().flatten())
1116 }
1117
1118 pub(crate) fn end_press(&mut self, landed: Option<Rc<Cell<bool>>>) -> Option<Call> {
1122 let press = self.pointer.pressed?;
1123 self.set_pressed(None);
1124 self.update_drop();
1125 self.stop_long_press(press.id);
1126 if press.dragging {
1127 self.drag_call(press, DragPhase::End, press.last, landed)
1128 } else {
1129 None
1130 }
1131 }
1132
1133 fn drag_motion(&mut self, at: Point) -> Vec<Call> {
1136 let Some(press) = self.pointer.pressed.as_mut() else {
1137 return Vec::new();
1138 };
1139 press.last = at;
1140 let press = *press;
1141 if press.button != PointerButton::Left {
1142 return Vec::new();
1143 }
1144 if press.dragging && self.selects(press.id) {
1145 self.drag_text(press.id, at);
1146 return Vec::new();
1147 }
1148 if press.dragging {
1149 return self
1150 .drag_call(press, DragPhase::Move, at, None)
1151 .into_iter()
1152 .collect();
1153 }
1154 if distance(press.at, at) <= DRAG_THRESHOLD {
1155 return Vec::new();
1156 }
1157 self.stop_long_press(press.id);
1158 if self.drags(press.id) {
1159 self.start_drag(at)
1160 } else {
1161 Vec::new()
1162 }
1163 }
1164
1165 fn start_drag(&mut self, at: Point) -> Vec<Call> {
1167 let Some(press) = self.pointer.pressed.as_mut() else {
1168 return Vec::new();
1169 };
1170 press.dragging = true;
1171 let press = *press;
1172 self.stop_long_press(press.id);
1173 self.update_drop();
1174 self
1175 .drag_call(press, DragPhase::Start, at, None)
1176 .into_iter()
1177 .collect()
1178 }
1179
1180 pub(crate) fn drag_call(
1181 &self,
1182 press: Press,
1183 phase: DragPhase,
1184 at: Point,
1185 landed: Option<Rc<Cell<bool>>>,
1186 ) -> Option<Call> {
1187 let rect = self.node(press.id)?.rect?;
1188 let drag = Drag {
1189 phase,
1190 start: press.start,
1191 position: self.button_local(press.id, at).unwrap_or(press.start),
1194 size: Size::new(rect.width, rect.height),
1195 dropped: false,
1196 };
1197 self.call(press.id, Action::Drag(drag, landed))
1198 }
1199
1200 fn arm_long_press(&mut self, id: NodeId) {
1203 let tree = self.this.clone();
1204 let Some(Node { cx, kind, .. }) = self.node_mut(id) else {
1205 return;
1206 };
1207 let NodeKind::Button(button) = kind else {
1208 return;
1209 };
1210 match button.long_press {
1211 Some(timer) => timer.restart(),
1212 None => {
1213 let timer = cx.after(LONG_PRESS, move || long_press_fired(&tree, id));
1214 button.long_press = Some(timer);
1215 }
1216 }
1217 }
1218
1219 fn stop_long_press(&self, id: NodeId) {
1220 if let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind)
1221 && let Some(timer) = button.long_press
1222 {
1223 timer.stop();
1224 }
1225 }
1226
1227 fn long_press(&mut self, id: NodeId) -> Option<Call> {
1229 let press = self.pointer.pressed.as_mut().filter(|press| {
1230 press.id == id
1231 && press.button == PointerButton::Left
1232 && !press.dragging
1233 && !press.long_pressed
1234 })?;
1235 press.long_pressed = true;
1236 self.call(id, Action::LongPress)
1237 }
1238
1239 pub(crate) fn leave(&mut self) -> Vec<Call> {
1242 self.pointer.position = None;
1243 self.release_bar();
1244 self.flick_release(None);
1245 if let Some(id) = self.pointer.gesture.take() {
1246 self.release_view(id, None);
1247 }
1248 let out = self.pointer.pressed.is_some_and(|press| press.out);
1250 let calls = match out {
1251 true => Vec::new(),
1252 false => self.end_press(None).into_iter().collect(),
1253 };
1254 self.set_hovered(None, &[]);
1255 self.set_positions(&[], None);
1256 self.hover_link();
1257 calls
1258 }
1259
1260 pub(crate) fn set_enabled(&mut self, id: NodeId, enabled: bool) -> Vec<Call> {
1264 let Some(NodeKind::Button(button)) = self.node_mut(id).map(|node| &mut node.kind) else {
1265 return Vec::new();
1266 };
1267 if std::mem::replace(&mut button.enabled, enabled) == enabled {
1268 return Vec::new();
1269 }
1270 self.node_event(id, |id| AccessEvent::Enabled(id, enabled));
1271 let mut calls = Vec::new();
1272 if !enabled {
1273 if self.pointer.pressed.is_some_and(|press| press.id == id) {
1274 calls.extend(self.end_press(None));
1275 }
1276 if self.keyboard.focused == Some(id) {
1277 self.focus(None);
1278 }
1279 }
1280 if let Some(at) = self.pointer.position {
1281 self.hover_at(at);
1282 }
1283 calls
1284 }
1285
1286 pub(crate) fn bind_enabled(&mut self, id: NodeId, prop: Prop<bool>) {
1289 let mut compute = match prop.0 {
1290 PropKind::Value(enabled) => {
1292 self.set_enabled(id, enabled);
1293 return;
1294 }
1295 PropKind::Binding(compute) => compute,
1296 };
1297 let Some(node) = self.node(id) else {
1298 return;
1299 };
1300 let label = format!("{}.enabled", node.path);
1301 let tree = self.this.clone();
1302 node
1303 .cx
1304 .effect(move || {
1305 let enabled = compute();
1306 let Some(tree) = tree.upgrade() else {
1307 return;
1308 };
1309 let calls = borrow(&tree).set_enabled(id, enabled);
1310 untrack(|| run_all(calls));
1312 })
1313 .named(label);
1314 }
1315
1316 pub(crate) fn enabled(&self, id: NodeId) -> bool {
1318 match self.node(id).map(|node| &node.kind) {
1319 Some(NodeKind::Button(button)) => button.enabled,
1320 _ => true,
1321 }
1322 }
1323
1324 fn scroll(&mut self, wheel: Wheel, time: u32) -> Vec<Call> {
1325 let wants = |h: &Handlers| h.scroll.is_some() || h.wheel.is_some();
1326 let target = self.pointer.hovered.filter(|&id| self.has(id, wants));
1327 let calls = match target {
1328 None => {
1329 self.scroll_view(wheel, time);
1330 Vec::new()
1331 }
1332 Some(target) => {
1333 let mut calls = Vec::new();
1334 if self.has(target, |h| h.wheel.is_some()) {
1335 calls.extend(self.call(target, Action::Wheel(wheel)));
1336 }
1337 if self.has(target, |h| h.scroll.is_some()) {
1338 let down = self.steps(wheel.y);
1339 if down != 0 {
1341 calls.extend(self.call(target, Action::Scroll(down.saturating_neg())));
1342 }
1343 }
1344 calls
1345 }
1346 };
1347 if wheel.y.stop {
1348 self.pointer.pixels = 0.0;
1349 }
1350 if wheel.source == ScrollSource::Finger
1354 && (wheel.x.stop || wheel.y.stop)
1355 && let Some(id) = self.pointer.gesture.take()
1356 {
1357 self.release_view(id, Some(time));
1358 }
1359 calls
1360 }
1361
1362 fn steps(&mut self, axis: WheelAxis) -> i32 {
1365 if axis.notches != 0.0 && axis.notches.is_finite() {
1366 let value120 = (axis.notches * VALUE120_PER_STEP as f32).round() as i32;
1368 self.pointer.wheel = self.pointer.wheel.saturating_add(value120);
1369 let steps = self.pointer.wheel / VALUE120_PER_STEP;
1370 self.pointer.wheel -= steps * VALUE120_PER_STEP;
1371 steps
1372 } else if axis.pixels.is_finite() {
1373 self.pointer.pixels += axis.pixels;
1374 let steps = (self.pointer.pixels / PIXELS_PER_STEP).trunc();
1375 self.pointer.pixels -= steps * PIXELS_PER_STEP;
1376 steps as i32
1377 } else {
1378 0
1379 }
1380 }
1381
1382 pub(crate) fn cancel_press(&mut self) {
1385 if let Some(press) = self.pointer.pressed.filter(|press| !press.dragging) {
1386 self.set_pressed(None);
1387 self.stop_long_press(press.id);
1388 }
1389 }
1390
1391 pub(crate) fn has(&self, id: NodeId, f: impl FnOnce(&Handlers) -> bool) -> bool {
1393 let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
1394 return false;
1395 };
1396 untrack(|| button.handlers.try_with(f)).unwrap_or(false)
1397 }
1398
1399 pub(crate) fn local_point(&self, id: NodeId, point: Point) -> Option<Point> {
1403 self
1404 .path_to(id)
1405 .iter()
1406 .try_fold(point, |point, &id| local(self.node(id)?, point))
1407 }
1408
1409 pub(crate) fn window_rect(&self, id: NodeId, rect: Rect) -> Rect {
1413 let mut rect = rect;
1414 let mut at = Some(id);
1415 while let Some(current) = at {
1416 if let Some(transform) = self.node(current).and_then(|node| node.transform) {
1417 rect = transform.map_rect(rect);
1418 }
1419 at = self.taffy.parent(current);
1420 }
1421 rect
1422 }
1423
1424 pub(crate) fn click(&self, id: NodeId) -> Option<Call> {
1426 self.call(id, Action::Click)
1427 }
1428
1429 pub(crate) fn call(&self, id: NodeId, action: Action) -> Option<Call> {
1430 let node = self.node(id)?;
1431 let NodeKind::Button(button) = &node.kind else {
1432 return None;
1433 };
1434 Some(Call {
1435 cx: node.cx.clone(),
1436 path: Rc::clone(&node.path),
1437 handlers: Some(button.handlers),
1438 action,
1439 })
1440 }
1441}
1442
1443fn long_press_fired(tree: &Weak<RefCell<Tree>>, id: NodeId) {
1445 let Some(tree) = tree.upgrade() else {
1446 return;
1447 };
1448 let Ok(mut borrowed) = tree.try_borrow_mut() else {
1450 return;
1451 };
1452 let call = borrowed.long_press(id);
1453 drop(borrowed);
1454 if let Some(call) = call {
1455 call.run();
1456 }
1457}
1458
1459pub(crate) fn local(node: &Node, point: Point) -> Option<Point> {
1463 match node.transform {
1464 Some(transform) => Some(transform.invert()?.map(point)),
1465 None => Some(point),
1466 }
1467}
1468
1469#[derive(Clone)]
1470pub(crate) enum Action {
1471 Click,
1472 Press,
1473 AnyPress(PointerButton),
1474 Release,
1475 DoubleClick,
1476 LongPress,
1477 RightClick,
1478 MiddleClick,
1479 Back,
1480 Forward,
1481 Scroll(i32),
1482 Wheel(Wheel),
1483 Drag(Drag, Option<Rc<Cell<bool>>>),
1485 Drop(DragValue, Rc<Cell<bool>>),
1487 Link(LinkHandler, String, Weak<RefCell<Tree>>, NodeId),
1490}
1491
1492pub(crate) struct Call {
1494 cx: Cx,
1495 path: Rc<str>,
1496 handlers: Option<Signal<Handlers>>,
1498 action: Action,
1499}
1500
1501enum Picked {
1503 Plain(ClickHandler, &'static str),
1504 AnyPress(AnyPressHandler, PointerButton),
1505 Scroll(ScrollHandler, i32),
1506 Wheel(WheelHandler, Wheel),
1507 Drag(DragHandler, Drag),
1508 Drop(DropHandler, &'static str, DragValue, Rc<Cell<bool>>),
1509}
1510
1511impl Call {
1512 pub(crate) fn run(self) {
1513 let (path, cx) = (&self.path, &self.cx);
1514 if let Action::Link(handler, url, tree, id) = &self.action {
1515 run_isolated(path, "on_link", Rc::clone(handler), |f| f(cx, url));
1516 if handler.disabled()
1518 && let Some(tree) = tree.upgrade()
1519 && let Ok(mut tree) = tree.try_borrow_mut()
1520 {
1521 tree.light_link(*id, false, None);
1522 tree.light_link(*id, true, None);
1523 }
1524 return;
1525 }
1526 let Some(handlers) = self.handlers else {
1527 return;
1528 };
1529 let picked = untrack(|| {
1531 handlers.try_with(|h| {
1532 let plain = |handler: &Option<ClickHandler>, name| {
1533 handler.clone().map(|handler| Picked::Plain(handler, name))
1534 };
1535 match &self.action {
1536 Action::Click => plain(&h.click, "on_click"),
1537 Action::Press => plain(&h.press, "on_press"),
1538 Action::AnyPress(button) => h.any_press.clone().map(|f| Picked::AnyPress(f, *button)),
1539 Action::Release => plain(&h.release, "on_release"),
1540 Action::DoubleClick => plain(&h.double_click, "on_double_click"),
1541 Action::LongPress => plain(&h.long_press, "on_long_press"),
1542 Action::RightClick => plain(&h.right_click, "on_right_click"),
1543 Action::MiddleClick => plain(&h.middle_click, "on_middle_click"),
1544 Action::Back => plain(&h.back, "on_back"),
1545 Action::Forward => plain(&h.forward, "on_forward"),
1546 Action::Scroll(steps) => h.scroll.clone().map(|f| Picked::Scroll(f, *steps)),
1547 Action::Wheel(wheel) => h.wheel.clone().map(|f| Picked::Wheel(f, *wheel)),
1548 Action::Drag(drag, landed) => {
1549 let drag = Drag {
1550 dropped: landed.as_ref().is_some_and(|landed| landed.get()),
1551 ..*drag
1552 };
1553 h.drag.clone().map(|f| Picked::Drag(f, drag))
1554 }
1555 Action::Drop(value, landed) => {
1556 let target = h.drop.as_ref()?;
1557 Some(Picked::Drop(
1558 target.handler.clone(),
1559 target.name,
1560 Rc::clone(value),
1561 Rc::clone(landed),
1562 ))
1563 }
1564 Action::Link(..) => None,
1565 }
1566 })
1567 });
1568 let Some(Some(picked)) = picked else {
1569 return;
1570 };
1571 match picked {
1572 Picked::Plain(handler, name) => {
1573 run_isolated(path, name, handler, |f| f(cx));
1574 }
1575 Picked::AnyPress(handler, button) => {
1576 run_isolated(path, "on_any_press", handler, |f| f(cx, button));
1577 }
1578 Picked::Scroll(handler, steps) => {
1579 run_isolated(path, "on_scroll", handler, |f| f(cx, steps));
1580 }
1581 Picked::Wheel(handler, wheel) => {
1582 run_isolated(path, "on_wheel", handler, |f| f(cx, wheel));
1583 }
1584 Picked::Drag(handler, drag) => {
1585 run_isolated(path, "on_drag", handler, |f| f(cx, drag));
1586 }
1587 Picked::Drop(handler, name, value, landed) => {
1589 let ran = run_isolated(path, name, handler, move |f| f(cx, &*value));
1590 landed.set(ran.is_some());
1591 }
1592 }
1593 }
1594}
1595
1596pub(crate) fn run_isolated<F: ?Sized, R>(
1601 path: &str,
1602 name: &str,
1603 handler: Rc<Handler<F>>,
1604 call: impl FnOnce(&F) -> R,
1605) -> Option<R> {
1606 if handler.disabled.get() {
1607 return None;
1608 }
1609 let result = match panic::catch_unwind(AssertUnwindSafe(|| call(&handler.f))) {
1610 Ok(result) => Some(result),
1611 Err(payload) => {
1612 handler.disabled.set(true);
1613 tracing::error!(
1614 "handler {path}.{name} panicked and is disabled: {}",
1615 panic_message(payload.as_ref())
1616 );
1617 None
1618 }
1619 };
1620 if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(move || drop(handler))) {
1621 tracing::error!(
1622 "dropping handler {path}.{name} panicked: {}",
1623 panic_message(payload.as_ref())
1624 );
1625 }
1626 result
1627}
1628
1629pub(crate) fn panic_message(payload: &(dyn Any + Send)) -> &str {
1630 if let Some(message) = payload.downcast_ref::<&str>() {
1631 message
1632 } else if let Some(message) = payload.downcast_ref::<String>() {
1633 message
1634 } else {
1635 "(panic payload is not a string)"
1636 }
1637}