Skip to main content

gpui_deck/input/base/
touch.rs

1// Modified for GPUI Deck: remove coupling to excluded window-wide rich-text selection.
2//! Touch selection for the input engine: long press, grab handles, edit menu.
3//!
4//! A long press selects the word under the finger and keeps following the
5//! finger while it stays down, like the double-click-and-drag it stands in
6//! for. Releasing opens the edit menu; from then on the selection carries a
7//! handle at each end which the styled layer draws and which drags through
8//! [`InputBaseState::begin_edge_drag`].
9//!
10//! The touch selection remembers the range it made. As soon as the selection
11//! is something else — the caret moved, text was typed, another cursor was
12//! added — the handles and the menu are gone, without anyone having to hide
13//! them. Only the touch gesture and the menu's own actions move the range and
14//! carry the touch selection along.
15
16use gpui::{Context, LongPressEvent, Pixels, Point, TouchPhase, Window, point};
17
18use super::{InputBaseState, InputModeKind};
19use crate::touch_selection::{
20    EdgeDrag, SelectionEdge, TouchSelectionSnapshot, caret_in_view, caret_line_box,
21};
22
23/// The selection a touch gesture made, and what it is doing now.
24#[derive(Debug, Default)]
25pub(super) struct TouchSelection {
26    /// The range the gesture left; `None` when no touch selection is live.
27    range: Option<(usize, usize)>,
28    menu_open: bool,
29    drag: Option<EdgeDrag>,
30}
31
32impl<M: InputModeKind> InputBaseState<M> {
33    /// The live touch selection, laid out for the handles and the edit menu.
34    ///
35    /// `None` when the last touch selection has since changed into something
36    /// else, or when its ends are not laid out (scrolled out of view).
37    pub fn touch_selection(&self) -> Option<TouchSelectionSnapshot> {
38        let range = self.touch_selection.range?;
39        let selection = self.active_selection();
40        if (selection.start, selection.end) != range {
41            return None;
42        }
43
44        let layout = self.last_layout.as_ref()?;
45        let line_height = layout.line_height;
46        let laid_out = layout.visible_range_offset.clone();
47        let origin = self.last_bounds?.origin;
48        let viewport = self.input_bounds;
49        // An end scrolled out of the input gets no handle. Its line may not
50        // even be laid out; it then stands just outside the viewport on its
51        // side, which is all the other end's drag needs to know about it.
52        let caret_box = |offset: usize, stand_in_y: Pixels| {
53            let (_, _, position) = self.line_and_position_for_offset(offset);
54            match position.filter(|_| laid_out.contains(&offset) || laid_out.end == offset) {
55                Some(position) => caret_line_box(origin + position, line_height),
56                None => caret_line_box(point(viewport.left(), stand_in_y), line_height),
57            }
58        };
59        let start = caret_box(range.0, viewport.top() - line_height);
60        let end = caret_box(range.1, viewport.bottom());
61        Some(
62            TouchSelectionSnapshot::new(start, end)
63                .with_edge_visible(SelectionEdge::Start, caret_in_view(start, viewport))
64                .with_edge_visible(SelectionEdge::End, caret_in_view(end, viewport))
65                .with_menu_open(self.touch_selection.menu_open)
66                .with_dragging(self.touch_selection.drag.map(|drag| drag.edge())),
67        )
68    }
69
70    /// Records the current selection as the one the touch gesture made.
71    fn retain_touch_selection(&mut self) {
72        let selection = self.active_selection();
73        self.touch_selection.range = Some((selection.start, selection.end));
74    }
75
76    /// Keeps the current selection as a touch selection, with the menu open
77    /// over it: what a double tap's word selection asks for.
78    pub(super) fn keep_touch_selection(&mut self, cx: &mut Context<Self>) {
79        self.retain_touch_selection();
80        self.touch_selection.menu_open = true;
81        self.touch_selection.drag = None;
82        cx.notify();
83    }
84
85    /// Drops the handles and the edit menu. Called where the selection is
86    /// about to be moved by something other than the gesture.
87    pub(super) fn dismiss_touch_selection(&mut self, cx: &mut Context<Self>) {
88        if self.touch_selection.range.is_none() {
89            return;
90        }
91        self.touch_selection = TouchSelection::default();
92        cx.notify();
93    }
94
95    /// Closes the edit menu and keeps the selection with its handles.
96    ///
97    /// The menu's own actions end here: Copy has done its work, Select All
98    /// reopens the menu over the new range through [`Self::select_all`].
99    pub fn close_edit_menu(&mut self, cx: &mut Context<Self>) {
100        if !self.touch_selection.menu_open {
101            return;
102        }
103        self.touch_selection.menu_open = false;
104        cx.notify();
105    }
106
107    /// Reopens the edit menu when `position` is on the touch selection, the
108    /// way a tap on selected text asks for it. Returns whether it did.
109    pub(super) fn reopen_edit_menu_at(
110        &mut self,
111        position: Point<Pixels>,
112        cx: &mut Context<Self>,
113    ) -> bool {
114        let Some(snapshot) = self.touch_selection() else {
115            return false;
116        };
117        if snapshot.is_empty() {
118            return false;
119        }
120        let (offset, _, _) = self.resolve_mouse_position(position);
121        let selection = self.active_selection();
122        if offset <= selection.start || offset >= selection.end {
123            return false;
124        }
125        self.touch_selection.menu_open = true;
126        cx.notify();
127        true
128    }
129
130    /// Steps the menu aside while the content scrolls under a finger, and
131    /// brings it back over the handles once the finger lifts.
132    pub(super) fn edit_menu_on_scroll(&mut self, phase: TouchPhase, cx: &mut Context<Self>) {
133        if self.touch_selection.range.is_none() {
134            return;
135        }
136        match phase {
137            TouchPhase::Ended | TouchPhase::Cancelled => {
138                if !self.touch_selection.menu_open {
139                    self.touch_selection.menu_open = true;
140                    cx.notify();
141                }
142            }
143            _ => self.close_edit_menu(cx),
144        }
145    }
146
147    /// Selects everything and, when a touch selection is live, keeps the
148    /// handles and the edit menu over the new range.
149    pub fn select_all_from_edit_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
150        let touch = self.touch_selection.range.is_some();
151        self.select_all(window, cx);
152        if touch {
153            self.retain_touch_selection();
154            self.touch_selection.menu_open = true;
155            cx.notify();
156        }
157    }
158
159    /// Handles one phase of a long press inside the input.
160    ///
161    /// Returns whether the started phase was claimed; the caller then captures
162    /// the gesture so the moves keep coming even after the finger leaves the
163    /// input.
164    pub(super) fn on_long_press(
165        &mut self,
166        event: &LongPressEvent,
167        window: &mut Window,
168        cx: &mut Context<Self>,
169    ) -> bool {
170        match event.phase {
171            TouchPhase::Started => {
172                if self.disabled {
173                    return false;
174                }
175                if !self.focus_handle.is_focused(window) {
176                    window.focus(&self.focus_handle, cx);
177                }
178                self.undo_manager.break_transaction_coalescing();
179                M::clear_inline_completion(self, cx);
180                self.touch_selection = TouchSelection::default();
181
182                let (offset, line_end_affinity, _) =
183                    self.resolve_mouse_position(event.start_position);
184                self.selections.remove_all_but_active();
185                self.set_cursor_to(offset);
186                self.select_word(offset, window, cx);
187                let pressed_word = !self.active_selection().is_empty()
188                    && !self.selected_text().chars().all(char::is_whitespace);
189                if !pressed_word {
190                    // Whitespace or an empty field: the press places the caret,
191                    // and the menu offers Paste and Select All.
192                    self.move_to_with_affinity(offset, None, line_end_affinity, cx);
193                    self.selected_word_range = None;
194                }
195                self.selecting = true;
196                self.retain_touch_selection();
197                cx.notify();
198                true
199            }
200            TouchPhase::Moved => {
201                let (offset, line_end_affinity, _) = self.resolve_mouse_position(event.position);
202                if self.selected_word_range.is_some() {
203                    // The press took a word; the sweep grows it a word at a time.
204                    self.select_to_with_affinity(offset, line_end_affinity, cx);
205                } else {
206                    // The press placed the caret; the sweep carries it.
207                    self.move_to_with_affinity(offset, None, line_end_affinity, cx);
208                }
209                self.retain_touch_selection();
210                true
211            }
212            TouchPhase::Ended | TouchPhase::Cancelled => {
213                self.selecting = false;
214                self.selected_word_range = None;
215                if self.touch_selection.range.is_some() {
216                    self.touch_selection.menu_open = true;
217                }
218                cx.notify();
219                true
220            }
221        }
222    }
223
224    /// Starts dragging one end of the touch selection from `finger`.
225    ///
226    /// The other end stays where it is. The menu closes for the duration of the
227    /// drag and reopens on [`Self::end_edge_drag`].
228    pub fn begin_edge_drag(
229        &mut self,
230        edge: SelectionEdge,
231        finger: Point<Pixels>,
232        cx: &mut Context<Self>,
233    ) {
234        let Some(snapshot) = self.touch_selection() else {
235            return;
236        };
237        self.undo_manager.break_transaction_coalescing();
238        self.selected_word_range = None;
239        self.active_selection_mut().reversed = edge == SelectionEdge::Start;
240        self.touch_selection.drag = Some(EdgeDrag::begin(edge, snapshot.edge(edge), finger));
241        self.touch_selection.menu_open = false;
242        cx.notify();
243    }
244
245    /// Moves the dragged end to the text under `finger`.
246    ///
247    /// Past the top or bottom of a multi-line input the content scrolls under
248    /// the finger, so the end can reach text that was out of view.
249    pub fn update_edge_drag(&mut self, finger: Point<Pixels>, cx: &mut Context<Self>) {
250        let Some(drag) = self.touch_selection.drag else {
251            return;
252        };
253        let position = drag.text_position(finger);
254        self.extend_edge_drag_to(position, cx);
255
256        if self.is_single_line() {
257            return;
258        }
259        self.auto_scroll.last_drag_position = Some(position);
260        let delta = crate::AutoScroll::compute_delta(position.y, self.input_bounds);
261        // Input's ScrollHandle uses negative-y-is-down; negate the positive-towards-bottom delta.
262        let scroll_delta = delta.map(|delta| -delta);
263        self.auto_scroll.set(scroll_delta, cx, |delta, state, cx| {
264            let current = state.scroll_handle.offset();
265            state.update_scroll_offset(Some(point(current.x, current.y + delta)), cx);
266            if let Some(position) = state.auto_scroll.last_drag_position {
267                state.extend_edge_drag_to(position, cx);
268            }
269        });
270    }
271
272    fn extend_edge_drag_to(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
273        if self.touch_selection.drag.is_none() {
274            return;
275        }
276        let (offset, line_end_affinity, _) = self.resolve_mouse_position(position);
277        let before = *self.active_selection();
278        self.select_to_with_affinity(offset, line_end_affinity, cx);
279        // A handle never collapses the selection: at the other end it stops,
280        // and the finger has to pass that end to swap the two.
281        if self.active_selection().is_empty() {
282            *self.active_selection_mut() = before;
283            return;
284        }
285        // Dragging one end past the other swaps them: the selection now runs
286        // the other way and the finger holds what became the other handle.
287        let edge = if self.active_selection().reversed {
288            SelectionEdge::Start
289        } else {
290            SelectionEdge::End
291        };
292        if let Some(drag) = self.touch_selection.drag.as_mut() {
293            drag.set_edge(edge);
294        }
295        self.retain_touch_selection();
296        cx.notify();
297    }
298
299    /// Ends the handle drag and reopens the edit menu.
300    pub fn end_edge_drag(&mut self, cx: &mut Context<Self>) {
301        if self.touch_selection.drag.take().is_none() {
302            return;
303        }
304        self.auto_scroll.stop();
305        if self.active_selection().is_empty() {
306            self.active_selection_mut().reversed = false;
307        }
308        self.touch_selection.menu_open = true;
309        cx.notify();
310    }
311
312    #[cfg(test)]
313    pub(super) fn is_edit_menu_open(&self) -> bool {
314        self.touch_selection.menu_open
315    }
316
317    #[cfg(test)]
318    pub(super) fn touch_selection_range(&self) -> Option<std::ops::Range<usize>> {
319        self.touch_selection.range.map(|(start, end)| start..end)
320    }
321}
322
323#[cfg(test)]
324mod tests {
325    use gpui::{
326        AppContext as _, Context, Entity, IntoElement, LongPressEvent, MouseButton,
327        ParentElement as _, Render, Styled as _, TestAppContext, TouchPhase, VisualTestContext,
328        Window, div, point, px,
329    };
330
331    use crate::input::{InputState, TextareaState};
332    use crate::touch_selection::SelectionEdge;
333
334    struct TouchRoot(Entity<InputState>);
335
336    impl Render for TouchRoot {
337        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
338            div().size_full().child(self.0.clone())
339        }
340    }
341
342    struct TextareaRoot(Entity<TextareaState>);
343
344    impl Render for TextareaRoot {
345        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
346            // Short enough that forty lines scroll.
347            div().w(px(300.)).h(px(80.)).child(self.0.clone())
348        }
349    }
350
351    fn open_input<'a>(
352        cx: &'a mut TestAppContext,
353        value: &str,
354    ) -> (Entity<InputState>, &'a mut VisualTestContext) {
355        cx.update(crate::init);
356        let value = value.to_string();
357        let (root, cx) = cx.add_window_view(move |window, cx| {
358            let input = cx.new(|cx| {
359                let mut state = InputState::new(window, cx);
360                state.set_value(value, window, cx);
361                state
362            });
363            TouchRoot(input)
364        });
365        let input = root.read_with(cx, |root, _| root.0.clone());
366        cx.run_until_parked();
367        cx.update(|window, cx| {
368            let _ = window.draw(cx);
369        });
370        (input, cx)
371    }
372
373    fn long_press(
374        cx: &mut VisualTestContext,
375        phase: TouchPhase,
376        start: (f32, f32),
377        at: (f32, f32),
378    ) {
379        cx.simulate_event(LongPressEvent {
380            phase,
381            start_position: point(px(start.0), px(start.1)),
382            position: point(px(at.0), px(at.1)),
383        });
384        cx.update(|window, cx| {
385            let _ = window.draw(cx);
386        });
387    }
388
389    /// The window position of the caret before `offset`, in the input's line.
390    fn caret_at(input: &Entity<InputState>, cx: &VisualTestContext, offset: usize) -> (f32, f32) {
391        input.read_with(cx, |state, _| {
392            let (_, _, position) = state.line_and_position_for_offset(offset);
393            let position = state.last_bounds.unwrap().origin + position.unwrap();
394            let line_height = state.last_layout.as_ref().unwrap().line_height;
395            (position.x.into(), (position.y + line_height * 0.5).into())
396        })
397    }
398
399    #[gpui::test]
400    fn long_press_selects_word_then_release_opens_menu(cx: &mut TestAppContext) {
401        let (input, cx) = open_input(cx, "quick select value");
402        let start = caret_at(&input, cx, 8);
403        long_press(cx, TouchPhase::Started, start, start);
404        input.read_with(cx, |state, _| {
405            assert_eq!(state.selected_text().to_string(), "select");
406            assert!(!state.is_edit_menu_open());
407            let snapshot = state.touch_selection().expect("touch selection is live");
408            assert!(!snapshot.is_empty());
409            assert!(!snapshot.is_menu_open());
410        });
411
412        let end = caret_at(&input, cx, 18);
413        long_press(cx, TouchPhase::Moved, start, end);
414        input.read_with(cx, |state, _| {
415            assert_eq!(state.selected_text().to_string(), "select value");
416        });
417
418        long_press(cx, TouchPhase::Ended, start, end);
419        input.read_with(cx, |state, _| {
420            assert_eq!(state.selected_text().to_string(), "select value");
421            assert!(state.is_edit_menu_open());
422            let snapshot = state.touch_selection().expect("touch selection is live");
423            assert!(snapshot.is_menu_open());
424            assert!(snapshot.start().left() < snapshot.end().left());
425        });
426    }
427
428    #[gpui::test]
429    fn double_tap_selects_word_with_handles_and_menu(cx: &mut TestAppContext) {
430        let (input, cx) = open_input(cx, "quick select value");
431        let at = caret_at(&input, cx, 8);
432        let position = point(px(at.0), px(at.1));
433        // A tap arrives as mouse events; the touch that began it is what
434        // tells the input they came from a finger.
435        cx.update(|_, cx| crate::GlobalState::note_touch(cx));
436        for click_count in [1, 2] {
437            cx.simulate_event(gpui::MouseDownEvent {
438                position,
439                button: MouseButton::Left,
440                modifiers: Default::default(),
441                click_count,
442                first_mouse: false,
443            });
444            cx.simulate_event(gpui::MouseUpEvent {
445                position,
446                button: MouseButton::Left,
447                modifiers: Default::default(),
448                click_count,
449            });
450        }
451        cx.update(|window, cx| {
452            let _ = window.draw(cx);
453        });
454        input.read_with(cx, |state, _| {
455            assert_eq!(state.selected_text().to_string(), "select");
456            let snapshot = state
457                .touch_selection()
458                .expect("a double tap is a touch selection");
459            assert!(snapshot.is_menu_open());
460        });
461    }
462
463    #[gpui::test]
464    fn long_press_on_empty_input_places_caret_with_menu(cx: &mut TestAppContext) {
465        let (input, cx) = open_input(cx, "");
466        let caret = caret_at(&input, cx, 0);
467        long_press(cx, TouchPhase::Started, caret, caret);
468        long_press(cx, TouchPhase::Ended, caret, caret);
469        input.read_with(cx, |state, _| {
470            assert_eq!(state.selected_range(), 0..0);
471            let snapshot = state.touch_selection().expect("caret still gets a menu");
472            assert!(snapshot.is_empty());
473            assert!(snapshot.is_menu_open());
474        });
475    }
476
477    #[gpui::test]
478    fn dragging_a_handle_moves_that_end_only(cx: &mut TestAppContext) {
479        let (input, cx) = open_input(cx, "quick select value");
480        let start = caret_at(&input, cx, 8);
481        long_press(cx, TouchPhase::Started, start, start);
482        long_press(cx, TouchPhase::Ended, start, start);
483
484        // The finger holds the end knob, which hangs below the line.
485        let end_caret = caret_at(&input, cx, 12);
486        let finger = (end_caret.0, end_caret.1 + 20.);
487        cx.update(|_, cx| {
488            input.update(cx, |state, cx| {
489                state.begin_edge_drag(SelectionEdge::End, point(px(finger.0), px(finger.1)), cx);
490            });
491        });
492        input.read_with(cx, |state, _| {
493            let snapshot = state.touch_selection().unwrap();
494            assert_eq!(snapshot.dragging(), Some(SelectionEdge::End));
495            assert!(!snapshot.is_menu_open());
496        });
497
498        let target = caret_at(&input, cx, 18);
499        cx.update(|_, cx| {
500            input.update(cx, |state, cx| {
501                state.update_edge_drag(point(px(target.0), px(target.1 + 20.)), cx);
502            });
503        });
504        input.read_with(cx, |state, _| {
505            assert_eq!(state.selected_text().to_string(), "select value");
506        });
507
508        // Pull the start handle past the end: the ends swap, the finger keeps
509        // its handle.
510        cx.update(|_, cx| {
511            input.update(cx, |state, cx| {
512                state.end_edge_drag(cx);
513                assert!(state.is_edit_menu_open());
514                let start_caret = state.touch_selection().unwrap().start();
515                state.begin_edge_drag(SelectionEdge::Start, start_caret.origin, cx);
516            });
517        });
518        let target = caret_at(&input, cx, 0);
519        cx.update(|_, cx| {
520            input.update(cx, |state, cx| {
521                state.update_edge_drag(point(px(target.0), px(target.1)), cx);
522            });
523        });
524        input.read_with(cx, |state, _| {
525            assert_eq!(state.selected_text().to_string(), "quick select value");
526            assert_eq!(state.touch_selection_range(), Some(0..18));
527        });
528    }
529
530    #[gpui::test]
531    fn dragging_one_handle_past_the_other_swaps_them(cx: &mut TestAppContext) {
532        let (input, cx) = open_input(cx, "quick select value");
533        let start = caret_at(&input, cx, 8);
534        long_press(cx, TouchPhase::Started, start, start);
535        long_press(cx, TouchPhase::Ended, start, start);
536        input.read_with(cx, |state, _| {
537            assert_eq!(state.selected_text().to_string(), "select");
538        });
539
540        // Take the start handle and pull it past the end of "select" to the
541        // end of the text: the finger now holds the end handle, and the
542        // selection runs from the old end forward.
543        let start_caret = caret_at(&input, cx, 6);
544        cx.update(|_, cx| {
545            input.update(cx, |state, cx| {
546                state.begin_edge_drag(
547                    SelectionEdge::Start,
548                    point(px(start_caret.0), px(start_caret.1)),
549                    cx,
550                );
551            });
552        });
553        let target = caret_at(&input, cx, 18);
554        cx.update(|_, cx| {
555            input.update(cx, |state, cx| {
556                state.update_edge_drag(point(px(target.0), px(target.1)), cx);
557            });
558        });
559        input.read_with(cx, |state, _| {
560            assert_eq!(state.selected_text().to_string(), " value");
561            assert_eq!(
562                state.touch_selection().unwrap().dragging(),
563                Some(SelectionEdge::End)
564            );
565        });
566
567        // And back across again: it is the start handle once more.
568        let target = caret_at(&input, cx, 0);
569        cx.update(|_, cx| {
570            input.update(cx, |state, cx| {
571                state.update_edge_drag(point(px(target.0), px(target.1)), cx);
572                state.end_edge_drag(cx);
573            });
574        });
575        input.read_with(cx, |state, _| {
576            assert_eq!(state.selected_text().to_string(), "quick select");
577            assert!(state.is_edit_menu_open());
578        });
579    }
580
581    #[gpui::test]
582    fn touch_selection_goes_away_when_something_else_moves_the_selection(cx: &mut TestAppContext) {
583        let (input, cx) = open_input(cx, "quick select value");
584        let start = caret_at(&input, cx, 2);
585        long_press(cx, TouchPhase::Started, start, start);
586        long_press(cx, TouchPhase::Ended, start, start);
587        input.read_with(cx, |state, _| assert!(state.touch_selection().is_some()));
588
589        // Select All from the menu keeps it, over the new range.
590        cx.update(|window, cx| {
591            input.update(cx, |state, cx| state.select_all_from_edit_menu(window, cx));
592        });
593        input.read_with(cx, |state, _| {
594            assert_eq!(state.selected_range(), 0..18);
595            assert!(state.touch_selection().is_some());
596            assert!(state.is_edit_menu_open());
597        });
598
599        // Copy closes the menu but keeps the handles.
600        cx.update(|_, cx| input.update(cx, |state, cx| state.close_edit_menu(cx)));
601        input.read_with(cx, |state, _| {
602            let snapshot = state.touch_selection().unwrap();
603            assert!(!snapshot.is_menu_open());
604        });
605
606        // Typing replaces the selection; nothing is left to hold a handle.
607        cx.update(|window, cx| {
608            input.update(cx, |state, cx| {
609                state.replace_text_in_range_silent(None, "x", window, cx);
610            });
611        });
612        input.read_with(cx, |state, _| assert!(state.touch_selection().is_none()));
613
614        // A press elsewhere drops it too.
615        long_press(cx, TouchPhase::Started, start, start);
616        long_press(cx, TouchPhase::Ended, start, start);
617        input.read_with(cx, |state, _| assert!(state.touch_selection().is_some()));
618        let elsewhere = caret_at(&input, cx, 0);
619        cx.simulate_mouse_down(
620            point(px(elsewhere.0), px(elsewhere.1)),
621            MouseButton::Left,
622            Default::default(),
623        );
624        input.read_with(cx, |state, _| assert!(state.touch_selection().is_none()));
625    }
626
627    #[gpui::test]
628    fn scrolling_closes_the_menu_and_keeps_the_handles(cx: &mut TestAppContext) {
629        cx.update(crate::init);
630        let (root, cx) = cx.add_window_view(|window, cx| {
631            let textarea = cx.new(|cx| {
632                let mut state = TextareaState::new(window, cx);
633                let text = (0..40).map(|ix| format!("line {ix}")).collect::<Vec<_>>();
634                state.set_value(text.join("\n"), window, cx);
635                state
636            });
637            TextareaRoot(textarea)
638        });
639        let textarea = root.read_with(cx, |root, _| root.0.clone());
640        cx.run_until_parked();
641        cx.update(|window, cx| {
642            let _ = window.draw(cx);
643        });
644        let start = textarea.read_with(cx, |state, _| {
645            let (_, _, position) = state.line_and_position_for_offset(2);
646            let position = state.last_bounds.unwrap().origin + position.unwrap();
647            (f32::from(position.x), f32::from(position.y) + 4.)
648        });
649        long_press(cx, TouchPhase::Started, start, start);
650        long_press(cx, TouchPhase::Ended, start, start);
651        textarea.read_with(cx, |state, _| {
652            assert_eq!(state.selected_text().to_string(), "line");
653            assert!(state.touch_selection().unwrap().is_menu_open());
654        });
655
656        cx.update(|_, cx| {
657            textarea.update(cx, |state, cx| {
658                state.set_scroll_offset(point(px(0.), px(-8.)), cx);
659                state.close_edit_menu(cx);
660            });
661        });
662        cx.update(|window, cx| {
663            let _ = window.draw(cx);
664        });
665        textarea.read_with(cx, |state, _| {
666            let snapshot = state.touch_selection().expect("handles follow the text");
667            assert!(!snapshot.is_menu_open());
668            assert_eq!(state.selected_text().to_string(), "line");
669        });
670
671        // Scrolled far enough, the selection leaves the viewport: no handle
672        // for it, and no menu anchored to nothing.
673        cx.update(|_, cx| {
674            textarea.update(cx, |state, cx| {
675                state.set_scroll_offset(point(px(0.), px(-600.)), cx);
676            });
677        });
678        cx.update(|window, cx| {
679            let _ = window.draw(cx);
680        });
681        textarea.read_with(cx, |state, _| {
682            let snapshot = state
683                .touch_selection()
684                .expect("the selection is still the touch one");
685            assert!(!snapshot.is_edge_visible(SelectionEdge::Start));
686            assert!(!snapshot.is_edge_visible(SelectionEdge::End));
687            assert_eq!(snapshot.bounds(), None);
688        });
689    }
690}