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