Skip to main content

crabshell_ui/
input.rs

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