Skip to main content

gpui_base/
text_selection.rs

1use std::{
2    cell::{Cell, RefCell},
3    collections::HashMap,
4    ops::Range,
5    rc::Rc,
6    sync::atomic::{AtomicU64, Ordering},
7};
8
9use gpui::{
10    App, AppContext as _, Bounds, Context, Element, ElementId, Entity, EntityId, EventEmitter,
11    Global, GlobalElementId, Half, Hitbox, HitboxBehavior, Hsla, InputEvent as _,
12    InspectorElementId, IntoElement, LayoutId, LongPressEvent, MouseButton, MouseDownEvent,
13    MouseExitEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, ScrollDelta, ScrollEvent,
14    SharedString, Style, Subscription, TextLayout, TouchDragEvent, TouchPhase, WeakEntity, Window,
15    point, px,
16};
17
18use crate::text_boundary::{line_range_at, word_range_at};
19use crate::touch_selection::{
20    EdgeDrag, SelectionEdge, TouchHandle, TouchSelectionSnapshot, caret_in_view, caret_line_box,
21};
22use crate::{AutoScroll, GlobalState};
23
24/// An opaque selection layer identifier.
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
26pub struct TextSelectionScopeId(u64);
27
28impl TextSelectionScopeId {
29    /// Allocates a process-unique scope identifier.
30    ///
31    /// Keep the returned identifier for the semantic lifetime of the scope;
32    /// do not allocate a new identifier on every frame.
33    pub fn new() -> Self {
34        static NEXT_SCOPE_ID: AtomicU64 = AtomicU64::new(1);
35        let value = NEXT_SCOPE_ID
36            .try_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
37                value.checked_add(1)
38            })
39            .expect("text selection scope identifiers exhausted");
40        Self(value)
41    }
42
43    #[cfg(test)]
44    const fn from_raw(value: u64) -> Self {
45        Self(value)
46    }
47}
48
49/// Stable participant-defined identity for virtualized participant content.
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
51pub struct TextSelectionContentKey(u64);
52
53impl TextSelectionContentKey {
54    /// Creates a key from a participant-defined stable content identity.
55    pub const fn new(value: u64) -> Self {
56        Self(value)
57    }
58
59    /// Returns the participant-defined value.
60    pub const fn value(self) -> u64 {
61        self.0
62    }
63}
64
65/// A selection endpoint anchored to a participant's content coordinates.
66#[derive(Clone, Copy, Debug, PartialEq)]
67pub struct TextSelectionEndpoint {
68    entity_id: Option<EntityId>,
69    point: Point<Pixels>,
70    content_key: Option<TextSelectionContentKey>,
71}
72
73impl TextSelectionEndpoint {
74    /// Creates an endpoint at a participant-relative content point.
75    pub(crate) const fn new(entity_id: Option<EntityId>, point: Point<Pixels>) -> Self {
76        Self {
77            entity_id,
78            point,
79            content_key: None,
80        }
81    }
82
83    /// Sets participant-defined endpoint metadata.
84    pub(crate) const fn with_content_key(mut self, content_key: TextSelectionContentKey) -> Self {
85        self.content_key = Some(content_key);
86        self
87    }
88
89    /// Returns the participant which owns this endpoint, when it hit one.
90    pub const fn entity_id(&self) -> Option<EntityId> {
91        self.entity_id
92    }
93
94    /// Returns the participant-relative content point.
95    pub const fn content_point(&self) -> Point<Pixels> {
96        self.point
97    }
98
99    /// Returns participant-defined endpoint metadata captured when it hit a participant.
100    pub const fn content_key(&self) -> Option<TextSelectionContentKey> {
101        self.content_key
102    }
103}
104
105/// Window-coordinate anchor and cursor points for painting a selection.
106#[derive(Clone, Copy, Debug, PartialEq)]
107pub struct TextSelectionWindowPoints {
108    anchor: Point<Pixels>,
109    cursor: Point<Pixels>,
110}
111
112impl TextSelectionWindowPoints {
113    /// Returns the stable anchor in window coordinates.
114    pub const fn anchor(&self) -> Point<Pixels> {
115        self.anchor
116    }
117
118    /// Returns the moving cursor in window coordinates.
119    pub const fn cursor(&self) -> Point<Pixels> {
120        self.cursor
121    }
122}
123
124/// Participant-relative selection endpoints with an optional rendering projection.
125#[derive(Clone, Copy, Debug, PartialEq)]
126pub struct TextSelectionSnapshot {
127    anchor: TextSelectionEndpoint,
128    cursor: TextSelectionEndpoint,
129    is_selecting: bool,
130    window_points: Option<TextSelectionWindowPoints>,
131    coverage: TextSelectionCoverage,
132}
133
134/// How much of one participant participates in a window selection.
135#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
136pub enum TextSelectionCoverage {
137    /// Only the interval between this participant's two endpoints is selected.
138    #[default]
139    Bounded,
140    /// The participant is selected from its beginning through its endpoint.
141    FromStart,
142    /// The participant is selected from its endpoint through its end.
143    ToEnd,
144    /// The entire participant lies between endpoints in other participants.
145    Full,
146}
147
148impl TextSelectionSnapshot {
149    /// Creates a snapshot from stable participant-relative endpoints.
150    pub(crate) const fn new(anchor: TextSelectionEndpoint, cursor: TextSelectionEndpoint) -> Self {
151        Self {
152            anchor,
153            cursor,
154            is_selecting: false,
155            window_points: None,
156            coverage: TextSelectionCoverage::Bounded,
157        }
158    }
159
160    /// Sets whether the pointer gesture is still active.
161    pub(crate) const fn with_selecting(mut self, is_selecting: bool) -> Self {
162        self.is_selecting = is_selecting;
163        self
164    }
165
166    /// Sets the current window-coordinate rendering projection.
167    pub(crate) const fn with_window_points(
168        mut self,
169        window_points: Option<TextSelectionWindowPoints>,
170    ) -> Self {
171        self.window_points = window_points;
172        self
173    }
174
175    /// Sets the portion of the receiving participant covered by this selection.
176    #[cfg(test)]
177    pub(crate) const fn with_coverage(mut self, coverage: TextSelectionCoverage) -> Self {
178        self.coverage = coverage;
179        self
180    }
181
182    /// Returns the stable anchor endpoint.
183    pub const fn anchor(&self) -> TextSelectionEndpoint {
184        self.anchor
185    }
186
187    /// Returns the moving cursor endpoint.
188    pub const fn cursor(&self) -> TextSelectionEndpoint {
189        self.cursor
190    }
191
192    /// Returns whether the pointer gesture is still active.
193    pub const fn is_selecting(&self) -> bool {
194        self.is_selecting
195    }
196
197    /// Returns the window-coordinate endpoints for participants that need them.
198    pub const fn window_points(&self) -> Option<TextSelectionWindowPoints> {
199        self.window_points
200    }
201
202    /// Returns the portion of the receiving participant covered by this selection.
203    pub const fn coverage(&self) -> TextSelectionCoverage {
204        self.coverage
205    }
206}
207
208/// Retained element state proving a participant is still in the window.
209///
210/// A participant reports its geometry from `paint`, which a cached view
211/// (`Entity::cached`) skips: GPUI replays the recorded frame instead. The
212/// element's retained state is replayed with it, so this marker outlives the
213/// frames whose paint never ran, and dies with the frame that drops the
214/// element for good.
215struct RenderedMarker;
216
217/// Per-frame geometry reported by a [`TextSelectionHandle`] participant.
218pub struct TextSelectionRegistration {
219    hitbox: Hitbox,
220    bounds: Bounds<Pixels>,
221    scroll_offset: Point<Pixels>,
222    scope: TextSelectionScopeId,
223    document_order: u64,
224    paint_order: bool,
225    text_bounds: Vec<Bounds<Pixels>>,
226    self_scroll: bool,
227    selection_edges: Option<(Bounds<Pixels>, Bounds<Pixels>)>,
228    rendered: Option<WeakEntity<RenderedMarker>>,
229}
230
231impl TextSelectionRegistration {
232    /// Creates a registration with default scope, order, and scroll offset.
233    pub fn new(hitbox: Hitbox, bounds: Bounds<Pixels>) -> Self {
234        Self {
235            hitbox,
236            bounds,
237            scroll_offset: Point::default(),
238            scope: TextSelectionScopeId::default(),
239            document_order: 0,
240            paint_order: false,
241            text_bounds: Vec::new(),
242            self_scroll: false,
243            selection_edges: None,
244            rendered: None,
245        }
246    }
247
248    /// Ties this registration to the retained state of the element reporting
249    /// it, so that a frame replayed from that element's cached view keeps it.
250    ///
251    /// Call this from the reporting element's `prepaint` or `paint`. A
252    /// registration made outside a drawing element cannot be tied to one and
253    /// is swept the first frame it misses, as every registration used to be.
254    pub fn with_rendered_element(
255        mut self,
256        participant: &TextSelectionHandle,
257        window: &mut Window,
258        cx: &mut App,
259    ) -> Self {
260        self.rendered = Some(
261            window
262                .use_keyed_state(
263                    ElementId::NamedInteger(
264                        "text-selection-participant".into(),
265                        participant.entity_id().as_u64(),
266                    ),
267                    cx,
268                    |_, _| RenderedMarker,
269                )
270                .downgrade(),
271        );
272        self
273    }
274
275    /// Whether the element that reported this registration is still part of
276    /// the window, even if it did not paint the frame that just finished.
277    fn is_rendered(&self) -> bool {
278        self.rendered
279            .as_ref()
280            .is_some_and(|marker| marker.upgrade().is_some())
281    }
282
283    /// Marks a participant that scrolls its own content in response to
284    /// [`TextSelectionEvent::AutoScroll`]. Drag auto-scroll then drives it
285    /// directly, measured against its own bounds, instead of synthesizing a
286    /// wheel event for the nearest scrollable ancestor.
287    pub(crate) fn with_self_scroll(mut self, self_scroll: bool) -> Self {
288        self.self_scroll = self_scroll;
289        self
290    }
291
292    /// Sets the participant's content scroll offset.
293    pub fn with_scroll_offset(mut self, scroll_offset: Point<Pixels>) -> Self {
294        self.scroll_offset = scroll_offset;
295        self
296    }
297
298    /// Sets the opaque selection scope.
299    pub fn with_scope(mut self, scope: TextSelectionScopeId) -> Self {
300        self.scope = scope;
301        self
302    }
303
304    /// Sets the stable logical document order.
305    pub fn with_document_order(mut self, document_order: u64) -> Self {
306        self.document_order = document_order;
307        self
308    }
309
310    /// Uses the order of the TextViews in a complete painted frame. A cached
311    /// view keeps that order while only some of its siblings paint again.
312    pub(crate) fn in_paint_order(mut self) -> Self {
313        self.paint_order = true;
314        self
315    }
316
317    /// Sets the glyph-bearing bounds used to reject blank-only gestures.
318    pub fn with_text_bounds(mut self, text_bounds: Vec<Bounds<Pixels>>) -> Self {
319        self.text_bounds = text_bounds;
320        self
321    }
322
323    /// Sets where the participant painted the two ends of its selection: the
324    /// caret line box before its first selected character and the one after
325    /// its last, in window coordinates. The touch handles are drawn there.
326    pub fn with_selection_edges(mut self, start: Bounds<Pixels>, end: Bounds<Pixels>) -> Self {
327        self.selection_edges = Some((start, end));
328        self
329    }
330
331    /// Returns the participant hitbox.
332    pub fn hitbox(&self) -> &Hitbox {
333        &self.hitbox
334    }
335
336    /// Returns the participant's window-coordinate bounds.
337    pub const fn bounds(&self) -> Bounds<Pixels> {
338        self.bounds
339    }
340
341    /// Returns the participant's content scroll offset.
342    pub const fn scroll_offset(&self) -> Point<Pixels> {
343        self.scroll_offset
344    }
345
346    /// Returns the opaque selection scope.
347    pub const fn scope(&self) -> TextSelectionScopeId {
348        self.scope
349    }
350
351    /// Returns the stable logical document order.
352    pub const fn document_order(&self) -> u64 {
353        self.document_order
354    }
355
356    /// Returns the glyph-bearing bounds used to reject blank-only gestures.
357    pub fn text_bounds(&self) -> &[Bounds<Pixels>] {
358        &self.text_bounds
359    }
360
361    /// Returns the caret line boxes at the participant's selection ends.
362    pub const fn selection_edges(&self) -> Option<(Bounds<Pixels>, Bounds<Pixels>)> {
363        self.selection_edges
364    }
365}
366
367/// Laid-out text reported by a plain selection participant during paint.
368#[derive(Clone)]
369pub struct TextSelectionRun {
370    /// Logical order within the containing participant.
371    document_order: u64,
372    /// The exact text used to produce `layout`.
373    text: SharedString,
374    /// Laid-out glyph geometry in window coordinates.
375    layout: TextLayout,
376    /// The run's window-coordinate paint bounds.
377    bounds: Bounds<Pixels>,
378    /// The boundary a triple-click drag snaps to in this run.
379    triple_click: TripleClickSelection,
380}
381
382#[derive(Clone, Copy)]
383enum TripleClickSelection {
384    LogicalLine,
385    Paragraph,
386    Row(Bounds<Pixels>),
387}
388
389impl TextSelectionRun {
390    /// Creates a laid-out text run.
391    pub fn new(text: impl Into<SharedString>, layout: TextLayout, bounds: Bounds<Pixels>) -> Self {
392        Self {
393            document_order: 0,
394            text: text.into(),
395            layout,
396            bounds,
397            triple_click: TripleClickSelection::LogicalLine,
398        }
399    }
400
401    /// Sets the run's logical order within the participant.
402    pub const fn with_document_order(mut self, document_order: u64) -> Self {
403        self.document_order = document_order;
404        self
405    }
406
407    /// Uses TextView's triple-click boundary: the whole paragraph, or the
408    /// laid-out row when this run is one piece of an inline flow.
409    pub(crate) const fn with_paragraph(mut self, row: Option<Bounds<Pixels>>) -> Self {
410        self.triple_click = match row {
411            Some(row) => TripleClickSelection::Row(row),
412            None => TripleClickSelection::Paragraph,
413        };
414        self
415    }
416
417    /// Returns the run's logical order within its participant.
418    pub const fn document_order(&self) -> u64 {
419        self.document_order
420    }
421
422    /// Returns the exact text used to produce the layout.
423    pub fn text(&self) -> &SharedString {
424        &self.text
425    }
426
427    /// Returns the laid-out glyph geometry.
428    pub fn layout(&self) -> &TextLayout {
429        &self.layout
430    }
431
432    /// Returns the run's window-coordinate paint bounds.
433    pub const fn bounds(&self) -> Bounds<Pixels> {
434        self.bounds
435    }
436}
437
438/// Selection projected onto a participant's laid-out text runs.
439#[derive(Clone, Debug, Default, PartialEq, Eq)]
440pub struct TextSelectionProjection {
441    /// Selected UTF-8 byte ranges paired with the input runs.
442    ranges: Vec<Option<Range<usize>>>,
443    /// Whether the participant participates in the current selection.
444    is_active: bool,
445}
446
447impl TextSelectionProjection {
448    /// Returns selected UTF-8 byte ranges paired with the input runs.
449    pub fn ranges(&self) -> &[Option<Range<usize>>] {
450        &self.ranges
451    }
452
453    /// Returns whether the participant participates in the selection.
454    pub const fn is_active(&self) -> bool {
455        self.is_active
456    }
457}
458
459/// Projects a participant selection snapshot onto laid-out plain-text runs.
460///
461/// The returned states retain the input order so callers can pair every state
462/// with its run. The ranges are always character boundaries; `order` is used
463/// only when a participant caches selected text for copying.
464fn project_ranges(
465    snapshot: Option<TextSelectionSnapshot>,
466    runs: &[TextSelectionRun],
467) -> TextSelectionProjection {
468    let Some(snapshot) = snapshot else {
469        return TextSelectionProjection {
470            ranges: vec![None; runs.len()],
471            is_active: false,
472        };
473    };
474    let Some(window_points) = snapshot.window_points() else {
475        return TextSelectionProjection {
476            ranges: vec![None; runs.len()],
477            is_active: true,
478        };
479    };
480
481    TextSelectionProjection {
482        ranges: runs
483            .iter()
484            .map(|run| selection_range_for_run(run, window_points.anchor, window_points.cursor))
485            .collect(),
486        is_active: true,
487    }
488}
489
490fn selection_range_for_run(
491    run: &TextSelectionRun,
492    selection_start: Point<Pixels>,
493    selection_end: Point<Pixels>,
494) -> Option<Range<usize>> {
495    if run.text.len() != run.layout.len() {
496        return None;
497    }
498
499    if run.text.is_empty() {
500        return None;
501    }
502
503    let line_height = run.layout.line_height();
504    // Each character is tested with its row's top and height, so a run whose
505    // rows all miss the band, or all lie strictly inside it with no endpoint
506    // on any row, has the same answer for every character. Decide those
507    // without the walk below, which scans the layout twice per character.
508    let (rows_top, rows_bottom) = text_rows_extent(&run.layout, line_height);
509    let band_top = selection_start.y.min(selection_end.y);
510    let band_bottom = selection_start.y.max(selection_end.y);
511    if rows_bottom <= band_top || rows_top > band_bottom {
512        return None;
513    }
514    if band_top < rows_top && band_bottom >= rows_bottom {
515        return Some(0..run.text.len());
516    }
517
518    let mut range = None;
519    for (offset, character) in run.text.char_indices() {
520        let next_offset = offset + character.len_utf8();
521        let Some(position) = run.layout.position_for_index(offset) else {
522            continue;
523        };
524
525        let char_width = run
526            .layout
527            .position_for_index(next_offset)
528            .filter(|next| next.y == position.y)
529            .map_or_else(|| line_height.half(), |next| next.x - position.x);
530
531        if point_in_selection_band(
532            position,
533            char_width,
534            selection_start,
535            selection_end,
536            line_height,
537        ) {
538            range.get_or_insert(offset..offset).end = next_offset;
539        }
540    }
541    range
542}
543
544/// The top of the first laid-out row of `text_layout` and the bottom of its
545/// last one, each row `line_height` tall as a selection band test sees it.
546///
547/// Both ends are accumulated the way [`TextLayout::position_for_index`] places
548/// rows, so comparisons against them agree with a per-character walk to the
549/// bit. The last laid-out row may hold no character such a walk tests (a
550/// trailing empty line, or a row whose only character is placed at the end of
551/// the row before it); callers treat the extent as covering, never as exact.
552pub(crate) fn text_rows_extent(text_layout: &TextLayout, line_height: Pixels) -> (Pixels, Pixels) {
553    let top = text_layout.bounds().top();
554    let layout_line_height = text_layout.line_height();
555    let lines = text_layout.line_layouts();
556    let mut last_line_top = top;
557    for line in lines.iter().take(lines.len().saturating_sub(1)) {
558        last_line_top += line.size(layout_line_height).height;
559    }
560    let last_row_top = lines.last().map_or(top, |line| {
561        last_line_top + line.wrap_boundaries.len() as f32 * layout_line_height
562    });
563    (top, last_row_top + line_height)
564}
565
566/// The carets at the two ends of what `click_count` clicks at `position`
567/// select: the word under it for two, its line or paragraph for three.
568fn carets_for_multi_click(
569    runs: &[TextSelectionRun],
570    position: Point<Pixels>,
571    click_count: usize,
572) -> Option<(Bounds<Pixels>, Bounds<Pixels>)> {
573    let run = runs.iter().find(|run| run.bounds.contains(&position))?;
574    if run.text.len() != run.layout.len() {
575        return None;
576    }
577    let offset = match run.layout.index_for_position(position) {
578        Ok(offset) => offset,
579        // Beside a line, as after a short last one: three clicks still mean that line.
580        Err(nearest) if click_count >= 3 => nearest,
581        Err(_) => return None,
582    };
583    unit_carets(run, offset, click_count)
584}
585
586/// The carets at the two ends of the word (`click_count` 2) or the run's
587/// triple-click boundary (3 or more) at the byte `offset` of `run`.
588fn unit_carets(
589    run: &TextSelectionRun,
590    offset: usize,
591    click_count: usize,
592) -> Option<(Bounds<Pixels>, Bounds<Pixels>)> {
593    let range = match click_count {
594        2 => word_range_at(&run.text, offset)?,
595        3.. => match run.triple_click {
596            TripleClickSelection::LogicalLine => line_range_at(&run.text, offset),
597            TripleClickSelection::Paragraph => 0..run.text.len(),
598            TripleClickSelection::Row(row) => {
599                return Some((
600                    caret_line_box(row.origin, row.size.height),
601                    caret_line_box(row.top_right(), row.size.height),
602                ));
603            }
604        },
605        _ => return None,
606    };
607    if range.is_empty() {
608        return None;
609    }
610    let line_height = run.layout.line_height();
611    Some((
612        caret_line_box(run.layout.position_for_index(range.start)?, line_height),
613        caret_line_box(run.layout.position_for_index(range.end)?, line_height),
614    ))
615}
616
617fn point_in_selection_band(
618    position: Point<Pixels>,
619    char_width: Pixels,
620    selection_start: Point<Pixels>,
621    selection_end: Point<Pixels>,
622    line_height: Pixels,
623) -> bool {
624    let point_in_line =
625        |point: Point<Pixels>| point.y >= position.y && point.y < position.y + line_height;
626    let top = selection_start.y.min(selection_end.y);
627    let bottom = selection_start.y.max(selection_end.y);
628    let x = position.x + char_width.half();
629
630    if position.y + line_height <= top || position.y > bottom {
631        return false;
632    }
633
634    if point_in_line(selection_start) && point_in_line(selection_end) {
635        let left = selection_start.x.min(selection_end.x);
636        let right = selection_start.x.max(selection_end.x);
637        return x >= left && x <= right;
638    }
639
640    let (top_point, bottom_point) = if selection_start.y < selection_end.y {
641        (selection_start, selection_end)
642    } else {
643        (selection_end, selection_start)
644    };
645    if point_in_line(top_point) {
646        x >= top_point.x
647    } else if point_in_line(bottom_point) {
648        x <= bottom_point.x
649    } else {
650        true
651    }
652}
653
654type FocusCallback = Rc<dyn Fn(&mut Window, &mut App)>;
655type ClearHandler = Rc<dyn Fn(&mut App)>;
656type CopyCallback = Rc<dyn Fn(&mut App) -> String>;
657type ContentKeyResolver = Rc<dyn Fn(Point<Pixels>, &App) -> Option<TextSelectionContentKey>>;
658
659/// Notifications emitted by a text-selection participant.
660#[derive(Clone, Copy, Debug, PartialEq)]
661pub enum TextSelectionEvent {
662    /// The participant's window-selection projection changed.
663    SelectionChanged(Option<TextSelectionSnapshot>),
664    /// The active drag requests vertical auto-scroll, or `None` to stop.
665    AutoScroll(Option<Pixels>),
666    /// Window selection cleared the participant's participant-local state.
667    Cleared,
668    /// The touch selection the participant takes part in changed: it
669    /// appeared, its ends moved, a handle drag began or ended, or it went
670    /// away. The participant paints the handles and lays their hitboxes out
671    /// from the ends it painted last frame, so it renders once more.
672    TouchSelectionChanged,
673}
674
675struct CopyItem {
676    document_order: u64,
677    callback: Option<CopyCallback>,
678    fallback: String,
679}
680
681fn resolve_copy_items(mut items: Vec<CopyItem>, cx: &mut App) -> String {
682    items.sort_by_key(|item| item.document_order);
683    items
684        .into_iter()
685        .map(|item| {
686            item.callback
687                .map(|callback| callback(cx))
688                .unwrap_or(item.fallback)
689        })
690        .filter(|text| !text.trim().is_empty())
691        .collect::<Vec<_>>()
692        .join("\n")
693}
694
695fn dispatch_clear_handlers(handlers: Vec<ClearHandler>, cx: &mut App) {
696    for handler in handlers {
697        handler(cx);
698    }
699}
700
701fn clear_departed_participants(
702    participants: Vec<Entity<SelectableTextState>>,
703    cx: &mut App,
704) -> Vec<ClearHandler> {
705    participants
706        .into_iter()
707        .filter_map(|participant| {
708            participant
709                .read(cx)
710                .has_selection_to_clear()
711                .then(|| participant.update(cx, |state, cx| state.clear_state(cx)))
712                .flatten()
713        })
714        .collect()
715}
716
717struct SelectableTextState {
718    fallback_copy_text: String,
719    window_selection: RefCell<Option<WeakEntity<WindowSelectionState>>>,
720    /// The selected text as the participant last painted it. Painting
721    /// projects it, which is not a change of the participant.
722    projected_copy_text: RefCell<Option<String>>,
723    /// The participant's text as it last painted it, for hit testing.
724    runs: RefCell<Vec<TextSelectionRun>>,
725    local_selection: bool,
726    snapshot: Option<TextSelectionSnapshot>,
727    on_focus: Option<FocusCallback>,
728    clear: Option<ClearHandler>,
729    copy: Option<CopyCallback>,
730    content_key_resolver: Option<ContentKeyResolver>,
731}
732
733impl EventEmitter<TextSelectionEvent> for SelectableTextState {}
734
735impl SelectableTextState {
736    fn new(fallback_copy_text: impl Into<String>) -> Self {
737        Self {
738            fallback_copy_text: fallback_copy_text.into(),
739            window_selection: RefCell::new(None),
740            projected_copy_text: RefCell::new(None),
741            runs: RefCell::new(Vec::new()),
742            local_selection: false,
743            snapshot: None,
744            on_focus: None,
745            clear: None,
746            copy: None,
747            content_key_resolver: None,
748        }
749    }
750
751    /// The current geometry selection snapshot for this participant.
752    fn snapshot(&self) -> Option<TextSelectionSnapshot> {
753        self.snapshot
754    }
755
756    /// Sets the text copied by this participant when it participates in selection.
757    fn set_fallback_copy_text(&mut self, text: impl Into<String>) {
758        self.fallback_copy_text = text.into();
759        *self.projected_copy_text.get_mut() = None;
760    }
761
762    /// Marks participant-local selection (for example select-all) as active.
763    fn set_local_selection(&mut self, active: bool) {
764        self.local_selection = active;
765    }
766
767    /// Projects this participant's current snapshot onto plain-text runs and caches
768    /// their selected substrings for the window selection query.
769    ///
770    /// Call this once per painted run. A snapshot change or
771    /// Clearing window selection invalidates the cache immediately, so copy
772    /// never returns text from a previous projection while waiting to repaint.
773    fn update_runs(&self, runs: &[TextSelectionRun]) -> TextSelectionProjection {
774        *self.runs.borrow_mut() = runs.to_vec();
775        let states = project_ranges(self.snapshot, runs);
776        let mut selected_runs = runs
777            .iter()
778            .zip(states.ranges())
779            .enumerate()
780            .filter_map(|(index, (run, state))| {
781                state.as_ref().map(|range| {
782                    debug_assert!(run.text.is_char_boundary(range.start));
783                    debug_assert!(run.text.is_char_boundary(range.end));
784                    (
785                        run.document_order,
786                        index,
787                        run.text[range.clone()].to_string(),
788                    )
789                })
790            })
791            .collect::<Vec<_>>();
792        selected_runs.sort_by_key(|(order, index, _)| (*order, *index));
793        *self.projected_copy_text.borrow_mut() =
794            Some(selected_runs.into_iter().map(|(_, _, text)| text).collect());
795        states
796    }
797
798    /// Installs the callback which focuses the participant when a drag begins in it.
799    fn set_focus_handler(&mut self, callback: impl Fn(&mut Window, &mut App) + 'static) {
800        self.on_focus = Some(Rc::new(callback));
801    }
802
803    fn clear_with(&mut self, callback: impl Fn(&mut App) + 'static) {
804        self.clear = Some(Rc::new(callback));
805    }
806
807    /// Installs a participant-specific copy projection.
808    fn copy_with(&mut self, callback: impl Fn(&mut App) -> String + 'static) {
809        self.copy = Some(Rc::new(callback));
810    }
811
812    /// Installs a participant-specific lookup for stable virtualized content keys.
813    fn resolve_content_key_with(
814        &mut self,
815        callback: impl Fn(Point<Pixels>, &App) -> Option<TextSelectionContentKey> + 'static,
816    ) {
817        self.content_key_resolver = Some(Rc::new(callback));
818    }
819
820    fn set_snapshot_quietly(&mut self, snapshot: Option<TextSelectionSnapshot>) -> bool {
821        if self.snapshot == snapshot {
822            return false;
823        }
824        self.snapshot = snapshot;
825        *self.projected_copy_text.get_mut() = None;
826        true
827    }
828
829    fn set_snapshot(&mut self, snapshot: Option<TextSelectionSnapshot>, cx: &mut Context<Self>) {
830        if self.set_snapshot_quietly(snapshot) {
831            cx.emit(TextSelectionEvent::SelectionChanged(snapshot));
832        }
833    }
834
835    /// Whether clearing the participant would change anything: it is part
836    /// of the window selection, or selected on its own.
837    fn has_selection_to_clear(&self) -> bool {
838        self.snapshot.is_some() || self.local_selection
839    }
840
841    fn clear_state(&mut self, cx: &mut Context<Self>) -> Option<ClearHandler> {
842        self.snapshot = None;
843        *self.projected_copy_text.get_mut() = None;
844        self.local_selection = false;
845        cx.emit(TextSelectionEvent::Cleared);
846        cx.emit(TextSelectionEvent::SelectionChanged(None));
847        self.clear.clone()
848    }
849
850    fn set_auto_scroll(&self, delta: Option<Pixels>, cx: &mut Context<Self>) {
851        cx.emit(TextSelectionEvent::AutoScroll(delta));
852    }
853
854    fn focus(&self, window: &mut Window, cx: &mut App) {
855        if let Some(callback) = self.on_focus.clone() {
856            window.defer(cx, move |window, cx| callback(window, cx));
857        }
858    }
859
860    fn copy_item(&self, document_order: u64) -> Option<CopyItem> {
861        (self.snapshot.is_some() || self.local_selection).then(|| CopyItem {
862            document_order,
863            callback: self.copy.clone(),
864            fallback: self
865                .projected_copy_text
866                .borrow()
867                .clone()
868                .unwrap_or_else(|| self.fallback_copy_text.clone()),
869        })
870    }
871}
872
873/// The touch handles a participant laid out for a frame, with their hitboxes.
874#[derive(Default)]
875pub struct TouchHandleLayout {
876    hitboxes: Vec<(SelectionEdge, Hitbox)>,
877}
878
879/// A stable, participant-neutral handle for text that participates in window selection.
880#[derive(Clone)]
881pub struct TextSelectionHandle(Entity<SelectableTextState>);
882
883impl TextSelectionHandle {
884    /// Creates a selection participant handle with fallback text for copying.
885    pub fn new(fallback_copy_text: impl Into<String>, cx: &mut App) -> Self {
886        Self(cx.new(|_| SelectableTextState::new(fallback_copy_text)))
887    }
888
889    /// Returns this participant's stable identity.
890    pub fn entity_id(&self) -> EntityId {
891        self.0.entity_id()
892    }
893
894    /// Returns the current geometry selection snapshot for this participant.
895    pub fn snapshot(&self, cx: &App) -> Option<TextSelectionSnapshot> {
896        self.0.read(cx).snapshot()
897    }
898
899    /// Records the anchor cell during prepaint, before any participant paints.
900    pub(crate) fn record_table_cell(&self, bounds: Bounds<Pixels>, cx: &App) {
901        let Some(state) = self.window_selection(cx) else {
902            return;
903        };
904        let state = state.read(cx);
905        if state.touch_select_all {
906            return;
907        }
908        let Some(snapshot) = self.snapshot(cx) else {
909            return;
910        };
911        if snapshot.anchor().entity_id() == Some(self.entity_id())
912            && snapshot
913                .window_points()
914                .is_some_and(|points| bounds.contains(&points.anchor()))
915        {
916            state
917                .table_cell_anchor
918                .set(Some((snapshot.anchor(), bounds)));
919        }
920    }
921
922    /// The current gesture's anchor cell, shared only by participants in its window.
923    pub(crate) fn table_cell_selection(&self, cx: &App) -> Option<Bounds<Pixels>> {
924        let state = self.window_selection(cx)?;
925        let state = state.read(cx);
926        if state.touch_select_all {
927            return None;
928        }
929        let (anchor, bounds) = state.table_cell_anchor.get()?;
930        (self.snapshot(cx)?.anchor() == anchor).then_some(bounds)
931    }
932
933    /// Retires an anchor projection when its participant replaces its content.
934    pub(crate) fn clear_table_cell_selection(&self, cx: &App) {
935        if let Some(state) = self.window_selection(cx) {
936            let state = state.read(cx);
937            if state
938                .table_cell_anchor
939                .get()
940                .is_some_and(|(endpoint, _)| endpoint.entity_id() == Some(self.entity_id()))
941            {
942                state.table_cell_anchor.set(None);
943            }
944        }
945    }
946
947    fn window_selection(&self, cx: &App) -> Option<Entity<WindowSelectionState>> {
948        self.0
949            .read(cx)
950            .window_selection
951            .borrow()
952            .as_ref()?
953            .upgrade()
954    }
955
956    /// Sets the fallback text copied while this participant participates.
957    pub fn set_fallback_copy_text(&self, text: impl Into<String>, cx: &mut App) {
958        self.0
959            .update(cx, |state, _| state.set_fallback_copy_text(text));
960    }
961
962    /// Marks participant-local selection, such as select-all, as active.
963    pub fn set_local_selection(&self, active: bool, cx: &mut App) {
964        self.0
965            .update(cx, |state, _| state.set_local_selection(active));
966    }
967
968    /// Returns whether participant-local selection is active.
969    pub fn has_local_selection(&self, cx: &App) -> bool {
970        self.0.read(cx).local_selection
971    }
972
973    /// Registers this participant and its geometry for the current frame.
974    pub fn register(
975        &self,
976        mut registration: TextSelectionRegistration,
977        window: &mut Window,
978        cx: &mut App,
979    ) {
980        if let Some(scope) = current_text_selection_scope(window.window_handle().window_id(), cx) {
981            registration.scope = scope;
982        }
983        let Some(state) = WindowSelectionState::existing(window, cx) else {
984            return;
985        };
986        *self.0.read(cx).window_selection.borrow_mut() = Some(state.downgrade());
987        state.read(cx).register_quietly(self, registration);
988        let snapshot = state.read(cx).participant_snapshot(self.entity_id());
989        if self.snapshot(cx) != snapshot {
990            // Plain text projects its runs immediately after registering.
991            // Rich text may already have painted, so notify after the frame
992            // as well, when another draw can actually be scheduled.
993            self.0.update(cx, |participant, _| {
994                participant.set_snapshot_quietly(snapshot);
995            });
996            state
997                .read(cx)
998                .draw_changed
999                .borrow_mut()
1000                .insert(self.entity_id(), self.downgrade());
1001        }
1002        schedule_selection_frame(&state, window, cx);
1003    }
1004
1005    /// Projects the current snapshot onto plain-text runs and caches their copy text.
1006    pub fn update_runs(&self, runs: &[TextSelectionRun], cx: &mut App) -> TextSelectionProjection {
1007        self.0.read(cx).update_runs(runs)
1008    }
1009
1010    /// The projected text this participant adds to the window's selected
1011    /// text, or `None` when it adds none or copies through its own callback.
1012    pub(crate) fn projected_copy_text(&self, cx: &App) -> Option<String> {
1013        self.0
1014            .read(cx)
1015            .copy_item(0)
1016            .filter(|item| item.callback.is_none())
1017            .map(|item| item.fallback)
1018    }
1019
1020    // Rich text renders its own selection; retain geometry only for word hit testing.
1021    pub(crate) fn set_hit_test_runs(&self, runs: &[TextSelectionRun], cx: &mut App) {
1022        *self.0.read(cx).runs.borrow_mut() = runs.to_vec();
1023    }
1024
1025    /// Lets a drag from a double or triple click that this participant
1026    /// selected for itself, from the caret `start` to the caret `end` in
1027    /// window coordinates, extend the selection by the same unit through the
1028    /// window selection, as a shift-click after it does.
1029    pub(crate) fn hold_multi_click(
1030        &self,
1031        start: Bounds<Pixels>,
1032        end: Bounds<Pixels>,
1033        click_count: usize,
1034        cx: &mut App,
1035    ) {
1036        let Some(state) = self.window_selection(cx) else {
1037            return;
1038        };
1039        state.update(cx, |state, cx| {
1040            if let Some(unit) = state.unit_of(&self.0, start, end, click_count, cx) {
1041                state.hold_unit(unit, cx);
1042            }
1043        });
1044    }
1045
1046    /// Subscribes to participant selection notifications.
1047    pub fn subscribe(
1048        &self,
1049        mut callback: impl FnMut(&TextSelectionEvent, &mut App) + 'static,
1050        cx: &mut App,
1051    ) -> Subscription {
1052        cx.subscribe(&self.0, move |_, event, cx| callback(event, cx))
1053    }
1054
1055    /// Subscribes `window` to refresh whenever this participant's selection changes.
1056    #[must_use = "retain the subscription or explicitly detach it"]
1057    pub fn refresh_window_on_change(&self, window: &Window, cx: &mut App) -> Subscription {
1058        let window = window.window_handle();
1059        self.subscribe(
1060            move |event, cx| {
1061                if matches!(event, TextSelectionEvent::SelectionChanged(_)) {
1062                    _ = window.update(cx, |_, window, _| window.refresh());
1063                }
1064            },
1065            cx,
1066        )
1067    }
1068
1069    /// Sets the callback which focuses the participant when a drag begins in it.
1070    pub fn focus_with(&self, callback: impl Fn(&mut Window, &mut App) + 'static, cx: &mut App) {
1071        self.0
1072            .update(cx, |state, _| state.set_focus_handler(callback));
1073    }
1074
1075    /// Sets the synchronous participant cleanup command used by window clear.
1076    pub fn clear_with(&self, callback: impl Fn(&mut App) + 'static, cx: &mut App) {
1077        self.0.update(cx, |state, _| state.clear_with(callback));
1078    }
1079
1080    /// Sets a participant-specific copy projection.
1081    pub fn copy_with(&self, callback: impl Fn(&mut App) -> String + 'static, cx: &mut App) {
1082        self.0.update(cx, |state, _| state.copy_with(callback));
1083    }
1084
1085    /// Lays out the touch handles at the ends of this participant's
1086    /// selection, as they were painted last frame, and gives each a hitbox
1087    /// where the finger takes it. Call during the participant's prepaint;
1088    /// hand the result to [`Self::paint_touch_handles`].
1089    pub fn prepaint_touch_handles(&self, window: &mut Window, cx: &App) -> TouchHandleLayout {
1090        let Some(state) = WindowSelectionState::existing(window, cx) else {
1091            return TouchHandleLayout::default();
1092        };
1093        let hitboxes = state
1094            .read(cx)
1095            .touch_handles_of(self.entity_id())
1096            .into_iter()
1097            .map(|(edge, caret)| {
1098                let hitbox = window.insert_hitbox(
1099                    TouchHandle::hit_bounds(edge, caret),
1100                    HitboxBehavior::BlockMouse,
1101                );
1102                (edge, hitbox)
1103            })
1104            .collect();
1105        TouchHandleLayout { hitboxes }
1106    }
1107
1108    /// Paints the touch handles at the ends of this participant's selection,
1109    /// in `color`, where the participant is in the paint order — so whatever
1110    /// is drawn over the text is drawn over its handles too. Call at the end
1111    /// of the participant's paint, after [`Self::register`] for the frame.
1112    ///
1113    /// The handles take the finger's drag from there; Base moves the
1114    /// selection with it.
1115    pub fn paint_touch_handles(
1116        &self,
1117        layout: &TouchHandleLayout,
1118        color: Hsla,
1119        window: &mut Window,
1120        cx: &mut App,
1121    ) {
1122        let Some(state) = WindowSelectionState::existing(window, cx) else {
1123            return;
1124        };
1125        for (edge, caret) in state.read(cx).touch_handles_of(self.entity_id()) {
1126            TouchHandle::paint(edge, caret, color, window);
1127        }
1128        let bounds: Vec<Bounds<Pixels>> = layout
1129            .hitboxes
1130            .iter()
1131            .map(|(_, hitbox)| hitbox.bounds)
1132            .collect();
1133        if !state.read(cx).handles_painted_at(self.entity_id(), &bounds) {
1134            state.update(cx, |state, _| {
1135                state.register_handles(self.entity_id(), bounds)
1136            });
1137        }
1138        for (edge, hitbox) in &layout.hitboxes {
1139            let edge = *edge;
1140            // Touch: the drag is offered on the first touch, before it can
1141            // become a tap, a long press or a pan.
1142            window.on_mouse_event({
1143                let hitbox = hitbox.clone();
1144                let state = state.downgrade();
1145                move |event: &TouchDragEvent, phase, window, cx| {
1146                    if !phase.bubble()
1147                        || event.phase != TouchPhase::Started
1148                        || window.default_prevented()
1149                        || !hitbox.is_hovered(window)
1150                    {
1151                        return;
1152                    }
1153                    let Some(state) = state.upgrade() else {
1154                        return;
1155                    };
1156                    window.prevent_default();
1157                    cx.stop_propagation();
1158                    state.update(cx, |state, cx| {
1159                        state.begin_edge_drag(edge, event.position, window, cx)
1160                    });
1161                    WindowSelectionState::resolve_content_keys(&state, cx);
1162                }
1163            });
1164            // Mouse: the same drag for a pointer.
1165            window.on_mouse_event({
1166                let hitbox = hitbox.clone();
1167                let state = state.downgrade();
1168                move |event: &MouseDownEvent, phase, window, cx| {
1169                    if !phase.bubble()
1170                        || event.button != MouseButton::Left
1171                        || !hitbox.is_hovered(window)
1172                    {
1173                        return;
1174                    }
1175                    let Some(state) = state.upgrade() else {
1176                        return;
1177                    };
1178                    cx.stop_propagation();
1179                    state.update(cx, |state, cx| {
1180                        state.begin_edge_drag(edge, event.position, window, cx)
1181                    });
1182                    WindowSelectionState::resolve_content_keys(&state, cx);
1183                }
1184            });
1185        }
1186    }
1187
1188    /// Sets a participant-specific lookup for stable virtualized content keys.
1189    pub fn resolve_content_key_with(
1190        &self,
1191        callback: impl Fn(Point<Pixels>, &App) -> Option<TextSelectionContentKey> + 'static,
1192        cx: &mut App,
1193    ) {
1194        self.0
1195            .update(cx, |state, _| state.resolve_content_key_with(callback));
1196    }
1197
1198    fn downgrade(&self) -> WeakEntity<SelectableTextState> {
1199        self.0.downgrade()
1200    }
1201}
1202
1203#[derive(Clone)]
1204struct ParticipantRegistration {
1205    participant: WeakEntity<SelectableTextState>,
1206    registration: Rc<TextSelectionRegistration>,
1207    document_order: u64,
1208    generation: u64,
1209}
1210
1211#[derive(Clone)]
1212struct SelectionEndpoint {
1213    participant: Option<WeakEntity<SelectableTextState>>,
1214    point: Point<Pixels>,
1215    inside: bool,
1216    inside_text: bool,
1217    content_key: Option<TextSelectionContentKey>,
1218    content_key_resolver: Option<(ContentKeyResolver, Point<Pixels>)>,
1219}
1220
1221impl SelectionEndpoint {
1222    fn snapshot(&self) -> TextSelectionEndpoint {
1223        let snapshot = TextSelectionEndpoint::new(self.entity_id(), self.point);
1224        if let Some(content_key) = self.content_key {
1225            snapshot.with_content_key(content_key)
1226        } else {
1227            snapshot
1228        }
1229    }
1230
1231    fn resolve(
1232        &self,
1233        participants: &HashMap<EntityId, ParticipantRegistration>,
1234    ) -> Option<Point<Pixels>> {
1235        let participant = self.participant.as_ref()?;
1236        let registration = participants.get(&participant.entity_id())?;
1237        participant.upgrade()?;
1238        Some(
1239            self.point
1240                + registration.registration.scroll_offset
1241                + registration.registration.bounds.origin,
1242        )
1243    }
1244
1245    fn entity_id(&self) -> Option<EntityId> {
1246        self.participant
1247            .as_ref()
1248            .map(|participant| participant.entity_id())
1249    }
1250
1251    /// This endpoint moved by `delta` within its participant, its content
1252    /// key to be resolved again.
1253    fn moved(&self, delta: Point<Pixels>) -> Self {
1254        let point = self.point + delta;
1255        Self {
1256            point,
1257            content_key: None,
1258            content_key_resolver: self
1259                .content_key_resolver
1260                .clone()
1261                .map(|(resolver, _)| (resolver, point)),
1262            ..self.clone()
1263        }
1264    }
1265}
1266
1267/// The word or line a double or triple click selected. A drag from the
1268/// click, and a shift-click after it, extend the selection by the same unit,
1269/// and it stays selected whichever way they go.
1270#[derive(Clone)]
1271struct SelectionUnit {
1272    click_count: usize,
1273    start: SelectionEndpoint,
1274    end: SelectionEndpoint,
1275    /// The heights of the rows the unit starts and ends on.
1276    row_heights: (Pixels, Pixels),
1277}
1278
1279/// What a long press left behind: the handles and the edit menu.
1280///
1281/// The presentation layer draws both and reports their bounds each frame, so
1282/// that a press on a handle or a menu item is not taken for a press on the
1283/// text underneath, which would clear the very selection they belong to.
1284#[derive(Default)]
1285struct TouchSelection {
1286    /// The current selection was made by touch and carries handles.
1287    active: bool,
1288    menu_open: bool,
1289    drag: Option<EdgeDrag>,
1290    /// Where the menu was painted this frame, and the frame before: a press
1291    /// arrives between frames, and the surfaces may have moved in the one
1292    /// that has not painted yet.
1293    ui_bounds: Vec<Bounds<Pixels>>,
1294    previous_ui_bounds: Vec<Bounds<Pixels>>,
1295    /// Where each participant last painted its handles. A participant drawn
1296    /// from an earlier frame, which does not paint again, still shows its
1297    /// handles where it painted them; one that paints again replaces them.
1298    handle_bounds: HashMap<EntityId, Vec<Bounds<Pixels>>>,
1299    /// The ends as last laid out: `(start, end, start_visible, end_visible)`.
1300    /// A frame in which no participant paints a selection — the cursor sits
1301    /// between two characters mid-drag — would otherwise lose the handle the
1302    /// finger holds, and with it the rest of the drag.
1303    last_edges: std::cell::Cell<Option<(Bounds<Pixels>, Bounds<Pixels>, bool, bool)>>,
1304}
1305
1306impl TouchSelection {
1307    fn covers(&self, position: Point<Pixels>) -> bool {
1308        self.active
1309            && self
1310                .ui_bounds
1311                .iter()
1312                .chain(&self.previous_ui_bounds)
1313                .chain(self.handle_bounds.values().flatten())
1314                .any(|bounds| bounds.contains(&position))
1315    }
1316
1317    /// Whether the handles or the menu were painted in either of the last
1318    /// two frames, which [`Self::begin_frame`] has to shift.
1319    fn painted_any(&self) -> bool {
1320        !self.ui_bounds.is_empty() || !self.previous_ui_bounds.is_empty()
1321    }
1322
1323    /// A new frame begins: what was painted last frame is kept one frame more.
1324    fn begin_frame(&mut self) {
1325        self.previous_ui_bounds = std::mem::take(&mut self.ui_bounds);
1326    }
1327
1328    /// Drops the handles and the menu; returns whether there were any.
1329    fn reset(&mut self) -> bool {
1330        let had = self.active;
1331        self.handle_bounds.clear();
1332        self.active = false;
1333        self.menu_open = false;
1334        self.drag = None;
1335        self.last_edges.set(None);
1336        had
1337    }
1338}
1339
1340/// Automatic order is committed only after all live TextViews have painted.
1341/// A partial frame is a subsequence of that order, not a new document.
1342#[derive(Default)]
1343struct ParticipantPaintOrder {
1344    next: u64,
1345    painted: Vec<EntityId>,
1346    last: Option<u64>,
1347    dirty: bool,
1348    refresh_requested: bool,
1349}
1350
1351/// Window-local generic text-selection state.
1352#[derive(Default)]
1353struct WindowSelectionState {
1354    /// What each participant painted this frame, or last painted. Painting
1355    /// reports it without changing the selection: see
1356    /// [`WindowSelectionState::register_quietly`].
1357    participants: RefCell<HashMap<EntityId, ParticipantRegistration>>,
1358    active_scope: TextSelectionScopeId,
1359    /// A prepaint projection owned by this window and reset with its selection.
1360    table_cell_anchor: Cell<Option<(TextSelectionEndpoint, Bounds<Pixels>)>>,
1361    touch_select_all: bool,
1362    anchor: Option<SelectionEndpoint>,
1363    cursor: Option<SelectionEndpoint>,
1364    pending_extension_anchor: Option<SelectionEndpoint>,
1365    unit: Option<SelectionUnit>,
1366    is_selecting: bool,
1367    did_hit_text: bool,
1368    frame_generation: Cell<u64>,
1369    finish_frame_scheduled: Cell<bool>,
1370    layer_painted: Cell<bool>,
1371    paint_order: RefCell<ParticipantPaintOrder>,
1372    /// Participants given an updated snapshot while drawing. Their observers
1373    /// run after the frame, including adapters which registered after paint.
1374    draw_changed: RefCell<HashMap<EntityId, WeakEntity<SelectableTextState>>>,
1375    refresh_held_cursor: Cell<bool>,
1376    touch_edges_moved: Cell<bool>,
1377    #[cfg(test)]
1378    snapshot_visits: Cell<usize>,
1379    mouse_down_prepared: bool,
1380    mouse_lifecycle: Vec<Subscription>,
1381    auto_scroll: AutoScroll,
1382    /// Where the anchor's text was when the last synthetic wheel went out,
1383    /// and how many went out without moving it. A container at its end
1384    /// cannot scroll further; pushing it on would only make one that
1385    /// bounces stretch and snap back on every tick.
1386    auto_scroll_stall: (Option<(Bounds<Pixels>, Point<Pixels>)>, u8),
1387    touch: TouchSelection,
1388    /// The hitboxes where a press keeps the selection, by element (see
1389    /// [`crate::ElementExt::keep_text_selection`]). One drawn from an earlier
1390    /// frame (a cached view) keeps its hitbox, and one no longer drawn never
1391    /// hits again. GPUI cannot tell the two apart, so an entry stays for the
1392    /// window's lifetime: one per element id.
1393    keep_regions: HashMap<GlobalElementId, Hitbox>,
1394    /// This entity, so that touch changes can notify observers from paths that
1395    /// only hold an [`App`].
1396    entity_id: Option<EntityId>,
1397}
1398
1399impl WindowSelectionState {
1400    fn resolve_content_keys(state: &Entity<Self>, cx: &mut App) {
1401        let pending = state.read_with(cx, |state, _| {
1402            [
1403                state
1404                    .anchor
1405                    .as_ref()
1406                    .and_then(|endpoint| endpoint.content_key_resolver.clone()),
1407                state
1408                    .cursor
1409                    .as_ref()
1410                    .and_then(|endpoint| endpoint.content_key_resolver.clone()),
1411            ]
1412        });
1413        // Nothing to resolve and no selection to publish: an event that
1414        // changed nothing does not change the state either.
1415        if pending.iter().all(Option::is_none) && !state.read(cx).is_active() {
1416            return;
1417        }
1418        let resolved =
1419            pending.map(|pending| pending.and_then(|(callback, point)| callback(point, cx)));
1420        state.update(cx, |state, cx| {
1421            if let (Some(endpoint), Some(key)) = (state.anchor.as_mut(), resolved[0]) {
1422                endpoint.content_key = Some(key);
1423                endpoint.content_key_resolver = None;
1424            }
1425            if let (Some(endpoint), Some(key)) = (state.cursor.as_mut(), resolved[1]) {
1426                endpoint.content_key = Some(key);
1427                endpoint.content_key_resolver = None;
1428            }
1429            state.publish_snapshots(cx);
1430        });
1431    }
1432    fn acquire(window_id: gpui::WindowId, cx: &mut App) -> Entity<Self> {
1433        if !cx.has_global::<SelectionStateRegistry>() {
1434            cx.set_global(SelectionStateRegistry::default());
1435        }
1436        if let Some(state) = cx
1437            .global::<SelectionStateRegistry>()
1438            .0
1439            .get(&window_id)
1440            .and_then(WeakEntity::upgrade)
1441        {
1442            return state;
1443        }
1444
1445        let active_scope = if cx.has_global::<PendingTextSelectionScopes>() {
1446            cx.global_mut::<PendingTextSelectionScopes>()
1447                .0
1448                .remove(&window_id)
1449                .unwrap_or_default()
1450        } else {
1451            TextSelectionScopeId::default()
1452        };
1453
1454        let state = cx.new(move |cx| {
1455            let entity_id = cx.entity_id();
1456            cx.on_release(move |state: &mut WindowSelectionState, cx| {
1457                let handlers = state.clear_state(cx);
1458                if cx.has_global::<SelectionStateRegistry>() {
1459                    let registry = &mut cx.global_mut::<SelectionStateRegistry>().0;
1460                    if registry
1461                        .get(&window_id)
1462                        .is_some_and(|state| state.entity_id() == entity_id)
1463                    {
1464                        registry.remove(&window_id);
1465                    }
1466                }
1467                if !handlers.is_empty() {
1468                    cx.defer(move |cx| dispatch_clear_handlers(handlers, cx));
1469                }
1470            })
1471            .detach();
1472            Self {
1473                active_scope,
1474                entity_id: Some(entity_id),
1475                ..Self::default()
1476            }
1477        });
1478        cx.global_mut::<SelectionStateRegistry>()
1479            .0
1480            .insert(window_id, state.downgrade());
1481        state
1482    }
1483
1484    #[cfg(test)]
1485    fn ensure(window: &Window, cx: &mut App) -> Entity<Self> {
1486        Self::acquire(window.window_handle().window_id(), cx)
1487    }
1488
1489    fn existing(window: &Window, cx: &App) -> Option<Entity<Self>> {
1490        if !cx.has_global::<SelectionStateRegistry>() {
1491            return None;
1492        }
1493        cx.global::<SelectionStateRegistry>()
1494            .0
1495            .get(&window.window_handle().window_id())
1496            .and_then(WeakEntity::upgrade)
1497    }
1498
1499    /// Updates the active scope. Participants from other scopes cannot participate.
1500    #[cfg(test)]
1501    fn set_active_scope(&mut self, scope: TextSelectionScopeId, cx: &mut App) {
1502        let handlers = self.set_active_scope_state(scope, cx);
1503        dispatch_clear_handlers(handlers, cx);
1504    }
1505
1506    fn set_active_scope_state(
1507        &mut self,
1508        scope: TextSelectionScopeId,
1509        cx: &mut App,
1510    ) -> Vec<ClearHandler> {
1511        if self.active_scope == scope {
1512            return Vec::new();
1513        }
1514        let handlers = self.clear_state(cx);
1515        self.active_scope = scope;
1516        self.publish_snapshots(cx);
1517        handlers
1518    }
1519
1520    /// Sweeps participants after a rendered frame has completed.
1521    ///
1522    /// Registrations are stamped with the current generation while any sibling
1523    /// is painting. Sweeping only after paint makes registration independent of
1524    /// whether a participant or the lifecycle element paints first.
1525    ///
1526    /// A missed generation alone does not mean the participant left the window:
1527    /// a cached view replays its recorded frame, painting the same text at the
1528    /// same place without running any of its elements. Such a participant keeps
1529    /// the registration it last reported, which still describes what is on
1530    /// screen; only one whose element GPUI has dropped is swept.
1531    ///
1532    /// Removing an endpoint also retires the window's gesture. Clearing only
1533    /// the participant snapshot would restore that selection if its retained
1534    /// entity were registered again.
1535    #[cfg(test)]
1536    fn finish_frame(&mut self, cx: &mut App) -> Vec<ClearHandler> {
1537        let stale = self.stale_participants(true);
1538        let mut handlers = if self.endpoint_departed(&stale) {
1539            self.clear_state(cx)
1540        } else {
1541            Vec::new()
1542        };
1543        let departed = self.remove_stale_participants(stale);
1544        handlers.extend(clear_departed_participants(departed, cx));
1545        self.finish_registrations();
1546        self.publish_snapshots(cx);
1547        handlers
1548    }
1549
1550    fn stale_participants(
1551        &self,
1552        full_frame: bool,
1553    ) -> Vec<(EntityId, WeakEntity<SelectableTextState>)> {
1554        let generation = self.frame_generation.get();
1555        self.participants
1556            .borrow()
1557            .iter()
1558            .filter_map(|(id, participant)| {
1559                let registration = &participant.registration;
1560                let missed_frame = participant.generation != generation
1561                    && !registration.is_rendered()
1562                    && (full_frame || registration.rendered.is_some());
1563                (missed_frame || participant.participant.upgrade().is_none())
1564                    .then(|| (*id, participant.participant.clone()))
1565            })
1566            .collect()
1567    }
1568
1569    fn endpoint_departed(&self, stale: &[(EntityId, WeakEntity<SelectableTextState>)]) -> bool {
1570        stale.iter().any(|(id, _)| {
1571            [
1572                self.anchor.as_ref(),
1573                self.cursor.as_ref(),
1574                self.pending_extension_anchor.as_ref(),
1575            ]
1576            .into_iter()
1577            .flatten()
1578            .chain(self.unit.iter().flat_map(|unit| [&unit.start, &unit.end]))
1579            .any(|endpoint| endpoint.entity_id() == Some(*id))
1580        })
1581    }
1582
1583    fn remove_stale_participants(
1584        &self,
1585        stale: Vec<(EntityId, WeakEntity<SelectableTextState>)>,
1586    ) -> Vec<Entity<SelectableTextState>> {
1587        let mut participants = self.participants.borrow_mut();
1588        stale
1589            .into_iter()
1590            .filter_map(|(id, participant)| {
1591                participants.remove(&id);
1592                participant.upgrade()
1593            })
1594            .collect()
1595    }
1596
1597    /// Finishes bookkeeping through a read of the window entity. Updating it
1598    /// would invalidate every retained view that registered a participant.
1599    /// Returns whether one complete frame is needed to recover paint order.
1600    fn finish_registrations(&self) -> bool {
1601        let generation = self.frame_generation.get();
1602        let mut participants = self.participants.borrow_mut();
1603        let mut order = self.paint_order.borrow_mut();
1604        let complete = participants.values().all(|participant| {
1605            !participant.registration.paint_order || participant.generation == generation
1606        });
1607        let refresh = if complete {
1608            let mut next = 0;
1609            for id in order.painted.drain(..) {
1610                if let Some(participant) = participants.get_mut(&id)
1611                    && participant.registration.paint_order
1612                {
1613                    next += 1;
1614                    participant.document_order = next;
1615                }
1616            }
1617            order.next = next;
1618            order.dirty = false;
1619            order.refresh_requested = false;
1620            false
1621        } else {
1622            let refresh = order.dirty && !order.refresh_requested;
1623            order.refresh_requested |= refresh;
1624            order.painted.clear();
1625            refresh
1626        };
1627        order.last = None;
1628        self.finish_frame_scheduled.set(false);
1629        self.layer_painted.set(false);
1630        self.frame_generation.set(generation.wrapping_add(1));
1631        refresh
1632    }
1633
1634    fn schedule_finish_frame(&self) -> bool {
1635        !self.finish_frame_scheduled.replace(true)
1636    }
1637
1638    /// Whether there is a selection, or a gesture or touch selection that
1639    /// may make one: what painting the participants reports can change it.
1640    fn is_active(&self) -> bool {
1641        self.anchor.is_some()
1642            || self.cursor.is_some()
1643            || self.pending_extension_anchor.is_some()
1644            || self.is_selecting
1645            || self.refresh_held_cursor.get()
1646            || self.touch.active
1647    }
1648
1649    /// Records one participant in constant time, even during a selection.
1650    /// Full publication belongs to input handling or the end of the frame,
1651    /// never to each participant's draw callback.
1652    fn register_quietly(
1653        &self,
1654        selection: &TextSelectionHandle,
1655        registration: TextSelectionRegistration,
1656    ) {
1657        let mut participants = self.participants.borrow_mut();
1658        let previous = participants.get(&selection.entity_id());
1659        if self.is_selecting
1660            && registration.self_scroll
1661            && self.anchor.as_ref().and_then(SelectionEndpoint::entity_id)
1662                == Some(selection.entity_id())
1663            && previous.is_some_and(|previous| {
1664                previous.registration.scroll_offset != registration.scroll_offset
1665                    || previous.registration.bounds != registration.bounds
1666            })
1667        {
1668            self.refresh_held_cursor.set(true);
1669        }
1670        // The handles sit on the painted ends; when those moved — a scroll, a
1671        // reflow, a select-all — whoever draws the handles needs to know.
1672        if self.touch.active
1673            && previous.is_none_or(|previous| {
1674                previous.registration.selection_edges != registration.selection_edges
1675            })
1676        {
1677            self.touch_edges_moved.set(true);
1678        }
1679        let generation = self.frame_generation.get();
1680        let document_order = if registration.paint_order {
1681            let mut order = self.paint_order.borrow_mut();
1682            let previous = previous.filter(|previous| previous.registration.paint_order);
1683            let number = previous.map_or_else(
1684                || {
1685                    order.next += 1;
1686                    order.dirty = true;
1687                    order.next
1688                },
1689                |previous| previous.document_order,
1690            );
1691            // Reparenting an element changes its keyed marker and may move it
1692            // among retained siblings. Geometry alone is not a topology change:
1693            // scrolling an ancestor moves its text without changing its order.
1694            if previous.is_some_and(|previous| {
1695                previous
1696                    .registration
1697                    .rendered
1698                    .as_ref()
1699                    .map(|marker| marker.entity_id())
1700                    != registration
1701                        .rendered
1702                        .as_ref()
1703                        .map(|marker| marker.entity_id())
1704            }) {
1705                order.dirty = true;
1706            }
1707            let inverted = order.last.is_some_and(|last| last > number);
1708            order.dirty |= inverted;
1709            order.last = Some(number);
1710            // As with geometry, a handle painted twice takes its last position.
1711            order.painted.push(selection.entity_id());
1712            number
1713        } else {
1714            registration.document_order
1715        };
1716        participants.insert(
1717            selection.entity_id(),
1718            ParticipantRegistration {
1719                participant: selection.downgrade(),
1720                registration: Rc::new(registration),
1721                document_order,
1722                generation,
1723            },
1724        );
1725    }
1726
1727    #[cfg(test)]
1728    fn register_participant(
1729        &mut self,
1730        selection: TextSelectionHandle,
1731        registration: TextSelectionRegistration,
1732        cx: &mut App,
1733    ) {
1734        self.register_quietly(&selection, registration);
1735        self.publish_snapshots(cx);
1736    }
1737
1738    /// Starts a selection gesture using bounds hit testing (useful to adapters/tests).
1739    #[cfg(test)]
1740    fn begin(&mut self, position: Point<Pixels>, extend: bool, cx: &mut App) {
1741        self.begin_impl(position, extend, false, None, cx);
1742    }
1743
1744    /// Updates the current gesture using bounds hit testing.
1745    #[cfg(test)]
1746    fn update(&mut self, position: Point<Pixels>, cx: &mut App) {
1747        self.update_impl(position, None, cx);
1748    }
1749
1750    /// Ends the current gesture and keeps its selection visible.
1751    pub fn end(&mut self, cx: &mut App) {
1752        self.pending_extension_anchor = None;
1753        if !self.is_selecting {
1754            return;
1755        }
1756        self.is_selecting = false;
1757        if !self.did_hit_text {
1758            self.anchor = None;
1759            self.cursor = None;
1760        }
1761        self.stop_anchor_auto_scroll(cx);
1762        self.publish_snapshots(cx);
1763    }
1764
1765    /// Clears both window selection and every participant's local selection.
1766    pub fn clear(&mut self, cx: &mut App) {
1767        let handlers = self.clear_state(cx);
1768        dispatch_clear_handlers(handlers, cx);
1769    }
1770
1771    fn clear_state(&mut self, cx: &mut App) -> Vec<ClearHandler> {
1772        self.draw_changed.get_mut().clear();
1773        self.table_cell_anchor.set(None);
1774        self.touch_select_all = false;
1775        self.stop_anchor_auto_scroll(cx);
1776        self.anchor = None;
1777        self.cursor = None;
1778        self.pending_extension_anchor = None;
1779        self.unit = None;
1780        self.is_selecting = false;
1781        self.did_hit_text = false;
1782        if self.touch.reset() {
1783            self.touch_changed(cx);
1784        }
1785        self.prune_dead_participants();
1786        self.participants
1787            .borrow()
1788            .values()
1789            .filter_map(|registration| registration.participant.upgrade())
1790            .filter_map(|participant| participant.update(cx, |state, cx| state.clear_state(cx)))
1791            .collect()
1792    }
1793
1794    /// Tells whoever draws the handles and the menu that they changed.
1795    ///
1796    /// Deferred, because the change may come from a participant painting its
1797    /// selection ends: a notification raised inside a draw marks the view
1798    /// dirty but starts no frame, and the handles would sit where they were
1799    /// until something else redrew the window.
1800    ///
1801    /// The participants in the selection hear it too: they paint the
1802    /// handles, and lay the handles' hitboxes out from the ends they painted
1803    /// last frame, so they render once more. A participant under a cached
1804    /// view would otherwise not, and the next frame would replay this one,
1805    /// with no hitbox where a handle is.
1806    fn touch_changed(&self, cx: &mut App) {
1807        let participants = self
1808            .participants
1809            .borrow()
1810            .values()
1811            .filter_map(|registration| registration.participant.upgrade())
1812            .filter(|participant| participant.read(cx).snapshot.is_some())
1813            .collect::<Vec<_>>();
1814        let entity_id = self.entity_id;
1815        cx.defer(move |cx| {
1816            for participant in participants {
1817                participant.update(cx, |_, cx| {
1818                    cx.emit(TextSelectionEvent::TouchSelectionChanged)
1819                });
1820            }
1821            if let Some(entity_id) = entity_id {
1822                cx.notify(entity_id);
1823            }
1824        });
1825    }
1826
1827    fn copy_items(&self, cx: &App) -> Vec<CopyItem> {
1828        self.participants
1829            .borrow()
1830            .values()
1831            .filter_map(|registration| {
1832                let participant = registration.participant.upgrade()?;
1833                participant.read(cx).copy_item(registration.document_order)
1834            })
1835            .collect()
1836    }
1837
1838    #[cfg(test)]
1839    fn selected_text(&self, cx: &mut App) -> String {
1840        resolve_copy_items(self.copy_items(cx), cx)
1841    }
1842
1843    /// Whether the current endpoints take in at least one character of some
1844    /// participant's painted text, as opposed to two points with nothing
1845    /// between them.
1846    fn selects_text(&self, cx: &App) -> bool {
1847        self.snapshot().is_some()
1848            && self.participants.borrow().values().any(|registration| {
1849                registration
1850                    .participant
1851                    .upgrade()
1852                    .is_some_and(|participant| {
1853                        let participant = participant.read(cx);
1854                        project_ranges(participant.snapshot, &participant.runs.borrow())
1855                            .ranges()
1856                            .iter()
1857                            .any(|range| range.as_ref().is_some_and(|range| !range.is_empty()))
1858                    })
1859            })
1860    }
1861
1862    /// Returns whether a drag or a participant-local selection is active.
1863    pub fn has_selection(&self, cx: &App) -> bool {
1864        self.snapshot().is_some()
1865            || self.participants.borrow().values().any(|registration| {
1866                registration
1867                    .participant
1868                    .upgrade()
1869                    .is_some_and(|participant| participant.read(cx).local_selection)
1870            })
1871    }
1872
1873    /// Returns the current resolved selection endpoints.
1874    pub fn snapshot(&self) -> Option<TextSelectionSnapshot> {
1875        if !self.did_hit_text {
1876            return None;
1877        }
1878        let anchor_endpoint = self.anchor.as_ref()?;
1879        let cursor_endpoint = self.cursor.as_ref()?;
1880        let anchor = anchor_endpoint.resolve(&self.participants.borrow())?;
1881        let cursor = cursor_endpoint.resolve(&self.participants.borrow())?;
1882        (anchor != cursor).then(|| {
1883            TextSelectionSnapshot::new(anchor_endpoint.snapshot(), cursor_endpoint.snapshot())
1884                .with_selecting(self.is_selecting)
1885                .with_window_points(Some(TextSelectionWindowPoints { anchor, cursor }))
1886        })
1887    }
1888
1889    /// Returns whether a drag is currently in progress.
1890    #[cfg(test)]
1891    fn is_selecting(&self) -> bool {
1892        self.is_selecting
1893    }
1894
1895    fn prepare_for_mouse_down(&mut self, extend: bool, cx: &mut App) -> Vec<ClearHandler> {
1896        let pending_extension_anchor = extend.then(|| self.anchor.clone()).flatten();
1897        let unit = extend.then(|| self.unit.take()).flatten();
1898        if !extend {
1899            self.table_cell_anchor.set(None);
1900            self.touch_select_all = false;
1901        }
1902        self.stop_anchor_auto_scroll(cx);
1903        self.anchor = None;
1904        self.cursor = None;
1905        self.pending_extension_anchor = None;
1906        self.unit = unit;
1907        self.is_selecting = false;
1908        self.did_hit_text = false;
1909        if self.touch.reset() {
1910            self.touch_changed(cx);
1911        }
1912        self.prune_dead_participants();
1913        let handlers = self
1914            .participants
1915            .borrow()
1916            .values()
1917            .filter_map(|registration| registration.participant.upgrade())
1918            .filter_map(|participant| participant.update(cx, |state, cx| state.clear_state(cx)))
1919            .collect();
1920        self.pending_extension_anchor = pending_extension_anchor;
1921        handlers
1922    }
1923
1924    /// The touch selection laid out for its handles and edit menu.
1925    ///
1926    /// The ends come from the participants: the first selected character of
1927    /// the earliest participant in document order and the last of the latest.
1928    /// A participant whose selection is entirely scrolled away paints no ends,
1929    /// so the handles disappear with the text they mark.
1930    fn touch_selection(&self) -> Option<TouchSelectionSnapshot> {
1931        if !self.touch.active {
1932            return None;
1933        }
1934        // Each end with its owner's viewport: an end scrolled out of its
1935        // participant gets no handle.
1936        let mut start: Option<(u64, Bounds<Pixels>, bool)> = None;
1937        let mut end: Option<(u64, Bounds<Pixels>, bool)> = None;
1938        for registration in self.participants.borrow().values() {
1939            let geometry = &registration.registration;
1940            if geometry.scope != self.active_scope || registration.participant.upgrade().is_none() {
1941                continue;
1942            }
1943            let Some((edge_start, edge_end)) = geometry.selection_edges else {
1944                continue;
1945            };
1946            let order = registration.document_order;
1947            let viewport = geometry.hitbox.bounds;
1948            if start.is_none_or(|(best, ..)| order < best) {
1949                start = Some((order, edge_start, caret_in_view(edge_start, viewport)));
1950            }
1951            if end.is_none_or(|(best, ..)| order >= best) {
1952                end = Some((order, edge_end, caret_in_view(edge_end, viewport)));
1953            }
1954        }
1955        let edges = match (start, end) {
1956            (Some((_, start, start_visible)), Some((_, end, end_visible))) => {
1957                let edges = (start, end, start_visible, end_visible);
1958                self.touch.last_edges.set(Some(edges));
1959                edges
1960            }
1961            _ if self.touch.drag.is_some() => self.touch.last_edges.get()?,
1962            _ => return None,
1963        };
1964        let (start, end, start_visible, end_visible) = edges;
1965        Some(
1966            TouchSelectionSnapshot::new(start, end)
1967                .with_edge_visible(SelectionEdge::Start, start_visible)
1968                .with_edge_visible(SelectionEdge::End, end_visible)
1969                .with_menu_open(self.touch.menu_open)
1970                .with_dragging(self.touch.drag.map(|drag| drag.edge())),
1971        )
1972    }
1973
1974    /// The handles `participant` paints: the start when no participant
1975    /// earlier in document order has a selection end, the end when none
1976    /// later has. Participants paint in document order, so a later one that
1977    /// takes the end over has registered its ends by the time it asks.
1978    fn touch_handles_of(&self, participant: EntityId) -> Vec<(SelectionEdge, Bounds<Pixels>)> {
1979        if !self.touch.active {
1980            return Vec::new();
1981        }
1982        let Some(own) = self.participants.borrow().get(&participant).cloned() else {
1983            return Vec::new();
1984        };
1985        let Some((start, end)) = own.registration.selection_edges else {
1986            return Vec::new();
1987        };
1988        if start == end {
1989            return Vec::new();
1990        }
1991        let order = own.document_order;
1992        let participants = self.participants.borrow();
1993        let others = participants.iter().filter(|(id, registration)| {
1994            **id != participant
1995                && registration.registration.scope == self.active_scope
1996                && registration.registration.selection_edges.is_some()
1997                && registration.participant.upgrade().is_some()
1998        });
1999        let (mut earlier, mut later) = (false, false);
2000        for (_, registration) in others {
2001            let other = registration.document_order;
2002            earlier |= other < order;
2003            later |= other > order;
2004        }
2005        let viewport = own.registration.hitbox.bounds;
2006        let mut handles = Vec::with_capacity(2);
2007        if !earlier && caret_in_view(start, viewport) {
2008            handles.push((SelectionEdge::Start, start));
2009        }
2010        if !later && caret_in_view(end, viewport) {
2011            handles.push((SelectionEdge::End, end));
2012        }
2013        handles
2014    }
2015
2016    /// Keeps the selection a long press made, and opens the edit menu over it.
2017    fn keep_touch_selection(&mut self, cx: &mut App) {
2018        self.touch.active = self.snapshot().is_some();
2019        self.touch.menu_open = self.touch.active;
2020        self.touch.drag = None;
2021        self.touch_changed(cx);
2022    }
2023
2024    /// Records where the menu is painted this frame.
2025    fn register_touch_ui(&mut self, bounds: Bounds<Pixels>) {
2026        self.touch.ui_bounds.push(bounds);
2027    }
2028
2029    /// Whether a press at `position` acts on the selection instead of
2030    /// replacing it: one on a touch handle, the edit menu or an element
2031    /// marked with [`crate::ElementExt::keep_text_selection`].
2032    fn keeps_selection_at(&self, position: Point<Pixels>, window: &Window) -> bool {
2033        // the bounds first: each hit test walks the frame's hitboxes
2034        self.touch.covers(position)
2035            || self.keep_regions.values().any(|hitbox| {
2036                hitbox.bounds.contains(&position) && hitbox.is_hovered_at(position, window)
2037            })
2038    }
2039
2040    /// Whether `bounds` are where `participant` painted its handles last.
2041    fn handles_painted_at(&self, participant: EntityId, bounds: &[Bounds<Pixels>]) -> bool {
2042        self.touch
2043            .handle_bounds
2044            .get(&participant)
2045            .map_or(bounds.is_empty(), |painted| painted == bounds)
2046    }
2047
2048    /// Records where `participant` painted its handles, which replace those
2049    /// it painted before.
2050    fn register_handles(&mut self, participant: EntityId, bounds: Vec<Bounds<Pixels>>) {
2051        self.touch.handle_bounds.insert(participant, bounds);
2052    }
2053
2054    fn close_edit_menu(&mut self, cx: &mut App) {
2055        if !self.touch.menu_open {
2056            return;
2057        }
2058        self.touch.menu_open = false;
2059        self.touch_changed(cx);
2060    }
2061
2062    /// The handles follow the text, but the menu would sit over whatever
2063    /// scrolls underneath it: it steps aside while a finger scrolls and comes
2064    /// back over the handles once the finger lifts.
2065    fn edit_menu_on_scroll(&mut self, phase: TouchPhase, cx: &mut App) {
2066        if !self.touch.active || self.touch.drag.is_some() {
2067            return;
2068        }
2069        match phase {
2070            TouchPhase::Ended | TouchPhase::Cancelled => {
2071                if !self.touch.menu_open {
2072                    self.touch.menu_open = true;
2073                    self.touch_changed(cx);
2074                }
2075            }
2076            _ => self.close_edit_menu(cx),
2077        }
2078    }
2079
2080    /// Selects all of the participant the touch selection started in.
2081    ///
2082    /// This stays a point selection — anchored on the participant's first
2083    /// line of text, ending on its last — rather than switching the
2084    /// participant to a local select-all: one selection, painted, reported
2085    /// and copied the one way, with handles that drag on from its ends.
2086    fn select_all_touched(&mut self, cx: &mut App) {
2087        if !self.touch.active {
2088            return;
2089        }
2090        let Some((participant, registration)) = self.anchor_registration() else {
2091            return;
2092        };
2093        // From the participant's text runs, not its painted line bounds:
2094        // those are clipped to the viewport, and a message taller than the
2095        // screen would only select what is on it.
2096        let (anchor, cursor) = {
2097            let runs = &participant.read(cx).runs.borrow();
2098            let (Some(first), Some(last)) = (
2099                runs.iter().min_by_key(|run| run.document_order),
2100                runs.iter().max_by_key(|run| run.document_order),
2101            ) else {
2102                return;
2103            };
2104            let (Some(start), Some(end)) = (
2105                first.layout.position_for_index(0),
2106                last.layout.position_for_index(last.text.len()),
2107            ) else {
2108                return;
2109            };
2110            // Just inside the first and the last glyph, mid-line, so both
2111            // land on text.
2112            let inset = px(1.);
2113            (
2114                point(start.x + inset, start.y + first.layout.line_height() / 2.),
2115                point(end.x - inset, end.y + last.layout.line_height() / 2.),
2116            )
2117        };
2118        let content_key_resolver = participant.read(cx).content_key_resolver.clone();
2119        let to_endpoint = |window_point: Point<Pixels>| {
2120            let content_point =
2121                window_point - registration.bounds.origin - registration.scroll_offset;
2122            SelectionEndpoint {
2123                participant: Some(participant.downgrade()),
2124                point: content_point,
2125                inside: true,
2126                inside_text: true,
2127                content_key: None,
2128                content_key_resolver: content_key_resolver
2129                    .clone()
2130                    .map(|resolver| (resolver, content_point)),
2131            }
2132        };
2133        self.table_cell_anchor.set(None);
2134        self.touch_select_all = true;
2135        self.anchor = Some(to_endpoint(anchor));
2136        self.cursor = Some(to_endpoint(cursor));
2137        self.did_hit_text = true;
2138        self.is_selecting = false;
2139        self.touch.menu_open = true;
2140        self.publish_snapshots(cx);
2141        self.touch_changed(cx);
2142    }
2143
2144    /// Starts dragging one end of the touch selection from `finger`.
2145    ///
2146    /// The selection is rebuilt from the painted ends, anchored at the end that
2147    /// stays: a select-all or a word selection becomes an ordinary point
2148    /// selection which the drag then extends.
2149    fn begin_edge_drag(
2150        &mut self,
2151        edge: SelectionEdge,
2152        finger: Point<Pixels>,
2153        window: &mut Window,
2154        cx: &mut App,
2155    ) {
2156        let Some(snapshot) = self.touch_selection() else {
2157            return;
2158        };
2159        let handlers = self.prepare_for_mouse_down(false, cx);
2160        dispatch_clear_handlers(handlers, cx);
2161        let held = snapshot.edge(edge.opposite());
2162        // Just inside the held end, so the anchor lands on the character it
2163        // marks rather than on the boundary between two participants.
2164        let nudge = px(1.);
2165        let anchor_point = match edge {
2166            SelectionEdge::Start => point(held.left() - nudge, held.center().y),
2167            SelectionEdge::End => point(held.left() + nudge, held.center().y),
2168        };
2169        let anchor = self.endpoint(anchor_point, None, cx);
2170        let drag = EdgeDrag::begin(edge, snapshot.edge(edge), finger);
2171        let cursor = self.endpoint(drag.text_position(finger), Some(window), cx);
2172        self.did_hit_text = anchor.inside_text || cursor.inside_text;
2173        self.anchor = Some(anchor);
2174        self.cursor = Some(cursor);
2175        self.is_selecting = true;
2176        self.touch.active = true;
2177        self.touch.menu_open = false;
2178        self.touch.drag = Some(drag);
2179        self.publish_snapshots(cx);
2180        self.touch_changed(cx);
2181    }
2182
2183    fn update_edge_drag(&mut self, finger: Point<Pixels>, window: &Window, cx: &mut Context<Self>) {
2184        let Some(drag) = self.touch.drag else {
2185            return;
2186        };
2187        let before = self.cursor.clone();
2188        self.update_in_window(drag.text_position(finger), window, cx);
2189        // A handle never collapses the selection: at the other end it stops,
2190        // and the finger has to pass that end, onto text, to swap the two.
2191        if !self.selects_text(cx) {
2192            self.cursor = before;
2193            self.publish_snapshots(cx);
2194            return;
2195        }
2196        // Dragging one end past the other swaps them: the cursor now lies
2197        // before the anchor, so the finger holds what became the start.
2198        if let Some(points) = self
2199            .snapshot()
2200            .and_then(|snapshot| snapshot.window_points())
2201        {
2202            let (anchor, cursor) = (points.anchor(), points.cursor());
2203            let cursor_first = cursor.y < anchor.y || (cursor.y == anchor.y && cursor.x < anchor.x);
2204            let edge = if cursor_first {
2205                SelectionEdge::Start
2206            } else {
2207                SelectionEdge::End
2208            };
2209            if let Some(drag) = self.touch.drag.as_mut() {
2210                drag.set_edge(edge);
2211            }
2212        }
2213        self.touch_changed(cx);
2214    }
2215
2216    fn end_edge_drag(&mut self, cx: &mut App) {
2217        if self.touch.drag.take().is_none() {
2218            return;
2219        }
2220        self.end(cx);
2221        self.keep_touch_selection(cx);
2222    }
2223
2224    fn begin_in_window(
2225        &mut self,
2226        position: Point<Pixels>,
2227        extend: bool,
2228        window: &mut Window,
2229        cx: &mut App,
2230    ) {
2231        self.begin_impl(position, extend, true, Some(window), cx);
2232    }
2233
2234    fn update_in_window(
2235        &mut self,
2236        position: Point<Pixels>,
2237        window: &Window,
2238        cx: &mut Context<Self>,
2239    ) {
2240        if !cx.has_active_drag() {
2241            self.update_impl(position, Some(window), cx);
2242            self.update_auto_scroll(position, window, cx);
2243        }
2244    }
2245
2246    /// Selects the word or line under `position`, and returns it.
2247    fn select_at(
2248        &mut self,
2249        position: Point<Pixels>,
2250        click_count: usize,
2251        window: &mut Window,
2252        cx: &mut App,
2253    ) -> Option<SelectionUnit> {
2254        GlobalState::init(cx);
2255        if GlobalState::is_text_selection_suppressed(cx) {
2256            return None;
2257        }
2258        let hit = self.endpoint(position, Some(window), cx);
2259        if !hit.inside_text {
2260            return None;
2261        }
2262        let participant = hit.participant?.upgrade()?;
2263        let (start, end) =
2264            carets_for_multi_click(&participant.read(cx).runs.borrow(), position, click_count)?;
2265        let unit = self.unit_of(&participant, start, end, click_count, cx)?;
2266        self.anchor = Some(unit.start.clone());
2267        self.cursor = Some(unit.end.clone());
2268        self.did_hit_text = true;
2269        self.is_selecting = false;
2270        participant.update(cx, |state, cx| state.focus(window, cx));
2271        self.publish_snapshots(cx);
2272        Some(unit)
2273    }
2274
2275    /// The word or line of `participant` from the caret `start` to the caret
2276    /// `end`, both in window coordinates, that `click_count` clicks selected.
2277    fn unit_of(
2278        &self,
2279        participant: &Entity<SelectableTextState>,
2280        start: Bounds<Pixels>,
2281        end: Bounds<Pixels>,
2282        click_count: usize,
2283        cx: &App,
2284    ) -> Option<SelectionUnit> {
2285        let registration = self
2286            .participants
2287            .borrow()
2288            .get(&participant.entity_id())?
2289            .registration
2290            .clone();
2291        let content_key_resolver = participant.read(cx).content_key_resolver.clone();
2292        let to_endpoint = |point: Point<Pixels>| {
2293            let content_point = point - registration.bounds.origin - registration.scroll_offset;
2294            SelectionEndpoint {
2295                participant: Some(participant.downgrade()),
2296                point: content_point,
2297                inside: true,
2298                inside_text: true,
2299                content_key: None,
2300                content_key_resolver: content_key_resolver
2301                    .clone()
2302                    .map(|resolver| (resolver, content_point)),
2303            }
2304        };
2305        Some(SelectionUnit {
2306            click_count,
2307            start: to_endpoint(start.origin),
2308            end: to_endpoint(end.origin),
2309            row_heights: (start.size.height, end.size.height),
2310        })
2311    }
2312
2313    /// Keeps the gesture of the click that selected `unit` going: a drag
2314    /// from it, until the button is released, and a shift-click after it
2315    /// extend the selection by the same unit.
2316    fn hold_unit(&mut self, unit: SelectionUnit, cx: &mut App) {
2317        self.unit = Some(unit);
2318        self.is_selecting = true;
2319        self.publish_snapshots(cx);
2320    }
2321
2322    /// Moves the cursor to the edge of the unit at `position`, which
2323    /// `endpoint` hit, and the anchor to the far edge of `unit`. A pointer
2324    /// over no text moves the cursor to itself, as a plain drag does.
2325    fn extend_unit(
2326        &mut self,
2327        unit: &SelectionUnit,
2328        position: Point<Pixels>,
2329        endpoint: SelectionEndpoint,
2330        cx: &App,
2331    ) {
2332        let (start, end) = {
2333            let participants = self.participants.borrow();
2334            (
2335                unit.start.resolve(&participants),
2336                unit.end.resolve(&participants),
2337            )
2338        };
2339        let (Some(start), Some(end)) = (start, end) else {
2340            self.did_hit_text |= endpoint.inside_text;
2341            self.cursor = Some(endpoint);
2342            return;
2343        };
2344        let (start_height, end_height) = unit.row_heights;
2345        let before =
2346            position.y < start.y || (position.y < start.y + start_height && position.x < start.x);
2347        let after = position.y >= end.y + end_height || (position.y >= end.y && position.x > end.x);
2348        if !before && !after {
2349            // A participant's own multi-click selection stands until the
2350            // pointer leaves it.
2351            if self.anchor.is_some() {
2352                self.anchor = Some(unit.start.clone());
2353                self.cursor = Some(unit.end.clone());
2354                self.did_hit_text = true;
2355            }
2356            return;
2357        }
2358        let (edge, anchor) = if before {
2359            (SelectionEdge::Start, &unit.end)
2360        } else {
2361            (SelectionEdge::End, &unit.start)
2362        };
2363        let cursor = Self::unit_edge_at(&endpoint, position, unit.click_count, edge, cx);
2364        self.anchor = Some(anchor.clone());
2365        self.cursor = Some(cursor.unwrap_or(endpoint));
2366        self.did_hit_text = true;
2367    }
2368
2369    /// `endpoint`, hit at `position`, moved to the `edge` of the word or line
2370    /// under the pointer.
2371    fn unit_edge_at(
2372        endpoint: &SelectionEndpoint,
2373        position: Point<Pixels>,
2374        click_count: usize,
2375        edge: SelectionEdge,
2376        cx: &App,
2377    ) -> Option<SelectionEndpoint> {
2378        if !endpoint.inside {
2379            return None;
2380        }
2381        let participant = endpoint.participant.as_ref()?.upgrade()?;
2382        let runs = participant.read(cx).runs.borrow();
2383        let run = runs.iter().find(|run| run.bounds.contains(&position))?;
2384        if run.text.len() != run.layout.len() {
2385            return None;
2386        }
2387        // Past the end of a row, the pointer takes the character closest to it.
2388        let offset = run
2389            .layout
2390            .index_for_position(position)
2391            .unwrap_or_else(|closest| closest);
2392        let (start, end) = unit_carets(run, offset, click_count)?;
2393        let caret = match edge {
2394            SelectionEdge::Start => start,
2395            SelectionEdge::End => end,
2396        };
2397        Some(endpoint.moved(caret.origin - position))
2398    }
2399
2400    #[cfg(test)]
2401    fn update_in_window_with_active_drag(
2402        &mut self,
2403        position: Point<Pixels>,
2404        active_drag: bool,
2405        window: &Window,
2406        cx: &mut App,
2407    ) {
2408        if !active_drag {
2409            self.update_impl(position, Some(window), cx);
2410        }
2411    }
2412
2413    fn begin_impl(
2414        &mut self,
2415        position: Point<Pixels>,
2416        extend: bool,
2417        already_prepared: bool,
2418        window: Option<&mut Window>,
2419        cx: &mut App,
2420    ) {
2421        GlobalState::init(cx);
2422        if GlobalState::is_text_selection_suppressed(cx) {
2423            self.pending_extension_anchor = None;
2424            return;
2425        }
2426        let previous_anchor = extend
2427            .then(|| {
2428                self.pending_extension_anchor
2429                    .take()
2430                    .or_else(|| self.anchor.clone())
2431            })
2432            .flatten()
2433            .filter(|anchor| anchor.resolve(&self.participants.borrow()).is_some());
2434        if !extend && !already_prepared {
2435            self.clear(cx);
2436        }
2437        let endpoint = self.endpoint(position, window.as_deref(), cx);
2438        let focus_participant = endpoint
2439            .inside
2440            .then(|| endpoint.participant.clone())
2441            .flatten();
2442        let anchor = previous_anchor.unwrap_or_else(|| endpoint.clone());
2443        self.anchor = Some(anchor.clone());
2444        self.cursor = Some(endpoint.clone());
2445        self.did_hit_text = anchor.inside_text || endpoint.inside_text;
2446        self.is_selecting = true;
2447        // A shift-click after a double or triple click extends by its unit.
2448        if let Some(unit) = extend.then(|| self.unit.clone()).flatten() {
2449            self.extend_unit(&unit, position, endpoint, cx);
2450        }
2451        if let Some(participant) = focus_participant.and_then(|participant| participant.upgrade()) {
2452            if let Some(window) = window {
2453                participant.update(cx, |state, cx| state.focus(window, cx));
2454            }
2455        }
2456        self.publish_snapshots(cx);
2457    }
2458
2459    fn update_impl(&mut self, position: Point<Pixels>, window: Option<&Window>, cx: &mut App) {
2460        if !self.is_selecting {
2461            return;
2462        }
2463        let endpoint = self.endpoint(position, window, cx);
2464        match self.unit.clone() {
2465            Some(unit) => self.extend_unit(&unit, position, endpoint, cx),
2466            None => {
2467                self.did_hit_text |= endpoint.inside_text;
2468                self.cursor = Some(endpoint);
2469            }
2470        }
2471        if window.is_none() {
2472            self.update_participant_auto_scroll(position, cx);
2473        }
2474        self.publish_snapshots(cx);
2475    }
2476
2477    fn endpoint(
2478        &mut self,
2479        position: Point<Pixels>,
2480        window: Option<&Window>,
2481        cx: &App,
2482    ) -> SelectionEndpoint {
2483        self.prune_dead_participants();
2484        let mut hit: Option<(ParticipantRegistration, f32)> = None;
2485        let mut predecessor: Option<ParticipantRegistration> = None;
2486        let mut first: Option<ParticipantRegistration> = None;
2487
2488        for registration in self.participants.borrow().values() {
2489            if registration.registration.scope != self.active_scope
2490                || registration.participant.upgrade().is_none()
2491            {
2492                continue;
2493            }
2494            let participant_geometry = &registration.registration;
2495            let hovered = window.map_or_else(
2496                || participant_geometry.bounds.contains(&position),
2497                |window| participant_geometry.hitbox.is_hovered(window),
2498            );
2499            if hovered {
2500                let area = f32::from(participant_geometry.bounds.size.width)
2501                    * f32::from(participant_geometry.bounds.size.height);
2502                if hit.as_ref().is_none_or(|(best, best_area)| {
2503                    area < *best_area
2504                        || (area == *best_area && registration.document_order < best.document_order)
2505                }) {
2506                    hit = Some((registration.clone(), area));
2507                }
2508            }
2509            if participant_geometry.bounds.top() <= position.y
2510                && predecessor.as_ref().is_none_or(|best| {
2511                    participant_geometry.bounds.top() > best.registration.bounds.top()
2512                        || (participant_geometry.bounds.top() == best.registration.bounds.top()
2513                            && registration.document_order < best.document_order)
2514                })
2515            {
2516                predecessor = Some(registration.clone());
2517            }
2518            if first.as_ref().is_none_or(|best| {
2519                participant_geometry.bounds.top() < best.registration.bounds.top()
2520                    || (participant_geometry.bounds.top() == best.registration.bounds.top()
2521                        && registration.document_order < best.document_order)
2522            }) {
2523                first = Some(registration.clone());
2524            }
2525        }
2526
2527        let selection = hit.map(|(participant, _)| (participant, true)).or_else(|| {
2528            predecessor
2529                .or(first)
2530                .map(|participant| (participant, false))
2531        });
2532        match selection {
2533            Some((participant, inside)) => {
2534                let registration = participant.registration;
2535                let participant = participant.participant;
2536                let point = position - registration.bounds.origin - registration.scroll_offset;
2537                let content_key_resolver = participant.upgrade().and_then(|participant| {
2538                    participant
2539                        .read(cx)
2540                        .content_key_resolver
2541                        .clone()
2542                        .map(|callback| (callback, point))
2543                });
2544                SelectionEndpoint {
2545                    point,
2546                    participant: Some(participant),
2547                    inside,
2548                    inside_text: inside
2549                        && registration
2550                            .text_bounds
2551                            .iter()
2552                            .any(|bounds| bounds.contains(&position)),
2553                    content_key: None,
2554                    content_key_resolver,
2555                }
2556            }
2557            None => SelectionEndpoint {
2558                participant: None,
2559                point: position,
2560                inside: false,
2561                inside_text: false,
2562                content_key: None,
2563                content_key_resolver: None,
2564            },
2565        }
2566    }
2567
2568    fn publish_snapshots(&mut self, cx: &mut App) {
2569        self.prune_dead_participants();
2570        for (participant, snapshot) in self.changed_snapshots(cx) {
2571            self.draw_changed.get_mut().remove(&participant.entity_id());
2572            participant.update(cx, |state, cx| state.set_snapshot(snapshot, cx));
2573        }
2574    }
2575
2576    fn participant_snapshot(&self, id: EntityId) -> Option<TextSelectionSnapshot> {
2577        #[cfg(test)]
2578        self.snapshot_visits.set(self.snapshot_visits.get() + 1);
2579
2580        let participants = self.participants.borrow();
2581        let registration = participants.get(&id)?;
2582        (registration.registration.scope == self.active_scope
2583            && self.participates(id, registration)
2584            && self.single_participant().is_none_or(|single| single == id))
2585        .then(|| self.snapshot())
2586        .flatten()
2587        .map(|mut snapshot| {
2588            snapshot.coverage = self.coverage_for(id);
2589            snapshot
2590        })
2591    }
2592
2593    fn changed_snapshots(
2594        &self,
2595        cx: &App,
2596    ) -> Vec<(Entity<SelectableTextState>, Option<TextSelectionSnapshot>)> {
2597        self.participants
2598            .borrow()
2599            .iter()
2600            .filter_map(|(id, registration)| {
2601                let participant = registration.participant.upgrade()?;
2602                let snapshot = self.participant_snapshot(*id);
2603                (participant.read(cx).snapshot != snapshot).then_some((participant, snapshot))
2604            })
2605            .collect()
2606    }
2607
2608    fn coverage_for(&self, id: EntityId) -> TextSelectionCoverage {
2609        let Some(anchor) = self.anchor.as_ref().and_then(SelectionEndpoint::entity_id) else {
2610            return TextSelectionCoverage::Bounded;
2611        };
2612        let Some(cursor) = self.cursor.as_ref().and_then(SelectionEndpoint::entity_id) else {
2613            return TextSelectionCoverage::Bounded;
2614        };
2615        if anchor == cursor {
2616            return TextSelectionCoverage::Bounded;
2617        }
2618        let anchor_order = self.participants.borrow()[&anchor].document_order;
2619        let cursor_order = self.participants.borrow()[&cursor].document_order;
2620        if id != anchor && id != cursor {
2621            TextSelectionCoverage::Full
2622        } else if (id == anchor) == (anchor_order < cursor_order) {
2623            TextSelectionCoverage::ToEnd
2624        } else {
2625            TextSelectionCoverage::FromStart
2626        }
2627    }
2628
2629    fn single_participant(&self) -> Option<EntityId> {
2630        let anchor = self.anchor.as_ref()?.entity_id()?;
2631        let cursor = self.cursor.as_ref()?.entity_id()?;
2632        (anchor == cursor).then_some(anchor)
2633    }
2634
2635    fn participates(&self, id: EntityId, registration: &ParticipantRegistration) -> bool {
2636        let Some(anchor) = self.anchor.as_ref().and_then(SelectionEndpoint::entity_id) else {
2637            return false;
2638        };
2639        let Some(cursor) = self.cursor.as_ref().and_then(SelectionEndpoint::entity_id) else {
2640            return false;
2641        };
2642        let Some(anchor_registration) = self.participants.borrow().get(&anchor).cloned() else {
2643            return false;
2644        };
2645        let Some(cursor_registration) = self.participants.borrow().get(&cursor).cloned() else {
2646            return false;
2647        };
2648        let start = anchor_registration
2649            .document_order
2650            .min(cursor_registration.document_order);
2651        let end = anchor_registration
2652            .document_order
2653            .max(cursor_registration.document_order);
2654        (start..=end).contains(&registration.document_order) || id == anchor || id == cursor
2655    }
2656
2657    fn update_auto_scroll(
2658        &mut self,
2659        position: Point<Pixels>,
2660        window: &Window,
2661        cx: &mut Context<Self>,
2662    ) {
2663        // A finished gesture keeps its anchor for shift-click extension; only
2664        // a live drag may scroll.
2665        if !self.is_selecting {
2666            return;
2667        }
2668        let Some((_, registration)) = self.anchor_registration() else {
2669            return;
2670        };
2671        // Exactly one writer per drag: a participant that scrolls its own
2672        // content is notified directly; anything else gets a synthetic wheel.
2673        if registration.self_scroll {
2674            self.auto_scroll.stop();
2675            self.update_participant_auto_scroll(position, cx);
2676            return;
2677        }
2678        // Keeps the synthesized wheel event hit-testing inside the viewport.
2679        const HIT_TEST_INSET: Pixels = px(1.);
2680        // No text is hidden in either direction, or the viewport leaves an
2681        // empty clamp range below — stop.
2682        let Some(visible_bounds) = self.auto_scroll_viewport(&registration).filter(|bounds| {
2683            bounds.size.width >= HIT_TEST_INSET * 2. && bounds.size.height >= HIT_TEST_INSET * 2.
2684        }) else {
2685            self.stop_anchor_auto_scroll(cx);
2686            return;
2687        };
2688        let delta = AutoScroll::compute_delta(position.y, visible_bounds);
2689        let event_position = point(
2690            position.x.clamp(
2691                visible_bounds.left() + HIT_TEST_INSET,
2692                visible_bounds.right() - HIT_TEST_INSET,
2693            ),
2694            position.y.clamp(
2695                visible_bounds.top() + HIT_TEST_INSET,
2696                visible_bounds.bottom() - HIT_TEST_INSET,
2697            ),
2698        );
2699        self.auto_scroll.last_drag_position = Some(event_position);
2700        self.auto_scroll_stall = (None, 0);
2701        let window = window.window_handle();
2702        self.auto_scroll.set(delta, cx, move |delta, state, cx| {
2703            let Some(position) = state.auto_scroll.last_drag_position else {
2704                return;
2705            };
2706            // Hold off once the container has shown, over a few ticks, that
2707            // it has nowhere left to go; the next move of the finger asks
2708            // again.
2709            const STALLED_TICKS: u8 = 3;
2710            let geometry = state
2711                .anchor_registration()
2712                .map(|(_, registration)| (registration.bounds, registration.scroll_offset));
2713            let (last, stalled) = &mut state.auto_scroll_stall;
2714            if *last == geometry {
2715                *stalled = stalled.saturating_add(1);
2716                if *stalled >= STALLED_TICKS {
2717                    return;
2718                }
2719            } else {
2720                *last = geometry;
2721                *stalled = 0;
2722            }
2723            let window = window;
2724            cx.defer(move |cx| {
2725                _ = window.update(cx, |_, window, cx| {
2726                    window.dispatch_event(
2727                        ScrollEvent {
2728                            position,
2729                            delta: ScrollDelta::Pixels(point(px(0.), -delta)),
2730                            ..Default::default()
2731                        }
2732                        .to_platform_input(),
2733                        cx,
2734                    );
2735                });
2736            });
2737        });
2738    }
2739
2740    /// The viewport a drag scrolls: between the nearest edges above and below
2741    /// `anchor` that cut selectable text off. A clip that hides no text, such as
2742    /// a rounded card around the anchor, is not an edge. A side with no hidden
2743    /// text has no edge, so the pointer never reaches it and nothing scrolls
2744    /// that way. `None` when no text is hidden at all.
2745    ///
2746    /// The edges stay where they are while the content scrolls, so a drag keeps
2747    /// scrolling the same region after the anchor has moved out of view.
2748    fn auto_scroll_viewport(&self, anchor: &TextSelectionRegistration) -> Option<Bounds<Pixels>> {
2749        // Farther than any pointer position, for a side with no edge.
2750        const NO_EDGE: Pixels = px(1e7);
2751        let anchor_mask = anchor.hitbox.content_mask.bounds;
2752        let mut top = None::<Pixels>;
2753        let mut bottom = None::<Pixels>;
2754        for participant in self.participants.borrow().values() {
2755            let registration = &participant.registration;
2756            if registration.scope != self.active_scope {
2757                continue;
2758            }
2759            let mask = registration.hitbox.content_mask.bounds;
2760            if registration.bounds.top() < mask.top() && mask.top() <= anchor_mask.top() {
2761                top = Some(top.map_or(mask.top(), |top| top.max(mask.top())));
2762            }
2763            if registration.bounds.bottom() > mask.bottom() && mask.bottom() >= anchor_mask.bottom()
2764            {
2765                bottom = Some(bottom.map_or(mask.bottom(), |bottom| bottom.min(mask.bottom())));
2766            }
2767        }
2768        if top.is_none() && bottom.is_none() {
2769            return None;
2770        }
2771        Some(Bounds::from_corners(
2772            point(anchor_mask.left(), top.unwrap_or(-NO_EDGE)),
2773            point(anchor_mask.right(), bottom.unwrap_or(NO_EDGE)),
2774        ))
2775    }
2776
2777    /// Drives the anchor participant's own scrolling, measured against the
2778    /// visible portion of the participant's element bounds.
2779    fn update_participant_auto_scroll(&self, position: Point<Pixels>, cx: &mut App) {
2780        let Some((participant, registration)) = self.anchor_registration() else {
2781            return;
2782        };
2783        let visible_bounds = registration
2784            .bounds
2785            .intersect(&registration.hitbox.content_mask.bounds);
2786        let delta = if visible_bounds.size.width > px(0.) && visible_bounds.size.height > px(0.) {
2787            AutoScroll::compute_delta(position.y, visible_bounds)
2788        } else {
2789            None
2790        };
2791        participant.update(cx, |state, cx| state.set_auto_scroll(delta, cx));
2792    }
2793
2794    fn stop_anchor_auto_scroll(&mut self, cx: &mut App) {
2795        self.auto_scroll.stop();
2796        let Some(participant) = self.anchor_participant() else {
2797            return;
2798        };
2799        participant.update(cx, |state, cx| state.set_auto_scroll(None, cx));
2800    }
2801
2802    /// The live participant owning the anchor of the current gesture.
2803    fn anchor_participant(&self) -> Option<Entity<SelectableTextState>> {
2804        self.anchor
2805            .as_ref()
2806            .filter(|anchor| anchor.inside)?
2807            .participant
2808            .as_ref()?
2809            .upgrade()
2810    }
2811
2812    /// The anchor participant together with its current frame registration.
2813    fn anchor_registration(
2814        &self,
2815    ) -> Option<(Entity<SelectableTextState>, Rc<TextSelectionRegistration>)> {
2816        let participant = self.anchor_participant()?;
2817        let registration = self
2818            .participants
2819            .borrow()
2820            .get(&participant.entity_id())?
2821            .clone();
2822        Some((participant, registration.registration))
2823    }
2824
2825    fn prune_dead_participants(&mut self) {
2826        self.participants
2827            .get_mut()
2828            .retain(|_, registration| registration.participant.upgrade().is_some());
2829    }
2830}
2831
2832#[derive(Default)]
2833/// Non-owning window locator; retained [`TextSelection`] element state owns
2834/// each live selection entity.
2835struct SelectionStateRegistry(HashMap<gpui::WindowId, WeakEntity<WindowSelectionState>>);
2836
2837impl Global for SelectionStateRegistry {}
2838
2839#[derive(Default)]
2840struct PendingTextSelectionScopes(HashMap<gpui::WindowId, TextSelectionScopeId>);
2841
2842impl Global for PendingTextSelectionScopes {}
2843
2844#[derive(Default)]
2845struct TextSelectionScopeStacks(HashMap<gpui::WindowId, Vec<TextSelectionScopeId>>);
2846
2847impl Global for TextSelectionScopeStacks {}
2848
2849fn push_text_selection_scope(window_id: gpui::WindowId, scope: TextSelectionScopeId, cx: &mut App) {
2850    if !cx.has_global::<TextSelectionScopeStacks>() {
2851        cx.set_global(TextSelectionScopeStacks::default());
2852    }
2853    cx.global_mut::<TextSelectionScopeStacks>()
2854        .0
2855        .entry(window_id)
2856        .or_default()
2857        .push(scope);
2858}
2859
2860fn pop_text_selection_scope(window_id: gpui::WindowId, cx: &mut App) {
2861    let stacks = &mut cx.global_mut::<TextSelectionScopeStacks>().0;
2862    let remove_stack = stacks.get_mut(&window_id).is_some_and(|stack| {
2863        stack.pop();
2864        stack.is_empty()
2865    });
2866    if remove_stack {
2867        stacks.remove(&window_id);
2868    }
2869}
2870
2871fn current_text_selection_scope(
2872    window_id: gpui::WindowId,
2873    cx: &App,
2874) -> Option<TextSelectionScopeId> {
2875    cx.has_global::<TextSelectionScopeStacks>()
2876        .then(|| {
2877            cx.global::<TextSelectionScopeStacks>()
2878                .0
2879                .get(&window_id)
2880                .and_then(|stack| stack.last().copied())
2881        })
2882        .flatten()
2883}
2884
2885fn with_text_selection_scope<T>(
2886    window_id: gpui::WindowId,
2887    scope: TextSelectionScopeId,
2888    cx: &mut App,
2889    callback: impl FnOnce(&mut App) -> T,
2890) -> T {
2891    push_text_selection_scope(window_id, scope, cx);
2892    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| callback(cx)));
2893    pop_text_selection_scope(window_id, cx);
2894    match result {
2895        Ok(result) => result,
2896        Err(payload) => std::panic::resume_unwind(payload),
2897    }
2898}
2899
2900/// Window-level operations for text selection.
2901pub struct TextSelection;
2902
2903impl TextSelection {
2904    /// Returns whether `position` hits selectable text in the active scope.
2905    ///
2906    /// Uses the current frame's registered text geometry and hitboxes without
2907    /// starting or changing a selection. Blank space and text outside the active
2908    /// selection scope do not match. A containing control can yield a long press
2909    /// to the window's text selection before claiming the gesture itself.
2910    /// Call during pointer dispatch with the event's position, so the hitboxes
2911    /// reflect the point being queried. Touch-selection controls and the
2912    /// elements marked with [`crate::ElementExt::keep_text_selection`] do not
2913    /// match.
2914    pub fn is_selectable_at(position: Point<Pixels>, window: &Window, cx: &mut App) -> bool {
2915        live_text_selection_state(window, cx).is_some_and(|state| {
2916            state.update(cx, |state, cx| {
2917                !state.keeps_selection_at(position, window)
2918                    && state.endpoint(position, Some(window), cx).inside_text
2919            })
2920        })
2921    }
2922
2923    /// Returns the currently selected text in logical document order.
2924    pub fn selected_text(window: &mut Window, cx: &mut App) -> String {
2925        let Some(state) = live_text_selection_state(window, cx) else {
2926            return String::new();
2927        };
2928        let items = state.read(cx).copy_items(cx);
2929        resolve_copy_items(items, cx)
2930    }
2931
2932    /// Returns whether the window has a geometry selection or any participant
2933    /// has an active participant-local selection such as select-all.
2934    pub fn has_selection(window: &mut Window, cx: &mut App) -> bool {
2935        live_text_selection_state(window, cx).is_some_and(|state| state.read(cx).has_selection(cx))
2936    }
2937
2938    /// Clears window selection and every participant's local selection.
2939    pub fn clear(window: &mut Window, cx: &mut App) {
2940        if let Some(state) = live_text_selection_state(window, cx) {
2941            let handlers = state.update(cx, |state, cx| state.clear_state(cx));
2942            dispatch_clear_handlers(handlers, cx);
2943        }
2944    }
2945
2946    /// Clears selection for a known window identifier.
2947    ///
2948    /// Prefer [`Self::clear`] when a window reference is available. This
2949    /// narrow entry point supports hosts retiring deprecated window wrappers.
2950    pub fn clear_for_window(window_id: gpui::WindowId, cx: &mut App) {
2951        clear_window_text_selection(window_id, cx);
2952    }
2953
2954    /// Ends the current drag while leaving its selection visible.
2955    pub fn end(window: &mut Window, cx: &mut App) {
2956        if let Some(state) = live_text_selection_state(window, cx) {
2957            state.update(cx, |state, cx| state.end(cx));
2958        }
2959    }
2960
2961    /// Calls `callback` whenever the touch selection changes: it appears, its
2962    /// handles move, its menu opens or closes, or it goes away. Whoever draws
2963    /// the handles and the menu re-renders from here.
2964    pub fn observe_touch_selection(
2965        window: &Window,
2966        cx: &mut App,
2967        callback: impl Fn(&mut App) + 'static,
2968    ) -> Subscription {
2969        let state = WindowSelectionState::acquire(window.window_handle().window_id(), cx);
2970        cx.observe(&state, move |_, cx| callback(cx))
2971    }
2972
2973    /// Returns the selection a long press made, laid out for its handles and
2974    /// edit menu, or `None` when the selection was made with a pointer.
2975    pub fn touch_selection(window: &Window, cx: &App) -> Option<TouchSelectionSnapshot> {
2976        WindowSelectionState::existing(window, cx)?
2977            .read(cx)
2978            .touch_selection()
2979    }
2980
2981    /// Records where a touch handle or the edit menu is painted this frame, so
2982    /// that pressing it does not clear the selection it belongs to. Call from
2983    /// paint, every frame the surface is shown.
2984    pub fn register_touch_ui(bounds: Bounds<Pixels>, window: &Window, cx: &mut App) {
2985        if let Some(state) = WindowSelectionState::existing(window, cx) {
2986            state.update(cx, |state, _| state.register_touch_ui(bounds));
2987        }
2988    }
2989
2990    /// Closes the edit menu and keeps the selection with its handles.
2991    pub fn close_edit_menu(window: &mut Window, cx: &mut App) {
2992        if let Some(state) = live_text_selection_state(window, cx) {
2993            state.update(cx, |state, cx| state.close_edit_menu(cx));
2994        }
2995    }
2996
2997    /// Selects all of the text the touch selection started in, keeping the
2998    /// handles and the edit menu over the result.
2999    pub fn select_all(window: &mut Window, cx: &mut App) {
3000        if let Some(state) = live_text_selection_state(window, cx) {
3001            state.update(cx, |state, cx| state.select_all_touched(cx));
3002        }
3003    }
3004
3005    /// Starts dragging one end of the touch selection from `finger`. The other
3006    /// end stays; the menu closes until [`Self::end_edge_drag`].
3007    pub fn begin_edge_drag(
3008        edge: SelectionEdge,
3009        finger: Point<Pixels>,
3010        window: &mut Window,
3011        cx: &mut App,
3012    ) {
3013        if let Some(state) = live_text_selection_state(window, cx) {
3014            state.update(cx, |state, cx| {
3015                state.begin_edge_drag(edge, finger, window, cx)
3016            });
3017            WindowSelectionState::resolve_content_keys(&state, cx);
3018        }
3019    }
3020
3021    /// Moves the dragged end to the text under `finger`.
3022    pub fn update_edge_drag(finger: Point<Pixels>, window: &mut Window, cx: &mut App) {
3023        if let Some(state) = live_text_selection_state(window, cx) {
3024            state.update(cx, |state, cx| state.update_edge_drag(finger, window, cx));
3025            WindowSelectionState::resolve_content_keys(&state, cx);
3026        }
3027    }
3028
3029    /// Ends the handle drag and reopens the edit menu over the result.
3030    pub fn end_edge_drag(window: &mut Window, cx: &mut App) {
3031        if let Some(state) = live_text_selection_state(window, cx) {
3032            state.update(cx, |state, cx| state.end_edge_drag(cx));
3033        }
3034    }
3035
3036    /// Activates the opaque selection scope for this window.
3037    pub fn activate_scope(scope: TextSelectionScopeId, window: &mut Window, cx: &mut App) {
3038        let Some(state) = WindowSelectionState::existing(window, cx) else {
3039            if !cx.has_global::<PendingTextSelectionScopes>() {
3040                cx.set_global(PendingTextSelectionScopes::default());
3041            }
3042            cx.global_mut::<PendingTextSelectionScopes>()
3043                .0
3044                .insert(window.window_handle().window_id(), scope);
3045            return;
3046        };
3047        if state.read(cx).active_scope == scope {
3048            return;
3049        }
3050        let handlers = state.update(cx, |state, cx| state.set_active_scope_state(scope, cx));
3051        dispatch_clear_handlers(handlers, cx);
3052    }
3053}
3054
3055/// A zero-sized root layer which enables text selection for a window.
3056///
3057/// Mount one as the root's first child. Its stable `"window-text-selection"`
3058/// element identity retains the window-local selection entity across frames.
3059pub struct TextSelectionLayer;
3060
3061pub(crate) fn keep_text_selection(id: ElementId) -> impl IntoElement {
3062    KeepTextSelection { id }
3063}
3064
3065/// Covers its parent with a hitbox where a press keeps the selection.
3066struct KeepTextSelection {
3067    id: ElementId,
3068}
3069
3070impl Element for KeepTextSelection {
3071    type RequestLayoutState = ();
3072    type PrepaintState = ();
3073
3074    fn id(&self) -> Option<ElementId> {
3075        Some(self.id.clone())
3076    }
3077
3078    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
3079        None
3080    }
3081
3082    fn request_layout(
3083        &mut self,
3084        _: Option<&GlobalElementId>,
3085        _: Option<&InspectorElementId>,
3086        window: &mut Window,
3087        cx: &mut App,
3088    ) -> (LayoutId, Self::RequestLayoutState) {
3089        // Without an inset, an absolute child starts after the padding but is
3090        // still sized to the padding box, overhanging the far edges.
3091        let mut style = Style::default();
3092        style.position = gpui::Position::Absolute;
3093        style.inset.top = px(0.).into();
3094        style.inset.left = px(0.).into();
3095        style.size = gpui::size(gpui::relative(1.).into(), gpui::relative(1.).into());
3096        (window.request_layout(style, [], cx), ())
3097    }
3098
3099    fn prepaint(
3100        &mut self,
3101        id: Option<&GlobalElementId>,
3102        _: Option<&InspectorElementId>,
3103        bounds: Bounds<Pixels>,
3104        _: &mut Self::RequestLayoutState,
3105        window: &mut Window,
3106        cx: &mut App,
3107    ) -> Self::PrepaintState {
3108        // `Normal`: the element under it is still hovered and clicked.
3109        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
3110        if let (Some(id), Some(state)) = (id, WindowSelectionState::existing(window, cx)) {
3111            state.update(cx, |state, _| {
3112                state.keep_regions.insert(id.clone(), hitbox);
3113            });
3114        }
3115    }
3116
3117    fn paint(
3118        &mut self,
3119        _: Option<&GlobalElementId>,
3120        _: Option<&InspectorElementId>,
3121        _: Bounds<Pixels>,
3122        _: &mut Self::RequestLayoutState,
3123        _: &mut Self::PrepaintState,
3124        _: &mut Window,
3125        _: &mut App,
3126    ) {
3127    }
3128}
3129
3130pub(crate) fn text_selection_scope(
3131    scope: TextSelectionScopeId,
3132    element: impl IntoElement,
3133) -> impl IntoElement {
3134    TextSelectionScopeMarker {
3135        scope,
3136        element: element.into_element(),
3137    }
3138}
3139
3140struct TextSelectionScopeMarker<E> {
3141    scope: TextSelectionScopeId,
3142    element: E,
3143}
3144
3145impl<E: Element> Element for TextSelectionScopeMarker<E> {
3146    type RequestLayoutState = E::RequestLayoutState;
3147    type PrepaintState = E::PrepaintState;
3148
3149    fn id(&self) -> Option<ElementId> {
3150        self.element.id()
3151    }
3152
3153    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
3154        self.element.source_location()
3155    }
3156
3157    fn request_layout(
3158        &mut self,
3159        id: Option<&GlobalElementId>,
3160        inspector_id: Option<&InspectorElementId>,
3161        window: &mut Window,
3162        cx: &mut App,
3163    ) -> (LayoutId, Self::RequestLayoutState) {
3164        let window_id = window.window_handle().window_id();
3165        with_text_selection_scope(window_id, self.scope, cx, |cx| {
3166            self.element.request_layout(id, inspector_id, window, cx)
3167        })
3168    }
3169
3170    fn prepaint(
3171        &mut self,
3172        id: Option<&GlobalElementId>,
3173        inspector_id: Option<&InspectorElementId>,
3174        bounds: Bounds<Pixels>,
3175        request_layout: &mut Self::RequestLayoutState,
3176        window: &mut Window,
3177        cx: &mut App,
3178    ) -> Self::PrepaintState {
3179        let window_id = window.window_handle().window_id();
3180        with_text_selection_scope(window_id, self.scope, cx, |cx| {
3181            self.element
3182                .prepaint(id, inspector_id, bounds, request_layout, window, cx)
3183        })
3184    }
3185
3186    fn paint(
3187        &mut self,
3188        id: Option<&GlobalElementId>,
3189        inspector_id: Option<&InspectorElementId>,
3190        bounds: Bounds<Pixels>,
3191        request_layout: &mut Self::RequestLayoutState,
3192        prepaint: &mut Self::PrepaintState,
3193        window: &mut Window,
3194        cx: &mut App,
3195    ) {
3196        let window_id = window.window_handle().window_id();
3197        with_text_selection_scope(window_id, self.scope, cx, |cx| {
3198            self.element.paint(
3199                id,
3200                inspector_id,
3201                bounds,
3202                request_layout,
3203                prepaint,
3204                window,
3205                cx,
3206            );
3207        });
3208    }
3209}
3210
3211#[doc(hidden)]
3212pub struct TextSelectionLayerPrepaintState(Entity<WindowSelectionState>);
3213
3214impl Element for TextSelectionLayer {
3215    type RequestLayoutState = ();
3216    type PrepaintState = TextSelectionLayerPrepaintState;
3217
3218    fn id(&self) -> Option<ElementId> {
3219        Some("window-text-selection".into())
3220    }
3221
3222    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
3223        None
3224    }
3225
3226    fn request_layout(
3227        &mut self,
3228        _: Option<&GlobalElementId>,
3229        _: Option<&InspectorElementId>,
3230        window: &mut Window,
3231        cx: &mut App,
3232    ) -> (LayoutId, Self::RequestLayoutState) {
3233        (window.request_layout(Style::default(), [], cx), ())
3234    }
3235
3236    fn prepaint(
3237        &mut self,
3238        global_id: Option<&GlobalElementId>,
3239        _: Option<&InspectorElementId>,
3240        _: Bounds<Pixels>,
3241        _: &mut Self::RequestLayoutState,
3242        window: &mut Window,
3243        cx: &mut App,
3244    ) -> Self::PrepaintState {
3245        GlobalState::init(cx);
3246        let state = retain_text_selection_state(global_id, window, cx);
3247        state.read(cx).layer_painted.set(true);
3248        // The handles and the menu register again as they paint this frame.
3249        if state.read(cx).touch.painted_any() {
3250            state.update(cx, |state, _| state.touch.begin_frame());
3251        }
3252        TextSelectionLayerPrepaintState(state)
3253    }
3254
3255    fn paint(
3256        &mut self,
3257        _: Option<&GlobalElementId>,
3258        _: Option<&InspectorElementId>,
3259        _: Bounds<Pixels>,
3260        _: &mut Self::RequestLayoutState,
3261        state: &mut Self::PrepaintState,
3262        window: &mut Window,
3263        cx: &mut App,
3264    ) {
3265        paint_text_selection(&state.0, window, cx);
3266    }
3267}
3268
3269fn retain_text_selection_state(
3270    global_id: Option<&GlobalElementId>,
3271    window: &mut Window,
3272    cx: &mut App,
3273) -> Entity<WindowSelectionState> {
3274    let window_id = window.window_handle().window_id();
3275    let state = window.with_element_state::<Entity<WindowSelectionState>, _>(
3276        global_id.expect("TextSelection has a stable element id"),
3277        |retained, _| {
3278            let state = retained.unwrap_or_else(|| WindowSelectionState::acquire(window_id, cx));
3279            (state.clone(), state)
3280        },
3281    );
3282    // Registered once: writing the global again every frame would change it,
3283    // and every view that reads it, on every frame.
3284    let registered = cx.has_global::<SelectionStateRegistry>()
3285        && cx
3286            .global::<SelectionStateRegistry>()
3287            .0
3288            .get(&window_id)
3289            .is_some_and(|registered| registered.entity_id() == state.entity_id());
3290    if !registered {
3291        if !cx.has_global::<SelectionStateRegistry>() {
3292            cx.set_global(SelectionStateRegistry::default());
3293        }
3294        cx.global_mut::<SelectionStateRegistry>()
3295            .0
3296            .insert(window_id, state.downgrade());
3297    }
3298    state.update(cx, |state, cx| {
3299        if state.mouse_lifecycle.is_empty() {
3300            state.mouse_lifecycle = vec![
3301                cx.observe_window_bounds(window, |state, _, cx| state.end(cx)),
3302                cx.observe_window_activation(window, |state, window, cx| {
3303                    if !window.is_window_active() {
3304                        state.end(cx);
3305                    }
3306                }),
3307            ];
3308        }
3309    });
3310    state
3311}
3312
3313fn schedule_selection_frame(
3314    state: &Entity<WindowSelectionState>,
3315    window: &mut Window,
3316    cx: &mut App,
3317) {
3318    if state.read(cx).schedule_finish_frame() {
3319        let state = state.downgrade();
3320        window.defer(cx, move |window, cx| {
3321            let Some(state) = state.upgrade() else {
3322                return;
3323            };
3324            let stale = state
3325                .read(cx)
3326                .stale_participants(state.read(cx).layer_painted.get());
3327            // Retiring an endpoint is a real selection change. Ordinary
3328            // frame publication does not write the shared window entity.
3329            let mut handlers = if state.read(cx).endpoint_departed(&stale) {
3330                state.update(cx, |state, cx| state.clear_state(cx))
3331            } else {
3332                Vec::new()
3333            };
3334            let departed = state.read(cx).remove_stale_participants(stale);
3335            handlers.extend(clear_departed_participants(departed, cx));
3336            let refresh_order = state.read(cx).finish_registrations();
3337            let mut changes = state
3338                .read(cx)
3339                .changed_snapshots(cx)
3340                .into_iter()
3341                .map(|(participant, snapshot)| (participant.entity_id(), (participant, snapshot)))
3342                .collect::<HashMap<_, _>>();
3343            let drawn = std::mem::take(&mut *state.read(cx).draw_changed.borrow_mut());
3344            for (id, participant) in drawn {
3345                if let Some(participant) = participant.upgrade() {
3346                    changes.entry(id).or_insert_with(|| {
3347                        let snapshot = participant.read(cx).snapshot;
3348                        (participant, snapshot)
3349                    });
3350                }
3351            }
3352            for (_, (participant, snapshot)) in changes {
3353                participant.update(cx, |participant, cx| {
3354                    participant.set_snapshot_quietly(snapshot);
3355                    cx.emit(TextSelectionEvent::SelectionChanged(snapshot));
3356                });
3357            }
3358            dispatch_clear_handlers(handlers, cx);
3359            if refresh_order {
3360                // GPUI does not expose the position of a replayed subtree in
3361                // paint order. Recover it once after an incomplete topology
3362                // change, not on ordinary partial selection redraws.
3363                window.refresh();
3364            }
3365            if state.read(cx).touch_edges_moved.replace(false) {
3366                state.update(cx, |state, cx| state.touch_changed(cx));
3367            }
3368            // Direct participant scrolling produces no wheel event. Refresh
3369            // the held cursor after paint registers the new scroll geometry.
3370            if state.read(cx).refresh_held_cursor.replace(false) && state.read(cx).is_selecting {
3371                state.update(cx, |state, cx| {
3372                    // A handle drag holds the finger off the text; keep the
3373                    // same offset, or the cursor would hop between the two.
3374                    let position = window.mouse_position();
3375                    let position = state
3376                        .touch
3377                        .drag
3378                        .map_or(position, |drag| drag.text_position(position));
3379                    state.update_in_window(position, window, cx);
3380                });
3381                WindowSelectionState::resolve_content_keys(&state, cx);
3382            }
3383        });
3384    }
3385}
3386
3387fn press_is_in_viewport(position: Point<Pixels>, window: &Window) -> bool {
3388    Bounds::new(Point::default(), window.viewport_size()).contains(&position)
3389}
3390
3391fn paint_text_selection(state: &Entity<WindowSelectionState>, window: &mut Window, cx: &mut App) {
3392    schedule_selection_frame(state, window, cx);
3393
3394    let mouse_down_state = state.downgrade();
3395    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
3396        if event.button != MouseButton::Left {
3397            return;
3398        }
3399        // Windows reports presses on the native title bar and resize frame
3400        // in client coordinates outside the viewport. Those start a window
3401        // move or resize, never a text selection, and must not clear one.
3402        if !press_is_in_viewport(event.position, window) {
3403            return;
3404        }
3405        let Some(state) = mouse_down_state.upgrade() else {
3406            return;
3407        };
3408        // A press on a handle, the edit menu or a control acts on the
3409        // selection; it must not clear it.
3410        if state.read(cx).keeps_selection_at(event.position, window) {
3411            return;
3412        }
3413        if phase.capture() {
3414            GlobalState::init(cx);
3415            GlobalState::reset_text_selection_suppression(cx);
3416            let handlers = state.update(cx, |state, cx| {
3417                if state.mouse_down_prepared {
3418                    return Vec::new();
3419                }
3420                state.mouse_down_prepared = true;
3421                state.prepare_for_mouse_down(event.click_count == 1 && event.modifiers.shift, cx)
3422            });
3423            dispatch_clear_handlers(handlers, cx);
3424
3425            // Selection layers share this latch for one dispatch. A release
3426            // may be stopped by a child or occur outside the window.
3427            let latch = state.downgrade();
3428            cx.defer(move |cx| {
3429                if let Some(state) = latch.upgrade() {
3430                    state.update(cx, |state, _| state.mouse_down_prepared = false);
3431                }
3432            });
3433        } else if event.click_count == 1 {
3434            if GlobalState::is_text_selection_suppressed(cx) {
3435                state.update(cx, |state, _| state.pending_extension_anchor = None);
3436                return;
3437            }
3438            state.update(cx, |state, cx| {
3439                if !state.is_selecting {
3440                    state.begin_in_window(event.position, event.modifiers.shift, window, cx)
3441                }
3442            });
3443            WindowSelectionState::resolve_content_keys(&state, cx);
3444        } else if event.click_count >= 2 {
3445            if GlobalState::is_text_selection_suppressed(cx) {
3446                return;
3447            }
3448            let touch = GlobalState::is_touch_press(cx);
3449            state.update(cx, |state, cx| {
3450                let unit = state.select_at(event.position, event.click_count, window, cx);
3451                // A double tap is touch's other way to select a word, and it
3452                // gets the handles and the menu like a long press does.
3453                if touch {
3454                    state.keep_touch_selection(cx);
3455                } else if let Some(unit) = unit {
3456                    state.hold_unit(unit, cx);
3457                }
3458            });
3459            WindowSelectionState::resolve_content_keys(&state, cx);
3460        }
3461    });
3462
3463    // Every touch is offered as a drag first; that is how a tap's mouse
3464    // events are later told apart from a mouse's.
3465    window.on_mouse_event(move |event: &TouchDragEvent, phase, _, cx| {
3466        if phase.capture() && event.phase == TouchPhase::Started {
3467            GlobalState::note_touch(cx);
3468        }
3469    });
3470
3471    // Touch panning remains scrolling until a long press actually hits text.
3472    // Claiming the gesture keeps subsequent moves out of the pan recognizer.
3473    let long_press_state = state.downgrade();
3474    window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {
3475        if !phase.bubble() {
3476            return;
3477        }
3478        let Some(state) = long_press_state.upgrade() else {
3479            return;
3480        };
3481        if event.phase == TouchPhase::Started {
3482            if window.default_prevented()
3483                || state
3484                    .read(cx)
3485                    .keeps_selection_at(event.start_position, window)
3486                || !state.update(cx, |state, cx| {
3487                    state
3488                        .endpoint(event.start_position, Some(window), cx)
3489                        .inside_text
3490                })
3491            {
3492                return;
3493            }
3494            GlobalState::init(cx);
3495            GlobalState::reset_text_selection_suppression(cx);
3496            let handlers = state.update(cx, |state, cx| state.prepare_for_mouse_down(false, cx));
3497            dispatch_clear_handlers(handlers, cx);
3498            let selected = state.update(cx, |state, cx| {
3499                state.select_at(event.start_position, 2, window, cx);
3500                state.anchor.is_some()
3501            });
3502            if !selected {
3503                return;
3504            }
3505            window.capture_long_press(&state);
3506        } else if !window.has_long_press_capture(&state) {
3507            return;
3508        } else {
3509            state.update(cx, |state, cx| match event.phase {
3510                TouchPhase::Moved => {
3511                    state.is_selecting = true;
3512                    state.update_in_window(event.position, window, cx);
3513                }
3514                TouchPhase::Ended | TouchPhase::Cancelled => {
3515                    state.end(cx);
3516                    // The finger is up; the selection it made gets its
3517                    // handles and the edit menu.
3518                    state.keep_touch_selection(cx);
3519                }
3520                _ => {}
3521            });
3522        }
3523        window.prevent_default();
3524        cx.stop_propagation();
3525        WindowSelectionState::resolve_content_keys(&state, cx);
3526    });
3527
3528    // A handle drag in progress follows the finger or the pointer wherever
3529    // it goes, whether or not the handle it took is laid out this frame.
3530    let drag_state = state.downgrade();
3531    window.on_mouse_event(move |event: &TouchDragEvent, phase, window, cx| {
3532        if !phase.bubble() || event.phase == TouchPhase::Started {
3533            return;
3534        }
3535        let Some(state) = drag_state.upgrade() else {
3536            return;
3537        };
3538        if state.read(cx).touch.drag.is_none() {
3539            return;
3540        }
3541        cx.stop_propagation();
3542        state.update(cx, |state, cx| match event.phase {
3543            TouchPhase::Moved => state.update_edge_drag(event.position, window, cx),
3544            _ => state.end_edge_drag(cx),
3545        });
3546        WindowSelectionState::resolve_content_keys(&state, cx);
3547    });
3548    let drag_state = state.downgrade();
3549    window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
3550        if phase.bubble()
3551            && event.pressed_button == Some(MouseButton::Left)
3552            && let Some(state) = drag_state.upgrade()
3553            && state.read(cx).touch.drag.is_some()
3554        {
3555            state.update(cx, |state, cx| {
3556                state.update_edge_drag(event.position, window, cx)
3557            });
3558            WindowSelectionState::resolve_content_keys(&state, cx);
3559        }
3560    });
3561    let drag_state = state.downgrade();
3562    window.on_mouse_event(move |event: &MouseUpEvent, phase, _, cx| {
3563        if phase.bubble()
3564            && event.button == MouseButton::Left
3565            && let Some(state) = drag_state.upgrade()
3566        {
3567            state.update(cx, |state, cx| state.end_edge_drag(cx));
3568        }
3569    });
3570
3571    let mouse_move_state = state.downgrade();
3572    window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
3573        if phase.capture() && event.pressed_button != Some(MouseButton::Left) {
3574            if let Some(state) = mouse_move_state.upgrade() {
3575                state.update(cx, |state, cx| state.end(cx));
3576            }
3577            return;
3578        }
3579        if phase.bubble()
3580            && event.pressed_button == Some(MouseButton::Left)
3581            && let Some(state) = mouse_move_state.upgrade()
3582            // Moving the pointer only moves a selection being made.
3583            && state.read(cx).is_selecting
3584        {
3585            state.update(cx, |state, cx| {
3586                // A handle drag maps the pointer through the handle's offset;
3587                // the raw pointer must not fight it.
3588                if state.touch.drag.is_some() {
3589                    return;
3590                }
3591                state.update_in_window(event.position, window, cx)
3592            });
3593            WindowSelectionState::resolve_content_keys(&state, cx);
3594        }
3595    });
3596
3597    let mouse_exit_state = state.downgrade();
3598    window.on_mouse_event(move |_: &MouseExitEvent, phase, _, cx| {
3599        if phase.capture()
3600            && let Some(state) = mouse_exit_state.upgrade()
3601        {
3602            state.update(cx, |state, cx| state.end(cx));
3603        }
3604    });
3605
3606    let mouse_up_state = state.downgrade();
3607    window.on_mouse_event(move |_: &MouseUpEvent, phase, _, cx| {
3608        if phase.bubble()
3609            && let Some(state) = mouse_up_state.upgrade()
3610        {
3611            state.update(cx, |state, cx| state.end(cx));
3612        }
3613    });
3614
3615    let scroll_state = state.downgrade();
3616    window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
3617        let Some(state) = scroll_state.upgrade() else {
3618            return;
3619        };
3620        // On capture, before a scroll container can stop the event: one
3621        // stretched past its end swallows the whole stream, the lift
3622        // included, and the menu would never come back.
3623        if phase.capture() {
3624            if state.read(cx).touch.active {
3625                state.update(cx, |state, cx| {
3626                    state.edit_menu_on_scroll(event.touch_phase, cx)
3627                });
3628            }
3629            return;
3630        }
3631        // A scroll only moves a selection being made under the pointer.
3632        if phase.bubble() && state.read(cx).is_selecting {
3633            let position = window.mouse_position();
3634            state.update(cx, |state, cx| {
3635                // A handle drag holds the finger off the text; keep its offset.
3636                let position = state
3637                    .touch
3638                    .drag
3639                    .map_or(position, |drag| drag.text_position(position));
3640                state.update_in_window(position, window, cx)
3641            });
3642            WindowSelectionState::resolve_content_keys(&state, cx);
3643        }
3644    });
3645}
3646
3647fn live_text_selection_state(
3648    window: &Window,
3649    cx: &mut App,
3650) -> Option<Entity<WindowSelectionState>> {
3651    WindowSelectionState::existing(window, cx)
3652}
3653
3654pub(crate) fn clear_window_text_selection(window_id: gpui::WindowId, cx: &mut App) {
3655    if !cx.has_global::<SelectionStateRegistry>() {
3656        return;
3657    }
3658    let Some(state) = cx
3659        .global::<SelectionStateRegistry>()
3660        .0
3661        .get(&window_id)
3662        .and_then(WeakEntity::upgrade)
3663    else {
3664        return;
3665    };
3666    let handlers = state.update(cx, |state, cx| state.clear_state(cx));
3667    dispatch_clear_handlers(handlers, cx);
3668}
3669
3670#[cfg(test)]
3671mod tests {
3672    use super::*;
3673    use crate::ElementExt as _;
3674    #[cfg(feature = "gpui-fast")]
3675    use gpui::StatefulInteractiveElement as _;
3676    use gpui::{
3677        Bounds, ContentMask, Context, Hitbox, HitboxBehavior, HitboxId, InteractiveElement as _,
3678        IntoElement, ParentElement as _, Render, SharedString, Styled as _, StyledText,
3679        TestAppContext, TextLayout, Window, div, point, prelude::FluentBuilder as _, px, size,
3680    };
3681    use std::{
3682        cell::{Cell, RefCell},
3683        rc::Rc,
3684    };
3685
3686    struct FakeParticipant {
3687        selection: TextSelectionHandle,
3688    }
3689
3690    struct WindowSelectionView {
3691        selection: TextSelectionHandle,
3692    }
3693
3694    struct SelectionElementOnlyView;
3695    struct ToggleSelectionElementView {
3696        enabled: bool,
3697        selection: TextSelectionHandle,
3698    }
3699
3700    struct DoubleSelectionElementView {
3701        selection: TextSelectionHandle,
3702    }
3703
3704    struct WindowOwnedSelectionView {
3705        selection: TextSelectionHandle,
3706    }
3707
3708    struct FirstFrameScopedSelectionView {
3709        selection: TextSelectionHandle,
3710    }
3711
3712    struct PlainRunLayoutView {
3713        texts: Vec<SharedString>,
3714        layouts: Vec<TextLayout>,
3715    }
3716
3717    impl Render for WindowSelectionView {
3718        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3719            div()
3720        }
3721    }
3722
3723    impl Render for SelectionElementOnlyView {
3724        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3725            div()
3726                .size_full()
3727                .child(TextSelectionLayer)
3728                .child(
3729                    div()
3730                        .size_full()
3731                        .on_mouse_down(MouseButton::Left, |_, _, cx| {
3732                            GlobalState::suppress_text_selection(cx);
3733                        }),
3734                )
3735        }
3736    }
3737
3738    impl Render for ToggleSelectionElementView {
3739        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3740            let selection = self.selection.clone();
3741            div().when(self.enabled, |this| {
3742                this.child(TextSelectionLayer)
3743                    .child(div().size_full().on_prepaint(move |bounds, window, cx| {
3744                        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
3745                        selection.register(
3746                            TextSelectionRegistration::new(hitbox, bounds)
3747                                .with_text_bounds(vec![bounds]),
3748                            window,
3749                            cx,
3750                        );
3751                    }))
3752            })
3753        }
3754    }
3755
3756    impl Render for DoubleSelectionElementView {
3757        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3758            let selection = self.selection.clone();
3759            div()
3760                .size_full()
3761                .child(TextSelectionLayer)
3762                .child(TextSelectionLayer)
3763                .on_prepaint(move |bounds, window, cx| {
3764                    let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
3765                    selection.register(
3766                        TextSelectionRegistration::new(hitbox, bounds)
3767                            .with_text_bounds(vec![bounds]),
3768                        window,
3769                        cx,
3770                    );
3771                })
3772        }
3773    }
3774
3775    impl Render for WindowOwnedSelectionView {
3776        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3777            let selection = self.selection.clone();
3778            div()
3779                .size_full()
3780                .child(TextSelectionLayer)
3781                .child(div().size_full().on_prepaint(move |bounds, window, cx| {
3782                    let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
3783                    selection.register(
3784                        TextSelectionRegistration::new(hitbox, bounds)
3785                            .with_text_bounds(vec![bounds]),
3786                        window,
3787                        cx,
3788                    );
3789                }))
3790        }
3791    }
3792
3793    impl Render for FirstFrameScopedSelectionView {
3794        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3795            let scope = TextSelectionScopeId::from_raw(23);
3796            TextSelection::activate_scope(scope, window, cx);
3797            let selection = self.selection.clone();
3798
3799            div().child(TextSelectionLayer).child(
3800                div()
3801                    .size_full()
3802                    .on_prepaint(move |bounds, window, cx| {
3803                        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
3804                        selection.register(
3805                            TextSelectionRegistration::new(hitbox, bounds)
3806                                .with_text_bounds(vec![bounds]),
3807                            window,
3808                            cx,
3809                        );
3810                    })
3811                    .text_selection_scope(scope),
3812            )
3813        }
3814    }
3815
3816    impl Render for PlainRunLayoutView {
3817        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3818            self.layouts.clear();
3819            let children = self
3820                .texts
3821                .iter()
3822                .enumerate()
3823                .map(|(index, text)| {
3824                    let text = StyledText::new(text.clone());
3825                    self.layouts.push(text.layout().clone());
3826                    div().absolute().top(px(index as f32 * 40.)).child(text)
3827                })
3828                .collect::<Vec<_>>();
3829            div().size_full().children(children)
3830        }
3831    }
3832
3833    impl FakeParticipant {
3834        fn new(text: &str, cx: &mut gpui::App) -> Self {
3835            let selection = TextSelectionHandle::new(text, cx);
3836            Self { selection }
3837        }
3838
3839        fn register(
3840            &self,
3841            selection_state: &mut WindowSelectionState,
3842            y: f32,
3843            scope: TextSelectionScopeId,
3844            document_order: u64,
3845            cx: &mut gpui::App,
3846        ) {
3847            let bounds = Bounds::new(point(px(0.), px(y)), size(px(100.), px(10.)));
3848            selection_state.register_participant(
3849                self.selection.clone(),
3850                TextSelectionRegistration::new(
3851                    Hitbox {
3852                        id: HitboxId::placeholder(),
3853                        bounds,
3854                        content_mask: ContentMask { bounds },
3855                        behavior: HitboxBehavior::Normal,
3856                    },
3857                    bounds,
3858                )
3859                .with_scope(scope)
3860                .with_document_order(document_order)
3861                .with_text_bounds(vec![bounds]),
3862                cx,
3863            );
3864        }
3865    }
3866
3867    fn laid_out_runs(texts: &[&str], cx: &mut TestAppContext) -> Vec<(SharedString, TextLayout)> {
3868        let texts = texts
3869            .iter()
3870            .map(|text| SharedString::from(*text))
3871            .collect::<Vec<_>>();
3872        let view = cx.add_window({
3873            let texts = texts.clone();
3874            move |_, _| PlainRunLayoutView {
3875                texts,
3876                layouts: Vec::new(),
3877            }
3878        });
3879        cx.update_window(*view, |_, window, cx| {
3880            let _ = window.draw(cx);
3881        })
3882        .unwrap();
3883        let layouts = cx.update(|cx| view.read(cx).unwrap().layouts.clone());
3884        texts.into_iter().zip(layouts).collect()
3885    }
3886
3887    fn plain_snapshot(anchor: Point<Pixels>, cursor: Point<Pixels>) -> TextSelectionSnapshot {
3888        TextSelectionSnapshot::new(
3889            TextSelectionEndpoint::new(None, anchor),
3890            TextSelectionEndpoint::new(None, cursor),
3891        )
3892        .with_window_points(Some(TextSelectionWindowPoints { anchor, cursor }))
3893    }
3894
3895    #[gpui::test]
3896    fn scope_stack_is_cleaned_after_panicking_subtree(cx: &mut TestAppContext) {
3897        let window_id = {
3898            let (_, window_cx) = cx.add_window_view(|_, _| SelectionElementOnlyView);
3899            window_cx.update(|window, _| window.window_handle().window_id())
3900        };
3901        let scope = TextSelectionScopeId::from_raw(41);
3902
3903        cx.update(|cx| {
3904            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3905                with_text_selection_scope(window_id, scope, cx, |_| panic!("subtree failed"));
3906            }));
3907
3908            assert!(result.is_err());
3909            assert_eq!(current_text_selection_scope(window_id, cx), None);
3910        });
3911    }
3912
3913    #[gpui::test]
3914    fn reentrant_scope_from_one_window_does_not_pollute_another(cx: &mut TestAppContext) {
3915        let first_window_id = {
3916            let (_, window_cx) = cx.add_window_view(|_, _| SelectionElementOnlyView);
3917            window_cx.update(|window, _| window.window_handle().window_id())
3918        };
3919        let second_window_id = {
3920            let (_, window_cx) = cx.add_window_view(|_, _| SelectionElementOnlyView);
3921            window_cx.update(|window, _| window.window_handle().window_id())
3922        };
3923        let scope = TextSelectionScopeId::from_raw(42);
3924
3925        cx.update(|cx| {
3926            with_text_selection_scope(first_window_id, scope, cx, |cx| {
3927                assert_eq!(current_text_selection_scope(second_window_id, cx), None);
3928                assert_eq!(
3929                    current_text_selection_scope(first_window_id, cx),
3930                    Some(scope)
3931                );
3932            });
3933        });
3934    }
3935
3936    #[gpui::test]
3937    fn selection_callback_can_reenter_its_selection_state(cx: &mut TestAppContext) {
3938        let called = Rc::new(Cell::new(false));
3939        let called_from_callback = called.clone();
3940        let (selection_state, participant) = cx.update(|cx| {
3941            let selection_state = cx.new(|_| WindowSelectionState::default());
3942            let selection_state_for_callback = selection_state.clone();
3943            let participant = FakeParticipant::new("participant", cx);
3944            participant
3945                .selection
3946                .subscribe(
3947                    move |event, cx| {
3948                        if matches!(event, TextSelectionEvent::SelectionChanged(Some(_))) {
3949                            selection_state_for_callback
3950                                .update(cx, |_, _| called_from_callback.set(true));
3951                        }
3952                    },
3953                    cx,
3954                )
3955                .detach();
3956            (selection_state, participant)
3957        });
3958        cx.run_until_parked();
3959        cx.update(|cx| {
3960            selection_state.update(cx, |selection_state, cx| {
3961                participant.register(selection_state, 0., TextSelectionScopeId::default(), 0, cx);
3962                selection_state.begin(point(px(1.), px(1.)), false, cx);
3963                selection_state.update(point(px(20.), px(1.)), cx);
3964            });
3965        });
3966        cx.run_until_parked();
3967        assert!(called.get());
3968    }
3969
3970    #[gpui::test]
3971    fn selection_events_preserve_snapshot_then_clear_order(cx: &mut TestAppContext) {
3972        let observed = Rc::new(RefCell::new(Vec::new()));
3973        let observed_for_callback = observed.clone();
3974        let selection = cx.update(|cx| {
3975            let selection = TextSelectionHandle::new("selection", cx);
3976            selection
3977                .subscribe(
3978                    move |event, _| {
3979                        if let TextSelectionEvent::SelectionChanged(snapshot) = event {
3980                            observed_for_callback.borrow_mut().push(snapshot.is_some());
3981                        }
3982                    },
3983                    cx,
3984                )
3985                .detach();
3986            selection
3987        });
3988        cx.run_until_parked();
3989        cx.update(|cx| {
3990            selection.0.update(cx, |state, cx| {
3991                state.set_snapshot(
3992                    Some(plain_snapshot(point(px(1.), px(1.)), point(px(8.), px(1.)))),
3993                    cx,
3994                );
3995                state.clear_state(cx);
3996            });
3997        });
3998        cx.run_until_parked();
3999        assert_eq!(&*observed.borrow(), &[true, false]);
4000    }
4001
4002    fn text_run(order: u64, text: SharedString, layout: TextLayout) -> TextSelectionRun {
4003        let bounds = layout.bounds();
4004        TextSelectionRun::new(text, layout, bounds).with_document_order(order)
4005    }
4006
4007    #[gpui::test]
4008    fn public_selection_data_uses_builders_and_readers(cx: &mut TestAppContext) {
4009        let bounds = Bounds::new(point(px(1.), px(2.)), size(px(30.), px(10.)));
4010        let hitbox = Hitbox {
4011            id: HitboxId::placeholder(),
4012            bounds,
4013            content_mask: ContentMask { bounds },
4014            behavior: HitboxBehavior::Normal,
4015        };
4016        let scope = TextSelectionScopeId::from_raw(7);
4017        let endpoint = TextSelectionEndpoint::new(None, bounds.origin)
4018            .with_content_key(TextSelectionContentKey::new(11));
4019        let snapshot = TextSelectionSnapshot::new(endpoint, endpoint)
4020            .with_selecting(true)
4021            .with_window_points(Some(TextSelectionWindowPoints {
4022                anchor: bounds.origin,
4023                cursor: bounds.bottom_right(),
4024            }))
4025            .with_coverage(TextSelectionCoverage::Full);
4026        let registration = TextSelectionRegistration::new(hitbox, bounds)
4027            .with_scroll_offset(point(px(3.), px(4.)))
4028            .with_scope(scope)
4029            .with_document_order(9)
4030            .with_text_bounds(vec![bounds]);
4031
4032        assert_eq!(endpoint.entity_id(), None);
4033        assert_eq!(endpoint.content_point(), bounds.origin);
4034        assert_eq!(
4035            endpoint.content_key(),
4036            Some(TextSelectionContentKey::new(11))
4037        );
4038        assert_eq!(snapshot.anchor(), endpoint);
4039        assert_eq!(snapshot.cursor(), endpoint);
4040        assert!(snapshot.is_selecting());
4041        assert_eq!(snapshot.coverage(), TextSelectionCoverage::Full);
4042        assert_eq!(
4043            snapshot.window_points(),
4044            Some(TextSelectionWindowPoints {
4045                anchor: bounds.origin,
4046                cursor: bounds.bottom_right(),
4047            })
4048        );
4049        assert_eq!(registration.bounds(), bounds);
4050        assert_eq!(registration.scroll_offset(), point(px(3.), px(4.)));
4051        assert_eq!(registration.scope(), scope);
4052        assert_eq!(registration.document_order(), 9);
4053        assert_eq!(registration.text_bounds(), &[bounds]);
4054
4055        let (text, layout) = laid_out_runs(&["aé"], cx).pop().unwrap();
4056        let text_run = TextSelectionRun::new(text.clone(), layout.clone(), layout.bounds())
4057            .with_document_order(3);
4058        assert_eq!(text_run.document_order(), 3);
4059        assert_eq!(text_run.text(), &text);
4060        assert_eq!(text_run.layout().len(), layout.len());
4061        assert_eq!(text_run.bounds(), layout.bounds());
4062
4063        let projection = TextSelectionProjection {
4064            ranges: vec![Some(1..3)],
4065            is_active: true,
4066        };
4067        assert_eq!(projection.ranges(), &[Some(1..3)]);
4068        assert!(projection.is_active());
4069    }
4070
4071    #[gpui::test]
4072    fn selection_handle_is_the_public_adapter_seam(cx: &mut TestAppContext) {
4073        let selected = Rc::new(Cell::new(false));
4074        let selected_from_callback = selected.clone();
4075        cx.update(|cx| {
4076            let selection = TextSelectionHandle::new("initial", cx);
4077            let entity_id = selection.entity_id();
4078            selection.set_fallback_copy_text("updated", cx);
4079            selection.set_local_selection(true, cx);
4080            selection
4081                .subscribe(
4082                    move |event, _| {
4083                        if let TextSelectionEvent::SelectionChanged(snapshot) = event {
4084                            selected_from_callback.set(snapshot.is_some());
4085                        }
4086                    },
4087                    cx,
4088                )
4089                .detach();
4090            selection.focus_with(|_, _| {}, cx);
4091            selection.copy_with(|_| "copied".to_string(), cx);
4092            selection.resolve_content_key_with(|_, _| Some(TextSelectionContentKey::new(3)), cx);
4093
4094            assert_eq!(selection.entity_id(), entity_id);
4095            assert_eq!(selection.snapshot(cx), None);
4096            assert_eq!(
4097                selection.update_runs(&[], cx),
4098                TextSelectionProjection::default()
4099            );
4100        });
4101        assert!(!selected.get());
4102    }
4103
4104    #[gpui::test]
4105    fn selection_handle_can_subscribe_its_window_to_refresh(cx: &mut TestAppContext) {
4106        let (_, cx) = cx.add_window_view(|_, cx| WindowSelectionView {
4107            selection: TextSelectionHandle::new("refresh", cx),
4108        });
4109        cx.update(|window, cx| {
4110            let selection = TextSelectionHandle::new("refresh", cx);
4111            selection.refresh_window_on_change(window, cx).detach();
4112        });
4113    }
4114
4115    #[gpui::test]
4116    fn plain_projection_preserves_forward_reversed_and_unicode_ranges(cx: &mut TestAppContext) {
4117        let (text, layout) = laid_out_runs(&["aé🙂z"], cx).pop().unwrap();
4118        let run = text_run(0, text, layout.clone());
4119        let start = layout.position_for_index(1).unwrap();
4120        let end = layout.position_for_index(7).unwrap();
4121
4122        let forward = project_ranges(Some(plain_snapshot(start, end)), std::slice::from_ref(&run));
4123        let reversed = project_ranges(Some(plain_snapshot(end, start)), &[run]);
4124
4125        assert_eq!(forward.ranges(), &[Some(1..7)]);
4126        assert_eq!(reversed.ranges(), &[Some(1..7)]);
4127        assert!(forward.is_active());
4128        assert!(reversed.is_active());
4129    }
4130
4131    #[gpui::test]
4132    fn double_click_expands_a_plain_run_to_the_input_word_boundary(cx: &mut TestAppContext) {
4133        let (text, layout) = laid_out_runs(&["one café, three"], cx).pop().unwrap();
4134        let run = text_run(0, text, layout.clone());
4135        let click = layout.position_for_index(6).unwrap();
4136
4137        let (anchor, cursor) =
4138            carets_for_multi_click(std::slice::from_ref(&run), click, 2).unwrap();
4139        let states = project_ranges(Some(plain_snapshot(anchor.origin, cursor.origin)), &[run]);
4140
4141        assert_eq!(states.ranges(), &[Some(4..9)]);
4142    }
4143
4144    #[gpui::test]
4145    fn multi_click_uses_text_layout_window_coordinates_at_a_nonzero_origin(
4146        cx: &mut TestAppContext,
4147    ) {
4148        let mut runs = laid_out_runs(&["above", "alpha beta"], cx);
4149        let (text, layout) = runs.pop().unwrap();
4150        assert!(layout.bounds().origin.y > px(0.));
4151        let run = text_run(0, text, layout.clone());
4152        let click = layout.position_for_index(7).unwrap();
4153
4154        let (anchor, cursor) =
4155            carets_for_multi_click(std::slice::from_ref(&run), click, 2).unwrap();
4156        let projection = project_ranges(Some(plain_snapshot(anchor.origin, cursor.origin)), &[run]);
4157
4158        assert_eq!(projection.ranges(), &[Some(6..10)]);
4159    }
4160
4161    #[gpui::test]
4162    fn triple_click_beside_a_short_line_selects_that_line(cx: &mut TestAppContext) {
4163        let (text, layout) = laid_out_runs(&["a long first line\nend"], cx)
4164            .pop()
4165            .unwrap();
4166        let run = text_run(0, text, layout.clone());
4167        // Right of "end", inside the run: the first line is wider.
4168        let beside = layout.position_for_index(21).unwrap() + point(px(20.), px(2.));
4169        assert!(run.bounds.contains(&beside));
4170        assert!(layout.index_for_position(beside).is_err());
4171
4172        let (anchor, cursor) =
4173            carets_for_multi_click(std::slice::from_ref(&run), beside, 3).unwrap();
4174        let states = project_ranges(
4175            Some(plain_snapshot(anchor.origin, cursor.origin)),
4176            std::slice::from_ref(&run),
4177        );
4178        assert_eq!(states.ranges(), &[Some(18..21)]);
4179        // Two clicks beside the text still select nothing.
4180        assert!(carets_for_multi_click(&[run], beside, 2).is_none());
4181    }
4182
4183    #[gpui::test]
4184    fn triple_click_expands_to_the_input_logical_line_not_the_visual_row(cx: &mut TestAppContext) {
4185        let (text, layout) = laid_out_runs(&["second line"], cx).pop().unwrap();
4186        let run = text_run(0, text, layout.clone());
4187        let click = layout.position_for_index(4).unwrap();
4188
4189        let (anchor, cursor) =
4190            carets_for_multi_click(std::slice::from_ref(&run), click, 4).unwrap();
4191        let states = project_ranges(Some(plain_snapshot(anchor.origin, cursor.origin)), &[run]);
4192
4193        assert_eq!(states.ranges(), &[Some(0..11)]);
4194        assert_eq!(line_range_at("first line\nsecond line\nthird", 15), 11..22);
4195    }
4196
4197    #[gpui::test]
4198    fn plain_projection_spans_multiple_runs_and_leaves_empty_gutters_unselected(
4199        cx: &mut TestAppContext,
4200    ) {
4201        let mut runs = laid_out_runs(&["first", "", "second"], cx);
4202        let (first_text, first_layout) = runs.remove(0);
4203        let (gutter_text, gutter_layout) = runs.remove(0);
4204        let (second_text, second_layout) = runs.remove(0);
4205        let start = first_layout.position_for_index(2).unwrap();
4206        let end = second_layout.position_for_index(3).unwrap();
4207        let states = project_ranges(
4208            Some(plain_snapshot(start, end)),
4209            &[
4210                text_run(2, second_text, second_layout),
4211                text_run(1, gutter_text, gutter_layout),
4212                text_run(0, first_text, first_layout),
4213            ],
4214        );
4215
4216        assert_eq!(states.ranges(), &[Some(0..3), None, Some(2..5)]);
4217        assert!(states.is_active());
4218    }
4219
4220    #[gpui::test]
4221    fn plain_projection_caches_multiple_participant_copies_in_document_order(
4222        cx: &mut TestAppContext,
4223    ) {
4224        let mut runs = laid_out_runs(&["one", "two"], cx);
4225        let (first_text, first_layout) = runs.remove(0);
4226        let (second_text, second_layout) = runs.remove(0);
4227        let snapshot = plain_snapshot(
4228            first_layout.position_for_index(1).unwrap(),
4229            second_layout.position_for_index(2).unwrap(),
4230        );
4231        cx.update(|cx| {
4232            let mut selection_state = WindowSelectionState::default();
4233            let first = FakeParticipant::new("", cx);
4234            let second = FakeParticipant::new("", cx);
4235            first.register(
4236                &mut selection_state,
4237                0.,
4238                TextSelectionScopeId::default(),
4239                1,
4240                cx,
4241            );
4242            second.register(
4243                &mut selection_state,
4244                20.,
4245                TextSelectionScopeId::default(),
4246                0,
4247                cx,
4248            );
4249
4250            first
4251                .selection
4252                .0
4253                .update(cx, |state, cx| state.set_snapshot(Some(snapshot), cx));
4254            let projection = first
4255                .selection
4256                .update_runs(&[text_run(0, first_text, first_layout)], cx);
4257            assert_eq!(projection.ranges(), &[Some(1..3)]);
4258            assert!(projection.is_active());
4259            second
4260                .selection
4261                .0
4262                .update(cx, |state, cx| state.set_snapshot(Some(snapshot), cx));
4263            let projection = second
4264                .selection
4265                .update_runs(&[text_run(0, second_text, second_layout)], cx);
4266            assert_eq!(projection.ranges(), &[Some(0..2)]);
4267            assert!(projection.is_active());
4268
4269            assert_eq!(selection_state.selected_text(cx), "tw\nne");
4270        });
4271    }
4272
4273    #[gpui::test]
4274    fn plain_projection_invalidates_cached_copy_when_the_snapshot_changes(cx: &mut TestAppContext) {
4275        let (text, layout) = laid_out_runs(&["first"], cx).pop().unwrap();
4276        let first_snapshot = plain_snapshot(
4277            layout.position_for_index(1).unwrap(),
4278            layout.position_for_index(3).unwrap(),
4279        );
4280        let changed_snapshot = plain_snapshot(
4281            layout.position_for_index(3).unwrap(),
4282            layout.position_for_index(5).unwrap(),
4283        );
4284        let run = text_run(0, text, layout);
4285        cx.update(|cx| {
4286            let mut selection_state = WindowSelectionState::default();
4287            let participant = FakeParticipant::new("", cx);
4288            participant.register(
4289                &mut selection_state,
4290                0.,
4291                TextSelectionScopeId::default(),
4292                0,
4293                cx,
4294            );
4295            participant.selection.0.update(cx, |state, cx| {
4296                state.set_snapshot(Some(first_snapshot), cx);
4297                state.update_runs(std::slice::from_ref(&run));
4298            });
4299            assert_eq!(selection_state.selected_text(cx), "ir");
4300
4301            participant.selection.0.update(cx, |state, cx| {
4302                state.set_snapshot(Some(changed_snapshot), cx);
4303            });
4304            assert_eq!(selection_state.selected_text(cx), "");
4305
4306            participant.selection.update_runs(&[run], cx);
4307            assert_eq!(selection_state.selected_text(cx), "st");
4308            selection_state.clear(cx);
4309            participant.selection.set_local_selection(true, cx);
4310            assert_eq!(selection_state.selected_text(cx), "");
4311        });
4312    }
4313
4314    #[gpui::test]
4315    fn plain_projection_orders_cached_runs_by_frame_order_not_input_order(cx: &mut TestAppContext) {
4316        let mut runs = laid_out_runs(&["one", "two"], cx);
4317        let (first_text, first_layout) = runs.remove(0);
4318        let (second_text, second_layout) = runs.remove(0);
4319        let snapshot = plain_snapshot(
4320            first_layout.position_for_index(1).unwrap(),
4321            second_layout.position_for_index(2).unwrap(),
4322        );
4323        cx.update(|cx| {
4324            let mut selection_state = WindowSelectionState::default();
4325            let participant = FakeParticipant::new("", cx);
4326            participant.register(
4327                &mut selection_state,
4328                0.,
4329                TextSelectionScopeId::default(),
4330                0,
4331                cx,
4332            );
4333            participant.selection.0.update(cx, |state, cx| {
4334                state.set_snapshot(Some(snapshot), cx);
4335                state.update_runs(&[
4336                    text_run(1, first_text, first_layout),
4337                    text_run(0, second_text, second_layout),
4338                ]);
4339            });
4340
4341            assert_eq!(selection_state.selected_text(cx), "twne");
4342        });
4343    }
4344
4345    #[gpui::test]
4346    fn plain_projection_safely_rejects_a_text_layout_length_mismatch(cx: &mut TestAppContext) {
4347        let (_, layout) = laid_out_runs(&["short"], cx).pop().unwrap();
4348        let start = layout.position_for_index(0).unwrap();
4349        let end = layout.position_for_index(5).unwrap();
4350        let states = project_ranges(
4351            Some(plain_snapshot(start, end)),
4352            &[text_run(0, SharedString::from("longer"), layout)],
4353        );
4354
4355        assert_eq!(states.ranges(), &[None]);
4356        assert!(states.is_active());
4357    }
4358
4359    #[gpui::test]
4360    fn begin_update_and_end_publish_a_cross_participant_selection(cx: &mut TestAppContext) {
4361        cx.update(|cx| {
4362            let mut selection_state = WindowSelectionState::default();
4363            let first = FakeParticipant::new("first", cx);
4364            let second = FakeParticipant::new("second", cx);
4365            first.register(
4366                &mut selection_state,
4367                0.,
4368                TextSelectionScopeId::default(),
4369                0,
4370                cx,
4371            );
4372            second.register(
4373                &mut selection_state,
4374                20.,
4375                TextSelectionScopeId::default(),
4376                1,
4377                cx,
4378            );
4379
4380            selection_state.begin(point(px(1.), px(1.)), false, cx);
4381            selection_state.update(point(px(1.), px(25.)), cx);
4382            assert!(selection_state.has_selection(cx));
4383            assert_eq!(selection_state.selected_text(cx), "first\nsecond");
4384
4385            selection_state.end(cx);
4386            assert!(!selection_state.is_selecting());
4387        });
4388    }
4389
4390    #[gpui::test]
4391    fn shift_extension_keeps_its_original_anchor_when_reversed(cx: &mut TestAppContext) {
4392        cx.update(|cx| {
4393            let mut selection_state = WindowSelectionState::default();
4394            let participant = FakeParticipant::new("participant", cx);
4395            participant.register(
4396                &mut selection_state,
4397                0.,
4398                TextSelectionScopeId::default(),
4399                0,
4400                cx,
4401            );
4402
4403            selection_state.begin(point(px(2.), px(2.)), false, cx);
4404            selection_state.end(cx);
4405            selection_state.begin(point(px(8.), px(2.)), true, cx);
4406            selection_state.end(cx);
4407            let first_anchor = selection_state.snapshot().unwrap().anchor();
4408
4409            selection_state.begin(point(px(0.), px(2.)), true, cx);
4410            selection_state.end(cx);
4411            let reversed = selection_state.snapshot().unwrap();
4412            assert_eq!(reversed.anchor(), first_anchor);
4413            assert!(reversed.cursor().content_point().x < reversed.anchor().content_point().x);
4414        });
4415    }
4416
4417    #[gpui::test]
4418    fn content_key_resolver_runs_outside_the_window_state_lease(cx: &mut TestAppContext) {
4419        cx.update(|cx| {
4420            let state = cx.new(|_| WindowSelectionState::default());
4421            let participant = FakeParticipant::new("virtual", cx);
4422            let state_for_callback = state.clone();
4423            participant.selection.resolve_content_key_with(
4424                move |_, cx| {
4425                    let _ = state_for_callback.read(cx).snapshot();
4426                    Some(TextSelectionContentKey::new(7))
4427                },
4428                cx,
4429            );
4430            state.update(cx, |state, cx| {
4431                participant.register(state, 0., TextSelectionScopeId::default(), 0, cx);
4432                state.begin(point(px(1.), px(1.)), false, cx);
4433                state.update(point(px(8.), px(1.)), cx);
4434            });
4435
4436            WindowSelectionState::resolve_content_keys(&state, cx);
4437
4438            assert_eq!(
4439                state.read(cx).snapshot().unwrap().cursor().content_key(),
4440                Some(TextSelectionContentKey::new(7))
4441            );
4442        });
4443    }
4444
4445    #[gpui::test]
4446    fn active_dnd_does_not_move_a_text_selection_cursor(cx: &mut TestAppContext) {
4447        let window = cx.add_window(|_, cx| WindowSelectionView {
4448            selection: TextSelectionHandle::new("unused", cx),
4449        });
4450        window
4451            .update(cx, |_, window, cx| {
4452                let mut state = WindowSelectionState::default();
4453                let participant = FakeParticipant::new("participant", cx);
4454                participant.register(&mut state, 0., TextSelectionScopeId::default(), 0, cx);
4455                state.begin(point(px(1.), px(1.)), false, cx);
4456                let before = state.cursor.as_ref().unwrap().point;
4457                state.update_in_window_with_active_drag(point(px(80.), px(1.)), true, window, cx);
4458                assert_eq!(state.cursor.as_ref().unwrap().point, before);
4459            })
4460            .unwrap();
4461    }
4462
4463    #[gpui::test]
4464    fn shift_extension_falls_back_when_the_anchor_participant_was_swept(cx: &mut TestAppContext) {
4465        cx.update(|cx| {
4466            let mut selection_state = WindowSelectionState::default();
4467            let first = FakeParticipant::new("first", cx);
4468            let second = FakeParticipant::new("second", cx);
4469            first.register(
4470                &mut selection_state,
4471                0.,
4472                TextSelectionScopeId::default(),
4473                0,
4474                cx,
4475            );
4476            selection_state.begin(point(px(1.), px(1.)), false, cx);
4477            selection_state.update(point(px(8.), px(1.)), cx);
4478            selection_state.end(cx);
4479
4480            selection_state.finish_frame(cx);
4481            selection_state.finish_frame(cx);
4482            second.register(
4483                &mut selection_state,
4484                20.,
4485                TextSelectionScopeId::default(),
4486                1,
4487                cx,
4488            );
4489            selection_state.begin(point(px(1.), px(21.)), true, cx);
4490            selection_state.update(point(px(8.), px(21.)), cx);
4491            selection_state.end(cx);
4492
4493            assert_eq!(selection_state.selected_text(cx), "second");
4494        });
4495    }
4496
4497    #[gpui::test]
4498    fn scope_and_suppression_prevent_unrelated_participants_from_participating(
4499        cx: &mut TestAppContext,
4500    ) {
4501        cx.update(|cx| {
4502            let mut selection_state = WindowSelectionState::default();
4503            let base = FakeParticipant::new("base", cx);
4504            let modal = FakeParticipant::new("modal", cx);
4505            base.register(
4506                &mut selection_state,
4507                0.,
4508                TextSelectionScopeId::default(),
4509                0,
4510                cx,
4511            );
4512            modal.register(&mut selection_state, 20., TextSelectionScopeId(1), 1, cx);
4513
4514            selection_state.set_active_scope(TextSelectionScopeId(1), cx);
4515            selection_state.begin(point(px(1.), px(21.)), false, cx);
4516            selection_state.update(point(px(8.), px(21.)), cx);
4517            selection_state.end(cx);
4518            assert_eq!(selection_state.selected_text(cx), "modal");
4519
4520            selection_state.clear(cx);
4521            GlobalState::init(cx);
4522            GlobalState::suppress_text_selection(cx);
4523            selection_state.begin(point(px(1.), px(21.)), false, cx);
4524            selection_state.update(point(px(8.), px(21.)), cx);
4525            assert!(!selection_state.has_selection(cx));
4526        });
4527    }
4528
4529    #[gpui::test]
4530    fn dead_participants_are_pruned_and_empty_selection_falls_back_safely(cx: &mut TestAppContext) {
4531        let selection_state = cx.update(|cx| {
4532            let selection_state = cx.new(|_| WindowSelectionState::default());
4533            let participant = FakeParticipant::new("gone", cx);
4534            selection_state.update(cx, |selection_state, cx| {
4535                participant.register(selection_state, 0., TextSelectionScopeId::default(), 0, cx)
4536            });
4537            selection_state
4538        });
4539        cx.update(|cx| {
4540            selection_state.update(cx, |selection_state, cx| {
4541                selection_state.begin(point(px(1.), px(1.)), false, cx);
4542                selection_state.update(point(px(8.), px(1.)), cx);
4543                selection_state.end(cx);
4544
4545                assert_eq!(selection_state.selected_text(cx), "");
4546                assert!(!selection_state.has_selection(cx));
4547            });
4548        });
4549    }
4550
4551    #[gpui::test]
4552    fn text_selection_namespace_reports_copies_ends_and_clears_selection(cx: &mut TestAppContext) {
4553        let (view, cx) = cx.add_window_view(|_, cx| WindowSelectionView {
4554            selection: TextSelectionHandle::new("copied", cx),
4555        });
4556        cx.update(|window, cx| {
4557            let selection = view.read(cx).selection.clone();
4558            let selection_state = WindowSelectionState::ensure(window, cx);
4559            selection_state.update(cx, |selection_state, cx| {
4560                FakeParticipant { selection }.register(
4561                    selection_state,
4562                    0.,
4563                    TextSelectionScopeId::default(),
4564                    0,
4565                    cx,
4566                );
4567                selection_state.begin(point(px(1.), px(1.)), false, cx);
4568                selection_state.update(point(px(8.), px(1.)), cx);
4569            });
4570
4571            assert!(TextSelection::has_selection(window, cx));
4572            assert_eq!(TextSelection::selected_text(window, cx), "copied");
4573            TextSelection::end(window, cx);
4574            assert!(TextSelection::has_selection(window, cx));
4575            TextSelection::clear(window, cx);
4576            assert!(!TextSelection::has_selection(window, cx));
4577            assert_eq!(TextSelection::selected_text(window, cx), "");
4578        });
4579    }
4580
4581    #[gpui::test]
4582    fn two_windows_isolate_selection_copy_clear_and_release_ownership(cx: &mut TestAppContext) {
4583        let first = cx.add_window(|_, cx| WindowOwnedSelectionView {
4584            selection: TextSelectionHandle::new("first", cx),
4585        });
4586        let second = cx.add_window(|_, cx| WindowOwnedSelectionView {
4587            selection: TextSelectionHandle::new("second", cx),
4588        });
4589        let first_selection = cx.update(|cx| first.read(cx).unwrap().selection.clone());
4590        let second_selection = cx.update(|cx| second.read(cx).unwrap().selection.clone());
4591
4592        let first_state = cx
4593            .update_window(*first, |_, window, cx| {
4594                let _ = window.draw(cx);
4595                first_selection.set_local_selection(true, cx);
4596                assert_eq!(TextSelection::selected_text(window, cx), "first");
4597                WindowSelectionState::existing(window, cx)
4598                    .unwrap()
4599                    .downgrade()
4600            })
4601            .unwrap();
4602        cx.update_window(*second, |_, window, cx| {
4603            let _ = window.draw(cx);
4604            second_selection.set_local_selection(true, cx);
4605            assert_eq!(TextSelection::selected_text(window, cx), "second");
4606        })
4607        .unwrap();
4608
4609        cx.update_window(*first, |_, window, cx| {
4610            TextSelection::clear(window, cx);
4611            assert_eq!(TextSelection::selected_text(window, cx), "");
4612        })
4613        .unwrap();
4614        cx.update_window(*second, |_, window, cx| {
4615            assert_eq!(TextSelection::selected_text(window, cx), "second");
4616        })
4617        .unwrap();
4618
4619        cx.update_window(*first, |_, window, _| window.remove_window())
4620            .unwrap();
4621        cx.run_until_parked();
4622
4623        assert!(first_state.upgrade().is_none());
4624        cx.update_window(*second, |_, window, cx| {
4625            assert_eq!(TextSelection::selected_text(window, cx), "second");
4626        })
4627        .unwrap();
4628        cx.update(|cx| {
4629            assert_eq!(cx.global::<SelectionStateRegistry>().0.len(), 1);
4630        });
4631    }
4632
4633    #[gpui::test]
4634    fn copy_callback_can_reenter_window_and_handle_selection(cx: &mut TestAppContext) {
4635        let (_, cx) = cx.add_window_view(|_, _| SelectionElementOnlyView);
4636        cx.update(|window, cx| {
4637            let _ = window.draw(cx);
4638            let state = WindowSelectionState::existing(window, cx).unwrap();
4639            let selection = TextSelectionHandle::new("fallback", cx);
4640            let state_for_copy = state.clone();
4641            let selection_for_copy = selection.clone();
4642            selection.copy_with(
4643                move |cx: &mut App| {
4644                    state_for_copy.update(cx, |state, _| {
4645                        assert!(state.snapshot().is_some());
4646                    });
4647                    assert!(selection_for_copy.snapshot(cx).is_some());
4648                    selection_for_copy.set_fallback_copy_text("reentered", cx);
4649                    "reentrant copy".to_string()
4650                },
4651                cx,
4652            );
4653            state.update(cx, |state, cx| {
4654                FakeParticipant {
4655                    selection: selection.clone(),
4656                }
4657                .register(state, 0., TextSelectionScopeId::default(), 0, cx);
4658                state.begin(point(px(1.), px(1.)), false, cx);
4659                state.update(point(px(8.), px(1.)), cx);
4660                state.end(cx);
4661            });
4662
4663            assert_eq!(TextSelection::selected_text(window, cx), "reentrant copy");
4664        });
4665    }
4666
4667    #[gpui::test]
4668    fn cross_participant_selection_excludes_participants_outside_its_document_interval(
4669        cx: &mut TestAppContext,
4670    ) {
4671        cx.update(|cx| {
4672            let mut selection_state = WindowSelectionState::default();
4673            let first = FakeParticipant::new("first", cx);
4674            let second = FakeParticipant::new("second", cx);
4675            let third = FakeParticipant::new("third", cx);
4676            first.register(
4677                &mut selection_state,
4678                0.,
4679                TextSelectionScopeId::default(),
4680                0,
4681                cx,
4682            );
4683            second.register(
4684                &mut selection_state,
4685                20.,
4686                TextSelectionScopeId::default(),
4687                1,
4688                cx,
4689            );
4690            third.register(
4691                &mut selection_state,
4692                40.,
4693                TextSelectionScopeId::default(),
4694                2,
4695                cx,
4696            );
4697
4698            selection_state.begin(point(px(1.), px(1.)), false, cx);
4699            selection_state.update(point(px(1.), px(25.)), cx);
4700            selection_state.end(cx);
4701
4702            assert_eq!(selection_state.selected_text(cx), "first\nsecond");
4703            assert!(third.selection.snapshot(cx).is_none());
4704        });
4705    }
4706
4707    #[gpui::test]
4708    fn changing_scope_clears_the_previous_scope_selection(cx: &mut TestAppContext) {
4709        cx.update(|cx| {
4710            let mut selection_state = WindowSelectionState::default();
4711            let base = FakeParticipant::new("base", cx);
4712            let modal = FakeParticipant::new("modal", cx);
4713            base.register(
4714                &mut selection_state,
4715                0.,
4716                TextSelectionScopeId::default(),
4717                0,
4718                cx,
4719            );
4720            modal.register(
4721                &mut selection_state,
4722                20.,
4723                TextSelectionScopeId::from_raw(1),
4724                1,
4725                cx,
4726            );
4727
4728            selection_state.begin(point(px(1.), px(1.)), false, cx);
4729            selection_state.update(point(px(8.), px(1.)), cx);
4730            selection_state.end(cx);
4731            selection_state.set_active_scope(TextSelectionScopeId::from_raw(1), cx);
4732
4733            assert!(!selection_state.has_selection(cx));
4734            assert!(base.selection.snapshot(cx).is_none());
4735        });
4736    }
4737
4738    #[gpui::test]
4739    fn blank_only_drag_never_publishes_or_copies_selection(cx: &mut TestAppContext) {
4740        cx.update(|cx| {
4741            let mut selection_state = WindowSelectionState::default();
4742            let participant = FakeParticipant::new("participant", cx);
4743            participant.register(
4744                &mut selection_state,
4745                0.,
4746                TextSelectionScopeId::default(),
4747                0,
4748                cx,
4749            );
4750
4751            selection_state.begin(point(px(200.), px(1.)), false, cx);
4752            selection_state.update(point(px(200.), px(8.)), cx);
4753            selection_state.end(cx);
4754
4755            assert!(!selection_state.has_selection(cx));
4756            assert_eq!(selection_state.selected_text(cx), "");
4757            assert!(participant.selection.snapshot(cx).is_none());
4758        });
4759    }
4760
4761    #[gpui::test]
4762    fn unmounted_selection_does_not_revive_when_the_participant_returns(cx: &mut TestAppContext) {
4763        cx.update(|cx| {
4764            let mut selection_state = WindowSelectionState::default();
4765            let participant = FakeParticipant::new("stale", cx);
4766            participant.register(
4767                &mut selection_state,
4768                0.,
4769                TextSelectionScopeId::default(),
4770                0,
4771                cx,
4772            );
4773            selection_state.begin(point(px(1.), px(1.)), false, cx);
4774            selection_state.update(point(px(8.), px(1.)), cx);
4775            selection_state.end(cx);
4776            assert_eq!(selection_state.selected_text(cx), "stale");
4777
4778            selection_state.finish_frame(cx);
4779            selection_state.finish_frame(cx);
4780            assert_eq!(selection_state.selected_text(cx), "");
4781            assert!(participant.selection.snapshot(cx).is_none());
4782            participant.register(
4783                &mut selection_state,
4784                0.,
4785                TextSelectionScopeId::default(),
4786                0,
4787                cx,
4788            );
4789            assert_eq!(selection_state.selected_text(cx), "");
4790            assert!(participant.selection.snapshot(cx).is_none());
4791
4792            selection_state.begin(point(px(1.), px(1.)), false, cx);
4793            selection_state.update(point(px(8.), px(1.)), cx);
4794            selection_state.end(cx);
4795            assert_eq!(selection_state.selected_text(cx), "stale");
4796        });
4797    }
4798
4799    #[gpui::test]
4800    fn removing_an_unselected_participant_preserves_the_current_selection(cx: &mut TestAppContext) {
4801        cx.update(|cx| {
4802            let mut selection_state = WindowSelectionState::default();
4803            let selected = FakeParticipant::new("selected", cx);
4804            let unrelated = FakeParticipant::new("unrelated", cx);
4805            let scope = TextSelectionScopeId::default();
4806            selected.register(&mut selection_state, 0., scope, 0, cx);
4807            unrelated.register(&mut selection_state, 20., scope, 1, cx);
4808            selection_state.begin(point(px(1.), px(1.)), false, cx);
4809            selection_state.update(point(px(8.), px(1.)), cx);
4810            selection_state.end(cx);
4811            assert_eq!(selection_state.selected_text(cx), "selected");
4812
4813            selection_state.finish_frame(cx);
4814            selected.register(&mut selection_state, 0., scope, 0, cx);
4815            selection_state.finish_frame(cx);
4816            assert_eq!(selection_state.selected_text(cx), "selected");
4817            unrelated.register(&mut selection_state, 20., scope, 1, cx);
4818            assert_eq!(selection_state.selected_text(cx), "selected");
4819        });
4820    }
4821
4822    #[gpui::test]
4823    fn removing_either_range_endpoint_discards_the_shared_selection(cx: &mut TestAppContext) {
4824        for remove_anchor in [true, false] {
4825            cx.update(|cx| {
4826                let mut selection_state = WindowSelectionState::default();
4827                let anchor = FakeParticipant::new("anchor", cx);
4828                let cursor = FakeParticipant::new("cursor", cx);
4829                let scope = TextSelectionScopeId::default();
4830                anchor.register(&mut selection_state, 0., scope, 0, cx);
4831                cursor.register(&mut selection_state, 20., scope, 1, cx);
4832                selection_state.begin(point(px(1.), px(1.)), false, cx);
4833                selection_state.update(point(px(8.), px(21.)), cx);
4834                selection_state.end(cx);
4835                assert_eq!(selection_state.selected_text(cx), "anchor\ncursor");
4836                selection_state.finish_frame(cx);
4837
4838                if remove_anchor {
4839                    cursor.register(&mut selection_state, 20., scope, 1, cx);
4840                } else {
4841                    anchor.register(&mut selection_state, 0., scope, 0, cx);
4842                }
4843                selection_state.finish_frame(cx);
4844                assert_eq!(selection_state.selected_text(cx), "");
4845                anchor.register(&mut selection_state, 0., scope, 0, cx);
4846                cursor.register(&mut selection_state, 20., scope, 1, cx);
4847                assert_eq!(selection_state.selected_text(cx), "");
4848            });
4849        }
4850    }
4851
4852    #[gpui::test]
4853    fn clear_or_unmount_stops_auto_scroll_before_discarding_the_anchor(cx: &mut TestAppContext) {
4854        for unmount in [false, true] {
4855            let commands = Rc::new(RefCell::new(Vec::new()));
4856            let observed = commands.clone();
4857            let (mut selection_state, participant) = cx.update(|cx| {
4858                let selection_state = WindowSelectionState::default();
4859                let participant = FakeParticipant::new("scroll", cx);
4860                participant
4861                    .selection
4862                    .subscribe(
4863                        move |event, _| {
4864                            if let TextSelectionEvent::AutoScroll(delta) = event {
4865                                observed.borrow_mut().push(*delta);
4866                            }
4867                        },
4868                        cx,
4869                    )
4870                    .detach();
4871                (selection_state, participant)
4872            });
4873            cx.run_until_parked();
4874            cx.update(|cx| {
4875                participant.register(
4876                    &mut selection_state,
4877                    0.,
4878                    TextSelectionScopeId::default(),
4879                    0,
4880                    cx,
4881                );
4882
4883                selection_state.begin(point(px(1.), px(1.)), false, cx);
4884                selection_state.update(point(px(1.), px(25.)), cx);
4885                if unmount {
4886                    selection_state.finish_frame(cx);
4887                    selection_state.finish_frame(cx);
4888                } else {
4889                    selection_state.clear(cx);
4890                }
4891            });
4892            cx.run_until_parked();
4893            assert!(commands.borrow().iter().any(Option::is_some));
4894            assert_eq!(commands.borrow().last(), Some(&None));
4895        }
4896    }
4897
4898    #[gpui::test]
4899    fn drag_auto_scroll_stops_when_the_content_mask_collapses(cx: &mut TestAppContext) {
4900        let window = cx.add_window(|_, cx| WindowSelectionView {
4901            selection: TextSelectionHandle::new("unused", cx),
4902        });
4903        window
4904            .update(cx, |_, window, cx| {
4905                let state = cx.new(|_| WindowSelectionState::default());
4906                let participant = FakeParticipant::new("participant", cx);
4907                state.update(cx, |state, cx| {
4908                    participant.register(state, 0., TextSelectionScopeId::default(), 0, cx);
4909                    state.begin(point(px(1.), px(1.)), false, cx);
4910                });
4911                // The scrollable ancestor got clipped away mid-drag, so the
4912                // refreshed registration carries a collapsed content mask.
4913                let collapsed = Bounds::new(point(px(0.), px(0.)), size(px(100.), px(0.)));
4914                state.update(cx, |state, cx| {
4915                    state.register_participant(
4916                        participant.selection.clone(),
4917                        TextSelectionRegistration::new(
4918                            Hitbox {
4919                                id: HitboxId::placeholder(),
4920                                bounds: collapsed,
4921                                content_mask: ContentMask { bounds: collapsed },
4922                                behavior: HitboxBehavior::Normal,
4923                            },
4924                            collapsed,
4925                        )
4926                        .with_text_bounds(vec![collapsed]),
4927                        cx,
4928                    );
4929                    state.update_in_window(point(px(1.), px(50.)), window, cx);
4930                    assert!(!state.auto_scroll.is_active());
4931                    assert!(state.auto_scroll.last_drag_position.is_none());
4932                });
4933            })
4934            .unwrap();
4935    }
4936
4937    #[gpui::test]
4938    fn drag_auto_scroll_starts_at_the_edge_that_hides_text(cx: &mut TestAppContext) {
4939        let window = cx.add_window(|_, cx| WindowSelectionView {
4940            selection: TextSelectionHandle::new("unused", cx),
4941        });
4942        let registration = |bounds: Bounds<Pixels>, mask: Bounds<Pixels>| {
4943            TextSelectionRegistration::new(
4944                Hitbox {
4945                    id: HitboxId::placeholder(),
4946                    bounds,
4947                    content_mask: ContentMask { bounds: mask },
4948                    behavior: HitboxBehavior::Normal,
4949                },
4950                bounds,
4951            )
4952            .with_text_bounds(vec![bounds])
4953        };
4954        window
4955            .update(cx, |_, window, cx| {
4956                let state = cx.new(|_| WindowSelectionState::default());
4957                let card = FakeParticipant::new("card", cx);
4958                let below = FakeParticipant::new("below", cx);
4959                // A card clips its own text and hides none of it.
4960                let card_bounds = Bounds::new(point(px(0.), px(40.)), size(px(100.), px(20.)));
4961                state.update(cx, |state, cx| {
4962                    state.register_participant(
4963                        card.selection.clone(),
4964                        registration(card_bounds, card_bounds),
4965                        cx,
4966                    );
4967                    state.begin(point(px(1.), px(45.)), false, cx);
4968
4969                    // Nothing is hidden: leaving the card scrolls nothing.
4970                    state.update_in_window(point(px(1.), px(70.)), window, cx);
4971                    assert!(!state.auto_scroll.is_active());
4972
4973                    // The viewport ends at 200 and cuts the text below the card.
4974                    let cut = Bounds::new(point(px(0.), px(190.)), size(px(100.), px(20.)));
4975                    let seen = Bounds::new(point(px(0.), px(190.)), size(px(100.), px(10.)));
4976                    state.register_participant(
4977                        below.selection.clone(),
4978                        registration(cut, seen),
4979                        cx,
4980                    );
4981                    state.update_in_window(point(px(1.), px(70.)), window, cx);
4982                    assert!(!state.auto_scroll.is_active());
4983                    state.update_in_window(point(px(1.), px(195.)), window, cx);
4984                    assert!(state.auto_scroll.is_active());
4985                    assert_eq!(
4986                        state.auto_scroll.last_drag_position,
4987                        Some(point(px(1.), px(195.)))
4988                    );
4989                    // Back inside the viewport, the scroll stops.
4990                    state.update_in_window(point(px(1.), px(70.)), window, cx);
4991                    assert!(!state.auto_scroll.is_active());
4992                    state.clear(cx);
4993                });
4994            })
4995            .unwrap();
4996    }
4997
4998    #[gpui::test]
4999    fn pointer_moves_after_a_click_do_not_auto_scroll(cx: &mut TestAppContext) {
5000        let window = cx.add_window(|_, cx| WindowSelectionView {
5001            selection: TextSelectionHandle::new("unused", cx),
5002        });
5003        window
5004            .update(cx, |_, window, cx| {
5005                let state = cx.new(|_| WindowSelectionState::default());
5006                let participant = FakeParticipant::new("participant", cx);
5007                state.update(cx, |state, cx| {
5008                    participant.register(state, 0., TextSelectionScopeId::default(), 0, cx);
5009                    // A click on text keeps its anchor so shift-click can extend it.
5010                    state.begin(point(px(1.), px(1.)), false, cx);
5011                    state.end(cx);
5012                    assert!(state.anchor.is_some());
5013
5014                    state.update_in_window(point(px(1.), px(50.)), window, cx);
5015                    assert!(!state.auto_scroll.is_active());
5016                });
5017            })
5018            .unwrap();
5019    }
5020
5021    #[gpui::test]
5022    fn proxy_endpoints_break_equal_position_ties_by_document_order(cx: &mut TestAppContext) {
5023        cx.update(|cx| {
5024            let mut selection_state = WindowSelectionState::default();
5025            let later = FakeParticipant::new("later", cx);
5026            let earlier = FakeParticipant::new("earlier", cx);
5027            later.register(
5028                &mut selection_state,
5029                0.,
5030                TextSelectionScopeId::default(),
5031                2,
5032                cx,
5033            );
5034            earlier.register(
5035                &mut selection_state,
5036                0.,
5037                TextSelectionScopeId::default(),
5038                1,
5039                cx,
5040            );
5041
5042            selection_state.begin(point(px(1.), px(1.)), false, cx);
5043            selection_state.update(point(px(200.), px(25.)), cx);
5044            let endpoint = selection_state.snapshot().unwrap().cursor();
5045
5046            assert_eq!(endpoint.entity_id(), Some(earlier.selection.entity_id()));
5047        });
5048    }
5049
5050    #[gpui::test]
5051    fn equal_area_hovered_participants_break_ties_by_document_order(cx: &mut TestAppContext) {
5052        cx.update(|cx| {
5053            for _ in 0..64 {
5054                let mut selection_state = WindowSelectionState::default();
5055                let later = FakeParticipant::new("later", cx);
5056                let earliest = FakeParticipant::new("earliest", cx);
5057                let middle = FakeParticipant::new("middle", cx);
5058                later.register(
5059                    &mut selection_state,
5060                    0.,
5061                    TextSelectionScopeId::default(),
5062                    30,
5063                    cx,
5064                );
5065                earliest.register(
5066                    &mut selection_state,
5067                    0.,
5068                    TextSelectionScopeId::default(),
5069                    10,
5070                    cx,
5071                );
5072                middle.register(
5073                    &mut selection_state,
5074                    0.,
5075                    TextSelectionScopeId::default(),
5076                    20,
5077                    cx,
5078                );
5079
5080                selection_state.begin(point(px(1.), px(1.)), false, cx);
5081                selection_state.update(point(px(8.), px(1.)), cx);
5082
5083                assert_eq!(
5084                    selection_state.snapshot().unwrap().anchor().entity_id(),
5085                    Some(earliest.selection.entity_id())
5086                );
5087            }
5088        });
5089    }
5090
5091    #[gpui::test]
5092    fn text_selection_namespace_is_a_safe_no_op_until_the_element_is_rendered(
5093        cx: &mut TestAppContext,
5094    ) {
5095        let (_, cx) = cx.add_window_view(|_, cx| WindowSelectionView {
5096            selection: TextSelectionHandle::new("not enabled", cx),
5097        });
5098        cx.update(|window, cx| {
5099            assert!(!TextSelection::has_selection(window, cx));
5100            assert_eq!(TextSelection::selected_text(window, cx), "");
5101            TextSelection::clear(window, cx);
5102            TextSelection::end(window, cx);
5103            assert!(!TextSelection::has_selection(window, cx));
5104        });
5105    }
5106
5107    #[gpui::test]
5108    fn unit_selection_element_supports_scope_and_registration_on_the_first_frame(
5109        cx: &mut TestAppContext,
5110    ) {
5111        let (view, cx) = cx.add_window_view(|_, cx| FirstFrameScopedSelectionView {
5112            selection: TextSelectionHandle::new("first frame", cx),
5113        });
5114        let selection = cx.update(|_, cx| view.read(cx).selection.clone());
5115
5116        cx.update(|window, cx| {
5117            let _ = window.draw(cx);
5118            let state = WindowSelectionState::existing(window, cx).unwrap();
5119            assert_eq!(
5120                state.read(cx).active_scope,
5121                TextSelectionScopeId::from_raw(23)
5122            );
5123            assert!(
5124                state
5125                    .read(cx)
5126                    .participants
5127                    .borrow()
5128                    .contains_key(&selection.entity_id())
5129            );
5130        });
5131    }
5132
5133    #[gpui::test]
5134    fn lazy_registration_does_not_enable_queries_without_the_element(cx: &mut TestAppContext) {
5135        let (_, cx) = cx.add_window_view(|_, cx| WindowSelectionView {
5136            selection: TextSelectionHandle::new("registered", cx),
5137        });
5138        cx.update(|window, cx| {
5139            let selection = TextSelectionHandle::new("registered", cx);
5140            selection.set_local_selection(true, cx);
5141            let bounds = Bounds::new(point(px(0.), px(0.)), size(px(100.), px(20.)));
5142            let hitbox = Hitbox {
5143                id: HitboxId::placeholder(),
5144                bounds,
5145                content_mask: ContentMask { bounds },
5146                behavior: HitboxBehavior::Normal,
5147            };
5148            selection.register(
5149                TextSelectionRegistration::new(hitbox, bounds).with_text_bounds(vec![bounds]),
5150                window,
5151                cx,
5152            );
5153            assert_eq!(TextSelection::selected_text(window, cx), "");
5154            assert!(!TextSelection::has_selection(window, cx));
5155            TextSelection::clear(window, cx);
5156            assert_eq!(TextSelection::selected_text(window, cx), "");
5157        });
5158    }
5159
5160    struct RetainedSelectionText {
5161        text: Entity<crate::text::TextViewState>,
5162        renders: Rc<Cell<usize>>,
5163        scrollable: bool,
5164    }
5165
5166    impl RetainedSelectionText {
5167        fn new(text: &str, cx: &mut App) -> Entity<Self> {
5168            let text = cx.new(|cx| crate::text::TextViewState::markdown(text, cx));
5169            cx.new(|_| Self {
5170                text,
5171                renders: Rc::new(Cell::new(0)),
5172                scrollable: false,
5173            })
5174        }
5175    }
5176
5177    impl Render for RetainedSelectionText {
5178        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5179            self.renders.set(self.renders.get() + 1);
5180            div()
5181                .w(px(240.))
5182                .h(px(32.))
5183                .child(crate::text::TextView::new(&self.text).scrollable(self.scrollable))
5184        }
5185    }
5186
5187    struct RetainedSelectionRoot {
5188        texts: Vec<Entity<RetainedSelectionText>>,
5189    }
5190
5191    impl Render for RetainedSelectionRoot {
5192        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5193            div()
5194                .size_full()
5195                .flex()
5196                .flex_col()
5197                .child(TextSelectionLayer)
5198                .children(self.texts.iter().cloned())
5199        }
5200    }
5201
5202    #[cfg(feature = "gpui-fast")]
5203    struct RetainedScrollingSelectionRoot {
5204        text: Entity<RetainedSelectionText>,
5205        unrelated: Entity<RetainedSelectionText>,
5206        scroll: gpui::ScrollHandle,
5207    }
5208
5209    #[cfg(feature = "gpui-fast")]
5210    impl Render for RetainedScrollingSelectionRoot {
5211        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5212            div()
5213                .size_full()
5214                .flex()
5215                .flex_col()
5216                .child(TextSelectionLayer)
5217                .child(
5218                    div()
5219                        .id("scrolling-texts")
5220                        .w(px(240.))
5221                        .h(px(64.))
5222                        .flex_none()
5223                        .overflow_y_scroll()
5224                        .track_scroll(&self.scroll)
5225                        .child(div().h(px(352.)).child(self.text.clone())),
5226                )
5227                .child(self.unrelated.clone())
5228        }
5229    }
5230
5231    fn draw_selection_frame(cx: &mut gpui::VisualTestContext) {
5232        cx.update(|window, cx| window.draw(cx).clear(cx));
5233        cx.run_until_parked();
5234    }
5235
5236    /// Dispatch the gesture and copy in the same update, before either paint
5237    /// or the TextView's selection subscription can repair its copy cache.
5238    fn select_retained_texts(
5239        last: usize,
5240        release: bool,
5241        cx: &mut gpui::VisualTestContext,
5242    ) -> String {
5243        cx.update(|window, cx| {
5244            let state = WindowSelectionState::existing(window, cx).unwrap();
5245            let mut bounds = state
5246                .read(cx)
5247                .participants
5248                .borrow()
5249                .values()
5250                .map(|participant| participant.registration.text_bounds[0])
5251                .collect::<Vec<_>>();
5252            bounds.sort_by(|a, b| a.top().partial_cmp(&b.top()).unwrap());
5253            let start = point(bounds[0].left() + px(0.1), bounds[0].center().y);
5254            let end = point(bounds[last].right() - px(0.1), bounds[last].center().y);
5255            window.dispatch_event(
5256                gpui::PlatformInput::MouseDown(MouseDownEvent {
5257                    position: start,
5258                    button: MouseButton::Left,
5259                    click_count: 1,
5260                    ..Default::default()
5261                }),
5262                cx,
5263            );
5264            window.dispatch_event(
5265                gpui::PlatformInput::MouseMove(MouseMoveEvent {
5266                    position: end,
5267                    pressed_button: Some(MouseButton::Left),
5268                    ..Default::default()
5269                }),
5270                cx,
5271            );
5272            if release {
5273                window.dispatch_event(
5274                    gpui::PlatformInput::MouseUp(MouseUpEvent {
5275                        position: end,
5276                        button: MouseButton::Left,
5277                        modifiers: gpui::Modifiers::default(),
5278                        click_count: 1,
5279                    }),
5280                    cx,
5281                );
5282            }
5283            assert!(TextSelection::has_selection(window, cx));
5284            TextSelection::selected_text(window, cx)
5285        })
5286    }
5287
5288    /// Uses only the original public TextView/selection APIs and real retained
5289    /// views, so this also runs against the implementation before this fix.
5290    #[cfg(feature = "gpui-fast")]
5291    #[gpui::test]
5292    fn active_selection_keeps_unrelated_text_views_retained(cx: &mut TestAppContext) {
5293        cx.update(crate::init);
5294        let (root, cx) = cx.add_window_view(|_, cx| RetainedSelectionRoot {
5295            texts: ["alpha", "bravo", "charlie"]
5296                .into_iter()
5297                .map(|text| RetainedSelectionText::new(text, cx))
5298                .collect(),
5299        });
5300        draw_selection_frame(cx);
5301        draw_selection_frame(cx);
5302        assert_eq!(select_retained_texts(0, false, cx).trim(), "alpha");
5303        draw_selection_frame(cx);
5304        draw_selection_frame(cx);
5305        let texts = root.read_with(cx, |root, _| root.texts.clone());
5306        let unrelated = texts[1].read_with(cx, |text, _| text.renders.clone());
5307        let before = unrelated.get();
5308        let first_line = cx.update(|window, cx| {
5309            let state = WindowSelectionState::existing(window, cx).unwrap();
5310            state
5311                .read(cx)
5312                .participants
5313                .borrow()
5314                .values()
5315                .map(|participant| participant.registration.text_bounds[0])
5316                .min_by(|a, b| a.top().partial_cmp(&b.top()).unwrap())
5317                .unwrap()
5318        });
5319        for fraction in [0.2, 0.4, 0.6, 0.8] {
5320            cx.update(|window, cx| {
5321                window.dispatch_event(
5322                    gpui::PlatformInput::MouseMove(MouseMoveEvent {
5323                        position: point(
5324                            first_line.left() + first_line.size.width * fraction,
5325                            first_line.center().y,
5326                        ),
5327                        pressed_button: Some(MouseButton::Left),
5328                        ..Default::default()
5329                    }),
5330                    cx,
5331                );
5332            });
5333            draw_selection_frame(cx);
5334        }
5335        assert_ne!(
5336            cx.update(|window, cx| TextSelection::selected_text(window, cx))
5337                .trim(),
5338            "alpha"
5339        );
5340        assert_eq!(
5341            unrelated.get(),
5342            before,
5343            "active registration redrew an unrelated view"
5344        );
5345    }
5346
5347    #[gpui::test]
5348    fn active_selection_frame_publication_visits_participants_linearly(cx: &mut TestAppContext) {
5349        for count in [4, 16] {
5350            cx.update(crate::init);
5351            let (_, cx) = cx.add_window_view(|_, cx| RetainedSelectionRoot {
5352                texts: (0..count)
5353                    .map(|_| RetainedSelectionText::new("text", cx))
5354                    .collect(),
5355            });
5356            draw_selection_frame(cx);
5357            draw_selection_frame(cx);
5358            assert_eq!(select_retained_texts(0, false, cx).trim(), "text");
5359            draw_selection_frame(cx);
5360            draw_selection_frame(cx);
5361            cx.update(|window, cx| {
5362                let state = WindowSelectionState::existing(window, cx).unwrap();
5363                state.read(cx).snapshot_visits.set(0);
5364                window.refresh();
5365                window.draw(cx).clear(cx);
5366            });
5367            cx.run_until_parked();
5368            cx.update(|window, cx| {
5369                let state = WindowSelectionState::existing(window, cx).unwrap();
5370                let visits = state.read(cx).snapshot_visits.get();
5371                assert!(
5372                    visits >= count,
5373                    "the frame must actually visit the participants"
5374                );
5375                assert!(
5376                    visits <= 3 * count,
5377                    "{count} participants required {visits} snapshot visits"
5378                );
5379            });
5380        }
5381    }
5382
5383    #[cfg(feature = "gpui-fast")]
5384    #[gpui::test]
5385    fn scrolling_selected_text_does_not_rebuild_unrelated_document_order(cx: &mut TestAppContext) {
5386        cx.update(crate::init);
5387        let (root, cx) = cx.add_window_view(|_, cx| {
5388            let scrolling = RetainedSelectionText::new("alpha\n\nbravo\n\ncharlie\n\ndelta", cx);
5389            scrolling.update(cx, |text, _| text.scrollable = true);
5390            RetainedSelectionRoot {
5391                texts: vec![scrolling, RetainedSelectionText::new("unrelated", cx)],
5392            }
5393        });
5394        draw_selection_frame(cx);
5395        draw_selection_frame(cx);
5396        assert_eq!(select_retained_texts(0, false, cx).trim(), "alpha");
5397        draw_selection_frame(cx);
5398        draw_selection_frame(cx);
5399        let unrelated = root.read_with(cx, |root, cx| root.texts[1].read(cx).renders.clone());
5400        let before = unrelated.get();
5401        let previous_offset = cx.update(|window, cx| {
5402            let state = WindowSelectionState::existing(window, cx).unwrap();
5403            let registration = state
5404                .read(cx)
5405                .participants
5406                .borrow()
5407                .values()
5408                .find(|participant| participant.registration.self_scroll)
5409                .unwrap()
5410                .registration
5411                .clone();
5412            let offset = registration.scroll_offset;
5413            window.dispatch_event(
5414                gpui::PlatformInput::Scroll(ScrollEvent {
5415                    position: registration.bounds.center(),
5416                    delta: ScrollDelta::Pixels(point(px(0.), px(-20.))),
5417                    touch_phase: TouchPhase::Moved,
5418                    ..Default::default()
5419                }),
5420                cx,
5421            );
5422            offset
5423        });
5424        for _ in 0..3 {
5425            draw_selection_frame(cx);
5426        }
5427        cx.update(|window, cx| {
5428            let state = WindowSelectionState::existing(window, cx).unwrap();
5429            let participants = state.read(cx).participants.borrow();
5430            let scrolling = participants
5431                .values()
5432                .find(|participant| participant.registration.self_scroll)
5433                .unwrap();
5434            assert_ne!(
5435                scrolling.registration.scroll_offset, previous_offset,
5436                "the content must actually scroll"
5437            );
5438            assert!(!state.read(cx).refresh_held_cursor.get());
5439        });
5440        assert_eq!(
5441            unrelated.get(),
5442            before,
5443            "a content scroll must not request a full order rebuild"
5444        );
5445    }
5446
5447    #[cfg(feature = "gpui-fast")]
5448    #[gpui::test]
5449    fn ancestor_scrolling_keeps_unrelated_text_views_retained(cx: &mut TestAppContext) {
5450        for selected in [false, true] {
5451            cx.update(crate::init);
5452            let (root, cx) = cx.add_window_view(|_, cx| RetainedScrollingSelectionRoot {
5453                text: RetainedSelectionText::new("alpha", cx),
5454                unrelated: RetainedSelectionText::new("unrelated", cx),
5455                scroll: gpui::ScrollHandle::new(),
5456            });
5457            draw_selection_frame(cx);
5458            draw_selection_frame(cx);
5459            if selected {
5460                assert_eq!(select_retained_texts(0, true, cx).trim(), "alpha");
5461                draw_selection_frame(cx);
5462                draw_selection_frame(cx);
5463            }
5464            let (scroll, renders, text) = root.read_with(cx, |root, cx| {
5465                (
5466                    root.scroll.clone(),
5467                    root.unrelated.read(cx).renders.clone(),
5468                    root.text.read(cx).text.clone(),
5469                )
5470            });
5471            let before = renders.get();
5472            let bounds_before = text.read_with(cx, |text, _| text.bounds());
5473            for _ in 0..4 {
5474                let previous_offset = scroll.offset();
5475                cx.update(|window, cx| {
5476                    window.dispatch_event(
5477                        gpui::PlatformInput::Scroll(ScrollEvent {
5478                            position: point(px(20.), px(20.)),
5479                            delta: ScrollDelta::Pixels(point(px(0.), px(-4.))),
5480                            touch_phase: TouchPhase::Moved,
5481                            ..Default::default()
5482                        }),
5483                        cx,
5484                    );
5485                });
5486                for _ in 0..3 {
5487                    draw_selection_frame(cx);
5488                }
5489                assert_ne!(scroll.offset(), previous_offset, "the ancestor must scroll");
5490                assert_eq!(
5491                    renders.get(),
5492                    before,
5493                    "ancestor scrolling rebuilt an unrelated text view (selected: {selected})"
5494                );
5495                let copied = cx.update(|window, cx| TextSelection::selected_text(window, cx));
5496                assert_eq!(copied.trim(), if selected { "alpha" } else { "" });
5497            }
5498            assert_ne!(text.read_with(cx, |text, _| text.bounds()), bounds_before);
5499        }
5500    }
5501
5502    #[gpui::test]
5503    fn retained_text_order_survives_partial_frames_insertion_and_reordering(
5504        cx: &mut TestAppContext,
5505    ) {
5506        cx.update(crate::init);
5507        let (root, cx) = cx.add_window_view(|_, cx| RetainedSelectionRoot {
5508            texts: ["alpha", "bravo", "charlie"]
5509                .into_iter()
5510                .map(|text| RetainedSelectionText::new(text, cx))
5511                .collect(),
5512        });
5513        draw_selection_frame(cx);
5514        draw_selection_frame(cx);
5515        let words = |text: String| {
5516            text.split_whitespace()
5517                .map(str::to_owned)
5518                .collect::<Vec<_>>()
5519        };
5520        assert_eq!(
5521            words(select_retained_texts(2, true, cx)),
5522            ["alpha", "bravo", "charlie"]
5523        );
5524        let texts = root.read_with(cx, |root, _| root.texts.clone());
5525        for _ in 0..3 {
5526            texts[1].update(cx, |_, cx| cx.notify());
5527            draw_selection_frame(cx);
5528            assert_eq!(
5529                words(cx.update(|window, cx| TextSelection::selected_text(window, cx))),
5530                ["alpha", "bravo", "charlie"]
5531            );
5532        }
5533        root.update(cx, |root, cx| {
5534            root.texts
5535                .insert(1, RetainedSelectionText::new("delta", cx));
5536            cx.notify();
5537        });
5538        for _ in 0..3 {
5539            draw_selection_frame(cx);
5540        }
5541        assert_eq!(
5542            words(cx.update(|window, cx| TextSelection::selected_text(window, cx))),
5543            ["alpha", "delta", "bravo", "charlie"]
5544        );
5545        root.update(cx, |root, cx| {
5546            root.texts.swap(1, 2);
5547            cx.notify();
5548        });
5549        for _ in 0..3 {
5550            draw_selection_frame(cx);
5551        }
5552        assert_eq!(
5553            words(cx.update(|window, cx| TextSelection::selected_text(window, cx))),
5554            ["alpha", "bravo", "delta", "charlie"]
5555        );
5556        #[cfg(feature = "gpui-fast")]
5557        {
5558            let renders = texts[0].read_with(cx, |text, _| text.renders.clone());
5559            let before = renders.get();
5560            for _ in 0..3 {
5561                draw_selection_frame(cx);
5562            }
5563            assert_eq!(renders.get(), before, "order recovery must settle");
5564        }
5565        // Keep the endpoint's entity alive after removing its element. A
5566        // later remount must not resurrect the retired window gesture.
5567        root.update(cx, |root, cx| {
5568            root.texts.pop();
5569            cx.notify();
5570        });
5571        draw_selection_frame(cx);
5572        draw_selection_frame(cx);
5573        assert!(
5574            cx.update(|window, cx| TextSelection::selected_text(window, cx))
5575                .is_empty()
5576        );
5577        root.update(cx, |root, cx| {
5578            root.texts.push(texts[2].clone());
5579            cx.notify();
5580        });
5581        draw_selection_frame(cx);
5582        assert!(
5583            cx.update(|window, cx| TextSelection::selected_text(window, cx))
5584                .is_empty()
5585        );
5586    }
5587
5588    /// A view reading the window's selection state, beside selectable text,
5589    /// counting its renders.
5590    #[cfg(feature = "gpui-fast")]
5591    struct SelectionStateReader {
5592        renders: Rc<Cell<usize>>,
5593    }
5594
5595    #[cfg(feature = "gpui-fast")]
5596    impl Render for SelectionStateReader {
5597        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5598            self.renders.set(self.renders.get() + 1);
5599            if let Some(state) = WindowSelectionState::existing(window, cx) {
5600                let _ = state.read(cx).participants.borrow().len();
5601            }
5602            div().size_full()
5603        }
5604    }
5605
5606    /// The selectable text of a [`ToggleSelectionElementView`] beside a
5607    /// [`SelectionStateReader`].
5608    #[cfg(feature = "gpui-fast")]
5609    struct ReaderBesideSelectionView {
5610        text: gpui::Entity<ToggleSelectionElementView>,
5611        reader: gpui::Entity<SelectionStateReader>,
5612    }
5613
5614    #[cfg(feature = "gpui-fast")]
5615    impl Render for ReaderBesideSelectionView {
5616        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5617            div()
5618                .size_full()
5619                .child(self.reader.clone())
5620                .child(self.text.clone())
5621        }
5622    }
5623
5624    /// Selectable text drawn again, nothing about its selection changed,
5625    /// writes neither the window's selection state nor its own: a view
5626    /// reading them is retained, as it would not be had they changed.
5627    #[cfg(feature = "gpui-fast")]
5628    #[gpui::test]
5629    fn redrawing_selectable_text_leaves_its_readers_retained(cx: &mut TestAppContext) {
5630        let renders = Rc::new(Cell::new(0));
5631        let (view, cx) = cx.add_window_view(|_, cx| ReaderBesideSelectionView {
5632            text: cx.new(|cx| ToggleSelectionElementView {
5633                enabled: true,
5634                selection: TextSelectionHandle::new("text", cx),
5635            }),
5636            reader: cx.new(|_| SelectionStateReader {
5637                renders: renders.clone(),
5638            }),
5639        });
5640        let text = cx.update(|_, cx| view.read(cx).text.clone());
5641        let redraw = |cx: &mut gpui::VisualTestContext| {
5642            text.update(cx, |_, cx| cx.notify());
5643            cx.update(|window, cx| {
5644                let _ = window.draw(cx);
5645                window.simulate_next_frame(cx);
5646            });
5647            cx.run_until_parked();
5648        };
5649        redraw(cx);
5650        redraw(cx);
5651        let before = renders.get();
5652        for _ in 0..4 {
5653            redraw(cx);
5654        }
5655        assert_eq!(renders.get(), before, "the reader rendered again");
5656    }
5657
5658    #[gpui::test]
5659    fn retained_selection_state_releases_and_does_not_resurrect_selection(cx: &mut TestAppContext) {
5660        let (view, cx) = cx.add_window_view(|_, cx| ToggleSelectionElementView {
5661            enabled: true,
5662            selection: TextSelectionHandle::new("local", cx),
5663        });
5664        let selection = cx.update(|_, cx| view.read(cx).selection.clone());
5665        cx.update(|window, cx| {
5666            let _ = window.draw(cx);
5667            selection.set_local_selection(true, cx);
5668            assert!(TextSelection::has_selection(window, cx));
5669
5670            window.simulate_next_frame(cx);
5671            assert!(TextSelection::has_selection(window, cx));
5672            let _ = window.draw(cx);
5673            assert!(TextSelection::has_selection(window, cx));
5674        });
5675        view.update(cx, |view, cx| {
5676            view.enabled = false;
5677            cx.notify();
5678        });
5679        cx.update(|window, cx| {
5680            let _ = window.draw(cx);
5681        });
5682        cx.update(|window, cx| {
5683            window.simulate_next_frame(cx);
5684        });
5685        cx.update(|window, cx| {
5686            window.simulate_next_frame(cx);
5687        });
5688        cx.run_until_parked();
5689        cx.update(|window, cx| {
5690            assert!(!TextSelection::has_selection(window, cx));
5691            assert_eq!(TextSelection::selected_text(window, cx), "");
5692            assert!(!selection.has_local_selection(cx));
5693        });
5694
5695        view.update(cx, |view, cx| {
5696            view.enabled = true;
5697            cx.notify();
5698        });
5699        cx.update(|window, cx| {
5700            let _ = window.draw(cx);
5701            assert!(!TextSelection::has_selection(window, cx));
5702            assert_eq!(TextSelection::selected_text(window, cx), "");
5703        });
5704    }
5705
5706    #[gpui::test]
5707    fn mounted_selection_element_does_not_keep_an_idle_frame_queue_alive(cx: &mut TestAppContext) {
5708        let (_, cx) = cx.add_window_view(|_, _| SelectionElementOnlyView);
5709        cx.update(|window, cx| {
5710            let _ = window.draw(cx);
5711            assert_eq!(window.simulate_next_frame(cx), 0);
5712            assert_eq!(window.simulate_next_frame(cx), 0);
5713            assert!(live_text_selection_state(window, cx).is_some());
5714        });
5715    }
5716
5717    #[gpui::test]
5718    fn selection_element_initializes_suppression_and_respects_bubble_suppression(
5719        cx: &mut TestAppContext,
5720    ) {
5721        let (_, cx) = cx.add_window_view(|_, _| SelectionElementOnlyView);
5722        cx.update(|window, cx| {
5723            let _ = window.draw(cx);
5724        });
5725        cx.simulate_mouse_down(
5726            point(px(1.), px(1.)),
5727            MouseButton::Left,
5728            gpui::Modifiers::default(),
5729        );
5730        cx.simulate_mouse_up(
5731            point(px(1.), px(1.)),
5732            MouseButton::Left,
5733            gpui::Modifiers::default(),
5734        );
5735        cx.update(|window, cx| {
5736            assert!(GlobalState::is_text_selection_suppressed(cx));
5737            assert!(!TextSelection::has_selection(window, cx));
5738        });
5739    }
5740
5741    #[gpui::test]
5742    fn frame_sweep_keeps_a_participant_registered_before_the_selection_element_paints(
5743        cx: &mut TestAppContext,
5744    ) {
5745        cx.update(|cx| {
5746            let mut selection_state = WindowSelectionState::default();
5747            let participant = FakeParticipant::new("painted first", cx);
5748            participant.register(
5749                &mut selection_state,
5750                0.,
5751                TextSelectionScopeId::default(),
5752                0,
5753                cx,
5754            );
5755            selection_state.begin(point(px(1.), px(1.)), false, cx);
5756            selection_state.update(point(px(8.), px(1.)), cx);
5757            selection_state.end(cx);
5758
5759            selection_state.finish_frame(cx);
5760
5761            assert_eq!(selection_state.selected_text(cx), "painted first");
5762            assert!(participant.selection.snapshot(cx).is_some());
5763        });
5764    }
5765
5766    #[gpui::test]
5767    fn two_selection_elements_schedule_only_one_post_frame_sweep(cx: &mut TestAppContext) {
5768        let (view, cx) = cx.add_window_view(|_, cx| DoubleSelectionElementView {
5769            selection: TextSelectionHandle::new("once", cx),
5770        });
5771        cx.update(|window, cx| {
5772            let selection_state = WindowSelectionState::ensure(window, cx);
5773            let selection = view.read(cx).selection.clone();
5774            selection_state.update(cx, |selection_state, cx| {
5775                FakeParticipant { selection }.register(
5776                    selection_state,
5777                    0.,
5778                    TextSelectionScopeId::default(),
5779                    0,
5780                    cx,
5781                );
5782                selection_state.begin(point(px(1.), px(1.)), false, cx);
5783                selection_state.update(point(px(8.), px(1.)), cx);
5784                selection_state.end(cx);
5785            });
5786
5787            let _ = window.draw(cx);
5788            window.simulate_next_frame(cx);
5789
5790            let items = selection_state.read(cx).copy_items(cx);
5791            assert_eq!(resolve_copy_items(items, cx), "once");
5792        });
5793    }
5794
5795    #[gpui::test]
5796    fn duplicate_selection_elements_gate_real_pointer_gestures_and_reentrant_clear(
5797        cx: &mut TestAppContext,
5798    ) {
5799        let (view, cx) = cx.add_window_view(|_, cx| DoubleSelectionElementView {
5800            selection: TextSelectionHandle::new("once", cx),
5801        });
5802        let clear_count = Rc::new(Cell::new(0));
5803        cx.update(|window, cx| {
5804            let state = WindowSelectionState::ensure(window, cx);
5805            let state_for_clear = state;
5806            let count = clear_count.clone();
5807            let selection = view.read(cx).selection.clone();
5808            selection
5809                .subscribe(
5810                    move |event, cx| {
5811                        if matches!(event, TextSelectionEvent::Cleared) {
5812                            count.set(count.get() + 1);
5813                            let _ = state_for_clear.read(cx).snapshot();
5814                        }
5815                    },
5816                    cx,
5817                )
5818                .detach();
5819            let _ = window.draw(cx);
5820        });
5821
5822        cx.simulate_mouse_down(
5823            point(px(10.), px(10.)),
5824            MouseButton::Left,
5825            gpui::Modifiers::default(),
5826        );
5827        cx.simulate_mouse_up(
5828            point(px(10.), px(10.)),
5829            MouseButton::Left,
5830            gpui::Modifiers::default(),
5831        );
5832        cx.simulate_mouse_down(
5833            point(px(70.), px(10.)),
5834            MouseButton::Left,
5835            gpui::Modifiers {
5836                shift: true,
5837                ..Default::default()
5838            },
5839        );
5840        cx.simulate_mouse_up(
5841            point(px(70.), px(10.)),
5842            MouseButton::Left,
5843            gpui::Modifiers::default(),
5844        );
5845        cx.update(|window, cx| assert!(TextSelection::has_selection(window, cx)));
5846
5847        cx.simulate_mouse_down(
5848            point(px(15.), px(10.)),
5849            MouseButton::Left,
5850            gpui::Modifiers::default(),
5851        );
5852        cx.simulate_mouse_move(
5853            point(px(85.), px(10.)),
5854            Some(MouseButton::Left),
5855            gpui::Modifiers::default(),
5856        );
5857        cx.simulate_mouse_up(
5858            point(px(85.), px(10.)),
5859            MouseButton::Left,
5860            gpui::Modifiers::default(),
5861        );
5862        cx.update(|window, cx| assert!(TextSelection::has_selection(window, cx)));
5863        assert_eq!(clear_count.get(), 3);
5864    }
5865
5866    #[gpui::test]
5867    fn selection_layer_ends_a_mouse_gesture_when_the_release_is_lost(cx: &mut TestAppContext) {
5868        let (text, layout) = laid_out_runs(&["alpha bravo charlie delta"], cx)
5869            .pop()
5870            .unwrap();
5871        let (view, cx) = cx.add_window_view(|_, cx| DoubleSelectionElementView {
5872            selection: TextSelectionHandle::new("", cx),
5873        });
5874        cx.update(|window, cx| {
5875            let _ = window.draw(cx);
5876            let selection = view.read(cx).selection.clone();
5877            selection.update_runs(&[text_run(0, text.clone(), layout.clone())], cx);
5878        });
5879        let start = layout.position_for_index(1).unwrap();
5880        let selected_to = layout.position_for_index(7).unwrap();
5881        let beyond = layout.position_for_index(18).unwrap();
5882        cx.simulate_mouse_down(start, MouseButton::Left, gpui::Modifiers::default());
5883        cx.simulate_mouse_move(selected_to, MouseButton::Left, gpui::Modifiers::default());
5884        let before = cx.update(|_, cx| {
5885            let snapshot = view.read(cx).selection.snapshot(cx).unwrap();
5886            assert!(snapshot.is_selecting());
5887            (snapshot.anchor(), snapshot.cursor())
5888        });
5889        // No MouseUp: its delivery was consumed by a compositor resize grab.
5890        cx.simulate_mouse_move(beyond, None, gpui::Modifiers::default());
5891        cx.update(|_, cx| {
5892            let snapshot = view.read(cx).selection.snapshot(cx).unwrap();
5893            assert!(!snapshot.is_selecting());
5894            assert_eq!((snapshot.anchor(), snapshot.cursor()), before);
5895        });
5896    }
5897
5898    #[gpui::test]
5899    fn selection_layer_ignores_presses_on_the_native_window_frame(cx: &mut TestAppContext) {
5900        let (text, layout) = laid_out_runs(&["alpha bravo charlie delta"], cx)
5901            .pop()
5902            .unwrap();
5903        let (view, cx) = cx.add_window_view(|_, cx| DoubleSelectionElementView {
5904            selection: TextSelectionHandle::new("", cx),
5905        });
5906        cx.update(|window, cx| {
5907            let _ = window.draw(cx);
5908            let selection = view.read(cx).selection.clone();
5909            selection.update_runs(&[text_run(0, text.clone(), layout.clone())], cx);
5910        });
5911        let start = layout.position_for_index(1).unwrap();
5912        let selected_to = layout.position_for_index(7).unwrap();
5913        cx.simulate_mouse_down(start, MouseButton::Left, gpui::Modifiers::default());
5914        cx.simulate_mouse_move(selected_to, MouseButton::Left, gpui::Modifiers::default());
5915        cx.simulate_mouse_up(selected_to, MouseButton::Left, gpui::Modifiers::default());
5916        let selected = cx.update(|_, cx| {
5917            let snapshot = view.read(cx).selection.snapshot(cx).unwrap();
5918            (snapshot.anchor(), snapshot.cursor())
5919        });
5920        // A press on the native title bar arrives above the client area and
5921        // the move loop swallows its release.
5922        let title_bar = point(start.x, px(-12.));
5923        cx.simulate_mouse_down(title_bar, MouseButton::Left, gpui::Modifiers::default());
5924        cx.simulate_mouse_move(start, MouseButton::Left, gpui::Modifiers::default());
5925        cx.simulate_mouse_move(selected_to, None, gpui::Modifiers::default());
5926        cx.update(|_, cx| {
5927            let snapshot = view.read(cx).selection.snapshot(cx).unwrap();
5928            assert!(!snapshot.is_selecting());
5929            assert_eq!((snapshot.anchor(), snapshot.cursor()), selected);
5930        });
5931    }
5932
5933    #[gpui::test]
5934    fn selection_layer_handles_real_double_and_triple_click_events(cx: &mut TestAppContext) {
5935        let (text, layout) = laid_out_runs(&["alpha beta"], cx).pop().unwrap();
5936        let (view, cx) = cx.add_window_view(|_, cx| DoubleSelectionElementView {
5937            selection: TextSelectionHandle::new("", cx),
5938        });
5939        cx.update(|window, cx| {
5940            let _ = window.draw(cx);
5941            let selection = view.read(cx).selection.clone();
5942            selection.resolve_content_key_with(|_, _| Some(TextSelectionContentKey::new(17)), cx);
5943            selection.update_runs(&[text_run(0, text.clone(), layout.clone())], cx);
5944        });
5945
5946        let position = layout.position_for_index(7).unwrap();
5947        cx.simulate_event(MouseDownEvent {
5948            position,
5949            modifiers: gpui::Modifiers::default(),
5950            button: MouseButton::Left,
5951            click_count: 2,
5952            first_mouse: false,
5953        });
5954        cx.simulate_event(MouseUpEvent {
5955            position,
5956            modifiers: gpui::Modifiers::default(),
5957            button: MouseButton::Left,
5958            click_count: 2,
5959        });
5960        cx.update(|window, cx| {
5961            let selection = view.read(cx).selection.clone();
5962            selection.update_runs(&[text_run(0, text.clone(), layout.clone())], cx);
5963            assert_eq!(TextSelection::selected_text(window, cx), "beta");
5964            let snapshot = selection.snapshot(cx).unwrap();
5965            assert_eq!(
5966                snapshot.anchor().content_key(),
5967                Some(TextSelectionContentKey::new(17))
5968            );
5969            assert_eq!(
5970                snapshot.cursor().content_key(),
5971                Some(TextSelectionContentKey::new(17))
5972            );
5973        });
5974
5975        cx.simulate_event(MouseDownEvent {
5976            position,
5977            modifiers: gpui::Modifiers::default(),
5978            button: MouseButton::Left,
5979            click_count: 3,
5980            first_mouse: false,
5981        });
5982        cx.simulate_event(MouseUpEvent {
5983            position,
5984            modifiers: gpui::Modifiers::default(),
5985            button: MouseButton::Left,
5986            click_count: 3,
5987        });
5988        cx.update(|window, cx| {
5989            let selection = view.read(cx).selection.clone();
5990            selection.update_runs(&[text_run(0, text, layout)], cx);
5991            assert_eq!(TextSelection::selected_text(window, cx), "alpha beta");
5992        });
5993    }
5994
5995    /// Each text a [`crate::SelectableText`] of its own, one below the other.
5996    struct SelectableTextsView {
5997        texts: Vec<&'static str>,
5998    }
5999
6000    impl Render for SelectableTextsView {
6001        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6002            div()
6003                .size_full()
6004                .child(TextSelectionLayer)
6005                .child(
6006                    div()
6007                        .w(px(400.))
6008                        .children(self.texts.iter().enumerate().map(|(ix, text)| {
6009                            crate::SelectableText::new(("text", ix), *text)
6010                                .document_order(ix as u64)
6011                        })),
6012                )
6013        }
6014    }
6015
6016    /// The middle of the character at `index` of `text`, as it was painted.
6017    fn painted_position(text: &str, index: usize, window: &Window, cx: &App) -> Point<Pixels> {
6018        let state = WindowSelectionState::existing(window, cx).unwrap();
6019        let participants = state.read(cx).participants.borrow();
6020        participants
6021            .values()
6022            .filter_map(|registration| registration.participant.upgrade())
6023            .find_map(|participant| {
6024                let runs = participant.read(cx).runs.borrow();
6025                let run = runs.iter().find(|run| run.text.as_ref() == text)?;
6026                let position = run.layout.position_for_index(index)?;
6027                Some(point(
6028                    position.x + px(1.),
6029                    position.y + run.layout.line_height() / 2.,
6030                ))
6031            })
6032            .unwrap()
6033    }
6034
6035    /// Presses the left button `click_count` times at the character `index`
6036    /// of `text`, and returns where.
6037    fn press_at(
6038        text: &str,
6039        index: usize,
6040        click_count: usize,
6041        shift: bool,
6042        cx: &mut gpui::VisualTestContext,
6043    ) -> Point<Pixels> {
6044        let position = cx.update(|window, cx| painted_position(text, index, window, cx));
6045        cx.simulate_event(MouseDownEvent {
6046            position,
6047            modifiers: gpui::Modifiers {
6048                shift,
6049                ..Default::default()
6050            },
6051            button: MouseButton::Left,
6052            click_count,
6053            first_mouse: false,
6054        });
6055        position
6056    }
6057
6058    /// Drags the pressed button to the character `index` of `text`, and
6059    /// returns the text selected there.
6060    fn drag_to(text: &str, index: usize, cx: &mut gpui::VisualTestContext) -> String {
6061        let position = cx.update(|window, cx| painted_position(text, index, window, cx));
6062        cx.simulate_event(MouseMoveEvent {
6063            position,
6064            pressed_button: Some(MouseButton::Left),
6065            modifiers: gpui::Modifiers::default(),
6066        });
6067        painted_selection(cx)
6068    }
6069
6070    fn release(click_count: usize, cx: &mut gpui::VisualTestContext) {
6071        let position = cx.update(|window, _| window.mouse_position());
6072        cx.simulate_event(MouseUpEvent {
6073            position,
6074            modifiers: gpui::Modifiers::default(),
6075            button: MouseButton::Left,
6076            click_count,
6077        });
6078    }
6079
6080    fn painted_selection(cx: &mut gpui::VisualTestContext) -> String {
6081        cx.update(|window, cx| {
6082            let _ = window.draw(cx);
6083            TextSelection::selected_text(window, cx)
6084        })
6085    }
6086
6087    #[gpui::test]
6088    fn double_click_drag_extends_the_selection_by_words(cx: &mut TestAppContext) {
6089        let (_, cx) = cx.add_window_view(|_, _| SelectableTextsView {
6090            texts: vec!["one two three", "four five six"],
6091        });
6092        painted_selection(cx);
6093
6094        press_at("one two three", 5, 2, false, cx);
6095        assert_eq!(painted_selection(cx), "two");
6096        assert_eq!(drag_to("one two three", 9, cx), "two three");
6097        // Backward, the whole of the word the drag started from stays.
6098        assert_eq!(drag_to("one two three", 1, cx), "one two");
6099        assert_eq!(drag_to("four five six", 6, cx), "two three\nfour five");
6100        release(2, cx);
6101        assert_eq!(painted_selection(cx), "two three\nfour five");
6102    }
6103
6104    #[gpui::test]
6105    fn a_press_without_a_release_does_not_keep_a_stale_selection(cx: &mut TestAppContext) {
6106        let (_, cx) = cx.add_window_view(|_, _| SelectableTextsView {
6107            texts: vec!["one two three", "four five six"],
6108        });
6109        painted_selection(cx);
6110
6111        press_at("one two three", 0, 1, false, cx);
6112        assert_eq!(drag_to("one two three", 7, cx), "one two");
6113
6114        press_at("four five six", 2, 1, false, cx);
6115        release(1, cx);
6116        assert_eq!(painted_selection(cx), "");
6117    }
6118
6119    #[gpui::test]
6120    fn triple_click_drag_extends_the_selection_by_lines(cx: &mut TestAppContext) {
6121        let text = "first line\nsecond line\nthird line";
6122        let (_, cx) = cx.add_window_view(|_, _| SelectableTextsView { texts: vec![text] });
6123        painted_selection(cx);
6124
6125        press_at(text, 13, 3, false, cx);
6126        assert_eq!(painted_selection(cx), "second line");
6127        assert_eq!(drag_to(text, 25, cx), "second line\nthird line");
6128        assert_eq!(drag_to(text, 2, cx), "first line\nsecond line");
6129        release(3, cx);
6130        assert_eq!(painted_selection(cx), "first line\nsecond line");
6131    }
6132
6133    #[gpui::test]
6134    fn shift_click_after_a_double_click_extends_by_words(cx: &mut TestAppContext) {
6135        let text = "one two three";
6136        let (_, cx) = cx.add_window_view(|_, _| SelectableTextsView { texts: vec![text] });
6137        painted_selection(cx);
6138
6139        press_at(text, 5, 2, false, cx);
6140        release(2, cx);
6141        press_at(text, 9, 1, true, cx);
6142        release(1, cx);
6143        assert_eq!(painted_selection(cx), "two three");
6144        press_at(text, 1, 1, true, cx);
6145        release(1, cx);
6146        assert_eq!(painted_selection(cx), "one two");
6147
6148        // A plain click ends the word selection: a drag from it is by characters.
6149        press_at(text, 5, 1, false, cx);
6150        assert_eq!(drag_to(text, 9, cx), "wo t");
6151        release(1, cx);
6152    }
6153}