use std::any::{Any, TypeId};
use std::cell::{Cell, RefCell};
use std::panic::{self, AssertUnwindSafe};
use std::rc::{Rc, Weak};
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use crabshell_reactive::{Signal, untrack};
use crate::cx::Cx;
use crate::geometry::{Point, Rect, Size};
use crate::keyboard::KeyHandler;
use crate::prop::{Prop, PropKind};
use crate::scrolling::{BarDrag, Flick};
use crate::tree::{ButtonNode, Change, Node, NodeId, NodeKind, Tree, borrow};
use crate::window::Window;
pub(crate) const PIXELS_PER_STEP: f32 = 15.0;
const VALUE120_PER_STEP: i32 = 120;
pub(crate) const DRAG_THRESHOLD: f32 = 10.0;
const LONG_PRESS: Duration = Duration::from_millis(800);
const DOUBLE_CLICK_MS: u32 = 400;
const DOUBLE_CLICK_DISTANCE: f32 = 5.0;
pub(crate) struct Handler<F: ?Sized> {
disabled: Cell<bool>,
f: F,
}
impl<F> Handler<F> {
pub(crate) fn new(f: F) -> Handler<F> {
Handler {
disabled: Cell::new(false),
f,
}
}
}
pub(crate) type ClickHandler = Rc<Handler<dyn Fn(&Cx)>>;
type ScrollHandler = Rc<Handler<dyn Fn(&Cx, i32)>>;
pub(crate) type WheelHandler = Rc<Handler<dyn Fn(&Cx, Wheel)>>;
pub(crate) type DragHandler = Rc<Handler<dyn Fn(&Cx, Drag)>>;
pub(crate) type DragValue = Rc<dyn Any>;
pub(crate) struct DropTarget {
pub(crate) accepts: TypeId,
pub(crate) handler: DropHandler,
}
pub(crate) type DropHandler = Rc<Handler<dyn Fn(&Cx, &dyn Any)>>;
#[derive(Default)]
pub(crate) struct Handlers {
pub(crate) click: Option<ClickHandler>,
pub(crate) press: Option<ClickHandler>,
pub(crate) release: Option<ClickHandler>,
pub(crate) double_click: Option<ClickHandler>,
pub(crate) long_press: Option<ClickHandler>,
pub(crate) right_click: Option<ClickHandler>,
pub(crate) middle_click: Option<ClickHandler>,
pub(crate) back: Option<ClickHandler>,
pub(crate) forward: Option<ClickHandler>,
pub(crate) scroll: Option<ScrollHandler>,
pub(crate) wheel: Option<WheelHandler>,
pub(crate) drag: Option<DragHandler>,
pub(crate) drop: Option<DropTarget>,
pub(crate) key: Option<KeyHandler>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PointerButton {
Left,
Right,
Middle,
Back,
Forward,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ScrollSource {
#[default]
Wheel,
Finger,
Continuous,
WheelTilt,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct WheelAxis {
pub pixels: f32,
pub notches: f32,
pub stop: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Wheel {
pub source: ScrollSource,
pub x: WheelAxis,
pub y: WheelAxis,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DragPhase {
Start,
Move,
End,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Drag {
pub phase: DragPhase,
pub start: Point,
pub position: Point,
pub size: Size,
pub dropped: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum CursorShape {
#[default]
Default,
ContextMenu,
Help,
Pointer,
Progress,
Wait,
Cell,
Crosshair,
Text,
VerticalText,
Alias,
Copy,
Move,
NoDrop,
NotAllowed,
Grab,
Grabbing,
EResize,
NResize,
NeResize,
NwResize,
SResize,
SeResize,
SwResize,
WResize,
EwResize,
NsResize,
NeswResize,
NwseResize,
ColResize,
RowResize,
AllScroll,
ZoomIn,
ZoomOut,
DndAsk,
AllResize,
}
#[derive(Clone, Copy)]
struct Press {
id: NodeId,
button: PointerButton,
at: Point,
last: Point,
start: Point,
dragging: bool,
long_pressed: bool,
}
#[derive(Default)]
pub(crate) struct Pointer {
pub(crate) position: Option<Point>,
pub(crate) hovered: Option<NodeId>,
inside: Vec<(NodeId, Signal<bool>)>,
positions: Vec<(NodeId, Signal<Option<Point>>, Point)>,
pressed: Option<Press>,
pub(crate) bar: Option<BarDrag>,
pub(crate) flick: Option<Flick>,
pub(crate) gesture: Option<NodeId>,
last_click: Option<(NodeId, u32, Point)>,
wheel: i32,
pixels: f32,
caused_layout: bool,
drop_over: Option<(NodeId, Option<Signal<bool>>)>,
}
impl Pointer {
pub(crate) fn forget(&mut self, removed: &[NodeId]) {
if self.hovered.is_some_and(|id| removed.contains(&id)) {
self.hovered = None;
}
let (gone, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut self.inside)
.into_iter()
.partition(|(id, _)| removed.contains(id));
for (_, signal) in gone {
if !kept.iter().any(|(_, other)| *other == signal) {
signal.try_set(false);
}
}
self.inside = kept;
self.positions.retain(|(id, signal, _)| {
let gone = removed.contains(id);
if gone {
signal.try_set(None);
}
!gone
});
let source_gone = self
.pressed
.is_some_and(|press| removed.contains(&press.id));
if source_gone {
self.pressed = None;
}
if source_gone || self.drop_over.is_some_and(|(id, _)| removed.contains(&id)) {
self.set_drop_over(None);
}
self.forget_views(removed);
if self
.last_click
.is_some_and(|(id, _, _)| removed.contains(&id))
{
self.last_click = None;
}
}
}
impl Pointer {
fn set_drop_over(&mut self, over: Option<(NodeId, Option<Signal<bool>>)>) {
let old = std::mem::replace(&mut self.drop_over, over);
if old.map(|(id, _)| id) == over.map(|(id, _)| id) {
return;
}
let (old, new) = (old.and_then(|(_, s)| s), over.and_then(|(_, s)| s));
if old != new {
if let Some(old) = old {
old.try_set(false);
}
if let Some(new) = new {
new.try_set(true);
}
}
}
}
impl Tree {
pub(crate) fn pointer_hide(&mut self, hidden: &[NodeId]) {
let held = [
self.pointer.hovered,
self.pointer.pressed.map(|press| press.id),
];
self.pointer.forget(hidden);
for id in held.into_iter().flatten().filter(|id| hidden.contains(id)) {
self.update_button_style(id, |button| {
button.hovered = false;
button.pressed = false;
});
}
}
}
fn now_ms() -> u32 {
static START: OnceLock<Instant> = OnceLock::new();
START.get_or_init(Instant::now).elapsed().as_millis() as u32
}
impl Window {
pub fn pointer_motion(&self, position: Point) -> CursorShape {
self.pointer_motion_at(position, now_ms())
}
pub fn pointer_motion_at(&self, position: Point, time: u32) -> CursorShape {
let calls = {
let mut tree = borrow(&self.tree);
tree.pointer.position = Some(position);
tree.bar_motion(position);
let calls = if tree.flick_motion(position, time) {
Vec::new()
} else {
tree.drag_motion(position)
};
tree.hover_at(position);
calls
};
run_all(calls);
self.cursor()
}
pub fn pointer_leave(&self) {
let calls = borrow(&self.tree).leave();
run_all(calls);
}
pub fn pointer_button(&self, button: PointerButton, pressed: bool) {
self.pointer_button_at(button, pressed, now_ms());
}
pub fn pointer_button_at(&self, button: PointerButton, pressed: bool, time: u32) {
let calls = borrow(&self.tree).button(button, pressed, time);
run_all(calls);
}
pub fn pointer_scroll(&self, wheel: Wheel) {
self.pointer_scroll_at(wheel, now_ms());
}
pub fn pointer_scroll_at(&self, wheel: Wheel, time: u32) {
let calls = borrow(&self.tree).scroll(wheel, time);
run_all(calls);
}
pub fn cursor(&self) -> CursorShape {
self.tree.borrow().cursor()
}
}
fn run_all(calls: Vec<Call>) {
for call in calls {
call.run();
}
}
fn distance(a: Point, b: Point) -> f32 {
(a.x - b.x).hypot(a.y - b.y)
}
impl Tree {
fn hit(
&self,
id: NodeId,
point: Point,
path: &mut Vec<NodeId>,
skip: Option<NodeId>,
) -> Option<NodeId> {
if skip == Some(id) {
return None;
}
let node = self.node(id)?;
let point = local(node, point)?;
let rect = node.rect?;
if !node.inner_bounds.contains(point) {
return None;
}
let style = node.effective_style();
let border = style.border.map_or(0.0, |border| border.width.max(0.0));
let corners = style.radius.unwrap_or_default();
let children = if node.clips() && !corners.contains(rect, border, point) {
Vec::new()
} else {
self.drawn_children(id)
};
path.push(id);
if let Some(hit) = children
.into_iter()
.rev()
.find_map(|child| self.hit(child, point, path, skip))
{
return Some(hit);
}
let takes = match &node.kind {
NodeKind::Button(button) => button.enabled,
NodeKind::Input(_) => true,
_ => false,
};
if rect.contains(point) && takes {
return Some(id);
}
path.pop();
None
}
pub(crate) fn hover_at(&mut self, point: Point) {
let mut path = Vec::new();
let hit = match self.pointer.pressed.filter(|press| press.dragging) {
Some(press) => {
path = self.path_to(press.id);
Some(press.id)
}
None => self.hit(self.root, point, &mut path, None),
};
self.set_hovered(hit, &path);
self.set_positions(&path, Some(point));
self.update_drop();
}
fn drag_type(&self, id: NodeId) -> Option<TypeId> {
let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
return None;
};
let data = button.drag_data?;
untrack(|| data.try_with(|data| data.as_ref().map(|value| (**value).type_id()))).flatten()
}
fn drop_target(&self) -> Option<NodeId> {
let press = self.pointer.pressed.filter(|press| press.dragging)?;
let carried = self.drag_type(press.id)?;
let mut path = Vec::new();
self.hit(self.root, self.pointer.position?, &mut path, Some(press.id))?;
path.into_iter().rev().find(|&id| {
self.enabled(id)
&& self.has(id, |h| {
h.drop
.as_ref()
.is_some_and(|target| target.accepts == carried && !target.handler.disabled.get())
})
})
}
fn update_drop(&mut self) {
let over = self.drop_target().map(|id| {
let signal = match self.node(id).map(|node| &node.kind) {
Some(NodeKind::Button(button)) => button.drop_hovered,
_ => None,
};
(id, signal)
});
self.pointer.set_drop_over(over);
}
pub(crate) fn drop_after_place(&mut self) {
if self.pointer.pressed.is_some_and(|press| press.dragging) {
self.update_drop();
}
}
fn drags(&self, id: NodeId) -> bool {
self.drag_type(id).is_some() || self.has(id, |h| h.drag.is_some())
}
pub(crate) fn path_to(&self, id: NodeId) -> Vec<NodeId> {
let mut path = vec![id];
while let Some(parent) = path.last().and_then(|&id| self.taffy.parent(id)) {
path.push(parent);
}
path.reverse();
path
}
fn cursor(&self) -> CursorShape {
match self
.pointer
.hovered
.and_then(|id| self.node(id))
.map(|node| &node.kind)
{
Some(NodeKind::Input(_)) => CursorShape::Text,
Some(NodeKind::Button(button)) => button.cursor,
_ => CursorShape::Default,
}
}
pub(crate) fn pointer_after_layout(&mut self) {
if std::mem::take(&mut self.pointer.caused_layout) {
return;
}
if let Some(position) = self.pointer.position {
self.hover_at(position);
}
}
fn set_hovered(&mut self, hovered: Option<NodeId>, path: &[NodeId]) {
self.set_inside(path);
let old = self.pointer.hovered;
if old == hovered {
return;
}
self.pointer.hovered = hovered;
self.pointer.wheel = 0;
self.pointer.pixels = 0.0;
if let Some(old) = old {
self.set_button_state(old, |button| button.hovered = false);
}
if let Some(new) = hovered {
self.set_button_state(new, |button| button.hovered = true);
}
}
fn path_buttons<T>(
&self,
path: &[NodeId],
pick: impl Fn(&ButtonNode) -> Option<T>,
) -> Vec<(NodeId, T)> {
path
.iter()
.filter_map(|&id| match &self.node(id)?.kind {
NodeKind::Button(button) if button.enabled => Some((id, pick(button)?)),
_ => None,
})
.collect()
}
fn set_inside(&mut self, path: &[NodeId]) {
let inside = self.path_buttons(path, |button| button.hover_signal);
let holds = |list: &[(NodeId, Signal<bool>)], signal| list.iter().any(|(_, s)| *s == signal);
let mut seen = Vec::new();
for &(_, signal) in self.pointer.inside.iter().chain(&inside) {
if seen.contains(&signal) {
continue;
}
seen.push(signal);
let now = holds(&inside, signal);
if holds(&self.pointer.inside, signal) != now {
signal.try_set(now);
}
}
self.pointer.inside = inside;
}
fn set_positions(&mut self, path: &[NodeId], at: Option<Point>) {
let now: Vec<(NodeId, Signal<Option<Point>>, Point)> = match at {
Some(at) => self
.path_buttons(path, |button| button.position_signal)
.into_iter()
.filter_map(|(id, signal)| Some((id, signal, self.button_local(id, at)?)))
.collect(),
None => Vec::new(),
};
for (id, signal, _) in &self.pointer.positions {
if !now.iter().any(|(other, ..)| other == id) {
signal.try_set(None);
}
}
for &(id, signal, point) in &now {
let same = |&(other, _, was): &(NodeId, _, Point)| other == id && was == point;
if !self.pointer.positions.iter().any(same) {
signal.try_set(Some(point));
}
}
self.pointer.positions = now;
}
fn button_local(&self, id: NodeId, point: Point) -> Option<Point> {
let rect = self.node(id)?.rect?;
let point = self.local_point(id, point)?;
Some(Point::new(point.x - rect.x, point.y - rect.y))
}
fn set_pressed(&mut self, pressed: Option<Press>) {
let old = std::mem::replace(&mut self.pointer.pressed, pressed);
if let Some(old) = old {
self.set_button_state(old.id, |button| button.pressed = false);
}
if let Some(new) = pressed {
self.set_button_state(new.id, |button| button.pressed = true);
}
}
fn set_button_state(&mut self, id: NodeId, f: impl FnOnce(&mut ButtonNode)) {
if self.update_button_style(id, f) == Change::Layout {
self.pointer.caused_layout = true;
}
}
fn button(&mut self, button: PointerButton, pressed: bool, time: u32) -> Vec<Call> {
if pressed {
self.press(button)
} else {
self.release(button, time)
}
}
fn press(&mut self, button: PointerButton) -> Vec<Call> {
if let (PointerButton::Left, None, Some(at)) =
(button, self.pointer.pressed, self.pointer.position)
&& self.press_bar(at)
{
return Vec::new();
}
if let (PointerButton::Left, None, Some(at)) =
(button, self.pointer.pressed, self.pointer.position)
{
let drags = self.pointer.hovered.is_some_and(|id| self.drags(id));
self.press_views(at, drags);
}
let (None, Some(id), Some(at)) = (
self.pointer.pressed,
self.pointer.hovered,
self.pointer.position,
) else {
return Vec::new();
};
let start = self.button_local(id, at).unwrap_or_default();
self.set_pressed(Some(Press {
id,
button,
at,
last: at,
start,
dragging: false,
long_pressed: false,
}));
if button != PointerButton::Left {
return Vec::new();
}
self.press_field(id);
let mut calls: Vec<Call> = self.call(id, Action::Press).into_iter().collect();
if self.has(id, |h| h.long_press.is_some()) {
self.arm_long_press(id);
}
let waits =
|h: &Handlers| h.click.is_some() || h.double_click.is_some() || h.long_press.is_some();
if self.drags(id) && !self.has(id, waits) {
calls.extend(self.start_drag(at));
}
calls
}
fn release(&mut self, button: PointerButton, time: u32) -> Vec<Call> {
if button == PointerButton::Left {
if let Some(bar) = self.pointer.bar.take() {
self.release_view(bar.view, None);
}
self.flick_release(Some(time));
}
let Some(press) = self.pointer.pressed.filter(|press| press.button == button) else {
return Vec::new();
};
let mut calls = Vec::new();
if button == PointerButton::Left {
calls.extend(self.call(press.id, Action::Release));
}
let landed = Rc::new(Cell::new(false));
calls.extend(self.drop_call(&landed));
calls.extend(self.end_press(Some(landed)));
if press.dragging {
if let Some(at) = self.pointer.position {
self.hover_at(at);
}
return calls;
}
if press.long_pressed || self.pointer.hovered != Some(press.id) {
return calls;
}
let action = match button {
PointerButton::Left => self.left_click(press.id, time, press.at),
PointerButton::Right => Action::RightClick,
PointerButton::Middle => Action::MiddleClick,
PointerButton::Back => Action::Back,
PointerButton::Forward => Action::Forward,
};
calls.extend(self.call(press.id, action));
calls
}
fn left_click(&mut self, id: NodeId, time: u32, at: Point) -> Action {
let close = self.pointer.last_click.is_some_and(|(last, then, place)| {
last == id
&& time.wrapping_sub(then) <= DOUBLE_CLICK_MS
&& distance(place, at) <= DOUBLE_CLICK_DISTANCE
});
if close && self.has(id, |h| h.double_click.is_some()) {
self.pointer.last_click = None;
Action::DoubleClick
} else {
self.pointer.last_click = Some((id, time, at));
Action::Click
}
}
fn drop_call(&self, landed: &Rc<Cell<bool>>) -> Option<Call> {
let target = self.drop_target()?;
let press = self.pointer.pressed?;
let Some(NodeKind::Button(button)) = self.node(press.id).map(|node| &node.kind) else {
return None;
};
let value = untrack(|| button.drag_data?.try_get().flatten())?;
self.call(target, Action::Drop(value, Rc::clone(landed)))
}
fn end_press(&mut self, landed: Option<Rc<Cell<bool>>>) -> Option<Call> {
let press = self.pointer.pressed?;
self.set_pressed(None);
self.update_drop();
self.stop_long_press(press.id);
if press.dragging {
self.drag_call(press, DragPhase::End, press.last, landed)
} else {
None
}
}
fn drag_motion(&mut self, at: Point) -> Vec<Call> {
let Some(press) = self.pointer.pressed.as_mut() else {
return Vec::new();
};
press.last = at;
let press = *press;
if press.button != PointerButton::Left {
return Vec::new();
}
if press.dragging {
return self
.drag_call(press, DragPhase::Move, at, None)
.into_iter()
.collect();
}
if distance(press.at, at) <= DRAG_THRESHOLD {
return Vec::new();
}
self.stop_long_press(press.id);
if self.drags(press.id) {
self.start_drag(at)
} else {
Vec::new()
}
}
fn start_drag(&mut self, at: Point) -> Vec<Call> {
let Some(press) = self.pointer.pressed.as_mut() else {
return Vec::new();
};
press.dragging = true;
let press = *press;
self.stop_long_press(press.id);
self.update_drop();
self
.drag_call(press, DragPhase::Start, at, None)
.into_iter()
.collect()
}
fn drag_call(
&self,
press: Press,
phase: DragPhase,
at: Point,
landed: Option<Rc<Cell<bool>>>,
) -> Option<Call> {
let rect = self.node(press.id)?.rect?;
let drag = Drag {
phase,
start: press.start,
position: self.button_local(press.id, at).unwrap_or(press.start),
size: Size::new(rect.width, rect.height),
dropped: false,
};
self.call(press.id, Action::Drag(drag, landed))
}
fn arm_long_press(&mut self, id: NodeId) {
let tree = self.this.clone();
let Some(Node { cx, kind, .. }) = self.node_mut(id) else {
return;
};
let NodeKind::Button(button) = kind else {
return;
};
match button.long_press {
Some(timer) => timer.restart(),
None => {
let timer = cx.after(LONG_PRESS, move || long_press_fired(&tree, id));
button.long_press = Some(timer);
}
}
}
fn stop_long_press(&self, id: NodeId) {
if let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind)
&& let Some(timer) = button.long_press
{
timer.stop();
}
}
fn long_press(&mut self, id: NodeId) -> Option<Call> {
let press = self.pointer.pressed.as_mut().filter(|press| {
press.id == id
&& press.button == PointerButton::Left
&& !press.dragging
&& !press.long_pressed
})?;
press.long_pressed = true;
self.call(id, Action::LongPress)
}
pub(crate) fn leave(&mut self) -> Vec<Call> {
self.pointer.position = None;
if let Some(bar) = self.pointer.bar.take() {
self.release_view(bar.view, None);
}
self.flick_release(None);
if let Some(id) = self.pointer.gesture.take() {
self.release_view(id, None);
}
let calls = self.end_press(None).into_iter().collect();
self.set_hovered(None, &[]);
self.set_positions(&[], None);
calls
}
pub(crate) fn set_enabled(&mut self, id: NodeId, enabled: bool) -> Vec<Call> {
let Some(NodeKind::Button(button)) = self.node_mut(id).map(|node| &mut node.kind) else {
return Vec::new();
};
if std::mem::replace(&mut button.enabled, enabled) == enabled {
return Vec::new();
}
let mut calls = Vec::new();
if !enabled {
if self.pointer.pressed.is_some_and(|press| press.id == id) {
calls.extend(self.end_press(None));
}
if self.keyboard.focused == Some(id) {
self.focus(None);
}
}
if let Some(at) = self.pointer.position {
self.hover_at(at);
}
calls
}
pub(crate) fn bind_enabled(&mut self, id: NodeId, prop: Prop<bool>) {
let mut compute = match prop.0 {
PropKind::Value(enabled) => {
self.set_enabled(id, enabled);
return;
}
PropKind::Binding(compute) => compute,
};
let Some(node) = self.node(id) else {
return;
};
let label = format!("{}.enabled", node.path);
let tree = self.this.clone();
node
.cx
.effect(move || {
let enabled = compute();
let Some(tree) = tree.upgrade() else {
return;
};
let calls = borrow(&tree).set_enabled(id, enabled);
untrack(|| run_all(calls));
})
.named(label);
}
pub(crate) fn enabled(&self, id: NodeId) -> bool {
match self.node(id).map(|node| &node.kind) {
Some(NodeKind::Button(button)) => button.enabled,
_ => true,
}
}
fn scroll(&mut self, wheel: Wheel, time: u32) -> Vec<Call> {
let wants = |h: &Handlers| h.scroll.is_some() || h.wheel.is_some();
let target = self.pointer.hovered.filter(|&id| self.has(id, wants));
let calls = match target {
None => {
self.scroll_view(wheel, time);
Vec::new()
}
Some(target) => {
let mut calls = Vec::new();
if self.has(target, |h| h.wheel.is_some()) {
calls.extend(self.call(target, Action::Wheel(wheel)));
}
if self.has(target, |h| h.scroll.is_some()) {
let down = self.steps(wheel.y);
if down != 0 {
calls.extend(self.call(target, Action::Scroll(down.saturating_neg())));
}
}
calls
}
};
if wheel.y.stop {
self.pointer.pixels = 0.0;
}
if wheel.source == ScrollSource::Finger
&& (wheel.x.stop || wheel.y.stop)
&& let Some(id) = self.pointer.gesture.take()
{
self.release_view(id, Some(time));
}
calls
}
fn steps(&mut self, axis: WheelAxis) -> i32 {
if axis.notches != 0.0 && axis.notches.is_finite() {
let value120 = (axis.notches * VALUE120_PER_STEP as f32).round() as i32;
self.pointer.wheel = self.pointer.wheel.saturating_add(value120);
let steps = self.pointer.wheel / VALUE120_PER_STEP;
self.pointer.wheel -= steps * VALUE120_PER_STEP;
steps
} else if axis.pixels.is_finite() {
self.pointer.pixels += axis.pixels;
let steps = (self.pointer.pixels / PIXELS_PER_STEP).trunc();
self.pointer.pixels -= steps * PIXELS_PER_STEP;
steps as i32
} else {
0
}
}
fn press_field(&mut self, id: NodeId) {
let Some(position) = self
.pointer
.position
.and_then(|at| self.local_point(id, at))
else {
return;
};
let Some(NodeKind::Input(input)) = self.node(id).map(|node| &node.kind) else {
return;
};
let at = input.hit(position);
self.focus(Some(id));
self.update_input(id, |input| {
input.edit.cursor = at;
input.edit.anchor = None;
});
}
pub(crate) fn cancel_press(&mut self) {
if let Some(press) = self.pointer.pressed.filter(|press| !press.dragging) {
self.set_pressed(None);
self.stop_long_press(press.id);
}
}
fn has(&self, id: NodeId, f: impl FnOnce(&Handlers) -> bool) -> bool {
let Some(NodeKind::Button(button)) = self.node(id).map(|node| &node.kind) else {
return false;
};
untrack(|| button.handlers.try_with(f)).unwrap_or(false)
}
pub(crate) fn local_point(&self, id: NodeId, point: Point) -> Option<Point> {
self
.path_to(id)
.iter()
.try_fold(point, |point, &id| local(self.node(id)?, point))
}
pub(crate) fn window_rect(&self, id: NodeId, rect: Rect) -> Rect {
let mut rect = rect;
let mut at = Some(id);
while let Some(current) = at {
if let Some(transform) = self.node(current).and_then(|node| node.transform) {
rect = transform.map_rect(rect);
}
at = self.taffy.parent(current);
}
rect
}
pub(crate) fn click(&self, id: NodeId) -> Option<Call> {
self.call(id, Action::Click)
}
fn call(&self, id: NodeId, action: Action) -> Option<Call> {
let node = self.node(id)?;
let NodeKind::Button(button) = &node.kind else {
return None;
};
Some(Call {
cx: node.cx.clone(),
path: Rc::clone(&node.path),
handlers: button.handlers,
action,
})
}
}
fn long_press_fired(tree: &Weak<RefCell<Tree>>, id: NodeId) {
let Some(tree) = tree.upgrade() else {
return;
};
let Ok(mut borrowed) = tree.try_borrow_mut() else {
return;
};
let call = borrowed.long_press(id);
drop(borrowed);
if let Some(call) = call {
call.run();
}
}
pub(crate) fn local(node: &Node, point: Point) -> Option<Point> {
match node.transform {
Some(transform) => Some(transform.invert()?.map(point)),
None => Some(point),
}
}
#[derive(Clone)]
enum Action {
Click,
Press,
Release,
DoubleClick,
LongPress,
RightClick,
MiddleClick,
Back,
Forward,
Scroll(i32),
Wheel(Wheel),
Drag(Drag, Option<Rc<Cell<bool>>>),
Drop(DragValue, Rc<Cell<bool>>),
}
pub(crate) struct Call {
cx: Cx,
path: Rc<str>,
handlers: Signal<Handlers>,
action: Action,
}
enum Picked {
Plain(ClickHandler, &'static str),
Scroll(ScrollHandler, i32),
Wheel(WheelHandler, Wheel),
Drag(DragHandler, Drag),
Drop(DropHandler, DragValue, Rc<Cell<bool>>),
}
impl Call {
pub(crate) fn run(self) {
let picked = untrack(|| {
self.handlers.try_with(|h| {
let plain = |handler: &Option<ClickHandler>, name| {
handler.clone().map(|handler| Picked::Plain(handler, name))
};
match &self.action {
Action::Click => plain(&h.click, "on_click"),
Action::Press => plain(&h.press, "on_press"),
Action::Release => plain(&h.release, "on_release"),
Action::DoubleClick => plain(&h.double_click, "on_double_click"),
Action::LongPress => plain(&h.long_press, "on_long_press"),
Action::RightClick => plain(&h.right_click, "on_right_click"),
Action::MiddleClick => plain(&h.middle_click, "on_middle_click"),
Action::Back => plain(&h.back, "on_back"),
Action::Forward => plain(&h.forward, "on_forward"),
Action::Scroll(steps) => h.scroll.clone().map(|f| Picked::Scroll(f, *steps)),
Action::Wheel(wheel) => h.wheel.clone().map(|f| Picked::Wheel(f, *wheel)),
Action::Drag(drag, landed) => {
let drag = Drag {
dropped: landed.as_ref().is_some_and(|landed| landed.get()),
..*drag
};
h.drag.clone().map(|f| Picked::Drag(f, drag))
}
Action::Drop(value, landed) => {
let target = h.drop.as_ref()?;
Some(Picked::Drop(
target.handler.clone(),
Rc::clone(value),
Rc::clone(landed),
))
}
}
})
});
let Some(Some(picked)) = picked else {
return;
};
let (path, cx) = (&self.path, &self.cx);
match picked {
Picked::Plain(handler, name) => {
run_isolated(path, name, handler, |f| f(cx));
}
Picked::Scroll(handler, steps) => {
run_isolated(path, "on_scroll", handler, |f| f(cx, steps));
}
Picked::Wheel(handler, wheel) => {
run_isolated(path, "on_wheel", handler, |f| f(cx, wheel));
}
Picked::Drag(handler, drag) => {
run_isolated(path, "on_drag", handler, |f| f(cx, drag));
}
Picked::Drop(handler, value, landed) => {
let ran = run_isolated(path, "on_drop", handler, move |f| f(cx, &*value));
landed.set(ran.is_some());
}
}
}
}
pub(crate) fn run_isolated<F: ?Sized, R>(
path: &str,
name: &str,
handler: Rc<Handler<F>>,
call: impl FnOnce(&F) -> R,
) -> Option<R> {
if handler.disabled.get() {
return None;
}
let result = match panic::catch_unwind(AssertUnwindSafe(|| call(&handler.f))) {
Ok(result) => Some(result),
Err(payload) => {
handler.disabled.set(true);
tracing::error!(
"handler {path}.{name} panicked and is disabled: {}",
panic_message(payload.as_ref())
);
None
}
};
if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(move || drop(handler))) {
tracing::error!(
"dropping handler {path}.{name} panicked: {}",
panic_message(payload.as_ref())
);
}
result
}
pub(crate) fn panic_message(payload: &(dyn Any + Send)) -> &str {
if let Some(message) = payload.downcast_ref::<&str>() {
message
} else if let Some(message) = payload.downcast_ref::<String>() {
message
} else {
"(panic payload is not a string)"
}
}