Skip to main content

crabshell_ui/
input.rs

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