Skip to main content

crabshell_ui/
input.rs

1//! Pointer input: hit testing, hover and pressed state, drags, long
2//! presses, double clicks, scrolling and calling button handlers.
3//!
4//! The platform turns `wl_pointer` and `wl_touch` events into calls on
5//! [`Window`]. Handlers run after the window's tree is released, inside
6//! `catch_unwind`, so a panicking handler is logged and disabled and the bar
7//! keeps running.
8
9use std::any::{Any, TypeId};
10use std::cell::{Cell, RefCell};
11use std::panic::{self, AssertUnwindSafe};
12use std::rc::{Rc, Weak};
13use std::sync::OnceLock;
14use std::time::{Duration, Instant};
15
16use crabshell_reactive::{Signal, untrack};
17
18use crate::cx::Cx;
19use crate::geometry::{Point, Rect, Size};
20use crate::keyboard::KeyHandler;
21use crate::prop::{Prop, PropKind};
22use crate::scrolling::{BarDrag, Flick};
23use crate::select::{TextClick, text_selection};
24use crate::tree::{ButtonNode, Change, Node, NodeId, NodeKind, Tree, add_damage, borrow};
25use crate::window::Window;
26
27/// Logical pixels of touchpad scrolling per scroll step.
28pub(crate) const PIXELS_PER_STEP: f32 = 15.0;
29
30/// `axis_value120` units per mouse-wheel notch.
31const VALUE120_PER_STEP: i32 = 120;
32
33/// How far a held left button moves before it drags, in logical pixels:
34/// Qt's `startDragDistance`.
35pub(crate) const DRAG_THRESHOLD: f32 = 10.0;
36
37/// How long the left button is held for a long press: Qt's
38/// `pressAndHoldInterval`.
39const LONG_PRESS: Duration = Duration::from_millis(800);
40
41/// The most time between two clicks of a double click, in milliseconds:
42/// Qt's `mouseDoubleClickInterval`.
43pub(crate) const DOUBLE_CLICK_MS: u32 = 400;
44
45/// The farthest apart two clicks of a double click are, in logical
46/// pixels: Qt's `mouseDoubleClickDistance`.
47pub(crate) const DOUBLE_CLICK_DISTANCE: f32 = 5.0;
48
49/// A user's event handler, and whether it was disabled after panicking.
50pub(crate) struct Handler<F: ?Sized> {
51  disabled: Cell<bool>,
52  f: F,
53}
54
55impl<F> Handler<F> {
56  pub(crate) fn new(f: F) -> Handler<F> {
57    Handler {
58      disabled: Cell::new(false),
59      f,
60    }
61  }
62}
63
64impl<F: ?Sized> Handler<F> {
65  /// Whether it panicked once, so it never runs again.
66  pub(crate) fn disabled(&self) -> bool {
67    self.disabled.get()
68  }
69}
70
71pub(crate) type ClickHandler = Rc<Handler<dyn Fn(&Cx)>>;
72type ScrollHandler = Rc<Handler<dyn Fn(&Cx, i32)>>;
73pub(crate) type WheelHandler = Rc<Handler<dyn Fn(&Cx, Wheel)>>;
74pub(crate) type DragHandler = Rc<Handler<dyn Fn(&Cx, Drag)>>;
75pub(crate) type LinkHandler = Rc<Handler<dyn Fn(&Cx, &str)>>;
76
77/// What a drag carries: a [`Button::drag_data`](crate::Button::drag_data)
78/// value of any type, shared so a drop doesn't copy it until a target
79/// takes it.
80pub(crate) type DragValue = Rc<dyn Any>;
81
82/// A button's `on_drop`, which takes values of one type only.
83pub(crate) struct DropTarget {
84  pub(crate) accepts: TypeId,
85  pub(crate) handler: DropHandler,
86}
87
88/// Takes a value it downcasts, so it is the same type for every `T`.
89pub(crate) type DropHandler = Rc<Handler<dyn Fn(&Cx, &dyn Any)>>;
90
91/// A button's handlers.
92#[derive(Default)]
93pub(crate) struct Handlers {
94  pub(crate) click: Option<ClickHandler>,
95  pub(crate) press: Option<ClickHandler>,
96  pub(crate) release: Option<ClickHandler>,
97  pub(crate) double_click: Option<ClickHandler>,
98  pub(crate) long_press: Option<ClickHandler>,
99  pub(crate) right_click: Option<ClickHandler>,
100  pub(crate) middle_click: Option<ClickHandler>,
101  pub(crate) back: Option<ClickHandler>,
102  pub(crate) forward: Option<ClickHandler>,
103  pub(crate) scroll: Option<ScrollHandler>,
104  pub(crate) wheel: Option<WheelHandler>,
105  pub(crate) drag: Option<DragHandler>,
106  pub(crate) drop: Option<DropTarget>,
107  pub(crate) key: Option<KeyHandler>,
108}
109
110/// A pointer button.
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub enum PointerButton {
113  /// The primary button; it runs `on_click`.
114  Left,
115  /// The secondary button; it runs `on_right_click`.
116  Right,
117  /// The middle button; it runs `on_middle_click`.
118  Middle,
119  /// The side button for going back (`BTN_SIDE` or `BTN_BACK`); it runs
120  /// `on_back`.
121  Back,
122  /// The side button for going forward (`BTN_EXTRA` or `BTN_FORWARD`); it
123  /// runs `on_forward`.
124  Forward,
125}
126
127/// Where scrolling came from, as `wl_pointer.axis_source` says.
128#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
129pub enum ScrollSource {
130  /// A mouse wheel, which turns in notches. The default.
131  #[default]
132  Wheel,
133  /// Fingers on a touchpad, which scroll by pixels. When they lift, the
134  /// last event has `stop` set: the moment a kinetic scroll takes over.
135  Finger,
136  /// Something else that scrolls by pixels, such as a trackpoint.
137  Continuous,
138  /// A wheel tilted sideways, in notches.
139  WheelTilt,
140}
141
142/// One axis of a [`Wheel`].
143#[derive(Clone, Copy, Debug, Default, PartialEq)]
144pub struct WheelAxis {
145  /// How far, in logical pixels: positive down or right, as content
146  /// moves under a scroll offset that grows.
147  pub pixels: f32,
148  /// How far in wheel notches, positive down or right:
149  /// `axis_value120` over 120, so a high-resolution wheel gives
150  /// fractions. 0 for a touchpad.
151  pub notches: f32,
152  /// The scroll on this axis ended: the fingers lifted
153  /// (`wl_pointer.axis_stop`).
154  pub stop: bool,
155}
156
157/// One scroll event on both axes, as [`Button::on_wheel`](crate::Button::on_wheel)
158/// gets it and the platform hands it to [`Window::pointer_scroll`].
159#[derive(Clone, Copy, Debug, Default, PartialEq)]
160pub struct Wheel {
161  /// What scrolled.
162  pub source: ScrollSource,
163  /// Sideways.
164  pub x: WheelAxis,
165  /// Up and down.
166  pub y: WheelAxis,
167}
168
169/// Where a [`Drag`] is.
170#[derive(Clone, Copy, Debug, PartialEq, Eq)]
171pub enum DragPhase {
172  /// The drag began: the held left button moved past the threshold, or
173  /// went down on a button that only drags.
174  Start,
175  /// The pointer moved while dragging.
176  Move,
177  /// The drag ended: the button came up, the pointer left the window, or
178  /// the button was disabled.
179  End,
180}
181
182/// What [`Button::on_drag`](crate::Button::on_drag) gets each time a drag
183/// starts, moves or ends. Points are in the button's own coordinates:
184/// (0, 0) is its top-left corner, through any transform, so a slider turns
185/// `position.x / size.width` into its value.
186#[derive(Clone, Copy, Debug, PartialEq)]
187pub struct Drag {
188  /// Whether it starts, moves or ends.
189  pub phase: DragPhase,
190  /// Where the left button went down.
191  pub start: Point,
192  /// Where the pointer is now. It goes past the button's size, and below
193  /// 0, when the pointer leaves the button while dragging.
194  pub position: Point,
195  /// The button's laid-out size.
196  pub size: Size,
197  /// At `End`, whether the drag was released over a button whose
198  /// [`on_drop`](crate::Button::on_drop) took its
199  /// [`drag_data`](crate::Button::drag_data). Always `false` before.
200  pub dropped: bool,
201}
202
203/// The cursor the platform should show: every shape of
204/// `wp_cursor_shape_device_v1`, named as in CSS.
205#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
206pub enum CursorShape {
207  /// The default arrow.
208  #[default]
209  Default,
210  /// A context menu is available.
211  ContextMenu,
212  /// Help is available.
213  Help,
214  /// A pointing hand, over a button.
215  Pointer,
216  /// Busy, but still taking input.
217  Progress,
218  /// Busy; wait.
219  Wait,
220  /// A cell or cells can be picked.
221  Cell,
222  /// A crosshair.
223  Crosshair,
224  /// An I-beam, over a text field.
225  Text,
226  /// An I-beam for vertical text.
227  VerticalText,
228  /// Dropping makes an alias.
229  Alias,
230  /// Dropping copies.
231  Copy,
232  /// Something moves.
233  Move,
234  /// Can't be dropped here.
235  NoDrop,
236  /// Not allowed.
237  NotAllowed,
238  /// Can be grabbed.
239  Grab,
240  /// Being grabbed.
241  Grabbing,
242  /// Resizing the east edge.
243  EResize,
244  /// Resizing the north edge.
245  NResize,
246  /// Resizing the north-east corner.
247  NeResize,
248  /// Resizing the north-west corner.
249  NwResize,
250  /// Resizing the south edge.
251  SResize,
252  /// Resizing the south-east corner.
253  SeResize,
254  /// Resizing the south-west corner.
255  SwResize,
256  /// Resizing the west edge.
257  WResize,
258  /// Resizing east and west.
259  EwResize,
260  /// Resizing north and south.
261  NsResize,
262  /// Resizing north-east and south-west.
263  NeswResize,
264  /// Resizing north-west and south-east.
265  NwseResize,
266  /// A column can be resized sideways.
267  ColResize,
268  /// A row can be resized up and down.
269  RowResize,
270  /// Scrolls in any direction.
271  AllScroll,
272  /// Zooms in.
273  ZoomIn,
274  /// Zooms out.
275  ZoomOut,
276  /// Dropping asks which action to take. Needs version 2 of the
277  /// protocol; on version 1 a context menu cursor shows.
278  DndAsk,
279  /// Moves or resizes in any direction. Needs version 2 of the protocol;
280  /// on version 1 the move cursor shows.
281  AllResize,
282}
283
284/// A pointer button held on a button, until it comes up.
285#[derive(Clone, Copy)]
286struct Press {
287  id: NodeId,
288  button: PointerButton,
289  /// Where it went down and where the pointer was last, in window
290  /// coordinates.
291  at: Point,
292  last: Point,
293  /// Where it went down, in the button's own coordinates.
294  start: Point,
295  /// A drag started.
296  dragging: bool,
297  /// The long press ran, so the release doesn't click.
298  long_pressed: bool,
299}
300
301/// Where the pointer is and what it is doing.
302#[derive(Default)]
303pub(crate) struct Pointer {
304  pub(crate) position: Option<Point>,
305  /// The button under the pointer.
306  pub(crate) hovered: Option<NodeId>,
307  /// The buttons with a `hovered` signal that the pointer is inside: the
308  /// hovered one and those around it.
309  inside: Vec<(NodeId, Signal<bool>)>,
310  /// The buttons with a `pointer_position` signal that the pointer is
311  /// inside, and the position last written to each.
312  positions: Vec<(NodeId, Signal<Option<Point>>, Point)>,
313  /// The button a pointer button went down on, until it comes up.
314  pressed: Option<Press>,
315  /// The text, span index and URL of the link the left button went down
316  /// on, until it comes up.
317  link: Option<(NodeId, usize, String)>,
318  /// The text and link span the pointer is over, drawn lit.
319  link_hover: Option<(NodeId, usize)>,
320  /// A scroll bar's handle held, until the left button comes up.
321  pub(crate) bar: Option<BarDrag>,
322  /// The scroll views under the left button, one maybe dragged, until it
323  /// comes up.
324  pub(crate) flick: Option<Flick>,
325  /// The scroll view the touchpad gesture under way moves.
326  pub(crate) gesture: Option<NodeId>,
327  /// The last left click on a button, with the time it came up and
328  /// where it went down, which a second one may make a double click.
329  pub(crate) last_click: Option<(NodeId, u32, Point)>,
330  /// The last left press on text, for double and triple clicks and the
331  /// drag after them.
332  pub(crate) text_click: Option<TextClick>,
333  /// Scrolling that hasn't added up to a whole step yet.
334  wheel: i32,
335  pixels: f32,
336  /// A hover or press change asked for the pending layout.
337  caused_layout: bool,
338  /// The button a drag carrying data it takes is over, and its
339  /// `drop_hovered` signal.
340  drop_over: Option<(NodeId, Option<Signal<bool>>)>,
341}
342
343impl Pointer {
344  /// Forgets nodes that were removed from the tree. Nothing of theirs
345  /// runs after: a drag on one ends without its `End`.
346  pub(crate) fn forget(&mut self, removed: &[NodeId]) {
347    if self.hovered.is_some_and(|id| removed.contains(&id)) {
348      self.hovered = None;
349    }
350    let (gone, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut self.inside)
351      .into_iter()
352      .partition(|(id, _)| removed.contains(id));
353    for (_, signal) in gone {
354      // Unless a button still here shares it.
355      if !kept.iter().any(|(_, other)| *other == signal) {
356        signal.try_set(false);
357      }
358    }
359    self.inside = kept;
360    self.positions.retain(|(id, signal, _)| {
361      let gone = removed.contains(id);
362      if gone {
363        signal.try_set(None);
364      }
365      !gone
366    });
367    let source_gone = self
368      .pressed
369      .is_some_and(|press| removed.contains(&press.id));
370    if source_gone {
371      self.pressed = None;
372    }
373    if source_gone || self.drop_over.is_some_and(|(id, _)| removed.contains(&id)) {
374      self.set_drop_over(None);
375    }
376    self.forget_views(removed);
377    if self
378      .last_click
379      .is_some_and(|(id, _, _)| removed.contains(&id))
380    {
381      self.last_click = None;
382    }
383    if self
384      .text_click
385      .is_some_and(|click| removed.contains(&click.id))
386    {
387      self.text_click = None;
388    }
389  }
390}
391
392impl Pointer {
393  /// Makes `over` the button a drag waits to drop on, writing `false` to
394  /// the old one's `drop_hovered` and `true` to the new one's.
395  fn set_drop_over(&mut self, over: Option<(NodeId, Option<Signal<bool>>)>) {
396    let old = std::mem::replace(&mut self.drop_over, over);
397    if old.map(|(id, _)| id) == over.map(|(id, _)| id) {
398      return;
399    }
400    let (old, new) = (old.and_then(|(_, s)| s), over.and_then(|(_, s)| s));
401    if old != new {
402      if let Some(old) = old {
403        old.try_set(false);
404      }
405      if let Some(new) = new {
406        new.try_set(true);
407      }
408    }
409  }
410}
411
412impl Tree {
413  /// Lets go of hidden nodes as of removed ones, and shows the hovered or
414  /// pressed button among them as neither, so it shows again unhovered.
415  pub(crate) fn pointer_hide(&mut self, hidden: &[NodeId]) {
416    let held = [
417      self.pointer.hovered,
418      self.pointer.pressed.map(|press| press.id),
419    ];
420    self.pointer.forget(hidden);
421    for id in held.into_iter().flatten().filter(|id| hidden.contains(id)) {
422      self.update_button_style(id, |button| {
423        button.hovered = false;
424        button.pressed = false;
425      });
426    }
427  }
428}
429
430/// Milliseconds on a clock of this process, for events that come without
431/// the compositor's time.
432fn now_ms() -> u32 {
433  static START: OnceLock<Instant> = OnceLock::new();
434  // Wraps after 49 days, as `wl_pointer`'s times do.
435  START.get_or_init(Instant::now).elapsed().as_millis() as u32
436}
437
438impl Window {
439  /// The pointer entered the window or moved, to `position` in logical
440  /// pixels, now. See [`pointer_motion_at`](Self::pointer_motion_at).
441  pub fn pointer_motion(&self, position: Point) -> CursorShape {
442    self.pointer_motion_at(position, now_ms())
443  }
444
445  /// The pointer moved to `position` at `time`, in milliseconds as
446  /// `wl_pointer.motion` counts them, which a drag's fling is timed by.
447  /// A held left button that moved far enough drags: its button's, or
448  /// else a scroll view's child. Returns the cursor to show.
449  pub fn pointer_motion_at(&self, position: Point, time: u32) -> CursorShape {
450    let calls = {
451      let mut tree = borrow(&self.tree);
452      tree.pointer.position = Some(position);
453      tree.bar_motion(position);
454      let calls = if tree.flick_motion(position, time) {
455        Vec::new()
456      } else {
457        tree.drag_motion(position)
458      };
459      tree.hover_at(position);
460      calls
461    };
462    run_all(calls);
463    self.cursor()
464  }
465
466  /// The pointer left the window, or a touch was cancelled. A drag ends
467  /// with its `End`, and a held button never clicks.
468  pub fn pointer_leave(&self) {
469    let calls = borrow(&self.tree).leave();
470    run_all(calls);
471  }
472
473  /// A pointer button went down or up, now. See
474  /// [`pointer_button_at`](Self::pointer_button_at).
475  pub fn pointer_button(&self, button: PointerButton, pressed: bool) {
476    self.pointer_button_at(button, pressed, now_ms());
477  }
478
479  /// A pointer button went down or up at `time`, in milliseconds as
480  /// `wl_pointer.button` counts them, which double clicks are timed by.
481  /// Releasing the left button runs `on_release` of the button it went
482  /// down on, then ends its drag, or else, over that button still, runs
483  /// its `on_click` or `on_double_click`. The other buttons run
484  /// `on_right_click`, `on_middle_click`, `on_back` or `on_forward` when
485  /// released over the button they went down on.
486  pub fn pointer_button_at(&self, button: PointerButton, pressed: bool, time: u32) {
487    let calls = borrow(&self.tree).button(button, pressed, time, false);
488    run_all(calls);
489  }
490
491  /// A finger on a touchscreen went down or lifted at `time`, in
492  /// milliseconds as `wl_touch` counts them: a left press or release, as
493  /// [`pointer_button_at`](Self::pointer_button_at) gives, except that
494  /// its drag moves a scroll view's child even where `mouse_drag` is off.
495  pub fn touch_at(&self, pressed: bool, time: u32) {
496    let calls = borrow(&self.tree).button(PointerButton::Left, pressed, time, true);
497    run_all(calls);
498  }
499
500  /// The pointer scrolled. A button under the pointer with `on_wheel`
501  /// gets every event, and one with `on_scroll` the whole vertical steps
502  /// as they add up. Without either, the innermost scroll view under the
503  /// pointer that can still move that way scrolls along its axis. A
504  /// touchpad takes it past an end, and a fling keeps it going after the
505  /// fingers lift. A vertical `stop` drops a touchpad's
506  /// partial step, so it doesn't carry into the next gesture; a wheel's
507  /// partial notch is kept.
508  pub fn pointer_scroll(&self, wheel: Wheel) {
509    self.pointer_scroll_at(wheel, now_ms());
510  }
511
512  /// The pointer scrolled at `time`, in milliseconds as `wl_pointer.axis`
513  /// counts them, which a touchpad's fling is timed by. See
514  /// [`pointer_scroll`](Self::pointer_scroll).
515  pub fn pointer_scroll_at(&self, wheel: Wheel, time: u32) {
516    let calls = borrow(&self.tree).scroll(wheel, time);
517    run_all(calls);
518  }
519
520  /// The cursor to show.
521  pub fn cursor(&self) -> CursorShape {
522    self.tree.borrow().cursor()
523  }
524}
525
526/// Runs the handlers an event called for, in order, each isolated.
527fn run_all(calls: Vec<Call>) {
528  for call in calls {
529    call.run();
530  }
531}
532
533pub(crate) fn distance(a: Point, b: Point) -> f32 {
534  (a.x - b.x).hypot(a.y - b.y)
535}
536
537impl Tree {
538  /// The deepest enabled button or field under `point`, in the
539  /// coordinates of `id`'s parent, in `id`'s subtree, with the nodes on
540  /// the way down to it, itself included, pushed onto `path`. Children
541  /// drawn later are on top, so they are tried first. A disabled button
542  /// lets the pointer through to what is around it, and so does `skip`
543  /// with everything in it.
544  fn hit(
545    &self,
546    id: NodeId,
547    point: Point,
548    path: &mut Vec<NodeId>,
549    skip: Option<NodeId>,
550  ) -> Option<NodeId> {
551    if skip == Some(id) {
552      return None;
553    }
554    let node = self.node(id)?;
555    let point = local(node, point)?;
556    let rect = node.rect?;
557    // Children reach past the box when they are moved or overflow it, so
558    // the subtree's whole area is searched, and the box only for itself.
559    if !node.inner_bounds.contains(point) {
560      return None;
561    }
562    let style = node.effective_style();
563    // A clip hides its children under its border and past its corners.
564    let border = style.border.map_or(0.0, |border| border.width.max(0.0));
565    let corners = style.radius.unwrap_or_default();
566    let children = if node.clips() && !corners.contains(rect, border, point) {
567      Vec::new()
568    } else {
569      self.drawn_children(id)
570    };
571    path.push(id);
572    if let Some(hit) = children
573      .into_iter()
574      .rev()
575      .find_map(|child| self.hit(child, point, path, skip))
576    {
577      return Some(hit);
578    }
579    let takes = match &node.kind {
580      NodeKind::Button(button) => button.enabled,
581      NodeKind::Input(_) => true,
582      NodeKind::Text(text) => text.selectable,
583      _ => false,
584    };
585    if rect.contains(point) && takes {
586      return Some(id);
587    }
588    // A link is hit by its glyphs, even where they overflow the box.
589    if matches!(&node.kind, NodeKind::Text(text) if text.link_at(point).is_some()) {
590      return Some(id);
591    }
592    path.pop();
593    None
594  }
595
596  /// Hovers the deepest button under `point`, and marks the buttons around
597  /// it as having the pointer inside. A drag keeps its button hovered
598  /// wherever the pointer goes.
599  pub(crate) fn hover_at(&mut self, point: Point) {
600    let mut path = Vec::new();
601    let hit = match self.pointer.pressed.filter(|press| press.dragging) {
602      Some(press) => {
603        path = self.path_to(press.id);
604        Some(press.id)
605      }
606      None => self.hit(self.root, point, &mut path, None),
607    };
608    self.set_hovered(hit, &path);
609    self.set_positions(&path, Some(point));
610    self.update_drop();
611    self.hover_link();
612  }
613
614  /// Lights the link under the pointer and puts out the one it left.
615  fn hover_link(&mut self) {
616    let now = self.pointer.hovered.zip(self.link_under_pointer());
617    let old = std::mem::replace(&mut self.pointer.link_hover, now);
618    if old == now {
619      return;
620    }
621    if let Some((id, _)) = old {
622      self.light_link(id, false, None);
623    }
624    if let Some((id, index)) = now {
625      self.light_link(id, false, Some(index));
626    }
627  }
628
629  /// Sets the link of text `id` that the pointer, or with `focus` the
630  /// keyboard focus, lights, and repaints only the links whose look
631  /// changed.
632  pub(crate) fn light_link(&mut self, id: NodeId, focus: bool, index: Option<usize>) {
633    let Some(node) = self.node_mut(id) else {
634      return;
635    };
636    let laid_out = node.rect.is_some();
637    let NodeKind::Text(text) = &mut node.kind else {
638      return;
639    };
640    let slot = match focus {
641      true => &mut text.focused_link,
642      false => &mut text.hovered_link,
643    };
644    let old = std::mem::replace(slot, index);
645    if old == index || !laid_out {
646      return;
647    }
648    let areas: Vec<Rect> = old
649      .into_iter()
650      .chain(index)
651      .flat_map(|index| text.link_areas(index))
652      .collect();
653    for area in areas {
654      let area = self.window_area(id, area);
655      add_damage(&mut self.damage, area);
656    }
657  }
658
659  /// The type of what button `id` carries when dragged, if anything.
660  fn drag_type(&self, id: NodeId) -> Option<TypeId> {
661    let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
662      return None;
663    };
664    let data = button.drag_data?;
665    // The type of the value inside, not of the `Rc` around it.
666    untrack(|| data.try_with(|data| data.as_ref().map(|value| (**value).type_id()))).flatten()
667  }
668
669  /// The deepest enabled button under the pointer, other than the
670  /// dragged one and what is inside it, whose `on_drop` takes what it
671  /// carries.
672  fn drop_target(&self) -> Option<NodeId> {
673    let press = self.pointer.pressed.filter(|press| press.dragging)?;
674    let carried = self.drag_type(press.id)?;
675    let mut path = Vec::new();
676    self.hit(self.root, self.pointer.position?, &mut path, Some(press.id))?;
677    path.into_iter().rev().find(|&id| {
678      self.enabled(id)
679        && self.has(id, |h| {
680          // One whose `on_drop` panicked takes nothing more.
681          h.drop
682            .as_ref()
683            .is_some_and(|target| target.accepts == carried && !target.handler.disabled.get())
684        })
685    })
686  }
687
688  /// Finds the button a drag would drop on again, and tells the old one
689  /// and the new one through their `drop_hovered`.
690  fn update_drop(&mut self) {
691    let over = self.drop_target().map(|id| {
692      let signal = match self.node(id).map(|node| &node.kind) {
693        Some(NodeKind::Button(button)) => button.drop_hovered,
694        _ => None,
695      };
696      (id, signal)
697    });
698    self.pointer.set_drop_over(over);
699  }
700
701  /// Finds what a drag would drop on again after a pass that only moved
702  /// where things are drawn, as a slide does under a still pointer.
703  pub(crate) fn drop_after_place(&mut self) {
704    if self.pointer.pressed.is_some_and(|press| press.dragging) {
705      self.update_drop();
706    }
707  }
708
709  /// Whether `id` drags: a button with `on_drag`, or whose `drag_data`
710  /// holds a value now, or text, which selects.
711  fn drags(&self, id: NodeId) -> bool {
712    self.selects(id) || self.drag_type(id).is_some() || self.has(id, |h| h.drag.is_some())
713  }
714
715  /// The nodes from the root down to `id`, both included.
716  pub(crate) fn path_to(&self, id: NodeId) -> Vec<NodeId> {
717    let mut path = vec![id];
718    while let Some(parent) = path.last().and_then(|&id| self.taffy.parent(id)) {
719      path.push(parent);
720    }
721    path.reverse();
722    path
723  }
724
725  fn cursor(&self) -> CursorShape {
726    // A button dragging shows the grabbing hand, unless it set a shape of
727    // its own, such as a resize arrow.
728    let dragged = self
729      .pointer
730      .pressed
731      .filter(|press| press.dragging)
732      .and_then(|press| match self.node(press.id).map(|node| &node.kind) {
733        Some(NodeKind::Button(button)) => Some(button.cursor),
734        _ => None,
735      });
736    if let Some(shape) = dragged {
737      return match shape {
738        CursorShape::Pointer | CursorShape::Grab => CursorShape::Grabbing,
739        shape => shape,
740      };
741    }
742    match self
743      .pointer
744      .hovered
745      .and_then(|id| self.node(id))
746      .map(|node| &node.kind)
747    {
748      Some(NodeKind::Text(_)) if self.link_under_pointer().is_some() => CursorShape::Pointer,
749      Some(NodeKind::Input(_) | NodeKind::Text(_)) => CursorShape::Text,
750      Some(NodeKind::Button(button)) => button.cursor,
751      _ => CursorShape::Default,
752    }
753  }
754
755  /// Hover checked again after a layout, since buttons may have moved
756  /// under a pointer that didn't. Not after a layout a hover change asked
757  /// for: a hover style that moves the button off the pointer would
758  /// otherwise unhover it, move it back, hover it again, and so on.
759  pub(crate) fn pointer_after_layout(&mut self) {
760    if std::mem::take(&mut self.pointer.caused_layout) {
761      return;
762    }
763    if let Some(position) = self.pointer.position {
764      self.hover_at(position);
765    }
766  }
767
768  /// `hovered` is the button under the pointer, and `path` the nodes from
769  /// the root down to it.
770  fn set_hovered(&mut self, hovered: Option<NodeId>, path: &[NodeId]) {
771    self.set_inside(path);
772    let old = self.pointer.hovered;
773    if old == hovered {
774      return;
775    }
776    self.pointer.hovered = hovered;
777    self.pointer.wheel = 0;
778    self.pointer.pixels = 0.0;
779    if let Some(old) = old {
780      self.set_button_state(old, |button| button.hovered = false);
781    }
782    if let Some(new) = hovered {
783      self.set_button_state(new, |button| button.hovered = true);
784    }
785  }
786
787  /// The enabled buttons on `path` and what `pick` takes from each.
788  fn path_buttons<T>(
789    &self,
790    path: &[NodeId],
791    pick: impl Fn(&ButtonNode) -> Option<T>,
792  ) -> Vec<(NodeId, T)> {
793    path
794      .iter()
795      .filter_map(|&id| match &self.node(id)?.kind {
796        NodeKind::Button(button) if button.enabled => Some((id, pick(button)?)),
797        _ => None,
798      })
799      .collect()
800  }
801
802  /// Writes `false` to the `hovered` signals of the buttons the pointer
803  /// left and `true` to those it entered, among the nodes on `path`.
804  fn set_inside(&mut self, path: &[NodeId]) {
805    let inside = self.path_buttons(path, |button| button.hover_signal);
806    // Each signal is written once, and only on a change: `true` while any
807    // button sharing it has the pointer inside.
808    let holds = |list: &[(NodeId, Signal<bool>)], signal| list.iter().any(|(_, s)| *s == signal);
809    let mut seen = Vec::new();
810    for &(_, signal) in self.pointer.inside.iter().chain(&inside) {
811      if seen.contains(&signal) {
812        continue;
813      }
814      seen.push(signal);
815      let now = holds(&inside, signal);
816      if holds(&self.pointer.inside, signal) != now {
817        signal.try_set(now);
818      }
819    }
820    self.pointer.inside = inside;
821  }
822
823  /// Writes where the pointer is to the `pointer_position` signals of the
824  /// buttons on `path`, in each one's own coordinates, and `None` to
825  /// those it left. Each is written only on a change.
826  fn set_positions(&mut self, path: &[NodeId], at: Option<Point>) {
827    let now: Vec<(NodeId, Signal<Option<Point>>, Point)> = match at {
828      Some(at) => self
829        .path_buttons(path, |button| button.position_signal)
830        .into_iter()
831        .filter_map(|(id, signal)| Some((id, signal, self.button_local(id, at)?)))
832        .collect(),
833      None => Vec::new(),
834    };
835    for (id, signal, _) in &self.pointer.positions {
836      if !now.iter().any(|(other, ..)| other == id) {
837        signal.try_set(None);
838      }
839    }
840    for &(id, signal, point) in &now {
841      let same = |&(other, _, was): &(NodeId, _, Point)| other == id && was == point;
842      if !self.pointer.positions.iter().any(same) {
843        signal.try_set(Some(point));
844      }
845    }
846    self.pointer.positions = now;
847  }
848
849  /// `point`, in window coordinates, in button `id`'s own: (0, 0) at its
850  /// top-left corner, through the transforms around it.
851  fn button_local(&self, id: NodeId, point: Point) -> Option<Point> {
852    let rect = self.node(id)?.rect?;
853    let point = self.local_point(id, point)?;
854    Some(Point::new(point.x - rect.x, point.y - rect.y))
855  }
856
857  fn set_pressed(&mut self, pressed: Option<Press>) {
858    let old = std::mem::replace(&mut self.pointer.pressed, pressed);
859    if let Some(old) = old {
860      self.set_button_state(old.id, |button| button.pressed = false);
861    }
862    if let Some(new) = pressed {
863      self.set_button_state(new.id, |button| button.pressed = true);
864    }
865  }
866
867  /// Changes a button's hover or pressed state, noting when that needs a
868  /// layout.
869  fn set_button_state(&mut self, id: NodeId, f: impl FnOnce(&mut ButtonNode)) {
870    if self.update_button_style(id, f) == Change::Layout {
871      self.pointer.caused_layout = true;
872    }
873  }
874
875  fn button(&mut self, button: PointerButton, pressed: bool, time: u32, touch: bool) -> Vec<Call> {
876    if pressed {
877      self.press(button, time, touch)
878    } else {
879      self.release(button, time)
880    }
881  }
882
883  fn press(&mut self, button: PointerButton, time: u32, touch: bool) -> Vec<Call> {
884    if button == PointerButton::Left {
885      self.press_away(self.pointer.hovered);
886    }
887    // A scroll bar is drawn over what is under it, so it takes the press.
888    if let (PointerButton::Left, None, Some(at)) =
889      (button, self.pointer.pressed, self.pointer.position)
890      && self.press_bar(at)
891    {
892      return Vec::new();
893    }
894    if let (PointerButton::Left, None, Some(at)) =
895      (button, self.pointer.pressed, self.pointer.position)
896    {
897      let drags = self.pointer.hovered.is_some_and(|id| self.drags(id));
898      self.press_views(at, drags, touch);
899    }
900    let (None, Some(id), Some(at)) = (
901      self.pointer.pressed,
902      self.pointer.hovered,
903      self.pointer.position,
904    ) else {
905      return Vec::new();
906    };
907    let start = self.button_local(id, at).unwrap_or_default();
908    self.set_pressed(Some(Press {
909      id,
910      button,
911      at,
912      last: at,
913      start,
914      dragging: false,
915      long_pressed: false,
916    }));
917    if button != PointerButton::Left {
918      return Vec::new();
919    }
920    self.pointer.link = self.link_under(id, at);
921    if self.selects(id) {
922      self.press_text(id, at, time);
923    }
924    let mut calls: Vec<Call> = self.call(id, Action::Press).into_iter().collect();
925    if self.has(id, |h| h.long_press.is_some()) {
926      self.arm_long_press(id);
927    }
928    // Nothing waits on the threshold, so a slider moves from the press.
929    let waits =
930      |h: &Handlers| h.click.is_some() || h.double_click.is_some() || h.long_press.is_some();
931    if self.drags(id) && !self.has(id, waits) {
932      calls.extend(self.start_drag(at));
933    }
934    calls
935  }
936
937  fn release(&mut self, button: PointerButton, time: u32) -> Vec<Call> {
938    if button == PointerButton::Left {
939      self.release_bar();
940      self.flick_release(Some(time));
941    }
942    let Some(press) = self.pointer.pressed.filter(|press| press.button == button) else {
943      return Vec::new();
944    };
945    let mut calls = Vec::new();
946    if button == PointerButton::Left {
947      calls.extend(self.call(press.id, Action::Release));
948      let link = self.pointer.link.take();
949      calls.extend(link.and_then(|link| self.link_click(press, link)));
950    }
951    // Set by the drop once its `on_drop` returns, before the `End` reads it.
952    let landed = Rc::new(Cell::new(false));
953    calls.extend(self.drop_call(&landed));
954    calls.extend(self.end_press(Some(landed)));
955    if press.dragging {
956      // The hover the drag held goes back to what is under the pointer.
957      if let Some(at) = self.pointer.position {
958        self.hover_at(at);
959      }
960      return calls;
961    }
962    if press.long_pressed || self.pointer.hovered != Some(press.id) {
963      return calls;
964    }
965    let action = match button {
966      PointerButton::Left => self.left_click(press.id, time, press.at),
967      PointerButton::Right => Action::RightClick,
968      PointerButton::Middle => Action::MiddleClick,
969      PointerButton::Back => Action::Back,
970      PointerButton::Forward => Action::Forward,
971    };
972    calls.extend(self.call(press.id, action));
973    calls
974  }
975
976  /// The hovered text's link span under the pointer, if any.
977  fn link_under_pointer(&self) -> Option<usize> {
978    let id = self.pointer.hovered?;
979    let NodeKind::Text(text) = &self.node(id)?.kind else {
980      return None;
981    };
982    text.link_at(self.local_point(id, self.pointer.position?)?)
983  }
984
985  /// The link of text `id` under `at`, in window coordinates: the text,
986  /// the span's index and its URL.
987  fn link_under(&self, id: NodeId, at: Point) -> Option<(NodeId, usize, String)> {
988    let NodeKind::Text(text) = &self.node(id)?.kind else {
989      return None;
990    };
991    let index = text.link_at(self.local_point(id, at)?)?;
992    Some((id, index, text.spans[index].link.clone()?))
993  }
994
995  /// The `on_link` a left release ending `press` runs: the press went
996  /// down on `pressed`, and the same link, by span and URL, is under the
997  /// release, with nothing selected. The press's link is the one under
998  /// the pointer then, so a layout while held can't put another there.
999  fn link_click(&self, press: Press, pressed: (NodeId, usize, String)) -> Option<Call> {
1000    let node = self.node(press.id)?;
1001    let NodeKind::Text(text) = &node.kind else {
1002      return None;
1003    };
1004    if text_selection(text).is_some() {
1005      return None;
1006    }
1007    let released = self.link_under(press.id, self.pointer.position?)?;
1008    if pressed != released {
1009      return None;
1010    }
1011    self.link_call(press.id, released.1)
1012  }
1013
1014  /// Text `id`'s `on_link` with the URL of link span `index`, unless the
1015  /// handler panicked before.
1016  pub(crate) fn link_call(&self, id: NodeId, index: usize) -> Option<Call> {
1017    let node = self.node(id)?;
1018    let NodeKind::Text(text) = &node.kind else {
1019      return None;
1020    };
1021    let handler = text.on_link.clone().filter(|handler| !handler.disabled())?;
1022    let url = text.spans.get(index)?.link.clone()?;
1023    Some(Call {
1024      cx: node.cx.clone(),
1025      path: Rc::clone(&node.path),
1026      handlers: None,
1027      action: Action::Link(handler, url, self.this.clone(), id),
1028    })
1029  }
1030
1031  /// A left click on `id`, coming up at `time` after going down at `at`:
1032  /// a double click if it has `on_double_click` and the click before was
1033  /// close enough in time and place.
1034  fn left_click(&mut self, id: NodeId, time: u32, at: Point) -> Action {
1035    let close = self.pointer.last_click.is_some_and(|(last, then, place)| {
1036      last == id
1037        && time.wrapping_sub(then) <= DOUBLE_CLICK_MS
1038        && distance(place, at) <= DOUBLE_CLICK_DISTANCE
1039    });
1040    if close && self.has(id, |h| h.double_click.is_some()) {
1041      self.pointer.last_click = None;
1042      Action::DoubleClick
1043    } else {
1044      self.pointer.last_click = Some((id, time, at));
1045      Action::Click
1046    }
1047  }
1048
1049  /// The drop of what the dragged button carries on the button under the
1050  /// pointer that takes it, as the drag is released.
1051  fn drop_call(&self, landed: &Rc<Cell<bool>>) -> Option<Call> {
1052    let target = self.drop_target()?;
1053    let press = self.pointer.pressed?;
1054    let Some(NodeKind::Button(button)) = self.node(press.id).map(|node| &node.kind) else {
1055      return None;
1056    };
1057    let value = untrack(|| button.drag_data?.try_get().flatten())?;
1058    self.call(target, Action::Drop(value, Rc::clone(landed)))
1059  }
1060
1061  /// Lets go of the held button: its pressed style and long press end,
1062  /// its drag with an `End` whose `dropped` is what `landed` holds when it
1063  /// runs, and the button it would drop on is told.
1064  fn end_press(&mut self, landed: Option<Rc<Cell<bool>>>) -> Option<Call> {
1065    let press = self.pointer.pressed?;
1066    self.set_pressed(None);
1067    self.update_drop();
1068    self.stop_long_press(press.id);
1069    if press.dragging {
1070      self.drag_call(press, DragPhase::End, press.last, landed)
1071    } else {
1072      None
1073    }
1074  }
1075
1076  /// What a move to `at` does to a held left button: start a drag past
1077  /// the threshold, which also stops a long press, or move one.
1078  fn drag_motion(&mut self, at: Point) -> Vec<Call> {
1079    let Some(press) = self.pointer.pressed.as_mut() else {
1080      return Vec::new();
1081    };
1082    press.last = at;
1083    let press = *press;
1084    if press.button != PointerButton::Left {
1085      return Vec::new();
1086    }
1087    if press.dragging && self.selects(press.id) {
1088      self.drag_text(press.id, at);
1089      return Vec::new();
1090    }
1091    if press.dragging {
1092      return self
1093        .drag_call(press, DragPhase::Move, at, None)
1094        .into_iter()
1095        .collect();
1096    }
1097    if distance(press.at, at) <= DRAG_THRESHOLD {
1098      return Vec::new();
1099    }
1100    self.stop_long_press(press.id);
1101    if self.drags(press.id) {
1102      self.start_drag(at)
1103    } else {
1104      Vec::new()
1105    }
1106  }
1107
1108  /// Starts dragging the held button, with the pointer at `at`.
1109  fn start_drag(&mut self, at: Point) -> Vec<Call> {
1110    let Some(press) = self.pointer.pressed.as_mut() else {
1111      return Vec::new();
1112    };
1113    press.dragging = true;
1114    let press = *press;
1115    self.stop_long_press(press.id);
1116    self.update_drop();
1117    self
1118      .drag_call(press, DragPhase::Start, at, None)
1119      .into_iter()
1120      .collect()
1121  }
1122
1123  fn drag_call(
1124    &self,
1125    press: Press,
1126    phase: DragPhase,
1127    at: Point,
1128    landed: Option<Rc<Cell<bool>>>,
1129  ) -> Option<Call> {
1130    let rect = self.node(press.id)?.rect?;
1131    let drag = Drag {
1132      phase,
1133      start: press.start,
1134      // A transform that squashes the button flat leaves it where it went
1135      // down.
1136      position: self.button_local(press.id, at).unwrap_or(press.start),
1137      size: Size::new(rect.width, rect.height),
1138      dropped: false,
1139    };
1140    self.call(press.id, Action::Drag(drag, landed))
1141  }
1142
1143  /// Arms button `id`'s long press, from now. Each button keeps one
1144  /// timer, made at its first long press and freed with the button.
1145  fn arm_long_press(&mut self, id: NodeId) {
1146    let tree = self.this.clone();
1147    let Some(Node { cx, kind, .. }) = self.node_mut(id) else {
1148      return;
1149    };
1150    let NodeKind::Button(button) = kind else {
1151      return;
1152    };
1153    match button.long_press {
1154      Some(timer) => timer.restart(),
1155      None => {
1156        let timer = cx.after(LONG_PRESS, move || long_press_fired(&tree, id));
1157        button.long_press = Some(timer);
1158      }
1159    }
1160  }
1161
1162  fn stop_long_press(&self, id: NodeId) {
1163    if let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind)
1164      && let Some(timer) = button.long_press
1165    {
1166      timer.stop();
1167    }
1168  }
1169
1170  /// Button `id`'s long press, if it is still held, without a drag.
1171  fn long_press(&mut self, id: NodeId) -> Option<Call> {
1172    let press = self.pointer.pressed.as_mut().filter(|press| {
1173      press.id == id
1174        && press.button == PointerButton::Left
1175        && !press.dragging
1176        && !press.long_pressed
1177    })?;
1178    press.long_pressed = true;
1179    self.call(id, Action::LongPress)
1180  }
1181
1182  /// The pointer left: a drag ends, a held button lets go without a
1183  /// click, and nothing is hovered.
1184  pub(crate) fn leave(&mut self) -> Vec<Call> {
1185    self.pointer.position = None;
1186    self.release_bar();
1187    self.flick_release(None);
1188    if let Some(id) = self.pointer.gesture.take() {
1189      self.release_view(id, None);
1190    }
1191    let calls = self.end_press(None).into_iter().collect();
1192    self.set_hovered(None, &[]);
1193    self.set_positions(&[], None);
1194    self.hover_link();
1195    calls
1196  }
1197
1198  /// Turns button `id` on or off. Turned off, its press and drag end, the
1199  /// drag with an `End` that is returned, and it loses the focus and the
1200  /// pointer.
1201  pub(crate) fn set_enabled(&mut self, id: NodeId, enabled: bool) -> Vec<Call> {
1202    let Some(NodeKind::Button(button)) = self.node_mut(id).map(|node| &mut node.kind) else {
1203      return Vec::new();
1204    };
1205    if std::mem::replace(&mut button.enabled, enabled) == enabled {
1206      return Vec::new();
1207    }
1208    let mut calls = Vec::new();
1209    if !enabled {
1210      if self.pointer.pressed.is_some_and(|press| press.id == id) {
1211        calls.extend(self.end_press(None));
1212      }
1213      if self.keyboard.focused == Some(id) {
1214        self.focus(None);
1215      }
1216    }
1217    if let Some(at) = self.pointer.position {
1218      self.hover_at(at);
1219    }
1220    calls
1221  }
1222
1223  /// Binds button `id`'s `enabled`. Unlike other bindings it may run a
1224  /// handler: the `End` of a drag it cuts short.
1225  pub(crate) fn bind_enabled(&mut self, id: NodeId, prop: Prop<bool>) {
1226    let mut compute = match prop.0 {
1227      // Nothing is held while the button is made.
1228      PropKind::Value(enabled) => {
1229        self.set_enabled(id, enabled);
1230        return;
1231      }
1232      PropKind::Binding(compute) => compute,
1233    };
1234    let Some(node) = self.node(id) else {
1235      return;
1236    };
1237    let label = format!("{}.enabled", node.path);
1238    let tree = self.this.clone();
1239    node
1240      .cx
1241      .effect(move || {
1242        let enabled = compute();
1243        let Some(tree) = tree.upgrade() else {
1244          return;
1245        };
1246        let calls = borrow(&tree).set_enabled(id, enabled);
1247        // What the handler reads doesn't rerun this binding.
1248        untrack(|| run_all(calls));
1249      })
1250      .named(label);
1251  }
1252
1253  /// Whether button `id` is enabled. Anything else counts as enabled.
1254  pub(crate) fn enabled(&self, id: NodeId) -> bool {
1255    match self.node(id).map(|node| &node.kind) {
1256      Some(NodeKind::Button(button)) => button.enabled,
1257      _ => true,
1258    }
1259  }
1260
1261  fn scroll(&mut self, wheel: Wheel, time: u32) -> Vec<Call> {
1262    let wants = |h: &Handlers| h.scroll.is_some() || h.wheel.is_some();
1263    let target = self.pointer.hovered.filter(|&id| self.has(id, wants));
1264    let calls = match target {
1265      None => {
1266        self.scroll_view(wheel, time);
1267        Vec::new()
1268      }
1269      Some(target) => {
1270        let mut calls = Vec::new();
1271        if self.has(target, |h| h.wheel.is_some()) {
1272          calls.extend(self.call(target, Action::Wheel(wheel)));
1273        }
1274        if self.has(target, |h| h.scroll.is_some()) {
1275          let down = self.steps(wheel.y);
1276          // Handlers count up as positive.
1277          if down != 0 {
1278            calls.extend(self.call(target, Action::Scroll(down.saturating_neg())));
1279          }
1280        }
1281        calls
1282      }
1283    };
1284    if wheel.y.stop {
1285      self.pointer.pixels = 0.0;
1286    }
1287    // The fingers lifted: the view the gesture moved goes back from past
1288    // an end or on at its speed, even when a button that scrolled under
1289    // the pointer took this last event.
1290    if wheel.source == ScrollSource::Finger
1291      && (wheel.x.stop || wheel.y.stop)
1292      && let Some(id) = self.pointer.gesture.take()
1293    {
1294      self.release_view(id, Some(time));
1295    }
1296    calls
1297  }
1298
1299  /// The whole steps down that `axis` adds up to, rounded toward zero;
1300  /// the rest waits for more scrolling.
1301  fn steps(&mut self, axis: WheelAxis) -> i32 {
1302    if axis.notches != 0.0 && axis.notches.is_finite() {
1303      // `as` saturates a value too large.
1304      let value120 = (axis.notches * VALUE120_PER_STEP as f32).round() as i32;
1305      self.pointer.wheel = self.pointer.wheel.saturating_add(value120);
1306      let steps = self.pointer.wheel / VALUE120_PER_STEP;
1307      self.pointer.wheel -= steps * VALUE120_PER_STEP;
1308      steps
1309    } else if axis.pixels.is_finite() {
1310      self.pointer.pixels += axis.pixels;
1311      let steps = (self.pointer.pixels / PIXELS_PER_STEP).trunc();
1312      self.pointer.pixels -= steps * PIXELS_PER_STEP;
1313      steps as i32
1314    } else {
1315      0
1316    }
1317  }
1318
1319  /// Lets go of the button the left button is on, without a click or its
1320  /// `on_release`, as a scroll view's drag takes the pointer from it.
1321  pub(crate) fn cancel_press(&mut self) {
1322    if let Some(press) = self.pointer.pressed.filter(|press| !press.dragging) {
1323      self.set_pressed(None);
1324      self.stop_long_press(press.id);
1325    }
1326  }
1327
1328  /// Whether button `id` has the handlers `f` looks for.
1329  fn has(&self, id: NodeId, f: impl FnOnce(&Handlers) -> bool) -> bool {
1330    let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
1331      return false;
1332    };
1333    untrack(|| button.handlers.try_with(f)).unwrap_or(false)
1334  }
1335
1336  /// `point`, in window coordinates, in the coordinates node `id`'s
1337  /// rectangle is in, through the transforms of the node and its
1338  /// ancestors. `None` if one of them squashes it flat.
1339  pub(crate) fn local_point(&self, id: NodeId, point: Point) -> Option<Point> {
1340    self
1341      .path_to(id)
1342      .iter()
1343      .try_fold(point, |point, &id| local(self.node(id)?, point))
1344  }
1345
1346  /// The smallest rectangle covering where `rect`, in the coordinates
1347  /// node `id`'s rectangle is in, is drawn in the window: through the
1348  /// transforms of the node and its ancestors.
1349  pub(crate) fn window_rect(&self, id: NodeId, rect: Rect) -> Rect {
1350    let mut rect = rect;
1351    let mut at = Some(id);
1352    while let Some(current) = at {
1353      if let Some(transform) = self.node(current).and_then(|node| node.transform) {
1354        rect = transform.map_rect(rect);
1355      }
1356      at = self.taffy.parent(current);
1357    }
1358    rect
1359  }
1360
1361  /// A click on button `id`, as from the keyboard.
1362  pub(crate) fn click(&self, id: NodeId) -> Option<Call> {
1363    self.call(id, Action::Click)
1364  }
1365
1366  fn call(&self, id: NodeId, action: Action) -> Option<Call> {
1367    let node = self.node(id)?;
1368    let NodeKind::Button(button) = &node.kind else {
1369      return None;
1370    };
1371    Some(Call {
1372      cx: node.cx.clone(),
1373      path: Rc::clone(&node.path),
1374      handlers: Some(button.handlers),
1375      action,
1376    })
1377  }
1378}
1379
1380/// Runs button `id`'s long press, its timer having fired.
1381fn long_press_fired(tree: &Weak<RefCell<Tree>>, id: NodeId) {
1382  let Some(tree) = tree.upgrade() else {
1383    return;
1384  };
1385  // Timers fire from the loop, never while a tree is borrowed.
1386  let Ok(mut borrowed) = tree.try_borrow_mut() else {
1387    return;
1388  };
1389  let call = borrowed.long_press(id);
1390  drop(borrowed);
1391  if let Some(call) = call {
1392    call.run();
1393  }
1394}
1395
1396/// `point`, in the coordinates of `node`'s parent, in the node's own:
1397/// moved back through its transform. `None` for a transform that squashes
1398/// it flat, as a scale of 0 does, which nothing can point at.
1399pub(crate) fn local(node: &Node, point: Point) -> Option<Point> {
1400  match node.transform {
1401    Some(transform) => Some(transform.invert()?.map(point)),
1402    None => Some(point),
1403  }
1404}
1405
1406#[derive(Clone)]
1407enum Action {
1408  Click,
1409  Press,
1410  Release,
1411  DoubleClick,
1412  LongPress,
1413  RightClick,
1414  MiddleClick,
1415  Back,
1416  Forward,
1417  Scroll(i32),
1418  Wheel(Wheel),
1419  /// A drag, and at its `End` after a drop, whether the drop landed.
1420  Drag(Drag, Option<Rc<Cell<bool>>>),
1421  /// A drop, which says whether its `on_drop` ran and returned.
1422  Drop(DragValue, Rc<Cell<bool>>),
1423  /// A text's `on_link`, with the URL of the link clicked, and the tree
1424  /// and text to repaint plain if it panics.
1425  Link(LinkHandler, String, Weak<RefCell<Tree>>, NodeId),
1426}
1427
1428/// A handler to run once the tree is released.
1429pub(crate) struct Call {
1430  cx: Cx,
1431  path: Rc<str>,
1432  /// A button's handlers; a text's link carries its own.
1433  handlers: Option<Signal<Handlers>>,
1434  action: Action,
1435}
1436
1437/// A handler picked for a [`Call`], with what it gets.
1438enum Picked {
1439  Plain(ClickHandler, &'static str),
1440  Scroll(ScrollHandler, i32),
1441  Wheel(WheelHandler, Wheel),
1442  Drag(DragHandler, Drag),
1443  Drop(DropHandler, DragValue, Rc<Cell<bool>>),
1444}
1445
1446impl Call {
1447  pub(crate) fn run(self) {
1448    let (path, cx) = (&self.path, &self.cx);
1449    if let Action::Link(handler, url, tree, id) = &self.action {
1450      run_isolated(path, "on_link", Rc::clone(handler), |f| f(cx, url));
1451      // A handler that panicked leaves its links plain text.
1452      if handler.disabled()
1453        && let Some(tree) = tree.upgrade()
1454        && let Ok(mut tree) = tree.try_borrow_mut()
1455      {
1456        tree.light_link(*id, false, None);
1457        tree.light_link(*id, true, None);
1458      }
1459      return;
1460    }
1461    let Some(handlers) = self.handlers else {
1462      return;
1463    };
1464    // Reading the handlers doesn't make anything depend on them.
1465    let picked = untrack(|| {
1466      handlers.try_with(|h| {
1467        let plain = |handler: &Option<ClickHandler>, name| {
1468          handler.clone().map(|handler| Picked::Plain(handler, name))
1469        };
1470        match &self.action {
1471          Action::Click => plain(&h.click, "on_click"),
1472          Action::Press => plain(&h.press, "on_press"),
1473          Action::Release => plain(&h.release, "on_release"),
1474          Action::DoubleClick => plain(&h.double_click, "on_double_click"),
1475          Action::LongPress => plain(&h.long_press, "on_long_press"),
1476          Action::RightClick => plain(&h.right_click, "on_right_click"),
1477          Action::MiddleClick => plain(&h.middle_click, "on_middle_click"),
1478          Action::Back => plain(&h.back, "on_back"),
1479          Action::Forward => plain(&h.forward, "on_forward"),
1480          Action::Scroll(steps) => h.scroll.clone().map(|f| Picked::Scroll(f, *steps)),
1481          Action::Wheel(wheel) => h.wheel.clone().map(|f| Picked::Wheel(f, *wheel)),
1482          Action::Drag(drag, landed) => {
1483            let drag = Drag {
1484              dropped: landed.as_ref().is_some_and(|landed| landed.get()),
1485              ..*drag
1486            };
1487            h.drag.clone().map(|f| Picked::Drag(f, drag))
1488          }
1489          Action::Drop(value, landed) => {
1490            let target = h.drop.as_ref()?;
1491            Some(Picked::Drop(
1492              target.handler.clone(),
1493              Rc::clone(value),
1494              Rc::clone(landed),
1495            ))
1496          }
1497          Action::Link(..) => None,
1498        }
1499      })
1500    });
1501    let Some(Some(picked)) = picked else {
1502      return;
1503    };
1504    match picked {
1505      Picked::Plain(handler, name) => {
1506        run_isolated(path, name, handler, |f| f(cx));
1507      }
1508      Picked::Scroll(handler, steps) => {
1509        run_isolated(path, "on_scroll", handler, |f| f(cx, steps));
1510      }
1511      Picked::Wheel(handler, wheel) => {
1512        run_isolated(path, "on_wheel", handler, |f| f(cx, wheel));
1513      }
1514      Picked::Drag(handler, drag) => {
1515        run_isolated(path, "on_drag", handler, |f| f(cx, drag));
1516      }
1517      // The value goes inside, so its last copy is dropped isolated too.
1518      Picked::Drop(handler, value, landed) => {
1519        let ran = run_isolated(path, "on_drop", handler, move |f| f(cx, &*value));
1520        landed.set(ran.is_some());
1521      }
1522    }
1523  }
1524}
1525
1526/// Calls `handler` through `call` unless it was disabled, and disables it if
1527/// it panics. Returns what it returned, or `None` if it didn't run or
1528/// panicked. The handler is dropped here too, isolated the same way: if
1529/// the call freed its button, this was the last reference.
1530pub(crate) fn run_isolated<F: ?Sized, R>(
1531  path: &str,
1532  name: &str,
1533  handler: Rc<Handler<F>>,
1534  call: impl FnOnce(&F) -> R,
1535) -> Option<R> {
1536  if handler.disabled.get() {
1537    return None;
1538  }
1539  let result = match panic::catch_unwind(AssertUnwindSafe(|| call(&handler.f))) {
1540    Ok(result) => Some(result),
1541    Err(payload) => {
1542      handler.disabled.set(true);
1543      tracing::error!(
1544        "handler {path}.{name} panicked and is disabled: {}",
1545        panic_message(payload.as_ref())
1546      );
1547      None
1548    }
1549  };
1550  if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(move || drop(handler))) {
1551    tracing::error!(
1552      "dropping handler {path}.{name} panicked: {}",
1553      panic_message(payload.as_ref())
1554    );
1555  }
1556  result
1557}
1558
1559pub(crate) fn panic_message(payload: &(dyn Any + Send)) -> &str {
1560  if let Some(message) = payload.downcast_ref::<&str>() {
1561    message
1562  } else if let Some(message) = payload.downcast_ref::<String>() {
1563    message
1564  } else {
1565    "(panic payload is not a string)"
1566  }
1567}