Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
gpui: Lock touch scrolling to the dominant axis (#63553)
Jakub Konka5e28272c1407
diff --git a/crates/gpui/src/gestures.rs b/crates/gpui/src/gestures.rsindex edf78957a6e..b3c625904bd 100644--- a/crates/gpui/src/gestures.rs+++ b/crates/gpui/src/gestures.rs@@ -24,6 +24,21 @@ use crate::{const SCROLL_EVENT_SEPARATION: Duration = Duration::from_millis(28);+fn dominant_axis(delta: Point<Pixels>) -> Axis {+ if delta.x.abs() <= delta.y.abs() {+ Axis::Vertical+ } else {+ Axis::Horizontal+ }+}++fn lock_delta_to_axis(delta: &mut Point<Pixels>, axis: Axis) {+ match axis {+ Axis::Vertical => delta.x = Pixels::ZERO,+ Axis::Horizontal => delta.y = Pixels::ZERO,+ }+}+/// Tracks the dominant axis across the events in a scroll gesture.#[derive(Clone, Copy, Debug, Default)]pub struct OngoingScroll {@@ -66,11 +81,7 @@ impl OngoingScroll {.is_none_or(|last_event| now.duration_since(last_event) >= SCROLL_EVENT_SEPARATION);let mut axis = self.axis;if starts_new_gesture {- axis = if x <= y {- Some(Axis::Vertical)- } else {- Some(Axis::Horizontal)- };+ axis = Some(dominant_axis(*delta));} else if x.max(y) >= UNLOCK_LOWER_BOUND {match axis {Some(Axis::Vertical) if x > y && x >= y * UNLOCK_PERCENT => {@@ -85,10 +96,8 @@ impl OngoingScroll {self.last_event = Some(now);self.axis = axis;- match axis {- Some(Axis::Vertical) => delta.x = Pixels::ZERO,- Some(Axis::Horizontal) => delta.y = Pixels::ZERO,- None => {}+ if let Some(axis) = axis {+ lock_delta_to_axis(delta, axis);}}}@@ -463,7 +472,10 @@ enum TouchGestureState {Pending(ActiveTouch),/// The touch exceeded `touch_slop`: it is a pan until it ends, and its/// movement flows out as scroll events.- Panning(ActiveTouch),+ Panning {+ touch: ActiveTouch,+ axis: Axis,+ },}struct ActiveTouch {@@ -493,6 +505,7 @@ struct Momentum {position: Point<Pixels>,/// Unit vector of the release velocity.direction: Point<f32>,+ axis: Axis,/// Release speed in pixels per second.speed: f32,started_at: Instant,@@ -532,9 +545,9 @@ impl TouchGestureRecognizer {Point::default(),TouchPhase::Ended,)));- true+ Some(momentum.axis)} else {- false+ None};if matches!(self.state, TouchGestureState::Idle) {let mut velocity_tracker = VelocityTracker::default();@@ -545,7 +558,7 @@ impl TouchGestureRecognizer {emitted_position: event.position,velocity_tracker,};- if caught_fling {+ if let Some(axis) = caught_fling {// A touch that catches a fling is a drag from the// first pixel: waiting out the slop would freeze the// content mid-scroll and then jump. It can also never@@ -556,7 +569,7 @@ impl TouchGestureRecognizer {Point::default(),TouchPhase::Started,)));- self.state = TouchGestureState::Panning(touch);+ self.state = TouchGestureState::Panning { touch, axis };} else {self.state = TouchGestureState::Pending(touch);}@@ -571,28 +584,32 @@ impl TouchGestureRecognizer {// step: the content catches up to the finger instead// of losing the slop distance.let target = event.predicted_position.unwrap_or(event.position);+ let axis = dominant_axis(accumulated);+ let mut delta = target - touch.start_position;+ lock_delta_to_axis(&mut delta, axis);touch.emitted_position = target;recognized.push(RecognizedTouchGesture::Scroll(scroll_event(touch.start_position,- target - touch.start_position,+ delta,TouchPhase::Started,)));- self.state = TouchGestureState::Panning(touch);+ self.state = TouchGestureState::Panning { touch, axis };} else {self.state = TouchGestureState::Pending(touch);}}- TouchGestureState::Panning(mut touch) if touch.id == event.id => {+ TouchGestureState::Panning { mut touch, axis } if touch.id == event.id => {touch.velocity_tracker.push(now, event.position);let target = event.predicted_position.unwrap_or(event.position);- let delta = target - touch.emitted_position;+ let mut delta = target - touch.emitted_position;+ lock_delta_to_axis(&mut delta, axis);touch.emitted_position = target;recognized.push(RecognizedTouchGesture::Scroll(scroll_event(touch.start_position,delta,TouchPhase::Moved,)));- self.state = TouchGestureState::Panning(touch);+ self.state = TouchGestureState::Panning { touch, axis };}other => self.state = other,},@@ -629,7 +646,7 @@ impl TouchGestureRecognizer {},});}- TouchGestureState::Panning(touch) if touch.id == event.id => {+ TouchGestureState::Panning { touch, axis } if touch.id == event.id => {// The release deliberately contributes no velocity// sample: it usually repeats the last movement's position// with a later timestamp, which would dilute the@@ -643,13 +660,18 @@ impl TouchGestureRecognizer {.is_none_or(|latest| {now.duration_since(latest) > VELOCITY_ASSUME_STOPPED_GAP});- let velocity = if finger_stopped {+ let mut velocity = if finger_stopped {Point::default()} else {touch.velocity_tracker.velocity()};+ match axis {+ Axis::Vertical => velocity.x = 0.,+ Axis::Horizontal => velocity.y = 0.,+ }let speed = (velocity.x.powi(2) + velocity.y.powi(2)).sqrt();let mut release_delta = event.position - touch.emitted_position;+ lock_delta_to_axis(&mut release_delta, axis);if speed >= self.tuning.min_fling_velocity {let direction = point(velocity.x / speed, velocity.y / speed);let speed = speed.min(MAX_FLING_VELOCITY);@@ -676,6 +698,7 @@ impl TouchGestureRecognizer {self.momentum = Some(Momentum {position: touch.start_position,direction,+ axis,speed,started_at: now,duration,@@ -693,7 +716,7 @@ impl TouchGestureRecognizer {},TouchPhase::Cancelled => match mem::replace(&mut self.state, TouchGestureState::Idle) {TouchGestureState::Pending(touch) if touch.id == event.id => {}- TouchGestureState::Panning(touch) if touch.id == event.id => {+ TouchGestureState::Panning { touch, .. } if touch.id == event.id => {recognized.push(RecognizedTouchGesture::Scroll(scroll_event(touch.start_position,Point::default(),@@ -1086,6 +1109,51 @@ mod tests {assert_eq!(scroll.touch_phase, TouchPhase::Ended);}+ #[test]+ fn touch_pan_stays_locked_to_its_initial_dominant_axis() {+ let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());+ let now = Instant::now();+ let touch = TouchId(1);++ recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 100., 100.), now);++ let recognized = recognizer.handle_event_at(+ &touch_event(touch, TouchPhase::Moved, 104., 120.),+ now + Duration::from_millis(16),+ );+ let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {+ panic!("expected scroll, got {recognized:?}");+ };+ assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(0.), px(20.)));++ let recognized = recognizer.handle_event_at(+ &touch_event(touch, TouchPhase::Moved, 134., 125.),+ now + Duration::from_millis(32),+ );+ let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {+ panic!("expected scroll, got {recognized:?}");+ };+ assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(0.), px(5.)));+ }++ #[test]+ fn touch_pan_locks_to_horizontal_axis() {+ let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());+ let now = Instant::now();+ let touch = TouchId(1);++ recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 100., 100.), now);++ let recognized = recognizer.handle_event_at(+ &touch_event(touch, TouchPhase::Moved, 120., 104.),+ now + Duration::from_millis(16),+ );+ let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {+ panic!("expected scroll, got {recognized:?}");+ };+ assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(20.), px(0.)));+ }+#[test]fn predicted_positions_lead_the_pan_but_totals_converge_on_release() {let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());@@ -1096,7 +1164,7 @@ mod tests {// The first pan step scrolls to the predicted position, not the raw one.let mut moved = touch_event(touch, TouchPhase::Moved, 100., 120.);- moved.predicted_position = Some(point(px(100.), px(128.)));+ moved.predicted_position = Some(point(px(106.), px(128.)));let recognized = recognizer.handle_event_at(&moved, now + Duration::from_millis(16));let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {panic!("expected scroll, got {recognized:?}");@@ -1106,7 +1174,7 @@ mod tests {// The next step is measured from where the previous prediction left// the content, so an overshoot is paid back here.let mut moved = touch_event(touch, TouchPhase::Moved, 100., 130.);- moved.predicted_position = Some(point(px(100.), px(134.)));+ moved.predicted_position = Some(point(px(104.), px(134.)));let recognized = recognizer.handle_event_at(&moved, now + Duration::from_millis(32));let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {panic!("expected scroll, got {recognized:?}");@@ -1249,6 +1317,46 @@ mod tests {assert!(recognizer.tick_momentum_at(time).is_none());}+ #[test]+ fn diagonal_release_flings_only_on_locked_axis() {+ let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());+ let now = Instant::now();+ let touch = TouchId(1);++ recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 100., 300.), now);+ for step in 1..=5 {+ let recognized = recognizer.handle_event_at(+ &touch_event(+ touch,+ TouchPhase::Moved,+ 100. + step as f32 * 3.,+ 300. - step as f32 * 20.,+ ),+ now + Duration::from_millis(step * 16),+ );+ let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {+ panic!("expected scroll, got {recognized:?}");+ };+ assert_eq!(scroll.delta.pixel_delta(px(16.)).x, px(0.));+ }+ recognizer.handle_event_at(+ &touch_event(touch, TouchPhase::Ended, 115., 200.),+ now + Duration::from_millis(6 * 16),+ );+ assert!(recognizer.has_momentum());++ let mut time = now + Duration::from_millis(6 * 16);+ while recognizer.has_momentum() {+ time += Duration::from_millis(16);+ if let Some(RecognizedTouchGesture::Scroll(scroll)) = recognizer.tick_momentum_at(time)+ {+ let delta = scroll.delta.pixel_delta(px(16.));+ assert_eq!(delta.x, px(0.));+ assert!(delta.y <= px(0.));+ }+ }+ }+#[test]fn slow_release_does_not_start_momentum() {let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());