use std::{collections::VecDeque, time::Duration};
use super::{ElementHandle, TouchMomentum, TouchRoute, Tree, hit_test_tree};
use crate::{
app::events::{ScrollPhase, TouchPhase},
time::Instant,
};
#[cfg_attr(not(target_os = "ios"), allow(dead_code))]
pub(crate) const DOUBLE_TAP_DISTANCE: f32 = 40.0;
#[cfg_attr(not(target_os = "ios"), allow(dead_code))]
pub(crate) const DOUBLE_TAP_INTERVAL: Duration = Duration::from_millis(350);
const TAP_SLOP: f64 = 10.0;
pub(super) const PRESS_DELAY: Duration = Duration::from_millis(150);
pub(super) const TAP_HIGHLIGHT: Duration = Duration::from_millis(80);
pub(super) const LONG_PRESS: Duration = Duration::from_millis(500);
pub(crate) const SPRING_STEP: Duration = Duration::from_millis(4);
const FLING_STEP: Duration = Duration::from_millis(4);
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum TouchAction {
Move { x: f64, y: f64 },
Press { x: f64, y: f64 },
Release { x: f64, y: f64, tap: bool },
Tap { x: f64, y: f64 },
LongPress { x: f64, y: f64 },
CancelPress { x: f64, y: f64 },
Settle,
ScrollTarget { x: f64, y: f64, dx: f64, dy: f64 },
Scroll {
x: f64,
y: f64,
dx: f64,
dy: f64,
phase: ScrollPhase,
},
}
#[derive(Debug)]
enum State {
Idle,
Pending {
id: u64,
start: (f64, f64),
started_at: Instant,
caught: bool,
pressed: bool,
},
Dragging {
id: u64,
at: (f64, f64),
rest: Option<(Instant, (f64, f64))>,
taken: bool,
landed: (f64, f64),
travelled: bool,
},
Scrolling {
fingers: Vec<(u64, (f64, f64))>,
anchor: (f64, f64),
last: (f64, f64),
samples: VecDeque<(Instant, (f64, f64))>,
},
}
#[derive(Debug)]
struct Fling {
anchor: (f64, f64),
velocity: (f64, f64),
stop_speed: f64,
last_step: Instant,
}
#[derive(Debug)]
pub(super) struct TouchPointer {
state: State,
beside: Vec<(u64, (f64, f64))>,
fling: Option<Fling>,
momentum: TouchMomentum,
}
impl Default for TouchPointer {
fn default() -> Self {
Self {
state: State::Idle,
beside: Vec::new(),
fling: None,
momentum: TouchMomentum::default(),
}
}
}
impl TouchPointer {
pub(super) fn set_momentum(&mut self, momentum: TouchMomentum) {
self.momentum = momentum;
}
fn pressed_by_another(&self, id: u64) -> bool {
match &self.state {
State::Dragging { id: held, .. }
| State::Pending {
id: held,
pressed: true,
..
} => *held != id,
_ => false,
}
}
pub(super) fn beside(&mut self, id: u64, phase: TouchPhase, position: (f64, f64), scale: f64) -> Option<bool> {
if phase == TouchPhase::Start {
if !self.pressed_by_another(id) {
return None;
}
self.beside.push((id, position));
return Some(false);
}
let at = self.beside.iter().position(|(held, _)| *held == id)?;
let start = self.beside[at].1;
let near = (position.0 - start.0).hypot(position.1 - start.1) <= TAP_SLOP * scale;
match phase {
TouchPhase::Move if near => Some(false),
TouchPhase::End => {
self.beside.remove(at);
Some(near)
}
_ => {
self.beside[at].1 = (f64::INFINITY, f64::INFINITY);
if phase == TouchPhase::Cancel {
self.beside.remove(at);
}
Some(false)
}
}
}
pub(super) fn touch(
&mut self,
id: u64,
phase: TouchPhase,
position: (f64, f64),
now: Instant,
scale: f64,
springing: bool,
scrolls: impl FnOnce((f64, f64)) -> bool,
) -> Vec<TouchAction> {
match phase {
TouchPhase::Start => self.started(id, position, now, springing, scrolls),
TouchPhase::Move => self.moved(id, position, now, scale),
TouchPhase::End => self.ended(id, position, now, scale),
TouchPhase::Cancel => self.cancelled(id, position),
}
}
fn started(
&mut self,
id: u64,
position: (f64, f64),
now: Instant,
springing: bool,
scrolls: impl FnOnce((f64, f64)) -> bool,
) -> Vec<TouchAction> {
if let State::Scrolling {
fingers, last, samples, ..
} = &mut self.state
{
fingers.push((id, position));
*last = middle(fingers);
samples.clear();
return Vec::new();
}
if !matches!(self.state, State::Idle) {
return Vec::new();
}
let mut actions = Vec::new();
let fling = self.fling.take();
if fling.is_some() || springing {
self.state = State::Pending {
id,
start: position,
started_at: now,
caught: true,
pressed: false,
};
actions.extend(fling.map(|fling| scroll(fling.anchor, (0.0, 0.0), ScrollPhase::End)));
return actions;
}
if !scrolls(position) {
self.state = State::Dragging {
id,
at: position,
rest: Some((now + LONG_PRESS, position)),
taken: false,
landed: position,
travelled: false,
};
actions.push(TouchAction::Press {
x: position.0,
y: position.1,
});
return actions;
}
self.state = State::Pending {
id,
start: position,
started_at: now,
caught: false,
pressed: false,
};
actions
}
fn moved(&mut self, id: u64, position: (f64, f64), now: Instant, scale: f64) -> Vec<TouchAction> {
match &mut self.state {
State::Pending {
id: held,
start,
caught,
pressed,
..
} if *held == id => {
let (start, pressed) = (*start, *pressed);
let slop = if *caught { 0.0 } else { TAP_SLOP * scale };
if distance(start, position) <= slop {
return Vec::new();
}
self.state = State::Scrolling {
fingers: vec![(id, position)],
anchor: start,
last: position,
samples: VecDeque::from([(now, position)]),
};
let mut actions = Vec::new();
if pressed {
actions.push(TouchAction::CancelPress { x: start.0, y: start.1 });
}
actions.push(TouchAction::ScrollTarget {
x: start.0,
y: start.1,
dx: position.0 - start.0,
dy: position.1 - start.1,
});
actions.push(scroll(start, (0.0, 0.0), ScrollPhase::Start));
actions
}
State::Dragging {
id: held,
at,
rest,
landed,
travelled,
..
} if *held == id => {
*at = position;
if rest.is_some_and(|(_, start)| distance(start, position) > TAP_SLOP * scale) {
*rest = None;
}
*travelled |= distance(*landed, position) > TAP_SLOP * scale;
vec![TouchAction::Move {
x: position.0,
y: position.1,
}]
}
State::Scrolling {
fingers,
anchor,
last,
samples,
} => {
let Some(finger) = fingers.iter_mut().find(|(held, _)| *held == id) else {
return Vec::new();
};
finger.1 = position;
let position = middle(fingers);
let delta = (position.0 - last.0, position.1 - last.1);
*last = position;
samples.push_back((now, position));
while samples
.front()
.is_some_and(|(at, _)| now.saturating_duration_since(*at) > self.momentum.velocity_window)
{
samples.pop_front();
}
vec![scroll(*anchor, delta, ScrollPhase::Scroll)]
}
_ => Vec::new(),
}
}
fn ended(&mut self, id: u64, position: (f64, f64), now: Instant, scale: f64) -> Vec<TouchAction> {
if self.one_of_several_lifted(id) {
return Vec::new();
}
if self.held_id() != Some(id) {
return Vec::new();
}
match std::mem::replace(&mut self.state, State::Idle) {
State::Pending { caught: true, .. } => vec![TouchAction::Settle],
State::Pending {
start, pressed: true, ..
} => vec![TouchAction::Release {
x: start.0,
y: start.1,
tap: true,
}],
State::Pending { start, .. } => vec![TouchAction::Tap { x: start.0, y: start.1 }],
State::Dragging { taken: true, .. } => vec![TouchAction::CancelPress {
x: position.0,
y: position.1,
}],
State::Dragging { landed, travelled, .. } => vec![TouchAction::Release {
x: position.0,
y: position.1,
tap: !travelled && distance(landed, position) <= TAP_SLOP * scale,
}],
State::Scrolling {
anchor, last, samples, ..
} => {
let mut actions = vec![scroll(
anchor,
(position.0 - last.0, position.1 - last.1),
ScrollPhase::End,
)];
if let Some(velocity) = lift_velocity(&samples, position, now, scale, &self.momentum) {
actions.push(scroll(anchor, (0.0, 0.0), ScrollPhase::Start));
self.fling = Some(Fling {
anchor,
velocity,
stop_speed: f64::from(self.momentum.stop_speed) * scale,
last_step: now,
});
}
actions
}
State::Idle => Vec::new(),
}
}
fn cancelled(&mut self, id: u64, position: (f64, f64)) -> Vec<TouchAction> {
if self.one_of_several_lifted(id) {
return Vec::new();
}
if self.held_id() != Some(id) {
return Vec::new();
}
match std::mem::replace(&mut self.state, State::Idle) {
State::Pending { caught: true, .. } => vec![TouchAction::Settle],
State::Pending { pressed: false, .. } | State::Idle => Vec::new(),
State::Pending { .. } | State::Dragging { .. } => vec![TouchAction::CancelPress {
x: position.0,
y: position.1,
}],
State::Scrolling { anchor, .. } => vec![scroll(anchor, (0.0, 0.0), ScrollPhase::End)],
}
}
pub(super) fn tick(&mut self, now: Instant) -> Vec<TouchAction> {
if let State::Dragging { rest, .. } = &mut self.state
&& let Some((due, start)) = *rest
&& now >= due
{
*rest = None;
return vec![TouchAction::LongPress { x: start.0, y: start.1 }];
}
if let State::Pending {
id,
start,
started_at,
caught: false,
pressed,
} = &mut self.state
{
let rested = now.saturating_duration_since(*started_at);
let press = (!*pressed && rested >= PRESS_DELAY).then_some(TouchAction::Press { x: start.0, y: start.1 });
*pressed |= press.is_some();
let mut actions: Vec<TouchAction> = press.into_iter().collect();
if rested >= LONG_PRESS {
actions.push(TouchAction::LongPress { x: start.0, y: start.1 });
self.state = State::Dragging {
id: *id,
at: *start,
rest: None,
taken: false,
landed: *start,
travelled: false,
};
}
return actions;
}
let Some(fling) = self.fling.as_mut() else {
return Vec::new();
};
let elapsed = now.saturating_duration_since(fling.last_step);
if elapsed < FLING_STEP {
return Vec::new();
}
fling.last_step = now;
let seconds = elapsed.as_secs_f64();
let kept = f64::from(self.momentum.deceleration_rate).powf(seconds * 1000.0);
let (vx, vy) = fling.velocity;
let next = (vx * kept, vy * kept);
let delta = ((vx + next.0) * 0.5 * seconds, (vy + next.1) * 0.5 * seconds);
fling.velocity = next;
let anchor = fling.anchor;
let mut actions = vec![scroll(anchor, delta, ScrollPhase::Scroll)];
if next.0.hypot(next.1) < fling.stop_speed {
self.fling = None;
actions.push(scroll(anchor, (0.0, 0.0), ScrollPhase::End));
}
actions
}
pub(super) fn next_deadline(&self) -> Option<Instant> {
let rest = match self.state {
State::Pending {
started_at,
caught: false,
pressed,
..
} => Some(started_at + if pressed { LONG_PRESS } else { PRESS_DELAY }),
State::Dragging { rest, .. } => rest.map(|(due, _)| due),
_ => None,
};
let fling = self.fling.as_ref().map(|fling| fling.last_step + FLING_STEP);
rest.into_iter().chain(fling).min()
}
pub(super) fn abandon(&mut self) -> Vec<TouchAction> {
self.fling = None;
match std::mem::replace(&mut self.state, State::Idle) {
State::Idle
| State::Pending {
pressed: false,
caught: false,
..
} => Vec::new(),
State::Pending { caught: true, .. } => vec![TouchAction::Settle],
State::Pending { start, .. } => vec![TouchAction::CancelPress { x: start.0, y: start.1 }],
State::Dragging { at, .. } => vec![TouchAction::CancelPress { x: at.0, y: at.1 }],
State::Scrolling { anchor, .. } => vec![scroll(anchor, (0.0, 0.0), ScrollPhase::End)],
}
}
pub(super) fn holds_caught(&self) -> bool {
matches!(self.state, State::Pending { caught: true, .. })
}
pub(super) fn long_press_taken(&mut self) {
if let State::Dragging { taken, .. } = &mut self.state {
*taken = true;
}
}
pub(super) fn end_fling(&mut self) -> Option<(TouchAction, (f64, f64))> {
let fling = self.fling.take()?;
Some((scroll(fling.anchor, (0.0, 0.0), ScrollPhase::End), fling.velocity))
}
fn one_of_several_lifted(&mut self, id: u64) -> bool {
let State::Scrolling {
fingers, last, samples, ..
} = &mut self.state
else {
return false;
};
if fingers.len() < 2 {
return false;
}
let Some(index) = fingers.iter().position(|(held, _)| *held == id) else {
return false;
};
fingers.remove(index);
*last = middle(fingers);
samples.clear();
true
}
fn held_id(&self) -> Option<u64> {
match &self.state {
State::Idle => None,
State::Pending { id, .. } | State::Dragging { id, .. } => Some(*id),
State::Scrolling { fingers, .. } => fingers.first().map(|(id, _)| *id),
}
}
}
fn scroll(anchor: (f64, f64), delta: (f64, f64), phase: ScrollPhase) -> TouchAction {
TouchAction::Scroll {
x: anchor.0,
y: anchor.1,
dx: delta.0,
dy: delta.1,
phase,
}
}
pub(super) fn ends_scroll(actions: &[TouchAction]) -> bool {
actions.iter().any(|action| {
matches!(
action,
TouchAction::Scroll {
phase: ScrollPhase::End,
..
}
)
})
}
fn middle(fingers: &[(u64, (f64, f64))]) -> (f64, f64) {
let count = fingers.len().max(1) as f64;
let (x, y) = fingers
.iter()
.fold((0.0, 0.0), |sum, (_, at)| (sum.0 + at.0, sum.1 + at.1));
(x / count, y / count)
}
fn distance(a: (f64, f64), b: (f64, f64)) -> f64 {
(a.0 - b.0).hypot(a.1 - b.1)
}
fn lift_velocity(
samples: &VecDeque<(Instant, (f64, f64))>,
position: (f64, f64),
now: Instant,
scale: f64,
momentum: &TouchMomentum,
) -> Option<(f64, f64)> {
let (at, from) = samples
.iter()
.find(|(at, _)| now.saturating_duration_since(*at) <= momentum.velocity_window)?;
let seconds = now.saturating_duration_since(*at).as_secs_f64();
if seconds <= 0.0 {
return None;
}
let velocity = ((position.0 - from.0) / seconds, (position.1 - from.1) / seconds);
let speed = velocity.0.hypot(velocity.1);
if speed < f64::from(momentum.min_speed) * scale {
return None;
}
let limit = (f64::from(momentum.max_speed) * scale / speed).min(1.0);
Some((velocity.0 * limit, velocity.1 * limit))
}
impl Tree {
pub fn finger(&mut self, id: u64, phase: TouchPhase, x: f32, y: f32, force: Option<f32>) -> TouchRoute {
let now = self.press_clock.unwrap_or_else(Instant::now);
self.finger_at(id, phase, x, y, force, false, now)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn finger_at(
&mut self,
id: u64,
phase: TouchPhase,
x: f32,
y: f32,
force: Option<f32>,
pen: bool,
now: Instant,
) -> TouchRoute {
if phase == TouchPhase::Start {
self.touch_pointer.pen = pen;
self.set_input_modality(super::focus_visible::InputModality::Pointer);
}
let scale = self.scale_factor();
if self.touch_text_finger(id, phase, x / scale, y / scale) {
return TouchRoute::Taken;
}
let route = self.touch_event_at(id, phase, x, y, force, now);
let scale = f64::from(self.scale_factor());
let (x, y) = (f64::from(x), f64::from(y));
if route == TouchRoute::Pointer
&& let Some(tapped) = self.finger.beside(id, phase, (x, y), scale)
{
if tapped {
self.tap_beside(x as f32, y as f32);
}
return route;
}
let actions = match route {
TouchRoute::Pointer => {
let momentum = self.touch_momentum();
self.finger.set_momentum(momentum);
let springing = phase == TouchPhase::Start && self.touch_scroll_catch();
let scrolls = phase == TouchPhase::Start && self.touch_scrolls_at(x as f32, y as f32);
self.finger.touch(id, phase, (x, y), now, scale, springing, |_| scrolls)
}
TouchRoute::Gesture => self.finger.abandon(),
TouchRoute::Taken => return route,
};
let lifted =
ends_scroll(&actions) && (route != TouchRoute::Pointer || matches!(phase, TouchPhase::End | TouchPhase::Cancel));
if self.finger.holds_caught() {
self.touch_scroll_caught();
}
self.apply_finger_actions(actions, false);
if lifted {
self.page_after_finger_scroll(now);
}
self.touch_scroll_rest(now);
route
}
fn tap_beside(&mut self, x: f32, y: f32) {
let scale = self.scale_factor();
let (x, y) = (x / scale, y / scale);
self.rebuild_if_dirty();
let target = {
let (Some(root), Some(layout)) = (&self.root, &self.last_layout) else {
return;
};
let mut hits = Vec::new();
hit_test_tree(root, layout, 0.0, 0.0, x, y, &self.layout_engine.radii(), &mut hits);
hits
.iter()
.find(|(node, _)| !node.events.on_click.is_empty())
.map(|(node, _)| node.node_id())
};
if let Some(node_id) = target {
ElementHandle { tree: self, node_id }.click();
}
}
pub fn finger_tick(&mut self, now: Instant) {
let actions = self.finger.tick(now);
if !self.apply_finger_actions(actions, true)
&& let Some((end, velocity)) = self.finger.end_fling()
{
self.apply_finger_actions(vec![end], true);
self.touch_scroll_bounce(velocity.0 as f32, velocity.1 as f32, now);
}
self.touch_tick(now);
}
pub fn finger_deadline(&self) -> Option<Instant> {
self
.finger
.next_deadline()
.into_iter()
.chain(self.touch_animating().then(|| Instant::now() + SPRING_STEP))
.min()
}
fn page_after_finger_scroll(&mut self, now: Instant) {
if !self.touch_scroll_pages() {
return;
}
let velocity = match self.finger.end_fling() {
Some((end, velocity)) => {
self.apply_finger_actions(vec![end], false);
velocity
}
None => (0.0, 0.0),
};
self.touch_scroll_page(velocity.0 as f32, velocity.1 as f32, now);
}
fn apply_finger_actions(&mut self, actions: Vec<TouchAction>, momentum: bool) -> bool {
let mut moved = true;
for action in actions {
match action {
TouchAction::Move { x, y } => self.touch_pointer_move(x as f32, y as f32),
TouchAction::Press { x, y } => self.touch_press(x as f32, y as f32),
TouchAction::Release { x, y, tap } => {
if !tap && !self.has_active_input_interaction() {
self.touch_release_without_click();
}
self.touch_release(x as f32, y as f32);
}
TouchAction::Tap { x, y } => self.touch_tap(x as f32, y as f32, TAP_HIGHLIGHT),
TouchAction::LongPress { x, y } => {
if self.touch_long_press(x as f32, y as f32) {
self.finger.long_press_taken();
}
}
TouchAction::CancelPress { x, y } => self.touch_cancel_press(x as f32, y as f32),
TouchAction::Settle => self.touch_scroll_settle(),
TouchAction::ScrollTarget { x, y, dx, dy } => {
self.touch_scroll_begin(x as f32, y as f32, dx as f32, dy as f32);
}
TouchAction::Scroll { x, y, dx, dy, phase } => {
let scrolled = self.touch_scroll(x as f32, y as f32, dx as f32, dy as f32, phase, momentum);
if matches!(phase, ScrollPhase::Scroll) {
moved = scrolled;
}
}
}
}
moved
}
}