use std::any::Any;
use std::fmt::{self, Debug};
use std::rc::Rc;
use waft_embedder::clamp_double;
use waft_foundation::App;
use waft_gestures::{K_MAX_FLING_VELOCITY, K_MIN_FLING_VELOCITY, K_TOUCH_SLOP};
use waft_physics::{ScrollSpringSimulation, Simulation, SpringDescription, Tolerance};
use crate::framework::BuildContext;
use crate::view::View;
use crate::widgets::scroll_metrics::ScrollMetrics;
use crate::widgets::scroll_simulation::{BouncingScrollSimulation, ClampingScrollSimulation};
pub type ScrollPhysicsRef = Rc<dyn ScrollPhysics>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ScrollDecelerationRate {
Normal,
Fast,
}
pub trait ScrollPhysics: Debug {
fn as_any(&self) -> &dyn Any;
fn parent(&self) -> Option<&ScrollPhysicsRef>;
fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
ScrollPhysicsBase::apply_to(self, ancestor)
}
fn apply_physics_to_user_offset(&self, position: &dyn ScrollMetrics, offset: f64) -> f64 {
ScrollPhysicsBase::apply_physics_to_user_offset(self, position, offset)
}
fn should_accept_user_offset(&self, position: &dyn ScrollMetrics) -> bool {
ScrollPhysicsBase::should_accept_user_offset(self, position)
}
fn allow_selection_edge_scrolling(&self) -> bool {
match self.parent() {
None => true,
Some(parent) => parent.allow_selection_edge_scrolling(),
}
}
fn recommend_deferred_loading(
&self,
app: &mut App,
velocity: f64,
metrics: &dyn ScrollMetrics,
context: BuildContext,
) -> bool {
ScrollPhysicsBase::recommend_deferred_loading(self, app, velocity, metrics, context)
}
fn apply_boundary_conditions(&self, position: &dyn ScrollMetrics, value: f64) -> f64 {
ScrollPhysicsBase::apply_boundary_conditions(self, position, value)
}
fn adjust_position_for_new_dimensions(
&self,
old_position: &dyn ScrollMetrics,
new_position: &dyn ScrollMetrics,
is_scrolling: bool,
velocity: f64,
) -> f64 {
ScrollPhysicsBase::adjust_position_for_new_dimensions(
self,
old_position,
new_position,
is_scrolling,
velocity,
)
}
fn create_ballistic_simulation(
&self,
position: &dyn ScrollMetrics,
velocity: f64,
) -> Option<Box<dyn Simulation>> {
ScrollPhysicsBase::create_ballistic_simulation(self, position, velocity)
}
fn spring(&self) -> SpringDescription {
ScrollPhysicsBase::spring(self)
}
fn tolerance_for(&self, metrics: &dyn ScrollMetrics) -> Tolerance {
ScrollPhysicsBase::tolerance_for(self, metrics)
}
fn min_fling_distance(&self) -> f64 {
ScrollPhysicsBase::min_fling_distance(self)
}
fn min_fling_velocity(&self) -> f64 {
ScrollPhysicsBase::min_fling_velocity(self)
}
fn max_fling_velocity(&self) -> f64 {
ScrollPhysicsBase::max_fling_velocity(self)
}
fn carried_momentum(&self, existing_velocity: f64) -> f64 {
ScrollPhysicsBase::carried_momentum(self, existing_velocity)
}
fn drag_start_distance_motion_threshold(&self) -> Option<f64> {
ScrollPhysicsBase::drag_start_distance_motion_threshold(self)
}
fn allow_implicit_scrolling(&self) -> bool {
true
}
fn allow_user_scrolling(&self) -> bool {
true
}
}
pub struct ScrollPhysicsBase;
impl ScrollPhysicsBase {
pub fn build_parent<P: ScrollPhysics + ?Sized>(
physics: &P,
ancestor: Option<ScrollPhysicsRef>,
) -> Option<ScrollPhysicsRef> {
match physics.parent() {
Some(parent) => Some(parent.apply_to(ancestor)),
None => ancestor,
}
}
pub fn apply_to<P: ScrollPhysics + ?Sized>(
physics: &P,
ancestor: Option<ScrollPhysicsRef>,
) -> ScrollPhysicsRef {
Rc::new(PlainScrollPhysics {
parent: ScrollPhysicsBase::build_parent(physics, ancestor),
})
}
pub fn apply_physics_to_user_offset<P: ScrollPhysics + ?Sized>(
physics: &P,
position: &dyn ScrollMetrics,
offset: f64,
) -> f64 {
match physics.parent() {
Some(parent) => parent.apply_physics_to_user_offset(position, offset),
None => offset,
}
}
pub fn should_accept_user_offset<P: ScrollPhysics + ?Sized>(
physics: &P,
position: &dyn ScrollMetrics,
) -> bool {
if !physics.allow_user_scrolling() {
return false;
}
match physics.parent() {
None => {
position.pixels() != 0.0
|| position.min_scroll_extent() != position.max_scroll_extent()
}
Some(parent) => parent.should_accept_user_offset(position),
}
}
pub fn recommend_deferred_loading<P: ScrollPhysics + ?Sized>(
physics: &P,
app: &mut App,
velocity: f64,
metrics: &dyn ScrollMetrics,
context: BuildContext,
) -> bool {
match physics.parent() {
None => {
let physical_size = View::of(app, context).metrics().physical_size;
let max_physical_pixels = physical_size[0].max(physical_size[1]);
velocity.abs() > max_physical_pixels
}
Some(parent) => {
let parent = Rc::clone(parent);
parent.recommend_deferred_loading(app, velocity, metrics, context)
}
}
}
pub fn apply_boundary_conditions<P: ScrollPhysics + ?Sized>(
physics: &P,
position: &dyn ScrollMetrics,
value: f64,
) -> f64 {
match physics.parent() {
Some(parent) => parent.apply_boundary_conditions(position, value),
None => 0.0,
}
}
pub fn adjust_position_for_new_dimensions<P: ScrollPhysics + ?Sized>(
physics: &P,
old_position: &dyn ScrollMetrics,
new_position: &dyn ScrollMetrics,
is_scrolling: bool,
velocity: f64,
) -> f64 {
match physics.parent() {
None => new_position.pixels(),
Some(parent) => parent.adjust_position_for_new_dimensions(
old_position,
new_position,
is_scrolling,
velocity,
),
}
}
pub fn create_ballistic_simulation<P: ScrollPhysics + ?Sized>(
physics: &P,
position: &dyn ScrollMetrics,
velocity: f64,
) -> Option<Box<dyn Simulation>> {
physics
.parent()
.and_then(|parent| parent.create_ballistic_simulation(position, velocity))
}
pub fn spring<P: ScrollPhysics + ?Sized>(physics: &P) -> SpringDescription {
match physics.parent() {
Some(parent) => parent.spring(),
None => k_default_spring(),
}
}
pub fn tolerance_for<P: ScrollPhysics + ?Sized>(
physics: &P,
metrics: &dyn ScrollMetrics,
) -> Tolerance {
match physics.parent() {
Some(parent) => parent.tolerance_for(metrics),
None => Tolerance {
velocity: 1.0 / (0.050 * metrics.device_pixel_ratio()),
distance: 1.0 / metrics.device_pixel_ratio(),
..Tolerance::DEFAULT_TOLERANCE
},
}
}
pub fn min_fling_distance<P: ScrollPhysics + ?Sized>(physics: &P) -> f64 {
match physics.parent() {
Some(parent) => parent.min_fling_distance(),
None => K_TOUCH_SLOP,
}
}
pub fn min_fling_velocity<P: ScrollPhysics + ?Sized>(physics: &P) -> f64 {
match physics.parent() {
Some(parent) => parent.min_fling_velocity(),
None => K_MIN_FLING_VELOCITY,
}
}
pub fn max_fling_velocity<P: ScrollPhysics + ?Sized>(physics: &P) -> f64 {
match physics.parent() {
Some(parent) => parent.max_fling_velocity(),
None => K_MAX_FLING_VELOCITY,
}
}
pub fn carried_momentum<P: ScrollPhysics + ?Sized>(physics: &P, existing_velocity: f64) -> f64 {
match physics.parent() {
Some(parent) => parent.carried_momentum(existing_velocity),
None => 0.0,
}
}
pub fn drag_start_distance_motion_threshold<P: ScrollPhysics + ?Sized>(
physics: &P,
) -> Option<f64> {
physics
.parent()
.and_then(|parent| parent.drag_start_distance_motion_threshold())
}
}
fn k_default_spring() -> SpringDescription {
SpringDescription::with_damping_ratio_value(0.5, 100.0, 1.1)
}
fn fmt_scroll_physics(
f: &mut fmt::Formatter<'_>,
name: &str,
parent: Option<&ScrollPhysicsRef>,
) -> fmt::Result {
match parent {
None => write!(f, "{name}"),
Some(parent) => write!(f, "{name} -> {parent:?}"),
}
}
#[derive(Default)]
pub struct PlainScrollPhysics {
pub parent: Option<ScrollPhysicsRef>,
}
impl PlainScrollPhysics {
pub fn new() -> PlainScrollPhysics {
PlainScrollPhysics::default()
}
pub fn with_parent(mut self, parent: ScrollPhysicsRef) -> PlainScrollPhysics {
self.parent = Some(parent);
self
}
}
impl ScrollPhysics for PlainScrollPhysics {
fn as_any(&self) -> &dyn Any {
self
}
fn parent(&self) -> Option<&ScrollPhysicsRef> {
self.parent.as_ref()
}
}
impl Debug for PlainScrollPhysics {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt_scroll_physics(f, "ScrollPhysics", self.parent.as_ref())
}
}
#[derive(Default)]
pub struct RangeMaintainingScrollPhysics {
pub parent: Option<ScrollPhysicsRef>,
}
impl RangeMaintainingScrollPhysics {
pub fn new() -> RangeMaintainingScrollPhysics {
RangeMaintainingScrollPhysics::default()
}
pub fn with_parent(mut self, parent: ScrollPhysicsRef) -> RangeMaintainingScrollPhysics {
self.parent = Some(parent);
self
}
}
impl ScrollPhysics for RangeMaintainingScrollPhysics {
fn as_any(&self) -> &dyn Any {
self
}
fn parent(&self) -> Option<&ScrollPhysicsRef> {
self.parent.as_ref()
}
fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
Rc::new(RangeMaintainingScrollPhysics {
parent: ScrollPhysicsBase::build_parent(self, ancestor),
})
}
fn adjust_position_for_new_dimensions(
&self,
old_position: &dyn ScrollMetrics,
new_position: &dyn ScrollMetrics,
is_scrolling: bool,
velocity: f64,
) -> f64 {
let mut maintain_overscroll = true;
let mut enforce_boundary = true;
if velocity != 0.0 {
maintain_overscroll = false;
enforce_boundary = false;
}
if old_position.min_scroll_extent() == new_position.min_scroll_extent()
&& old_position.max_scroll_extent() == new_position.max_scroll_extent()
{
maintain_overscroll = false;
}
if old_position.pixels() != new_position.pixels() {
maintain_overscroll = false;
if old_position.min_scroll_extent().is_finite()
&& old_position.max_scroll_extent().is_finite()
&& new_position.min_scroll_extent().is_finite()
&& new_position.max_scroll_extent().is_finite()
{
enforce_boundary = false;
}
}
if old_position.pixels() < old_position.min_scroll_extent()
|| old_position.pixels() > old_position.max_scroll_extent()
{
enforce_boundary = false;
}
if maintain_overscroll {
if old_position.pixels() < old_position.min_scroll_extent()
&& new_position.min_scroll_extent() > old_position.min_scroll_extent()
{
let old_delta = old_position.min_scroll_extent() - old_position.pixels();
return new_position.min_scroll_extent() - old_delta;
}
if old_position.pixels() > old_position.max_scroll_extent()
&& new_position.max_scroll_extent() < old_position.max_scroll_extent()
{
let old_delta = old_position.pixels() - old_position.max_scroll_extent();
return new_position.max_scroll_extent() + old_delta;
}
}
let mut result = ScrollPhysicsBase::adjust_position_for_new_dimensions(
self,
old_position,
new_position,
is_scrolling,
velocity,
);
if enforce_boundary {
result = clamp_double(
result,
new_position.min_scroll_extent(),
new_position.max_scroll_extent(),
);
}
result
}
}
impl Debug for RangeMaintainingScrollPhysics {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt_scroll_physics(f, "RangeMaintainingScrollPhysics", self.parent.as_ref())
}
}
pub struct BouncingScrollPhysics {
pub deceleration_rate: ScrollDecelerationRate,
pub parent: Option<ScrollPhysicsRef>,
}
impl Default for BouncingScrollPhysics {
fn default() -> BouncingScrollPhysics {
BouncingScrollPhysics {
deceleration_rate: ScrollDecelerationRate::Normal,
parent: None,
}
}
}
impl BouncingScrollPhysics {
pub fn new() -> BouncingScrollPhysics {
BouncingScrollPhysics::default()
}
pub fn with_deceleration_rate(
mut self,
deceleration_rate: ScrollDecelerationRate,
) -> BouncingScrollPhysics {
self.deceleration_rate = deceleration_rate;
self
}
pub fn with_parent(mut self, parent: ScrollPhysicsRef) -> BouncingScrollPhysics {
self.parent = Some(parent);
self
}
pub fn friction_factor(&self, overscroll_fraction: f64) -> f64 {
(1.0 - overscroll_fraction).powi(2)
* match self.deceleration_rate {
ScrollDecelerationRate::Fast => 0.26,
ScrollDecelerationRate::Normal => 0.52,
}
}
}
fn apply_friction(extent_outside: f64, abs_delta: f64, gamma: f64) -> f64 {
debug_assert!(abs_delta > 0.0);
let mut abs_delta = abs_delta;
let mut total = 0.0;
if extent_outside > 0.0 {
let delta_to_limit = extent_outside / gamma;
if abs_delta < delta_to_limit {
return abs_delta * gamma;
}
total += extent_outside;
abs_delta -= delta_to_limit;
}
total + abs_delta
}
impl ScrollPhysics for BouncingScrollPhysics {
fn as_any(&self) -> &dyn Any {
self
}
fn parent(&self) -> Option<&ScrollPhysicsRef> {
self.parent.as_ref()
}
fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
Rc::new(BouncingScrollPhysics {
parent: ScrollPhysicsBase::build_parent(self, ancestor),
deceleration_rate: self.deceleration_rate,
})
}
fn apply_physics_to_user_offset(&self, position: &dyn ScrollMetrics, offset: f64) -> f64 {
debug_assert!(offset != 0.0);
debug_assert!(position.min_scroll_extent() <= position.max_scroll_extent());
if !position.out_of_range() {
return offset;
}
let overscroll_past_start = (position.min_scroll_extent() - position.pixels()).max(0.0);
let overscroll_past_end = (position.pixels() - position.max_scroll_extent()).max(0.0);
let overscroll_past = overscroll_past_start.max(overscroll_past_end);
let easing = (overscroll_past_start > 0.0 && offset < 0.0)
|| (overscroll_past_end > 0.0 && offset > 0.0);
let friction = if easing {
self.friction_factor((overscroll_past - offset.abs()) / position.viewport_dimension())
} else {
self.friction_factor(overscroll_past / position.viewport_dimension())
};
let direction = offset.signum();
if easing && self.deceleration_rate == ScrollDecelerationRate::Fast {
return direction * offset.abs();
}
direction * apply_friction(overscroll_past, offset.abs(), friction)
}
fn apply_boundary_conditions(&self, _position: &dyn ScrollMetrics, _value: f64) -> f64 {
0.0
}
fn create_ballistic_simulation(
&self,
position: &dyn ScrollMetrics,
velocity: f64,
) -> Option<Box<dyn Simulation>> {
let tolerance = self.tolerance_for(position);
if velocity.abs() >= tolerance.velocity || position.out_of_range() {
return Some(Box::new(BouncingScrollSimulation::with_options(
position.pixels(),
velocity,
position.min_scroll_extent(),
position.max_scroll_extent(),
self.spring(),
match self.deceleration_rate {
ScrollDecelerationRate::Fast => 1400.0,
ScrollDecelerationRate::Normal => 0.0,
},
tolerance,
)));
}
None
}
fn min_fling_velocity(&self) -> f64 {
K_MIN_FLING_VELOCITY * 2.0
}
fn carried_momentum(&self, existing_velocity: f64) -> f64 {
existing_velocity.signum() * (0.000816 * existing_velocity.abs().powf(1.967)).min(40000.0)
}
fn drag_start_distance_motion_threshold(&self) -> Option<f64> {
Some(3.5)
}
fn max_fling_velocity(&self) -> f64 {
match self.deceleration_rate {
ScrollDecelerationRate::Fast => K_MAX_FLING_VELOCITY * 8.0,
ScrollDecelerationRate::Normal => ScrollPhysicsBase::max_fling_velocity(self),
}
}
fn spring(&self) -> SpringDescription {
match self.deceleration_rate {
ScrollDecelerationRate::Fast => {
SpringDescription::with_damping_ratio_value(0.3, 75.0, 1.3)
}
ScrollDecelerationRate::Normal => ScrollPhysicsBase::spring(self),
}
}
}
impl Debug for BouncingScrollPhysics {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt_scroll_physics(f, "BouncingScrollPhysics", self.parent.as_ref())
}
}
#[derive(Default)]
pub struct ClampingScrollPhysics {
pub parent: Option<ScrollPhysicsRef>,
}
impl ClampingScrollPhysics {
pub fn new() -> ClampingScrollPhysics {
ClampingScrollPhysics::default()
}
pub fn with_parent(mut self, parent: ScrollPhysicsRef) -> ClampingScrollPhysics {
self.parent = Some(parent);
self
}
}
impl ScrollPhysics for ClampingScrollPhysics {
fn as_any(&self) -> &dyn Any {
self
}
fn parent(&self) -> Option<&ScrollPhysicsRef> {
self.parent.as_ref()
}
fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
Rc::new(ClampingScrollPhysics {
parent: ScrollPhysicsBase::build_parent(self, ancestor),
})
}
fn apply_boundary_conditions(&self, position: &dyn ScrollMetrics, value: f64) -> f64 {
debug_assert!(
value != position.pixels(),
"ClampingScrollPhysics.applyBoundaryConditions() was called redundantly.\n\
The proposed new position, {value}, is exactly equal to the current position \
of the given ScrollMetrics, {}.\n\
The applyBoundaryConditions method should only be called when the value is \
going to actually change the pixels, otherwise it is redundant.",
position.pixels()
);
if value < position.pixels() && position.pixels() <= position.min_scroll_extent() {
return value - position.pixels();
}
if position.max_scroll_extent() <= position.pixels() && position.pixels() < value {
return value - position.pixels();
}
if value < position.min_scroll_extent() && position.min_scroll_extent() < position.pixels()
{
return value - position.min_scroll_extent();
}
if position.pixels() < position.max_scroll_extent() && position.max_scroll_extent() < value
{
return value - position.max_scroll_extent();
}
0.0
}
fn create_ballistic_simulation(
&self,
position: &dyn ScrollMetrics,
velocity: f64,
) -> Option<Box<dyn Simulation>> {
let tolerance = self.tolerance_for(position);
if position.out_of_range() {
let mut end = None;
if position.pixels() > position.max_scroll_extent() {
end = Some(position.max_scroll_extent());
}
if position.pixels() < position.min_scroll_extent() {
end = Some(position.min_scroll_extent());
}
let end = end.expect("an out-of-range position is past one of the two extents");
return Some(Box::new(ScrollSpringSimulation::new(
self.spring(),
position.pixels(),
end,
velocity.min(0.0),
tolerance,
)));
}
if velocity.abs() < tolerance.velocity {
return None;
}
if velocity > 0.0 && position.pixels() >= position.max_scroll_extent() {
return None;
}
if velocity < 0.0 && position.pixels() <= position.min_scroll_extent() {
return None;
}
Some(Box::new(ClampingScrollSimulation::with_options(
position.pixels(),
velocity,
ClampingScrollSimulation::DEFAULT_FRICTION,
tolerance,
)))
}
}
impl Debug for ClampingScrollPhysics {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt_scroll_physics(f, "ClampingScrollPhysics", self.parent.as_ref())
}
}
#[derive(Default)]
pub struct AlwaysScrollableScrollPhysics {
pub parent: Option<ScrollPhysicsRef>,
}
impl AlwaysScrollableScrollPhysics {
pub fn new() -> AlwaysScrollableScrollPhysics {
AlwaysScrollableScrollPhysics::default()
}
pub fn with_parent(mut self, parent: ScrollPhysicsRef) -> AlwaysScrollableScrollPhysics {
self.parent = Some(parent);
self
}
}
impl ScrollPhysics for AlwaysScrollableScrollPhysics {
fn as_any(&self) -> &dyn Any {
self
}
fn parent(&self) -> Option<&ScrollPhysicsRef> {
self.parent.as_ref()
}
fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
Rc::new(AlwaysScrollableScrollPhysics {
parent: ScrollPhysicsBase::build_parent(self, ancestor),
})
}
fn should_accept_user_offset(&self, _position: &dyn ScrollMetrics) -> bool {
true
}
}
impl Debug for AlwaysScrollableScrollPhysics {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt_scroll_physics(f, "AlwaysScrollableScrollPhysics", self.parent.as_ref())
}
}
#[derive(Default)]
pub struct NeverScrollableScrollPhysics {
pub parent: Option<ScrollPhysicsRef>,
}
impl NeverScrollableScrollPhysics {
pub fn new() -> NeverScrollableScrollPhysics {
NeverScrollableScrollPhysics::default()
}
pub fn with_parent(mut self, parent: ScrollPhysicsRef) -> NeverScrollableScrollPhysics {
self.parent = Some(parent);
self
}
}
impl ScrollPhysics for NeverScrollableScrollPhysics {
fn as_any(&self) -> &dyn Any {
self
}
fn parent(&self) -> Option<&ScrollPhysicsRef> {
self.parent.as_ref()
}
fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
Rc::new(NeverScrollableScrollPhysics {
parent: ScrollPhysicsBase::build_parent(self, ancestor),
})
}
fn allow_implicit_scrolling(&self) -> bool {
false
}
fn allow_user_scrolling(&self) -> bool {
false
}
}
impl Debug for NeverScrollableScrollPhysics {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt_scroll_physics(f, "NeverScrollableScrollPhysics", self.parent.as_ref())
}
}
#[cfg(test)]
mod tests {
use waft_painting::AxisDirection;
use super::*;
use crate::widgets::scroll_metrics::FixedScrollMetrics;
struct TestScrollPhysics {
name: &'static str,
parent: Option<ScrollPhysicsRef>,
}
impl TestScrollPhysics {
fn new(name: &'static str) -> TestScrollPhysics {
TestScrollPhysics { name, parent: None }
}
}
impl ScrollPhysics for TestScrollPhysics {
fn as_any(&self) -> &dyn Any {
self
}
fn parent(&self) -> Option<&ScrollPhysicsRef> {
self.parent.as_ref()
}
fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
Rc::new(TestScrollPhysics {
name: self.name,
parent: ScrollPhysicsBase::build_parent(self, ancestor),
})
}
}
impl Debug for TestScrollPhysics {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = format!("TestScrollPhysics({})", self.name);
fmt_scroll_physics(f, &name, self.parent.as_ref())
}
}
fn metrics(pixels: f64) -> FixedScrollMetrics {
FixedScrollMetrics::new(
Some(0.0),
Some(1000.0),
Some(pixels),
Some(100.0),
AxisDirection::Down,
3.0,
)
}
#[test]
fn apply_to_appends_the_ancestor_to_the_end_of_the_parent_chain() {
let a = TestScrollPhysics::new("a");
let b = TestScrollPhysics::new("b");
let c = TestScrollPhysics::new("c");
let d = TestScrollPhysics::new("d");
let e = TestScrollPhysics::new("e");
assert!(a.parent().is_none());
assert!(b.parent().is_none());
assert!(c.parent().is_none());
let ab = a.apply_to(Some(Rc::new(b)));
assert_eq!(
format!("{ab:?}"),
"TestScrollPhysics(a) -> TestScrollPhysics(b)"
);
let abc = ab.apply_to(Some(Rc::new(c)));
assert_eq!(
format!("{abc:?}"),
"TestScrollPhysics(a) -> TestScrollPhysics(b) -> TestScrollPhysics(c)"
);
let de = d.apply_to(Some(Rc::new(e)));
assert_eq!(
format!("{de:?}"),
"TestScrollPhysics(d) -> TestScrollPhysics(e)"
);
let abcde = abc.apply_to(Some(de));
assert_eq!(
format!("{abcde:?}"),
"TestScrollPhysics(a) -> TestScrollPhysics(b) -> TestScrollPhysics(c) \
-> TestScrollPhysics(d) -> TestScrollPhysics(e)"
);
}
#[test]
fn apply_to_keeps_each_type_and_its_own_arguments() {
let chain = BouncingScrollPhysics::new().apply_to(Some(
ClampingScrollPhysics::new().apply_to(Some(
NeverScrollableScrollPhysics::new()
.apply_to(Some(Rc::new(AlwaysScrollableScrollPhysics::new()))),
)),
));
assert_eq!(
format!("{chain:?}"),
"BouncingScrollPhysics -> ClampingScrollPhysics -> NeverScrollableScrollPhysics \
-> AlwaysScrollableScrollPhysics"
);
assert_eq!(format!("{:?}", PlainScrollPhysics::new()), "ScrollPhysics");
assert_eq!(
format!(
"{:?}",
RangeMaintainingScrollPhysics::new()
.apply_to(Some(Rc::new(ClampingScrollPhysics::new())))
),
"RangeMaintainingScrollPhysics -> ClampingScrollPhysics"
);
let desktop = BouncingScrollPhysics::new()
.with_deceleration_rate(ScrollDecelerationRate::Fast)
.apply_to(Some(Rc::new(AlwaysScrollableScrollPhysics::new())));
assert_eq!(desktop.max_fling_velocity(), K_MAX_FLING_VELOCITY * 8.0);
}
#[test]
fn bouncing_scroll_physics_applies_friction_only_past_the_edge() {
let physics = BouncingScrollPhysics::new();
let inside = metrics(300.0);
assert_eq!(physics.apply_physics_to_user_offset(&inside, 10.0), 10.0);
assert_eq!(physics.apply_physics_to_user_offset(&inside, -10.0), -10.0);
let less = physics.apply_physics_to_user_offset(&metrics(-20.0), 10.0);
let more = physics.apply_physics_to_user_offset(&metrics(-40.0), 10.0);
assert!(less > 1.0 && less < 20.0);
assert!(more > 1.0 && more < 20.0);
assert!(less.abs() > more.abs());
let easing = physics.apply_physics_to_user_offset(&metrics(-20.0), -10.0);
assert!(easing < -1.0 && easing > -10.0);
assert!(easing.abs() > less.abs());
let desktop =
BouncingScrollPhysics::new().with_deceleration_rate(ScrollDecelerationRate::Fast);
assert_eq!(physics.friction_factor(0.0), 0.52);
assert_eq!(desktop.friction_factor(0.0), 0.26);
assert_eq!(
desktop.apply_physics_to_user_offset(&metrics(-20.0), -10.0),
-10.0
);
assert_eq!(
physics.apply_boundary_conditions(&metrics(-20.0), -30.0),
0.0
);
}
#[test]
fn bouncing_scroll_physics_builds_a_simulation_that_bounces_back() {
let physics = BouncingScrollPhysics::new();
let overscrolled = metrics(-20.0);
let simulation = physics
.create_ballistic_simulation(&overscrolled, 0.0)
.expect("an out-of-range position always gets a simulation");
assert_eq!(simulation.x(0.0), -20.0);
let mut time = 0.0;
while !simulation.is_done(time) {
time += 1.0 / 60.0;
assert!(time < 10.0, "the spring must settle");
}
assert!(
simulation.x(time).abs() < 0.1,
"settled at {}",
simulation.x(time)
);
assert!(
physics
.create_ballistic_simulation(&metrics(300.0), 0.0)
.is_none()
);
let flung = physics
.create_ballistic_simulation(&metrics(20.0), 1000.0)
.expect("a fling gets a simulation");
assert!((flung.dx(0.0) - 1000.0).abs() < 1e-9);
}
#[test]
fn clamping_scroll_physics_clamps_at_the_boundary() {
let physics = ClampingScrollPhysics::new();
let inside = metrics(500.0);
assert_eq!(physics.apply_boundary_conditions(&inside, 1500.0), 500.0);
assert_eq!(physics.apply_boundary_conditions(&inside, -500.0), -500.0);
assert_eq!(physics.apply_boundary_conditions(&inside, 600.0), 0.0);
assert_eq!(physics.apply_boundary_conditions(&inside, 400.0), 0.0);
let over = metrics(1200.0);
assert_eq!(physics.apply_boundary_conditions(&over, 1300.0), 100.0);
assert_eq!(physics.apply_boundary_conditions(&over, 1100.0), 0.0);
}
#[test]
fn clamping_scroll_physics_builds_a_simulation_that_stops_at_the_edge() {
let physics = ClampingScrollPhysics::new();
let over = metrics(1200.0);
let spring = physics
.create_ballistic_simulation(&over, 0.0)
.expect("an out-of-range position always gets a simulation");
let mut time = 0.0;
while !spring.is_done(time) {
time += 1.0 / 60.0;
assert!(time < 10.0, "the spring must settle");
}
assert!(
(spring.x(time) - 1000.0).abs() < 0.1,
"settled at {}",
spring.x(time)
);
let fling = physics
.create_ballistic_simulation(&metrics(20.0), 1000.0)
.expect("a fling gets a simulation");
assert!((fling.dx(0.0) - 1000.0).abs() < 1e-9);
assert!(fling.is_done(1.0));
assert!(
physics
.create_ballistic_simulation(&metrics(300.0), 0.0)
.is_none()
);
assert!(
physics
.create_ballistic_simulation(&metrics(1000.0), 1000.0)
.is_none()
);
assert!(
physics
.create_ballistic_simulation(&metrics(0.0), -1000.0)
.is_none()
);
}
#[test]
fn always_and_never_scrollable_decide_whether_the_user_may_scroll() {
let empty = FixedScrollMetrics::new(
Some(0.0),
Some(0.0),
Some(0.0),
Some(600.0),
AxisDirection::Down,
3.0,
);
assert!(!PlainScrollPhysics::new().should_accept_user_offset(&empty));
assert!(PlainScrollPhysics::new().should_accept_user_offset(&metrics(0.0)));
assert!(AlwaysScrollableScrollPhysics::new().should_accept_user_offset(&empty));
let never = NeverScrollableScrollPhysics::new();
assert!(!never.should_accept_user_offset(&metrics(0.0)));
assert!(!never.allow_user_scrolling());
assert!(!never.allow_implicit_scrolling());
let never_over_always = NeverScrollableScrollPhysics::new()
.apply_to(Some(Rc::new(AlwaysScrollableScrollPhysics::new())));
assert!(!never_over_always.should_accept_user_offset(&empty));
}
#[test]
fn a_parent_answers_what_this_physics_has_no_opinion_on() {
let bouncing_over_always = BouncingScrollPhysics::new()
.apply_to(Some(Rc::new(AlwaysScrollableScrollPhysics::new())));
let empty = FixedScrollMetrics::new(
Some(0.0),
Some(0.0),
Some(0.0),
Some(600.0),
AxisDirection::Down,
3.0,
);
assert!(bouncing_over_always.should_accept_user_offset(&empty));
assert_eq!(
bouncing_over_always.min_fling_velocity(),
K_MIN_FLING_VELOCITY * 2.0
);
assert_eq!(
bouncing_over_always.drag_start_distance_motion_threshold(),
Some(3.5)
);
assert_eq!(PlainScrollPhysics::new().carried_momentum(1000.0), 0.0);
assert!(BouncingScrollPhysics::new().carried_momentum(1000.0) > 0.0);
assert_eq!(PlainScrollPhysics::new().min_fling_distance(), K_TOUCH_SLOP);
}
#[test]
fn range_maintaining_physics_keeps_the_overscroll_when_content_shrinks() {
let physics = RangeMaintainingScrollPhysics::new();
let old = FixedScrollMetrics::new(
Some(0.0),
Some(1000.0),
Some(1100.0),
Some(600.0),
AxisDirection::Down,
3.0,
);
let new = old.copy_with().with_max_scroll_extent(800.0);
assert_eq!(
physics.adjust_position_for_new_dimensions(&old, &new, false, 0.0),
900.0
);
let old_inside = old.copy_with().with_pixels(900.0);
let new_inside = old_inside.copy_with().with_max_scroll_extent(800.0);
assert_eq!(
physics.adjust_position_for_new_dimensions(&old_inside, &new_inside, false, 0.0),
800.0
);
assert_eq!(
physics.adjust_position_for_new_dimensions(&old_inside, &new_inside, true, 10.0),
900.0
);
}
}