Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
gpui: Add long-press gesture recognition (#63561)
Jakub Konka0855410ccd20
diff --git a/crates/gpui/src/gestures.rs b/crates/gpui/src/gestures.rsindex b3c625904bd..f11b1a7dd6d 100644--- a/crates/gpui/src/gestures.rs+++ b/crates/gpui/src/gestures.rs@@ -18,8 +18,9 @@ use scheduler::Instant;use smallvec::SmallVec;use crate::{- Axis, IsZero, Modifiers, MouseButton, MouseDownEvent, MouseUpEvent, Pixels, Point, ScrollDelta,- ScrollWheelEvent, TouchEvent, TouchId, TouchPhase, point, px,+ Axis, GestureEvent, InputEvent, IsZero, Modifiers, MouseButton, MouseDownEvent, MouseEvent,+ MouseUpEvent, Pixels, PlatformInput, Point, ScrollDelta, ScrollWheelEvent, TouchEvent, TouchId,+ TouchPhase, point, px, seal::Sealed,};const SCROLL_EVENT_SEPARATION: Duration = Duration::from_millis(28);@@ -375,19 +376,36 @@ impl GestureKinds {};}-/// A long-press gesture, mobile's context-menu trigger.-///-/// A bare long press is surfaced as a [`ClickEvent`](crate::ClickEvent) with-/// `long_press: true`, delivered to aux-click listeners alongside right-/// clicks. This event is the raw hook for elements that need the gesture-/// itself (e.g. long-press to start a drag); the registration API ships-/// together with the gesture arena.-#[derive(Clone, Debug, Default)]+/// A phased long-press gesture recognized from a touch.+#[derive(Clone, Debug)]pub struct LongPressEvent {- /// The position of the touch that was recognized as a long press.+ /// The phase of the long press.+ pub phase: TouchPhase,+ /// The position where the touch started.+ pub start_position: Point<Pixels>,+ /// The touch's current position.pub position: Point<Pixels>,}+impl Default for LongPressEvent {+ fn default() -> Self {+ Self {+ phase: TouchPhase::Started,+ start_position: Point::default(),+ position: Point::default(),+ }+ }+}++impl Sealed for LongPressEvent {}+impl InputEvent for LongPressEvent {+ fn to_platform_input(self) -> PlatformInput {+ PlatformInput::LongPress(self)+ }+}+impl GestureEvent for LongPressEvent {}+impl MouseEvent for LongPressEvent {}+/// Platform gesture recognition services.////// If your mobile platform supports native gesture recognition, use this@@ -442,8 +460,8 @@ const VELOCITY_MAX_SAMPLES: usize = 20;/// [`ClickEvent::Touch`](crate::ClickEvent), which keeps every existing/// mouse-driven behavior (click listeners, caret placement, double-tap/// selection) working before elements grow a direct tap-delivery path.-/// Long-press and pinch recognition are not implemented yet, and additional-/// touches are ignored while one is being recognized.+/// Pinch recognition is not implemented yet, and additional touches are ignored+/// while one is being recognized.pub(crate) struct TouchGestureRecognizer {tuning: GestureTuning,state: TouchGestureState,@@ -463,24 +481,32 @@ pub(crate) enum RecognizedTouchGesture {down: MouseDownEvent,up: MouseUpEvent,},+ LongPress(LongPressEvent),}enum TouchGestureState {Idle,/// The touch is still within `touch_slop` of where it started: it can/// still resolve into either a tap or a pan.- Pending(ActiveTouch),+ Pending {+ touch: ActiveTouch,+ deadline: Instant,+ offered: bool,+ },/// The touch exceeded `touch_slop`: it is a pan until it ends, and its/// movement flows out as scroll events.Panning {touch: ActiveTouch,axis: Axis,},+ LongPressing(ActiveTouch),}struct ActiveTouch {id: TouchId,start_position: Point<Pixels>,+ /// The latest raw position reported for this touch.+ last_position: Point<Pixels>,/// The position pan output has scrolled to so far. While panning this/// may run ahead of the raw touch by the event's predicted position;/// the release event targets the raw position again, so the total@@ -555,6 +581,7 @@ impl TouchGestureRecognizer {let touch = ActiveTouch {id: event.id,start_position: event.position,+ last_position: event.position,emitted_position: event.position,velocity_tracker,};@@ -571,13 +598,22 @@ impl TouchGestureRecognizer {)));self.state = TouchGestureState::Panning { touch, axis };} else {- self.state = TouchGestureState::Pending(touch);+ self.state = TouchGestureState::Pending {+ touch,+ deadline: now + self.tuning.long_press_duration,+ offered: false,+ };}}}TouchPhase::Moved => match mem::replace(&mut self.state, TouchGestureState::Idle) {- TouchGestureState::Pending(mut touch) if touch.id == event.id => {+ TouchGestureState::Pending {+ mut touch,+ deadline,+ offered,+ } if touch.id == event.id => {touch.velocity_tracker.push(now, event.position);+ touch.last_position = event.position;let accumulated = event.position - touch.start_position;if accumulated.magnitude() > f64::from(self.tuning.touch_slop) {// Carry the full movement so far into the first scroll@@ -595,11 +631,16 @@ impl TouchGestureRecognizer {)));self.state = TouchGestureState::Panning { touch, axis };} else {- self.state = TouchGestureState::Pending(touch);+ self.state = TouchGestureState::Pending {+ touch,+ deadline,+ offered,+ };}}TouchGestureState::Panning { mut touch, axis } if touch.id == event.id => {touch.velocity_tracker.push(now, event.position);+ touch.last_position = event.position;let target = event.predicted_position.unwrap_or(event.position);let mut delta = target - touch.emitted_position;lock_delta_to_axis(&mut delta, axis);@@ -611,10 +652,19 @@ impl TouchGestureRecognizer {)));self.state = TouchGestureState::Panning { touch, axis };}+ TouchGestureState::LongPressing(mut touch) if touch.id == event.id => {+ touch.last_position = event.position;+ recognized.push(RecognizedTouchGesture::LongPress(LongPressEvent {+ phase: TouchPhase::Moved,+ start_position: touch.start_position,+ position: event.position,+ }));+ self.state = TouchGestureState::LongPressing(touch);+ }other => self.state = other,},TouchPhase::Ended => match mem::replace(&mut self.state, TouchGestureState::Idle) {- TouchGestureState::Pending(touch) if touch.id == event.id => {+ TouchGestureState::Pending { touch, .. } if touch.id == event.id => {let tap_count = match &self.last_tap {Some(tap)if now.duration_since(tap.time) <= self.tuning.multi_tap_interval@@ -712,10 +762,17 @@ impl TouchGestureRecognizer {TouchPhase::Ended,)));}+ TouchGestureState::LongPressing(touch) if touch.id == event.id => {+ recognized.push(RecognizedTouchGesture::LongPress(LongPressEvent {+ phase: TouchPhase::Ended,+ start_position: touch.start_position,+ position: event.position,+ }));+ }other => self.state = other,},TouchPhase::Cancelled => match mem::replace(&mut self.state, TouchGestureState::Idle) {- TouchGestureState::Pending(touch) if touch.id == event.id => {}+ TouchGestureState::Pending { touch, .. } if touch.id == event.id => {}TouchGestureState::Panning { touch, .. } if touch.id == event.id => {recognized.push(RecognizedTouchGesture::Scroll(scroll_event(touch.start_position,@@ -723,12 +780,61 @@ impl TouchGestureRecognizer {TouchPhase::Cancelled,)));}+ TouchGestureState::LongPressing(touch) if touch.id == event.id => {+ recognized.push(RecognizedTouchGesture::LongPress(LongPressEvent {+ phase: TouchPhase::Cancelled,+ start_position: touch.start_position,+ position: event.position,+ }));+ }other => self.state = other,},}recognized}+ pub(crate) fn pending_long_press(&self) -> Option<(TouchId, Duration)> {+ let TouchGestureState::Pending {+ touch,+ deadline,+ offered: false,+ } = &self.state+ else {+ return None;+ };+ Some((touch.id, deadline.saturating_duration_since(Instant::now())))+ }++ pub(crate) fn offer_long_press(&mut self, id: TouchId) -> Option<RecognizedTouchGesture> {+ let TouchGestureState::Pending { touch, offered, .. } = &mut self.state else {+ return None;+ };+ if touch.id != id || *offered {+ return None;+ }+ *offered = true;+ Some(RecognizedTouchGesture::LongPress(LongPressEvent {+ phase: TouchPhase::Started,+ start_position: touch.start_position,+ position: touch.last_position,+ }))+ }++ pub(crate) fn resolve_long_press(&mut self, claimed: bool) {+ if !claimed {+ return;+ }+ let state = mem::replace(&mut self.state, TouchGestureState::Idle);+ self.state = match state {+ TouchGestureState::Pending {+ touch,+ offered: true,+ ..+ } => TouchGestureState::LongPressing(touch),+ other => other,+ };+ }+pub(crate) fn has_momentum(&self) -> bool {self.momentum.is_some()}@@ -1699,6 +1805,163 @@ mod tests {);}+ #[test]+ fn claimed_long_press_emits_phased_stream_without_tap() {+ let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());+ let touch = TouchId(1);+ let now = Instant::now();+ recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 10., 20.), now);+ let Some(RecognizedTouchGesture::LongPress(started)) = recognizer.offer_long_press(touch)+ else {+ panic!("expected long press");+ };+ assert_eq!(started.phase, TouchPhase::Started);+ assert_eq!(started.start_position, point(px(10.), px(20.)));+ recognizer.resolve_long_press(true);++ let moved = recognizer.handle_event_at(+ &touch_event(touch, TouchPhase::Moved, 12., 21.),+ now + Duration::from_millis(510),+ );+ let [RecognizedTouchGesture::LongPress(moved)] = moved.as_slice() else {+ panic!("expected moved long press, got {moved:?}");+ };+ assert_eq!(moved.phase, TouchPhase::Moved);++ let ended = recognizer.handle_event_at(+ &touch_event(touch, TouchPhase::Ended, 12., 21.),+ now + Duration::from_millis(520),+ );+ let [RecognizedTouchGesture::LongPress(ended)] = ended.as_slice() else {+ panic!("expected ended long press, got {ended:?}");+ };+ assert_eq!(ended.phase, TouchPhase::Ended);+ }++ #[test]+ fn unclaimed_long_press_remains_a_tap_candidate() {+ let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());+ let touch = TouchId(1);+ let now = Instant::now();+ recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 10., 20.), now);+ assert!(recognizer.offer_long_press(touch).is_some());+ recognizer.resolve_long_press(false);++ let ended = recognizer.handle_event_at(+ &touch_event(touch, TouchPhase::Ended, 10., 20.),+ now + Duration::from_millis(510),+ );+ assert!(matches!(+ ended.as_slice(),+ [RecognizedTouchGesture::Tap { .. }]+ ));+ }++ #[test]+ fn unclaimed_long_press_can_still_become_a_pan() {+ let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());+ let touch = TouchId(1);+ let now = Instant::now();+ recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 0., 0.), now);+ assert!(recognizer.offer_long_press(touch).is_some());+ recognizer.resolve_long_press(false);++ let moved = recognizer.handle_event_at(+ &touch_event(touch, TouchPhase::Moved, 20., 0.),+ now + Duration::from_millis(510),+ );+ assert!(matches!(+ moved.as_slice(),+ [RecognizedTouchGesture::Scroll(ScrollWheelEvent {+ touch_phase: TouchPhase::Started,+ ..+ })]+ ));+ }++ #[test]+ fn long_press_offer_is_one_shot_and_specific_to_pending_touch() {+ let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());+ let touch = TouchId(1);+ recognizer.handle_event(&touch_event(touch, TouchPhase::Started, 0., 0.));++ assert!(+ recognizer+ .handle_event(&touch_event(TouchId(2), TouchPhase::Moved, 20., 0.))+ .is_empty()+ );+ assert!(recognizer.offer_long_press(TouchId(2)).is_none());+ assert!(recognizer.offer_long_press(touch).is_some());+ assert!(recognizer.offer_long_press(touch).is_none());+ }++ #[test]+ fn long_press_cannot_be_offered_after_pending_touch_resolves() {+ for phase in [TouchPhase::Ended, TouchPhase::Cancelled, TouchPhase::Moved] {+ let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());+ let touch = TouchId(1);+ let now = Instant::now();+ recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 0., 0.), now);+ let position = if phase == TouchPhase::Moved { 20. } else { 0. };+ recognizer.handle_event_at(+ &touch_event(touch, phase, position, 0.),+ now + Duration::from_millis(10),+ );+ assert!(recognizer.offer_long_press(touch).is_none());+ }+ }++ #[test]+ fn claimed_long_press_emits_cancelled_for_its_touch_only() {+ let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());+ let touch = TouchId(1);+ recognizer.handle_event(&touch_event(touch, TouchPhase::Started, 4., 5.));+ assert!(recognizer.offer_long_press(touch).is_some());+ recognizer.resolve_long_press(true);++ assert!(+ recognizer+ .handle_event(&touch_event(TouchId(2), TouchPhase::Cancelled, 9., 9.))+ .is_empty()+ );+ let cancelled = recognizer.handle_event(&touch_event(touch, TouchPhase::Cancelled, 6., 7.));+ let [RecognizedTouchGesture::LongPress(cancelled)] = cancelled.as_slice() else {+ panic!("expected cancelled long press, got {cancelled:?}");+ };+ assert_eq!(cancelled.phase, TouchPhase::Cancelled);+ assert_eq!(cancelled.start_position, point(px(4.), px(5.)));+ assert_eq!(cancelled.position, point(px(6.), px(7.)));+ }++ #[test]+ fn unrelated_touch_cannot_end_or_cancel_pending_touch() {+ for phase in [TouchPhase::Ended, TouchPhase::Cancelled] {+ let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());+ let touch = TouchId(1);+ recognizer.handle_event(&touch_event(touch, TouchPhase::Started, 4., 5.));++ assert!(+ recognizer+ .handle_event(&touch_event(TouchId(2), phase, 9., 9.))+ .is_empty()+ );+ assert!(recognizer.offer_long_press(touch).is_some());+ }+ }++ #[test]+ fn completed_touch_id_cannot_claim_replacement_touch() {+ let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());+ let completed_touch = TouchId(1);+ let replacement_touch = TouchId(2);+ recognizer.handle_event(&touch_event(completed_touch, TouchPhase::Started, 0., 0.));+ recognizer.handle_event(&touch_event(completed_touch, TouchPhase::Cancelled, 0., 0.));+ recognizer.handle_event(&touch_event(replacement_touch, TouchPhase::Started, 5., 5.));++ assert!(recognizer.offer_long_press(completed_touch).is_none());+ assert!(recognizer.offer_long_press(replacement_touch).is_some());+ }+fn touch_event(id: TouchId, phase: TouchPhase, x: f32, y: f32) -> TouchEvent {TouchEvent {id,diff --git a/crates/gpui/src/interactive.rs b/crates/gpui/src/interactive.rsindex be77a1aff75..cfbf2bc82f4 100644--- a/crates/gpui/src/interactive.rs+++ b/crates/gpui/src/interactive.rs@@ -1,6 +1,6 @@use crate::{- Bounds, Capslock, Context, Empty, IntoElement, Keystroke, Modifiers, Pixels, Point, Render,- Window, point, seal::Sealed,+ Bounds, Capslock, Context, Empty, IntoElement, Keystroke, LongPressEvent, Modifiers, Pixels,+ Point, Render, Window, point, seal::Sealed,};use smallvec::SmallVec;use std::{any::Any, fmt::Debug, ops::Deref, path::PathBuf};@@ -103,8 +103,8 @@ pub enum TouchPhase {/// [`TouchPhase::Started`] through [`TouchPhase::Ended`] or/// [`TouchPhase::Cancelled`].///-/// The value is opaque and platform-defined; it is only guaranteed to be-/// stable for the duration of the touch and unique among concurrent touches.+/// The value is opaque and assigned by the platform. A platform window must+/// not reuse an identifier for a later touch.#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]pub struct TouchId(pub u64);@@ -789,6 +789,8 @@ pub enum PlatformInput {ScrollWheel(ScrollWheelEvent),/// A pinch gesture was performed.Pinch(PinchEvent),+ /// A long-press gesture recognized from touch input.+ LongPress(LongPressEvent),/// Files were dragged and dropped onto the window.FileDrop(FileDropEvent),/// A raw touch event on a touch screen.@@ -808,6 +810,7 @@ impl PlatformInput {PlatformInput::MouseExited(event) => Some(event),PlatformInput::ScrollWheel(event) => Some(event),PlatformInput::Pinch(event) => Some(event),+ PlatformInput::LongPress(event) => Some(event),PlatformInput::FileDrop(event) => Some(event),PlatformInput::Touch(_) => None,}@@ -825,6 +828,7 @@ impl PlatformInput {PlatformInput::MouseExited(_) => None,PlatformInput::ScrollWheel(_) => None,PlatformInput::Pinch(_) => None,+ PlatformInput::LongPress(_) => None,PlatformInput::FileDrop(_) => None,PlatformInput::Touch(_) => None,}@@ -844,6 +848,7 @@ impl PlatformInput {PlatformInput::MouseExited(_) => "mouse_exited",PlatformInput::ScrollWheel(_) => "scroll_wheel",PlatformInput::Pinch(_) => "pinch",+ PlatformInput::LongPress(_) => "long_press",PlatformInput::FileDrop(_) => "file_drop",PlatformInput::Touch(_) => "touch",}diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rsindex 97cd9f99f53..63b11d95b5f 100644--- a/crates/gpui/src/window.rs+++ b/crates/gpui/src/window.rs@@ -1194,6 +1194,8 @@ pub struct Window {last_input_modality: InputModality,touch_gestures: TouchGestureRecognizer,touch_prediction_enabled: bool,+ long_press_timer: Option<Task<()>>,+ long_press_capture: Option<EntityId>,pub(crate) refreshing: bool,pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,pub(crate) focus: Option<FocusId>,@@ -1890,6 +1892,8 @@ impl Window {.map_or_else(GestureTuning::default, |gestures| gestures.tuning()),),touch_prediction_enabled: true,+ long_press_timer: None,+ long_press_capture: None,refreshing: false,activation_observers: SubscriberSet::new(),focus: None,@@ -2838,6 +2842,20 @@ impl Window {self.captured_hitbox}+ /// Captures the current long press for the given entity.+ ///+ /// The capture is released when the gesture ends or is cancelled, or when+ /// a replacement touch begins. A listener must also call+ /// [`Self::prevent_default`] on the started event to claim the gesture.+ pub fn capture_long_press<T: 'static>(&mut self, entity: &Entity<T>) {+ self.long_press_capture = Some(entity.entity_id());+ }++ /// Returns whether the given entity has captured the current long press.+ pub fn has_long_press_capture<T: 'static>(&self, entity: &Entity<T>) -> bool {+ self.long_press_capture == Some(entity.entity_id())+ }+/// The current state of the keyboard's modifierspub fn modifiers(&self) -> Modifiers {self.modifiers@@ -5153,6 +5171,17 @@ impl Window {}},PlatformInput::Touch(touch) => PlatformInput::Touch(touch),+ PlatformInput::LongPress(long_press) => {+ self.mouse_position = if long_press.phase == crate::TouchPhase::Started {+ long_press.start_position+ } else {+ long_press.position+ };+ if long_press.phase == crate::TouchPhase::Started {+ self.long_press_capture = None;+ }+ PlatformInput::LongPress(long_press)+ }PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,};@@ -5163,6 +5192,17 @@ impl Window {} else if let Some(touch_event) = event.touch_event() {self.dispatch_touch_event(touch_event, cx);}+ if let PlatformInput::LongPress(long_press) = &event {+ match long_press.phase {+ crate::TouchPhase::Started if !self.default_prevented => {+ self.long_press_capture = None;+ }+ crate::TouchPhase::Ended | crate::TouchPhase::Cancelled => {+ self.long_press_capture = None;+ }+ crate::TouchPhase::Started | crate::TouchPhase::Moved => {}+ }+ }// Must run after the move is dispatched: the platform owns the gesture afterwards, so this// is the last chance for drag listeners to see the pointer leave and reset their state.@@ -5234,11 +5274,21 @@ impl Window {event.predicted_position = None;}let recognized_gestures = self.touch_gestures.handle_event(&event);+ if event.phase == crate::TouchPhase::Started+ && self.touch_gestures.pending_long_press().is_some()+ {+ self.long_press_capture = None;+ }let mut tapped = false;for gesture in recognized_gestures {tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });self.dispatch_recognized_touch_gesture(gesture, cx);}+ if event.phase == crate::TouchPhase::Started {+ self.schedule_long_press_timer(cx);+ } else if self.touch_gestures.pending_long_press().is_none() {+ self.long_press_timer.take();+ }// The platform's touch-release handler may inspect the input handler// as soon as this dispatch returns (the web platform decides virtual// keyboard visibility there, inside the user gesture). Input handlers@@ -5266,9 +5316,51 @@ impl Window {cx.propagate_event = true;self.dispatch_mouse_event(&up, cx);}+ RecognizedTouchGesture::LongPress(long_press) => {+ self.mouse_position = if long_press.phase == crate::TouchPhase::Started {+ long_press.start_position+ } else {+ long_press.position+ };+ cx.propagate_event = true;+ self.default_prevented = false;+ let started = long_press.phase == crate::TouchPhase::Started;+ let ended = matches!(+ long_press.phase,+ crate::TouchPhase::Ended | crate::TouchPhase::Cancelled+ );+ self.dispatch_mouse_event(&long_press, cx);+ if started {+ let claimed = self.default_prevented;+ self.touch_gestures.resolve_long_press(claimed);+ if !claimed {+ self.long_press_capture = None;+ }+ }+ if ended {+ self.long_press_capture = None;+ }+ }}}+ fn schedule_long_press_timer(&mut self, cx: &mut App) {+ self.long_press_timer.take();+ let Some((touch_id, duration)) = self.touch_gestures.pending_long_press() else {+ return;+ };+ self.long_press_timer = Some(self.spawn(cx, async move |cx| {+ cx.background_executor.timer(duration).await;+ cx.update(move |window, cx| {+ window.long_press_timer.take();+ if let Some(gesture) = window.touch_gestures.offer_long_press(touch_id) {+ window.dispatch_recognized_touch_gesture(gesture, cx);+ }+ })+ .log_err();+ }));+ }+fn schedule_touch_momentum_tick(&mut self) {self.on_next_frame(|window, cx| {if let Some(gesture) = window.touch_gestures.tick_momentum() {@@ -7011,15 +7103,16 @@ mod tests {cell::{Cell, RefCell},path::PathBuf,rc::Rc,+ time::Duration,};use crate::{- AnyWindowHandle, AppContext as _, Bounds, Context, DragMoveEvent, Empty,+ AnyWindowHandle, AppContext as _, Bounds, Context, DispatchPhase, DragMoveEvent, Empty,ExternalDragPayload, ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle,- InputEvent as _, InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent,- MouseMoveEvent, ParentElement, Pixels, Point, Render, RequestFrameOptions,- StatefulInteractiveElement as _, Styled, TestAppContext, Window, WindowAppearance,- WindowOptions, canvas, div, point, px, size,+ InputEvent as _, InteractiveElement as _, IntoElement, LongPressEvent, MouseButton,+ MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, Point, Render, RequestFrameOptions,+ StatefulInteractiveElement as _, Styled, TestAppContext, TouchEvent, TouchId, TouchPhase,+ Window, WindowAppearance, WindowOptions, canvas, div, point, px, size,};struct EmptyView;@@ -7721,4 +7814,183 @@ mod tests {.unwrap();assert_eq!(b_focus_count.get(), 1);}++ #[gpui::test]+ fn long_press_is_claimed_only_when_started_prevents_default(cx: &mut TestAppContext) {+ for response in [+ LongPressResponse::PreventDefault,+ LongPressResponse::StopPropagation,+ LongPressResponse::None,+ ] {+ let phases = Rc::new(RefCell::new(Vec::new()));+ let window = cx.add_window({+ let phases = phases.clone();+ move |_, _| LongPressListener { phases, response }+ });+ dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);+ cx.executor().advance_clock(Duration::from_millis(501));+ cx.executor().run_until_parked();+ window+ .update(cx, |_, window, _| {+ assert_eq!(+ window.long_press_capture.is_some(),+ response == LongPressResponse::PreventDefault+ );+ })+ .unwrap();+ dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);+ dispatch_touch(window, cx, TouchId(1), TouchPhase::Ended, 2.);+ window+ .update(cx, |_, window, _| {+ assert!(window.long_press_capture.is_none());+ })+ .unwrap();++ let phases = phases.borrow();+ if response == LongPressResponse::PreventDefault {+ assert_eq!(+ phases.as_slice(),+ [TouchPhase::Started, TouchPhase::Moved, TouchPhase::Ended]+ );+ } else {+ assert_eq!(phases.as_slice(), [TouchPhase::Started]);+ }+ }+ }++ #[gpui::test]+ fn stale_default_prevention_does_not_claim_long_press(cx: &mut TestAppContext) {+ let phases = Rc::new(RefCell::new(Vec::new()));+ let window = cx.add_window({+ let phases = phases.clone();+ move |_, _| LongPressListener {+ phases,+ response: LongPressResponse::None,+ }+ });+ window+ .update(cx, |_, window, _| {+ window.prevent_default();+ })+ .unwrap();++ dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);+ cx.executor().advance_clock(Duration::from_millis(501));+ cx.executor().run_until_parked();+ dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);++ assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);+ }++ #[gpui::test]+ fn resolved_touch_cancels_scheduled_long_press(cx: &mut TestAppContext) {+ for (phase, position) in [+ (TouchPhase::Ended, 0.),+ (TouchPhase::Cancelled, 0.),+ (TouchPhase::Moved, 20.),+ ] {+ let phases = Rc::new(RefCell::new(Vec::new()));+ let window = cx.add_window({+ let phases = phases.clone();+ move |_, _| LongPressListener {+ phases,+ response: LongPressResponse::PreventDefault,+ }+ });+ dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);+ dispatch_touch(window, cx, TouchId(1), phase, position);+ cx.executor().advance_clock(Duration::from_millis(501));+ cx.executor().run_until_parked();++ assert!(phases.borrow().is_empty(), "{phase:?} allowed long press");+ }+ }++ #[gpui::test]+ fn stale_long_press_timer_cannot_affect_replacement_touch(cx: &mut TestAppContext) {+ let phases = Rc::new(RefCell::new(Vec::new()));+ let window = cx.add_window({+ let phases = phases.clone();+ move |_, _| LongPressListener {+ phases,+ response: LongPressResponse::PreventDefault,+ }+ });+ let first_touch = TouchId(1);+ dispatch_touch(window, cx, first_touch, TouchPhase::Started, 0.);+ cx.executor().advance_clock(Duration::from_millis(250));+ dispatch_touch(window, cx, first_touch, TouchPhase::Cancelled, 0.);+ dispatch_touch(window, cx, TouchId(2), TouchPhase::Started, 10.);++ cx.executor().advance_clock(Duration::from_millis(251));+ cx.executor().run_until_parked();+ assert!(phases.borrow().is_empty());++ cx.executor().advance_clock(Duration::from_millis(250));+ cx.executor().run_until_parked();+ assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);+ }++ #[derive(Clone, Copy, PartialEq)]+ enum LongPressResponse {+ PreventDefault,+ StopPropagation,+ None,+ }++ struct LongPressListener {+ phases: Rc<RefCell<Vec<TouchPhase>>>,+ response: LongPressResponse,+ }++ impl Render for LongPressListener {+ fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let entity = cx.entity();+ let phases = self.phases.clone();+ let response = self.response;+ canvas(+ |_, _, _| {},+ move |_, _, window, _| {+ window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {+ if phase != DispatchPhase::Bubble {+ return;+ }+ phases.borrow_mut().push(event.phase);+ match response {+ LongPressResponse::PreventDefault => {+ window.capture_long_press(&entity);+ window.prevent_default();+ }+ LongPressResponse::StopPropagation => cx.stop_propagation(),+ LongPressResponse::None => {}+ }+ });+ },+ )+ }+ }++ fn dispatch_touch(+ window: crate::WindowHandle<LongPressListener>,+ cx: &mut TestAppContext,+ id: TouchId,+ phase: TouchPhase,+ x: f32,+ ) {+ window+ .update(cx, |_, window, cx| {+ window.dispatch_event(+ TouchEvent {+ id,+ phase,+ position: point(px(x), px(0.)),+ predicted_position: None,+ force: None,+ }+ .to_platform_input(),+ cx,+ );+ })+ .unwrap();+ }}diff --git a/crates/gpui_web/src/events.rs b/crates/gpui_web/src/events.rsindex 886803cc8dd..7afedeb4e8e 100644--- a/crates/gpui_web/src/events.rs+++ b/crates/gpui_web/src/events.rs@@ -1,4 +1,4 @@-use std::rc::Rc;+use std::{collections::HashMap, rc::Rc};use gpui::{Capslock, ClipboardEntry, ClipboardItem, ClipboardString, DispatchEventResult, GestureTuning,@@ -91,6 +91,30 @@ pub(crate) struct ClickState {current_count: usize,}+#[derive(Default)]+pub(crate) struct TouchIds {+ next: u64,+ active: HashMap<i32, TouchId>,+}++impl TouchIds {+ fn start(&mut self, pointer_id: i32) -> Option<TouchId> {+ let next = self.next.checked_add(1)?;+ let touch_id = TouchId(self.next);+ self.next = next;+ self.active.insert(pointer_id, touch_id);+ Some(touch_id)+ }++ fn active(&self, pointer_id: i32) -> Option<TouchId> {+ self.active.get(&pointer_id).copied()+ }++ fn end(&mut self, pointer_id: i32) -> Option<TouchId> {+ self.active.remove(&pointer_id)+ }+}+impl Default for ClickState {fn default() -> Self {Self {@@ -209,13 +233,17 @@ impl WebWindowInner {this.canvas.set_pointer_capture(event.pointer_id()).ok();if pointer_type == "touch" {+ let Some(touch_id) = this.touch_ids.borrow_mut().start(event.pointer_id()) else {+ log::error!("exhausted touch identifiers");+ return;+ };this.state.borrow_mut().mouse_position = position;if this.touch_tap_candidate.get().is_none() {this.touch_tap_candidate.set(Some((event.pointer_id(), position)));}this.dispatch_input(PlatformInput::Touch(TouchEvent {- id: TouchId(event.pointer_id() as u64),+ id: touch_id,phase: TouchPhase::Started,position,predicted_position: None,@@ -278,6 +306,9 @@ impl WebWindowInner {let position = pointer_position_in_element(&event);if event.pointer_type() == "touch" {+ let Some(touch_id) = this.touch_ids.borrow_mut().end(event.pointer_id()) else {+ return;+ };this.state.borrow_mut().mouse_position = position;let completes_tap = match this.touch_tap_candidate.get() {Some((pointer_id, _)) if pointer_id == event.pointer_id() => {@@ -291,7 +322,7 @@ impl WebWindowInner {// call, so the text-input check below sees the state the tap// produced.let dispatch_result = this.dispatch_input(PlatformInput::Touch(TouchEvent {- id: TouchId(event.pointer_id() as u64),+ id: touch_id,phase: TouchPhase::Ended,position,predicted_position: None,@@ -400,13 +431,16 @@ impl WebWindowInner {self.listen("pointercancel", move |event: JsValue| {let event: web_sys::PointerEvent = event.unchecked_into();if event.pointer_type() == "touch" {+ let Some(touch_id) = this.touch_ids.borrow_mut().end(event.pointer_id()) else {+ return;+ };if let Some((pointer_id, _)) = this.touch_tap_candidate.get()&& pointer_id == event.pointer_id(){this.touch_tap_candidate.set(None);}this.dispatch_input(PlatformInput::Touch(TouchEvent {- id: TouchId(event.pointer_id() as u64),+ id: touch_id,phase: TouchPhase::Cancelled,position: pointer_position_in_element(&event),predicted_position: None,@@ -521,6 +555,9 @@ impl WebWindowInner {let position = pointer_position_in_element(&event);if event.pointer_type() == "touch" {+ let Some(touch_id) = this.touch_ids.borrow().active(event.pointer_id()) else {+ return;+ };this.state.borrow_mut().mouse_position = position;// Mirror the slop rule of gpui's tap recognizer: once the// touch travels beyond it, its release must not affect the@@ -536,7 +573,7 @@ impl WebWindowInner {this.touch_tap_candidate.set(None);}this.dispatch_input(PlatformInput::Touch(TouchEvent {- id: TouchId(event.pointer_id() as u64),+ id: touch_id,phase: TouchPhase::Moved,position,predicted_position: predicted_pointer_position(&event, position),@@ -1392,6 +1429,22 @@ fn mouse_position_in_element(event: &web_sys::MouseEvent) -> Point<Pixels> {mod tests {use super::*;+ #[test]+ fn browser_pointer_id_reuse_gets_a_new_touch_id() {+ let mut touch_ids = TouchIds::default();+ let first = touch_ids.start(7).expect("first touch id");+ let concurrent = touch_ids.start(8).expect("concurrent touch id");++ assert_ne!(first, concurrent);+ assert_eq!(touch_ids.active(7), Some(first));+ assert_eq!(touch_ids.end(7), Some(first));+ assert_eq!(touch_ids.active(7), None);++ let reused = touch_ids.start(7).expect("reused pointer touch id");+ assert_ne!(reused, first);+ assert_ne!(reused, concurrent);+ }+#[test]fn handled_tap_preserves_unchanged_text_input() {assert!(should_preserve_focused_input(diff --git a/crates/gpui_web/src/window.rs b/crates/gpui_web/src/window.rsindex 08c43bae9c7..799c3fadcff 100644--- a/crates/gpui_web/src/window.rs+++ b/crates/gpui_web/src/window.rs@@ -1,5 +1,7 @@use crate::display::WebDisplay;-use crate::events::{ClickState, EventListenerHandle, WebEventListeners, is_mac_platform};+use crate::events::{+ ClickState, EventListenerHandle, TouchIds, WebEventListeners, is_mac_platform,+};use crate::ime_mirror::ImeMirror;use crate::platform::WebWindowLifecycle;use std::sync::Arc;@@ -53,6 +55,7 @@ pub(crate) struct WebWindowInner {pub(crate) state: RefCell<WebWindowMutableState>,pub(crate) callbacks: RefCell<WebWindowCallbacks>,pub(crate) click_state: RefCell<ClickState>,+ pub(crate) touch_ids: RefCell<TouchIds>,pub(crate) pressed_button: Cell<Option<MouseButton>>,pub(crate) last_physical_size: Cell<(u32, u32)>,pub(crate) notify_scale: Cell<bool>,@@ -196,6 +199,7 @@ impl WebWindow {state: RefCell::new(mutable_state),callbacks: RefCell::new(WebWindowCallbacks::default()),click_state: RefCell::new(ClickState::default()),+ touch_ids: RefCell::new(TouchIds::default()),pressed_button: Cell::new(None),last_physical_size: Cell::new((0, 0)),notify_scale: Cell::new(false),