use std::cell::RefCell;
use std::rc::{Rc, Weak};
use std::time::{Duration, Instant};
use crabshell_reactive::{Signal, untrack};
use crate::animation::{self, Spring};
use crate::geometry::{Point, Rect};
use crate::input::{DRAG_THRESHOLD, Pointer, ScrollSource, Wheel, WheelAxis, local};
use crate::scroll::PIXELS_PER_NOTCH;
use crate::tree::{Axis, Change, Node, NodeId, NodeKind, ScrollNode, Tree};
const DECELERATION: f32 = 1500.0;
const MAX_SPEED: f32 = 2500.0;
const MIN_FLING: f32 = 50.0;
const SAMPLE_MS: u32 = 100;
const OVERSHOOT_LIMIT: f32 = 0.25;
const RESISTANCE: f32 = 0.5;
const SPRING_BACK: Spring = Spring::new(150.0, 1.0);
const REST: (f32, f32) = (0.5, 10.0);
const REPEAT_DELAY: Duration = Duration::from_millis(300);
const REPEAT_INTERVAL: Duration = Duration::from_millis(50);
const MAX_STEP: f32 = 0.25;
#[derive(Default)]
pub(crate) struct Motion {
samples: Vec<(u32, f32)>,
raw: f32,
generation: u64,
}
#[derive(Clone, Copy)]
enum Phase {
Fling { v: f32 },
Spring { x: f32, v: f32 },
}
pub(crate) struct Flick {
views: Vec<NodeId>,
at: Point,
last: Point,
view: Option<NodeId>,
may_drag: bool,
touch: bool,
}
#[derive(Clone, Copy)]
pub(crate) struct BarDrag {
pub(crate) view: NodeId,
axis: usize,
from: f32,
offset: f32,
handle: bool,
}
impl Pointer {
pub(crate) fn forget_views(&mut self, removed: &[NodeId]) {
if let Some(flick) = self.flick.as_mut() {
flick.views.retain(|id| !removed.contains(id));
if flick.view.is_some_and(|id| removed.contains(&id)) {
flick.view = None;
flick.may_drag = false;
}
}
if self.gesture.is_some_and(|id| removed.contains(&id)) {
self.gesture = None;
}
if self.bar.is_some_and(|bar| removed.contains(&bar.view)) {
self.bar = None;
}
}
}
type Writes = [Option<(Signal<f32>, f32)>; 2];
fn write(writes: Writes) {
for (signal, offset) in writes.into_iter().flatten() {
signal.try_set(offset);
}
}
impl Axis {
pub(crate) fn current(&self) -> Option<f32> {
let now = untrack(|| self.signal.try_get())?;
Some(if now.is_nan() {
0.0
} else {
now.clamp(0.0, self.most)
})
}
fn part(&self, delta: Point) -> f32 {
if self.horizontal { delta.x } else { delta.y }
}
fn span(&self, rect: Rect) -> (f32, f32) {
if self.horizontal {
(rect.x, rect.width)
} else {
(rect.y, rect.height)
}
}
fn limit(&self) -> f32 {
(self.length * OVERSHOOT_LIMIT).max(0.0)
}
fn rubber(&self, raw: f32) -> f32 {
let limit = self.limit();
if limit <= 0.0 || !raw.is_finite() {
return 0.0;
}
raw.signum() * limit * (1.0 - (-RESISTANCE * raw.abs() / limit).exp())
}
fn unrubber(&self, shown: f32) -> f32 {
let limit = self.limit();
if limit <= 0.0 || shown == 0.0 {
return 0.0;
}
let part = (shown.abs() / limit).min(0.999);
-shown.signum() * limit / RESISTANCE * (1.0 - part).ln()
}
fn push(&mut self, delta: f32, time: u32, overshoots: bool) -> Option<(Option<f32>, bool)> {
let now = self.current()?;
let total = now + self.motion.raw + delta;
let offset = total.clamp(0.0, self.most);
self.motion.raw = if overshoots { total - offset } else { 0.0 };
let samples = &mut self.motion.samples;
samples.retain(|&(then, _)| time.wrapping_sub(then) <= SAMPLE_MS);
samples.push((time, delta));
let shown = self.rubber(self.motion.raw);
let moved = std::mem::replace(&mut self.overshoot, shown) != shown;
Some(((offset != now).then_some(offset), moved))
}
fn speed(&self, time: u32) -> f32 {
let recent: Vec<(u32, f32)> = self
.motion
.samples
.iter()
.copied()
.filter(|&(then, _)| time.wrapping_sub(then) <= SAMPLE_MS)
.collect();
let (Some(first), Some(last)) = (recent.first(), recent.last()) else {
return 0.0;
};
let span = last.0.wrapping_sub(first.0);
if span == 0 {
return 0.0;
}
let distance: f32 = recent[1..].iter().map(|&(_, delta)| delta).sum();
(distance * 1000.0 / span as f32).clamp(-MAX_SPEED, MAX_SPEED)
}
fn page_toward(&self, handle: Rect, rect: Rect, point: Point, offset: f32) -> Option<f32> {
let (start, length) = self.span(handle);
let (at, page) = (self.part(point), self.span(rect).1);
let to = if at < start {
offset - page
} else if at > start + length {
offset + page
} else {
return None;
};
Some(to.clamp(0.0, self.most))
}
fn stop(&mut self) -> bool {
self.motion.generation += 1;
self.motion.samples.clear();
self.motion.raw = 0.0;
std::mem::replace(&mut self.overshoot, 0.0) != 0.0
}
fn can_move(&self, delta: f32) -> bool {
self
.current()
.is_some_and(|now| (delta > 0.0 && now < self.most) || (delta < 0.0 && now > 0.0))
}
}
impl ScrollNode {
fn halt(&mut self) {
self.set_moving(false);
for axis in &mut self.axes {
axis.motion.generation += 1;
axis.motion.samples.clear();
axis.motion.raw = axis.unrubber(axis.overshoot);
}
}
pub(crate) fn stop_overshoot(&mut self) -> Change {
self.set_moving(false);
let mut change = Change::None;
for axis in &mut self.axes {
if axis.stop() {
change = Change::Place;
}
}
change
}
fn push(&mut self, delta: Point, time: u32) -> (Writes, Change) {
let overshoots = self.overshoots;
let (mut writes, mut change, mut pushed) = ([None; 2], Change::None, false);
for (slot, axis) in writes.iter_mut().zip(self.active_mut()) {
let Some((offset, moved)) = axis.push(axis.part(delta), time, overshoots) else {
continue;
};
pushed = true;
*slot = offset.map(|offset| (axis.signal, offset));
if moved {
change = Change::Place;
}
}
if pushed {
self.set_moving(true);
}
(writes, change)
}
fn set_moving(&self, moving: bool) {
if let Some(cell) = &self.moving {
cell.set(moving);
}
}
fn can_move(&self, delta: Point) -> bool {
self
.active()
.iter()
.any(|axis| axis.can_move(axis.part(delta)))
}
fn runs(&self, horizontal: bool) -> bool {
self
.active()
.iter()
.any(|axis| axis.horizontal == horizontal)
}
pub(crate) fn wheel_pixels(&self, wheel: Wheel) -> Option<Point> {
let notched = |axis: WheelAxis| {
(axis.notches != 0.0 && axis.notches.is_finite()).then_some(axis.notches * PIXELS_PER_NOTCH)
};
let smooth =
|axis: WheelAxis| (axis.pixels != 0.0 && axis.pixels.is_finite()).then_some(axis.pixels);
let along = |axis: WheelAxis| notched(axis).or_else(|| smooth(axis));
let (x, y) = match self.active() {
[main] if main.horizontal => (along(wheel.x).or_else(|| notched(wheel.y)), None),
[_] => (None, along(wheel.y)),
_ => (along(wheel.x), along(wheel.y)),
};
(x.is_some() || y.is_some()).then(|| Point::new(x.unwrap_or(0.0), y.unwrap_or(0.0)))
}
}
impl Tree {
pub(crate) fn scroll_views_at(&self, point: Point) -> Vec<NodeId> {
self.scroll_chain(self.root, point)
}
fn scroll_chain(&self, id: NodeId, point: Point) -> Vec<NodeId> {
let Some(node) = self.node(id) else {
return Vec::new();
};
let Some(point) = local(node, point) else {
return Vec::new();
};
if !node.inner_bounds.contains(point) {
return Vec::new();
}
let mut chain = self
.drawn_children(id)
.into_iter()
.rev()
.map(|child| self.scroll_chain(child, point))
.find(|chain| !chain.is_empty())
.unwrap_or_default();
if node.rect.is_some_and(|rect| rect.contains(point))
&& matches!(node.kind, NodeKind::Scroll(_))
{
chain.push(id);
}
chain
}
fn scroll_node(&self, id: NodeId) -> Option<&ScrollNode> {
match &self.node(id)?.kind {
NodeKind::Scroll(scroll) => Some(scroll),
_ => None,
}
}
pub(crate) fn scroll_view(&mut self, wheel: Wheel, time: u32) {
let finger = wheel.source == ScrollSource::Finger;
let Some((id, pixels)) = self.wheel_target(wheel, finger) else {
return;
};
if finger {
if self.pointer.gesture != Some(id) {
if let Some(last) = self.pointer.gesture.replace(id) {
self.release_view(last, None);
}
self.update_scroll(id, |scroll| {
scroll.halt();
Change::None
});
}
self.push_view(id, pixels, time);
return;
}
let mut writes = [None; 2];
self.update_scroll(id, |scroll| {
let change = scroll.stop_overshoot();
for (slot, axis) in writes.iter_mut().zip(scroll.active()) {
if let Some(now) = axis.current() {
let offset = (now + axis.part(pixels)).clamp(0.0, axis.most);
*slot = (offset != now).then_some((axis.signal, offset));
}
}
change
});
write(writes);
}
fn wheel_target(&self, wheel: Wheel, finger: bool) -> Option<(NodeId, Point)> {
let chain = self.scroll_views_at(self.pointer.position?);
let past = self
.pointer
.gesture
.filter(|id| finger && chain.contains(id))
.filter(|&id| {
self
.scroll_node(id)
.is_some_and(|scroll| scroll.active().iter().any(|axis| axis.motion.raw != 0.0))
});
if let Some(id) = past {
return Some((id, self.scroll_node(id)?.wheel_pixels(wheel)?));
}
let moves = chain.iter().find_map(|&id| {
let scroll = self.scroll_node(id)?;
let pixels = scroll.wheel_pixels(wheel)?;
scroll.can_move(pixels).then_some((id, pixels))
});
moves.or_else(|| {
chain.iter().filter(|_| finger).find_map(|&id| {
let scroll = self.scroll_node(id)?;
Some((
id,
scroll.wheel_pixels(wheel).filter(|_| scroll.overshoots)?,
))
})
})
}
fn push_view(&mut self, id: NodeId, delta: Point, time: u32) {
let mut writes = [None; 2];
self.update_scroll(id, |scroll| {
let (pushed, change) = scroll.push(delta, time);
writes = pushed;
change
});
write(writes);
}
pub(crate) fn release_view(&mut self, id: NodeId, time: Option<u32>) {
let Some(NodeKind::Scroll(scroll)) = self.node_mut(id).map(|node| &mut node.kind) else {
return;
};
let kinetic = scroll.kinetic;
let mut phases = [None; 2];
for (phase, axis) in phases.iter_mut().zip(scroll.active_mut()) {
let speed = time.map_or(0.0, |time| axis.speed(time));
axis.motion.samples.clear();
axis.motion.raw = 0.0;
*phase = if axis.overshoot != 0.0 {
Some(Phase::Spring {
x: axis.overshoot,
v: 0.0,
})
} else if kinetic && speed.abs() >= MIN_FLING {
Some(Phase::Fling { v: speed })
} else {
None
};
}
if phases.iter().all(Option::is_none) {
scroll.set_moving(false);
}
for (axis, phase) in phases.into_iter().enumerate() {
if let Some(phase) = phase {
self.start_motion(id, axis, phase);
}
}
}
fn start_motion(&mut self, id: NodeId, axis: usize, mut phase: Phase) {
let tree = self.this.clone();
let Some(node) = self.node_mut(id) else {
return;
};
let label: Rc<str> = format!("{}.kinetic", node.path).into();
let busy = node.cx.busy();
let NodeKind::Scroll(scroll) = &mut node.kind else {
return;
};
let Some(mut written) = scroll.axes[axis].current() else {
return;
};
if let Some(shifts) = scroll.shifts.as_ref().filter(|_| axis == 0) {
shifts.set(0.0);
}
let motion = &mut scroll.axes[axis].motion;
motion.generation += 1;
let generation = motion.generation;
let mut previous: Option<Instant> = None;
animation::start(
label,
busy,
Box::new(move |now| {
let Some(tree) = tree.upgrade() else {
return false;
};
let Ok(mut tree) = tree.try_borrow_mut() else {
return true;
};
let seconds = previous.map_or(0.0, |previous| {
now
.saturating_duration_since(previous)
.as_secs_f32()
.min(MAX_STEP)
});
previous = Some(now);
let step = Step {
id,
axis,
generation,
seconds,
};
tree.step_motion(step, &mut phase, &mut written)
}),
);
}
fn step_motion(&mut self, step: Step, phase: &mut Phase, written: &mut f32) -> bool {
let mut running = false;
let mut write = None;
self.update_scroll(step.id, |scroll| {
let ScrollNode {
axes,
overshoots,
shifts,
..
} = scroll;
let axis = &mut axes[step.axis];
if axis.motion.generation != step.generation {
return Change::None;
}
let Some(offset) = axis.current() else {
return Change::None;
};
if let Some(shifts) = shifts.as_ref().filter(|_| step.axis == 0) {
*written += shifts.take();
}
if offset != *written {
let moved = axis.stop();
scroll.set_moving(false);
return if moved { Change::Place } else { Change::None };
}
let seconds = step.seconds;
let mut to = offset;
let mut overshoot = axis.overshoot;
match phase {
Phase::Fling { v } => {
let slowed = v.signum() * (v.abs() - DECELERATION * seconds).max(0.0);
let moved = offset + (*v + slowed) / 2.0 * seconds;
to = moved.clamp(0.0, axis.most);
if moved != to && *overshoots {
overshoot = (moved - to).clamp(-axis.limit(), axis.limit());
*phase = Phase::Spring {
x: overshoot,
v: slowed,
};
running = true;
} else {
*phase = Phase::Fling { v: slowed };
running = moved == to && slowed != 0.0;
}
}
Phase::Spring { x, v } => {
let (mut x64, mut v64) = (f64::from(*x), f64::from(*v));
SPRING_BACK.advance(&mut x64, &mut v64, 0.0, f64::from(seconds));
let limit = axis.limit();
let clamped = (x64 as f32).clamp(-limit, limit);
let rest = clamped.abs() < REST.0 && (v64 as f32).abs() < REST.1;
*x = if rest { 0.0 } else { clamped };
*v = v64 as f32;
overshoot = *x;
running = !rest;
}
}
if to != offset {
*written = to;
write = Some((axis.signal, to));
}
let moved = std::mem::replace(&mut axis.overshoot, overshoot) != overshoot;
if !running {
scroll.set_moving(false);
}
if moved { Change::Place } else { Change::None }
});
if let Some((signal, offset)) = write {
signal.try_set(offset);
}
running
}
pub(crate) fn press_views(&mut self, at: Point, drags: bool, touch: bool) {
let mut views = self.scroll_views_at(at);
views.retain(|&id| self.press_reaches(id));
for &id in &views {
self.update_scroll(id, |scroll| {
scroll.halt();
Change::None
});
}
self.pointer.flick = (!views.is_empty()).then_some(Flick {
views,
at,
last: at,
view: None,
may_drag: !drags,
touch,
});
}
pub(crate) fn flick_motion(&mut self, at: Point, time: u32) -> bool {
let Some(flick) = self.pointer.flick.as_mut() else {
return false;
};
let last = std::mem::replace(&mut flick.last, at);
if let Some(id) = flick.view {
let delta = self.drag_delta(id, last, at);
self.push_view(id, delta, time);
return true;
}
let (dx, dy) = (at.x - flick.at.x, at.y - flick.at.y);
if !flick.may_drag || dx.abs().max(dy.abs()) <= DRAG_THRESHOLD {
return false;
}
let (from, views, touch) = (flick.at, flick.views.clone(), flick.touch);
let sideways = dx.abs() > dy.abs();
let along: Vec<(NodeId, Point)> = views
.into_iter()
.filter(|&id| {
self
.scroll_node(id)
.is_some_and(|scroll| scroll.runs(sideways) && (touch || scroll.mouse_drag))
})
.map(|id| (id, self.drag_delta(id, from, at)))
.collect();
let can =
|id: NodeId, test: &dyn Fn(&ScrollNode) -> bool| self.scroll_node(id).is_some_and(test);
let mostly = |delta: Point| {
if sideways {
Point::new(delta.x, 0.0)
} else {
Point::new(0.0, delta.y)
}
};
let picked = along
.iter()
.find(|&&(id, delta)| can(id, &|scroll| scroll.can_move(mostly(delta))))
.or_else(|| {
along
.iter()
.find(|&&(id, _)| can(id, &|scroll| scroll.overshoots))
})
.copied();
let Some((id, delta)) = picked else {
if let Some(flick) = self.pointer.flick.as_mut() {
flick.may_drag = false;
}
return false;
};
if let Some(flick) = self.pointer.flick.as_mut() {
flick.view = Some(id);
}
self.cancel_press();
self.push_view(id, delta, time);
true
}
fn drag_delta(&self, id: NodeId, from: Point, to: Point) -> Point {
match (self.local_point(id, from), self.local_point(id, to)) {
(Some(from), Some(to)) => Point::new(from.x - to.x, from.y - to.y),
_ => Point::default(),
}
}
pub(crate) fn flick_release(&mut self, time: Option<u32>) {
let Some(flick) = self.pointer.flick.take() else {
return;
};
for id in flick.views {
let time = time.filter(|_| flick.view == Some(id));
self.release_view(id, time);
}
}
pub(crate) fn press_bar(&mut self, at: Point) -> bool {
for id in self.scroll_views_at(at) {
if !self.press_reaches(id) {
continue;
}
let Some(point) = self.local_point(id, at) else {
continue;
};
let (Some(scroll), Some(rect)) = (self.scroll_node(id), self.node(id).and_then(|n| n.rect))
else {
continue;
};
let held = scroll.active().iter().enumerate().find_map(|(n, axis)| {
let (track, handle) = axis.handle?;
track.contains(point).then_some((n, handle))
});
let Some((n, handle)) = held else {
continue;
};
let axis = &scroll.axes[n];
let Some(offset) = axis.current() else {
return true;
};
let from = axis.part(point);
let on_handle = handle.contains(point);
let to = if on_handle {
offset
} else {
axis
.page_toward(handle, rect, point, offset)
.unwrap_or(offset)
};
let signal = axis.signal;
self.update_scroll(id, |scroll| {
scroll.halt();
scroll.set_moving(on_handle);
Change::None
});
if !on_handle {
self.arm_repeat(id);
}
self.pointer.bar = Some(BarDrag {
view: id,
axis: n,
from,
offset,
handle: on_handle,
});
if to != offset {
signal.try_set(to);
}
return true;
}
false
}
fn arm_repeat(&mut self, id: NodeId) {
let tree = self.this.clone();
let Some(Node {
cx,
kind: NodeKind::Scroll(scroll),
..
}) = self.node_mut(id)
else {
return;
};
let (delay, _) = *scroll.repeat.get_or_insert_with(|| {
let again = tree.clone();
let every = cx
.interval(REPEAT_INTERVAL, move || {
page_again(&again, id);
})
.stopped();
let delay = cx
.after(REPEAT_DELAY, move || {
if page_again(&tree, id) {
every.restart();
}
})
.stopped();
(delay, every)
});
delay.restart();
}
pub(crate) fn release_bar(&mut self) {
let Some(bar) = self.pointer.bar.take() else {
return;
};
self.stop_repeat(bar.view);
self.release_view(bar.view, None);
}
fn stop_repeat(&self, id: NodeId) {
if let Some((delay, every)) = self.scroll_node(id).and_then(|scroll| scroll.repeat) {
delay.stop();
every.stop();
}
}
fn page_toward_pointer(&mut self, id: NodeId) -> bool {
let Some(bar) = self.pointer.bar.filter(|bar| bar.view == id && !bar.handle) else {
return false;
};
let point = self
.pointer
.position
.and_then(|at| self.local_point(id, at));
let (Some(point), Some(scroll), Some(rect)) = (
point,
self.scroll_node(id),
self.node(id).and_then(|node| node.rect),
) else {
return false;
};
let axis = &scroll.axes[bar.axis];
let (Some((_, handle)), Some(offset)) = (axis.handle, axis.current()) else {
return false;
};
match axis.page_toward(handle, rect, point, offset) {
Some(to) if to != offset => {
axis.signal.try_set(to);
true
}
_ => false,
}
}
fn press_reaches(&self, id: NodeId) -> bool {
self
.pointer
.hovered
.is_none_or(|hovered| self.path_to(hovered).contains(&id))
}
pub(crate) fn bar_motion(&mut self, at: Point) {
let Some(drag) = self.pointer.bar.filter(|bar| bar.handle) else {
return;
};
let Some(point) = self.local_point(drag.view, at) else {
return;
};
let Some(axis) = self
.scroll_node(drag.view)
.map(|scroll| &scroll.axes[drag.axis])
else {
return;
};
let Some((track, handle)) = axis.handle else {
return;
};
let room = axis.span(track).1 - axis.span(handle).1;
if room <= 0.0 {
return;
}
let to =
(drag.offset + (axis.part(point) - drag.from) * axis.most / room).clamp(0.0, axis.most);
if axis.current() != Some(to) {
axis.signal.try_set(to);
}
}
}
fn page_again(tree: &Weak<RefCell<Tree>>, id: NodeId) -> bool {
let Some(tree) = tree.upgrade() else {
return false;
};
let Ok(mut tree) = tree.try_borrow_mut() else {
return false;
};
let paged = tree.page_toward_pointer(id);
if !paged {
tree.stop_repeat(id);
}
paged
}
struct Step {
id: NodeId,
axis: usize,
generation: u64,
seconds: f32,
}