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