Skip to main content

crabshell_ui/
input.rs

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