Skip to main content

crabshell_ui/
input.rs

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