Skip to main content

gpui_base/
text_selection.rs

1use std::{
2    collections::HashMap,
3    ops::Range,
4    rc::Rc,
5    sync::atomic::{AtomicU64, Ordering},
6};
7
8use gpui::{
9    App, AppContext as _, Bounds, Context, Element, ElementId, Entity, EntityId, EventEmitter,
10    Global, GlobalElementId, Half, Hitbox, HitboxBehavior, Hsla, InputEvent as _,
11    InspectorElementId, IntoElement, LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent,
12    MouseUpEvent, Pixels, Point, ScrollDelta, ScrollWheelEvent, SharedString, Style, Subscription,
13    TextLayout, TouchPhase, WeakEntity, Window, point, px,
14};
15
16use crate::text_boundary::{line_range_at, word_range_at};
17use crate::touch_selection::{
18    EdgeDrag, SelectionEdge, TouchHandle, TouchSelectionSnapshot, caret_in_view,
19};
20use crate::{AutoScroll, GlobalState};
21
22/// An opaque selection layer identifier.
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
24pub struct TextSelectionScopeId(u64);
25
26impl TextSelectionScopeId {
27    /// Allocates a process-unique scope identifier.
28    ///
29    /// Keep the returned identifier for the semantic lifetime of the scope;
30    /// do not allocate a new identifier on every frame.
31    pub fn new() -> Self {
32        static NEXT_SCOPE_ID: AtomicU64 = AtomicU64::new(1);
33        let value = NEXT_SCOPE_ID
34            .try_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
35                value.checked_add(1)
36            })
37            .expect("text selection scope identifiers exhausted");
38        Self(value)
39    }
40
41    #[cfg(test)]
42    const fn from_raw(value: u64) -> Self {
43        Self(value)
44    }
45}
46
47/// Stable participant-defined identity for virtualized participant content.
48#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
49pub struct TextSelectionContentKey(u64);
50
51impl TextSelectionContentKey {
52    /// Creates a key from a participant-defined stable content identity.
53    pub const fn new(value: u64) -> Self {
54        Self(value)
55    }
56
57    /// Returns the participant-defined value.
58    pub const fn value(self) -> u64 {
59        self.0
60    }
61}
62
63/// A selection endpoint anchored to a participant's content coordinates.
64#[derive(Clone, Copy, Debug, PartialEq)]
65pub struct TextSelectionEndpoint {
66    entity_id: Option<EntityId>,
67    point: Point<Pixels>,
68    content_key: Option<TextSelectionContentKey>,
69}
70
71impl TextSelectionEndpoint {
72    /// Creates an endpoint at a participant-relative content point.
73    pub(crate) const fn new(entity_id: Option<EntityId>, point: Point<Pixels>) -> Self {
74        Self {
75            entity_id,
76            point,
77            content_key: None,
78        }
79    }
80
81    /// Sets participant-defined endpoint metadata.
82    pub(crate) const fn with_content_key(mut self, content_key: TextSelectionContentKey) -> Self {
83        self.content_key = Some(content_key);
84        self
85    }
86
87    /// Returns the participant which owns this endpoint, when it hit one.
88    pub const fn entity_id(&self) -> Option<EntityId> {
89        self.entity_id
90    }
91
92    /// Returns the participant-relative content point.
93    pub const fn content_point(&self) -> Point<Pixels> {
94        self.point
95    }
96
97    /// Returns participant-defined endpoint metadata captured when it hit a participant.
98    pub const fn content_key(&self) -> Option<TextSelectionContentKey> {
99        self.content_key
100    }
101}
102
103/// Window-coordinate anchor and cursor points for painting a selection.
104#[derive(Clone, Copy, Debug, PartialEq)]
105pub struct TextSelectionWindowPoints {
106    anchor: Point<Pixels>,
107    cursor: Point<Pixels>,
108}
109
110impl TextSelectionWindowPoints {
111    /// Returns the stable anchor in window coordinates.
112    pub const fn anchor(&self) -> Point<Pixels> {
113        self.anchor
114    }
115
116    /// Returns the moving cursor in window coordinates.
117    pub const fn cursor(&self) -> Point<Pixels> {
118        self.cursor
119    }
120}
121
122/// Participant-relative selection endpoints with an optional rendering projection.
123#[derive(Clone, Copy, Debug, PartialEq)]
124pub struct TextSelectionSnapshot {
125    anchor: TextSelectionEndpoint,
126    cursor: TextSelectionEndpoint,
127    is_selecting: bool,
128    window_points: Option<TextSelectionWindowPoints>,
129    coverage: TextSelectionCoverage,
130}
131
132/// How much of one participant participates in a window selection.
133#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
134pub enum TextSelectionCoverage {
135    /// Only the interval between this participant's two endpoints is selected.
136    #[default]
137    Bounded,
138    /// The participant is selected from its beginning through its endpoint.
139    FromStart,
140    /// The participant is selected from its endpoint through its end.
141    ToEnd,
142    /// The entire participant lies between endpoints in other participants.
143    Full,
144}
145
146impl TextSelectionSnapshot {
147    /// Creates a snapshot from stable participant-relative endpoints.
148    pub(crate) const fn new(anchor: TextSelectionEndpoint, cursor: TextSelectionEndpoint) -> Self {
149        Self {
150            anchor,
151            cursor,
152            is_selecting: false,
153            window_points: None,
154            coverage: TextSelectionCoverage::Bounded,
155        }
156    }
157
158    /// Sets whether the pointer gesture is still active.
159    pub(crate) const fn with_selecting(mut self, is_selecting: bool) -> Self {
160        self.is_selecting = is_selecting;
161        self
162    }
163
164    /// Sets the current window-coordinate rendering projection.
165    pub(crate) const fn with_window_points(
166        mut self,
167        window_points: Option<TextSelectionWindowPoints>,
168    ) -> Self {
169        self.window_points = window_points;
170        self
171    }
172
173    /// Sets the portion of the receiving participant covered by this selection.
174    #[cfg(test)]
175    pub(crate) const fn with_coverage(mut self, coverage: TextSelectionCoverage) -> Self {
176        self.coverage = coverage;
177        self
178    }
179
180    /// Returns the stable anchor endpoint.
181    pub const fn anchor(&self) -> TextSelectionEndpoint {
182        self.anchor
183    }
184
185    /// Returns the moving cursor endpoint.
186    pub const fn cursor(&self) -> TextSelectionEndpoint {
187        self.cursor
188    }
189
190    /// Returns whether the pointer gesture is still active.
191    pub const fn is_selecting(&self) -> bool {
192        self.is_selecting
193    }
194
195    /// Returns the window-coordinate endpoints for participants that need them.
196    pub const fn window_points(&self) -> Option<TextSelectionWindowPoints> {
197        self.window_points
198    }
199
200    /// Returns the portion of the receiving participant covered by this selection.
201    pub const fn coverage(&self) -> TextSelectionCoverage {
202        self.coverage
203    }
204}
205
206/// Retained element state proving a participant is still in the window.
207///
208/// A participant reports its geometry from `paint`, which a cached view
209/// (`Entity::cached`) skips: GPUI replays the recorded frame instead. The
210/// element's retained state is replayed with it, so this marker outlives the
211/// frames whose paint never ran, and dies with the frame that drops the
212/// element for good.
213struct RenderedMarker;
214
215/// Per-frame geometry reported by a [`TextSelectionHandle`] participant.
216pub struct TextSelectionRegistration {
217    hitbox: Hitbox,
218    bounds: Bounds<Pixels>,
219    scroll_offset: Point<Pixels>,
220    scope: TextSelectionScopeId,
221    document_order: u64,
222    text_bounds: Vec<Bounds<Pixels>>,
223    self_scroll: bool,
224    selection_edges: Option<(Bounds<Pixels>, Bounds<Pixels>)>,
225    rendered: Option<WeakEntity<RenderedMarker>>,
226}
227
228impl TextSelectionRegistration {
229    /// Creates a registration with default scope, order, and scroll offset.
230    pub fn new(hitbox: Hitbox, bounds: Bounds<Pixels>) -> Self {
231        Self {
232            hitbox,
233            bounds,
234            scroll_offset: Point::default(),
235            scope: TextSelectionScopeId::default(),
236            document_order: 0,
237            text_bounds: Vec::new(),
238            self_scroll: false,
239            selection_edges: None,
240            rendered: None,
241        }
242    }
243
244    /// Ties this registration to the retained state of the element reporting
245    /// it, so that a frame replayed from that element's cached view keeps it.
246    ///
247    /// Call this from the reporting element's `prepaint` or `paint`. A
248    /// registration made outside a drawing element cannot be tied to one and
249    /// is swept the first frame it misses, as every registration used to be.
250    pub fn with_rendered_element(
251        mut self,
252        participant: &TextSelectionHandle,
253        window: &mut Window,
254        cx: &mut App,
255    ) -> Self {
256        self.rendered = Some(
257            window
258                .use_keyed_state(
259                    ElementId::NamedInteger(
260                        "text-selection-participant".into(),
261                        participant.entity_id().as_u64(),
262                    ),
263                    cx,
264                    |_, _| RenderedMarker,
265                )
266                .downgrade(),
267        );
268        self
269    }
270
271    /// Whether the element that reported this registration is still part of
272    /// the window, even if it did not paint the frame that just finished.
273    fn is_rendered(&self) -> bool {
274        self.rendered
275            .as_ref()
276            .is_some_and(|marker| marker.upgrade().is_some())
277    }
278
279    /// Marks a participant that scrolls its own content in response to
280    /// [`TextSelectionEvent::AutoScroll`]. Drag auto-scroll then drives it
281    /// directly, measured against its own bounds, instead of synthesizing a
282    /// wheel event for the nearest scrollable ancestor.
283    pub(crate) fn with_self_scroll(mut self, self_scroll: bool) -> Self {
284        self.self_scroll = self_scroll;
285        self
286    }
287
288    /// Sets the participant's content scroll offset.
289    pub fn with_scroll_offset(mut self, scroll_offset: Point<Pixels>) -> Self {
290        self.scroll_offset = scroll_offset;
291        self
292    }
293
294    /// Sets the opaque selection scope.
295    pub fn with_scope(mut self, scope: TextSelectionScopeId) -> Self {
296        self.scope = scope;
297        self
298    }
299
300    /// Sets the stable logical document order.
301    pub fn with_document_order(mut self, document_order: u64) -> Self {
302        self.document_order = document_order;
303        self
304    }
305
306    /// Sets the glyph-bearing bounds used to reject blank-only gestures.
307    pub fn with_text_bounds(mut self, text_bounds: Vec<Bounds<Pixels>>) -> Self {
308        self.text_bounds = text_bounds;
309        self
310    }
311
312    /// Sets where the participant painted the two ends of its selection: the
313    /// caret line box before its first selected character and the one after
314    /// its last, in window coordinates. The touch handles are drawn there.
315    pub fn with_selection_edges(mut self, start: Bounds<Pixels>, end: Bounds<Pixels>) -> Self {
316        self.selection_edges = Some((start, end));
317        self
318    }
319
320    /// Returns the participant hitbox.
321    pub fn hitbox(&self) -> &Hitbox {
322        &self.hitbox
323    }
324
325    /// Returns the participant's window-coordinate bounds.
326    pub const fn bounds(&self) -> Bounds<Pixels> {
327        self.bounds
328    }
329
330    /// Returns the participant's content scroll offset.
331    pub const fn scroll_offset(&self) -> Point<Pixels> {
332        self.scroll_offset
333    }
334
335    /// Returns the opaque selection scope.
336    pub const fn scope(&self) -> TextSelectionScopeId {
337        self.scope
338    }
339
340    /// Returns the stable logical document order.
341    pub const fn document_order(&self) -> u64 {
342        self.document_order
343    }
344
345    /// Returns the glyph-bearing bounds used to reject blank-only gestures.
346    pub fn text_bounds(&self) -> &[Bounds<Pixels>] {
347        &self.text_bounds
348    }
349
350    /// Returns the caret line boxes at the participant's selection ends.
351    pub const fn selection_edges(&self) -> Option<(Bounds<Pixels>, Bounds<Pixels>)> {
352        self.selection_edges
353    }
354}
355
356/// Laid-out text reported by a plain selection participant during paint.
357#[derive(Clone)]
358pub struct TextSelectionRun {
359    /// Logical order within the containing participant.
360    document_order: u64,
361    /// The exact text used to produce `layout`.
362    text: SharedString,
363    /// Laid-out glyph geometry in window coordinates.
364    layout: TextLayout,
365    /// The run's window-coordinate paint bounds.
366    bounds: Bounds<Pixels>,
367}
368
369impl TextSelectionRun {
370    /// Creates a laid-out text run.
371    pub fn new(text: impl Into<SharedString>, layout: TextLayout, bounds: Bounds<Pixels>) -> Self {
372        Self {
373            document_order: 0,
374            text: text.into(),
375            layout,
376            bounds,
377        }
378    }
379
380    /// Sets the run's logical order within the participant.
381    pub const fn with_document_order(mut self, document_order: u64) -> Self {
382        self.document_order = document_order;
383        self
384    }
385
386    /// Returns the run's logical order within its participant.
387    pub const fn document_order(&self) -> u64 {
388        self.document_order
389    }
390
391    /// Returns the exact text used to produce the layout.
392    pub fn text(&self) -> &SharedString {
393        &self.text
394    }
395
396    /// Returns the laid-out glyph geometry.
397    pub fn layout(&self) -> &TextLayout {
398        &self.layout
399    }
400
401    /// Returns the run's window-coordinate paint bounds.
402    pub const fn bounds(&self) -> Bounds<Pixels> {
403        self.bounds
404    }
405}
406
407/// Selection projected onto a participant's laid-out text runs.
408#[derive(Clone, Debug, Default, PartialEq, Eq)]
409pub struct TextSelectionProjection {
410    /// Selected UTF-8 byte ranges paired with the input runs.
411    ranges: Vec<Option<Range<usize>>>,
412    /// Whether the participant participates in the current selection.
413    is_active: bool,
414}
415
416impl TextSelectionProjection {
417    /// Returns selected UTF-8 byte ranges paired with the input runs.
418    pub fn ranges(&self) -> &[Option<Range<usize>>] {
419        &self.ranges
420    }
421
422    /// Returns whether the participant participates in the selection.
423    pub const fn is_active(&self) -> bool {
424        self.is_active
425    }
426}
427
428/// Projects a participant selection snapshot onto laid-out plain-text runs.
429///
430/// The returned states retain the input order so callers can pair every state
431/// with its run. The ranges are always character boundaries; `order` is used
432/// only when a participant caches selected text for copying.
433fn project_ranges(
434    snapshot: Option<TextSelectionSnapshot>,
435    runs: &[TextSelectionRun],
436) -> TextSelectionProjection {
437    let Some(snapshot) = snapshot else {
438        return TextSelectionProjection {
439            ranges: vec![None; runs.len()],
440            is_active: false,
441        };
442    };
443    let Some(window_points) = snapshot.window_points() else {
444        return TextSelectionProjection {
445            ranges: vec![None; runs.len()],
446            is_active: true,
447        };
448    };
449
450    TextSelectionProjection {
451        ranges: runs
452            .iter()
453            .map(|run| selection_range_for_run(run, window_points.anchor, window_points.cursor))
454            .collect(),
455        is_active: true,
456    }
457}
458
459fn selection_range_for_run(
460    run: &TextSelectionRun,
461    selection_start: Point<Pixels>,
462    selection_end: Point<Pixels>,
463) -> Option<Range<usize>> {
464    if run.text.len() != run.layout.len() {
465        return None;
466    }
467
468    if run.text.is_empty() {
469        return None;
470    }
471
472    let line_height = run.layout.line_height();
473    // Each character is tested with its row's top and height, so a run whose
474    // rows all miss the band, or all lie strictly inside it with no endpoint
475    // on any row, has the same answer for every character. Decide those
476    // without the walk below, which scans the layout twice per character.
477    let (rows_top, rows_bottom) = text_rows_extent(&run.layout, line_height);
478    let band_top = selection_start.y.min(selection_end.y);
479    let band_bottom = selection_start.y.max(selection_end.y);
480    if rows_bottom <= band_top || rows_top > band_bottom {
481        return None;
482    }
483    if band_top < rows_top && band_bottom >= rows_bottom {
484        return Some(0..run.text.len());
485    }
486
487    let mut range = None;
488    for (offset, character) in run.text.char_indices() {
489        let next_offset = offset + character.len_utf8();
490        let Some(position) = run.layout.position_for_index(offset) else {
491            continue;
492        };
493
494        let char_width = run
495            .layout
496            .position_for_index(next_offset)
497            .filter(|next| next.y == position.y)
498            .map_or_else(|| line_height.half(), |next| next.x - position.x);
499
500        if point_in_selection_band(
501            position,
502            char_width,
503            selection_start,
504            selection_end,
505            line_height,
506        ) {
507            range.get_or_insert(offset..offset).end = next_offset;
508        }
509    }
510    range
511}
512
513/// The top of the first laid-out row of `text_layout` and the bottom of its
514/// last one, each row `line_height` tall as a selection band test sees it.
515///
516/// Both ends are accumulated the way [`TextLayout::position_for_index`] places
517/// rows, so comparisons against them agree with a per-character walk to the
518/// bit. The last laid-out row may hold no character such a walk tests (a
519/// trailing empty line, or a row whose only character is placed at the end of
520/// the row before it); callers treat the extent as covering, never as exact.
521pub(crate) fn text_rows_extent(text_layout: &TextLayout, line_height: Pixels) -> (Pixels, Pixels) {
522    let top = text_layout.bounds().top();
523    let layout_line_height = text_layout.line_height();
524    let lines = text_layout.line_layouts();
525    let mut last_line_top = top;
526    for line in lines.iter().take(lines.len().saturating_sub(1)) {
527        last_line_top += line.size(layout_line_height).height;
528    }
529    let last_row_top = lines.last().map_or(top, |line| {
530        last_line_top + line.line_count().saturating_sub(1) as f32 * layout_line_height
531    });
532    (top, last_row_top + line_height)
533}
534
535fn points_for_multi_click(
536    runs: &[TextSelectionRun],
537    position: Point<Pixels>,
538    click_count: usize,
539) -> Option<(Point<Pixels>, Point<Pixels>)> {
540    let run = runs.iter().find(|run| run.bounds.contains(&position))?;
541    if run.text.len() != run.layout.len() {
542        return None;
543    }
544    let offset = run.layout.index_for_position(position).ok()?;
545    let range = match click_count {
546        2 => word_range_at(&run.text, offset)?,
547        3.. => line_range_at(&run.text, offset),
548        _ => return None,
549    };
550    if range.is_empty() {
551        return None;
552    }
553    Some((
554        run.layout.position_for_index(range.start)?,
555        run.layout.position_for_index(range.end)?,
556    ))
557}
558
559fn point_in_selection_band(
560    position: Point<Pixels>,
561    char_width: Pixels,
562    selection_start: Point<Pixels>,
563    selection_end: Point<Pixels>,
564    line_height: Pixels,
565) -> bool {
566    let point_in_line =
567        |point: Point<Pixels>| point.y >= position.y && point.y < position.y + line_height;
568    let top = selection_start.y.min(selection_end.y);
569    let bottom = selection_start.y.max(selection_end.y);
570    let x = position.x + char_width.half();
571
572    if position.y + line_height <= top || position.y > bottom {
573        return false;
574    }
575
576    if point_in_line(selection_start) && point_in_line(selection_end) {
577        let left = selection_start.x.min(selection_end.x);
578        let right = selection_start.x.max(selection_end.x);
579        return x >= left && x <= right;
580    }
581
582    let (top_point, bottom_point) = if selection_start.y < selection_end.y {
583        (selection_start, selection_end)
584    } else {
585        (selection_end, selection_start)
586    };
587    if point_in_line(top_point) {
588        x >= top_point.x
589    } else if point_in_line(bottom_point) {
590        x <= bottom_point.x
591    } else {
592        true
593    }
594}
595
596type FocusCallback = Rc<dyn Fn(&mut Window, &mut App)>;
597type ClearHandler = Rc<dyn Fn(&mut App)>;
598type CopyCallback = Rc<dyn Fn(&mut App) -> String>;
599type ContentKeyResolver = Rc<dyn Fn(Point<Pixels>, &App) -> Option<TextSelectionContentKey>>;
600
601/// Notifications emitted by a text-selection participant.
602#[derive(Clone, Copy, Debug, PartialEq)]
603pub enum TextSelectionEvent {
604    /// The participant's window-selection projection changed.
605    SelectionChanged(Option<TextSelectionSnapshot>),
606    /// The active drag requests vertical auto-scroll, or `None` to stop.
607    AutoScroll(Option<Pixels>),
608    /// Window selection cleared the participant's participant-local state.
609    Cleared,
610    /// The touch selection the participant takes part in changed: it
611    /// appeared, its ends moved, a handle drag began or ended, or it went
612    /// away. The participant paints the handles and lays their hitboxes out
613    /// from the ends it painted last frame, so it renders once more.
614    TouchSelectionChanged,
615}
616
617struct CopyItem {
618    document_order: u64,
619    callback: Option<CopyCallback>,
620    fallback: String,
621}
622
623fn resolve_copy_items(mut items: Vec<CopyItem>, cx: &mut App) -> String {
624    items.sort_by_key(|item| item.document_order);
625    items
626        .into_iter()
627        .map(|item| {
628            item.callback
629                .map(|callback| callback(cx))
630                .unwrap_or(item.fallback)
631        })
632        .filter(|text| !text.trim().is_empty())
633        .collect::<Vec<_>>()
634        .join("\n")
635}
636
637fn dispatch_clear_handlers(handlers: Vec<ClearHandler>, cx: &mut App) {
638    for handler in handlers {
639        handler(cx);
640    }
641}
642
643struct SelectableTextState {
644    fallback_copy_text: String,
645    projected_copy_text: Option<String>,
646    runs: Vec<TextSelectionRun>,
647    local_selection: bool,
648    snapshot: Option<TextSelectionSnapshot>,
649    on_focus: Option<FocusCallback>,
650    clear: Option<ClearHandler>,
651    copy: Option<CopyCallback>,
652    content_key_resolver: Option<ContentKeyResolver>,
653}
654
655impl EventEmitter<TextSelectionEvent> for SelectableTextState {}
656
657impl SelectableTextState {
658    fn new(fallback_copy_text: impl Into<String>) -> Self {
659        Self {
660            fallback_copy_text: fallback_copy_text.into(),
661            projected_copy_text: None,
662            runs: Vec::new(),
663            local_selection: false,
664            snapshot: None,
665            on_focus: None,
666            clear: None,
667            copy: None,
668            content_key_resolver: None,
669        }
670    }
671
672    /// The current geometry selection snapshot for this participant.
673    fn snapshot(&self) -> Option<TextSelectionSnapshot> {
674        self.snapshot
675    }
676
677    /// Sets the text copied by this participant when it participates in selection.
678    fn set_fallback_copy_text(&mut self, text: impl Into<String>) {
679        self.fallback_copy_text = text.into();
680        self.projected_copy_text = None;
681    }
682
683    /// Marks participant-local selection (for example select-all) as active.
684    fn set_local_selection(&mut self, active: bool) {
685        self.local_selection = active;
686    }
687
688    /// Projects this participant's current snapshot onto plain-text runs and caches
689    /// their selected substrings for the window selection query.
690    ///
691    /// Call this once per painted run. A snapshot change or
692    /// Clearing window selection invalidates the cache immediately, so copy
693    /// never returns text from a previous projection while waiting to repaint.
694    fn update_runs(&mut self, runs: &[TextSelectionRun]) -> TextSelectionProjection {
695        self.runs = runs.to_vec();
696        let states = project_ranges(self.snapshot, runs);
697        let mut selected_runs = runs
698            .iter()
699            .zip(states.ranges())
700            .enumerate()
701            .filter_map(|(index, (run, state))| {
702                state.as_ref().map(|range| {
703                    debug_assert!(run.text.is_char_boundary(range.start));
704                    debug_assert!(run.text.is_char_boundary(range.end));
705                    (
706                        run.document_order,
707                        index,
708                        run.text[range.clone()].to_string(),
709                    )
710                })
711            })
712            .collect::<Vec<_>>();
713        selected_runs.sort_by_key(|(order, index, _)| (*order, *index));
714        self.projected_copy_text =
715            Some(selected_runs.into_iter().map(|(_, _, text)| text).collect());
716        states
717    }
718
719    /// Installs the callback which focuses the participant when a drag begins in it.
720    fn set_focus_handler(&mut self, callback: impl Fn(&mut Window, &mut App) + 'static) {
721        self.on_focus = Some(Rc::new(callback));
722    }
723
724    fn clear_with(&mut self, callback: impl Fn(&mut App) + 'static) {
725        self.clear = Some(Rc::new(callback));
726    }
727
728    /// Installs a participant-specific copy projection.
729    fn copy_with(&mut self, callback: impl Fn(&mut App) -> String + 'static) {
730        self.copy = Some(Rc::new(callback));
731    }
732
733    /// Installs a participant-specific lookup for stable virtualized content keys.
734    fn resolve_content_key_with(
735        &mut self,
736        callback: impl Fn(Point<Pixels>, &App) -> Option<TextSelectionContentKey> + 'static,
737    ) {
738        self.content_key_resolver = Some(Rc::new(callback));
739    }
740
741    fn set_snapshot(&mut self, snapshot: Option<TextSelectionSnapshot>, cx: &mut Context<Self>) {
742        if self.snapshot == snapshot {
743            return;
744        }
745        self.snapshot = snapshot;
746        self.projected_copy_text = None;
747        cx.emit(TextSelectionEvent::SelectionChanged(snapshot));
748    }
749
750    fn clear_state(&mut self, cx: &mut Context<Self>) -> Option<ClearHandler> {
751        self.snapshot = None;
752        self.projected_copy_text = None;
753        self.local_selection = false;
754        cx.emit(TextSelectionEvent::Cleared);
755        cx.emit(TextSelectionEvent::SelectionChanged(None));
756        self.clear.clone()
757    }
758
759    fn set_auto_scroll(&self, delta: Option<Pixels>, cx: &mut Context<Self>) {
760        cx.emit(TextSelectionEvent::AutoScroll(delta));
761    }
762
763    fn focus(&self, window: &mut Window, cx: &mut App) {
764        if let Some(callback) = self.on_focus.clone() {
765            window.defer(cx, move |window, cx| callback(window, cx));
766        }
767    }
768
769    fn copy_item(&self, document_order: u64) -> Option<CopyItem> {
770        (self.snapshot.is_some() || self.local_selection).then(|| CopyItem {
771            document_order,
772            callback: self.copy.clone(),
773            fallback: self
774                .projected_copy_text
775                .clone()
776                .unwrap_or_else(|| self.fallback_copy_text.clone()),
777        })
778    }
779}
780
781/// The touch handles a participant laid out for a frame, with their hitboxes.
782#[derive(Default)]
783pub struct TouchHandleLayout {
784    hitboxes: Vec<(SelectionEdge, Hitbox)>,
785}
786
787/// A stable, participant-neutral handle for text that participates in window selection.
788#[derive(Clone)]
789pub struct TextSelectionHandle(Entity<SelectableTextState>);
790
791impl TextSelectionHandle {
792    /// Creates a selection participant handle with fallback text for copying.
793    pub fn new(fallback_copy_text: impl Into<String>, cx: &mut App) -> Self {
794        Self(cx.new(|_| SelectableTextState::new(fallback_copy_text)))
795    }
796
797    /// Returns this participant's stable identity.
798    pub fn entity_id(&self) -> EntityId {
799        self.0.entity_id()
800    }
801
802    /// Returns the current geometry selection snapshot for this participant.
803    pub fn snapshot(&self, cx: &App) -> Option<TextSelectionSnapshot> {
804        self.0.read(cx).snapshot()
805    }
806
807    /// Sets the fallback text copied while this participant participates.
808    pub fn set_fallback_copy_text(&self, text: impl Into<String>, cx: &mut App) {
809        self.0
810            .update(cx, |state, _| state.set_fallback_copy_text(text));
811    }
812
813    /// Marks participant-local selection, such as select-all, as active.
814    pub fn set_local_selection(&self, active: bool, cx: &mut App) {
815        self.0
816            .update(cx, |state, _| state.set_local_selection(active));
817    }
818
819    /// Returns whether participant-local selection is active.
820    pub fn has_local_selection(&self, cx: &App) -> bool {
821        self.0.read(cx).local_selection
822    }
823
824    /// Registers this participant and its geometry for the current frame.
825    pub fn register(
826        &self,
827        mut registration: TextSelectionRegistration,
828        window: &mut Window,
829        cx: &mut App,
830    ) {
831        if let Some(scope) = current_text_selection_scope(window.window_handle().window_id(), cx) {
832            registration.scope = scope;
833        }
834        let Some(state) = WindowSelectionState::existing(window, cx) else {
835            return;
836        };
837        state.update(cx, |state, cx| {
838            state.register_participant(self.clone(), registration, cx)
839        });
840    }
841
842    /// Projects the current snapshot onto plain-text runs and caches their copy text.
843    pub fn update_runs(&self, runs: &[TextSelectionRun], cx: &mut App) -> TextSelectionProjection {
844        self.0.update(cx, |state, _| state.update_runs(runs))
845    }
846
847    // Rich text renders its own selection; retain geometry only for word hit testing.
848    pub(crate) fn set_hit_test_runs(&self, runs: &[TextSelectionRun], cx: &mut App) {
849        self.0.update(cx, |state, _| state.runs = runs.to_vec());
850    }
851
852    /// Subscribes to participant selection notifications.
853    pub fn subscribe(
854        &self,
855        mut callback: impl FnMut(&TextSelectionEvent, &mut App) + 'static,
856        cx: &mut App,
857    ) -> Subscription {
858        cx.subscribe(&self.0, move |_, event, cx| callback(event, cx))
859    }
860
861    /// Subscribes `window` to refresh whenever this participant's selection changes.
862    #[must_use = "retain the subscription or explicitly detach it"]
863    pub fn refresh_window_on_change(&self, window: &Window, cx: &mut App) -> Subscription {
864        let window = window.window_handle();
865        self.subscribe(
866            move |event, cx| {
867                if matches!(event, TextSelectionEvent::SelectionChanged(_)) {
868                    _ = window.update(cx, |_, window, _| window.refresh());
869                }
870            },
871            cx,
872        )
873    }
874
875    /// Sets the callback which focuses the participant when a drag begins in it.
876    pub fn focus_with(&self, callback: impl Fn(&mut Window, &mut App) + 'static, cx: &mut App) {
877        self.0
878            .update(cx, |state, _| state.set_focus_handler(callback));
879    }
880
881    /// Sets the synchronous participant cleanup command used by window clear.
882    pub fn clear_with(&self, callback: impl Fn(&mut App) + 'static, cx: &mut App) {
883        self.0.update(cx, |state, _| state.clear_with(callback));
884    }
885
886    /// Sets a participant-specific copy projection.
887    pub fn copy_with(&self, callback: impl Fn(&mut App) -> String + 'static, cx: &mut App) {
888        self.0.update(cx, |state, _| state.copy_with(callback));
889    }
890
891    /// Lays out the touch handles at the ends of this participant's
892    /// selection, as they were painted last frame, and gives each a hitbox
893    /// where the finger takes it. Call during the participant's prepaint;
894    /// hand the result to [`Self::paint_touch_handles`].
895    pub fn prepaint_touch_handles(&self, window: &mut Window, cx: &App) -> TouchHandleLayout {
896        let Some(state) = WindowSelectionState::existing(window, cx) else {
897            return TouchHandleLayout::default();
898        };
899        let hitboxes = state
900            .read(cx)
901            .touch_handles_of(self.entity_id())
902            .into_iter()
903            .map(|(edge, caret)| {
904                let hitbox = window.insert_hitbox(
905                    TouchHandle::hit_bounds(edge, caret),
906                    HitboxBehavior::BlockMouse,
907                );
908                (edge, hitbox)
909            })
910            .collect();
911        TouchHandleLayout { hitboxes }
912    }
913
914    /// Paints the touch handles at the ends of this participant's selection,
915    /// in `color`, where the participant is in the paint order — so whatever
916    /// is drawn over the text is drawn over its handles too. Call at the end
917    /// of the participant's paint, after [`Self::register`] for the frame.
918    ///
919    /// The handles take the finger's drag from there; Base moves the
920    /// selection with it.
921    pub fn paint_touch_handles(
922        &self,
923        layout: &TouchHandleLayout,
924        color: Hsla,
925        window: &mut Window,
926        cx: &mut App,
927    ) {
928        let Some(state) = WindowSelectionState::existing(window, cx) else {
929            return;
930        };
931        for (edge, caret) in state.read(cx).touch_handles_of(self.entity_id()) {
932            TouchHandle::paint(edge, caret, color, window);
933        }
934        for (edge, hitbox) in &layout.hitboxes {
935            let edge = *edge;
936            state.update(cx, |state, _| state.register_touch_ui(hitbox.bounds));
937            // Mouse: the drag for a pointer.
938            window.on_mouse_event({
939                let hitbox = hitbox.clone();
940                let state = state.downgrade();
941                move |event: &MouseDownEvent, phase, window, cx| {
942                    if !phase.bubble()
943                        || event.button != MouseButton::Left
944                        || !hitbox.is_hovered(window)
945                    {
946                        return;
947                    }
948                    let Some(state) = state.upgrade() else {
949                        return;
950                    };
951                    cx.stop_propagation();
952                    state.update(cx, |state, cx| {
953                        state.begin_edge_drag(edge, event.position, window, cx)
954                    });
955                    WindowSelectionState::resolve_content_keys(&state, cx);
956                }
957            });
958        }
959    }
960
961    /// Sets a participant-specific lookup for stable virtualized content keys.
962    pub fn resolve_content_key_with(
963        &self,
964        callback: impl Fn(Point<Pixels>, &App) -> Option<TextSelectionContentKey> + 'static,
965        cx: &mut App,
966    ) {
967        self.0
968            .update(cx, |state, _| state.resolve_content_key_with(callback));
969    }
970
971    fn downgrade(&self) -> WeakEntity<SelectableTextState> {
972        self.0.downgrade()
973    }
974}
975
976#[derive(Clone)]
977struct ParticipantRegistration {
978    participant: WeakEntity<SelectableTextState>,
979    registration: Rc<TextSelectionRegistration>,
980    generation: u64,
981}
982
983#[derive(Clone)]
984struct SelectionEndpoint {
985    participant: Option<WeakEntity<SelectableTextState>>,
986    point: Point<Pixels>,
987    inside: bool,
988    inside_text: bool,
989    content_key: Option<TextSelectionContentKey>,
990    content_key_resolver: Option<(ContentKeyResolver, Point<Pixels>)>,
991}
992
993impl SelectionEndpoint {
994    fn snapshot(&self) -> TextSelectionEndpoint {
995        let snapshot = TextSelectionEndpoint::new(self.entity_id(), self.point);
996        if let Some(content_key) = self.content_key {
997            snapshot.with_content_key(content_key)
998        } else {
999            snapshot
1000        }
1001    }
1002
1003    fn resolve(
1004        &self,
1005        participants: &HashMap<EntityId, ParticipantRegistration>,
1006    ) -> Option<Point<Pixels>> {
1007        let participant = self.participant.as_ref()?;
1008        let registration = participants.get(&participant.entity_id())?;
1009        participant.upgrade()?;
1010        Some(
1011            self.point
1012                + registration.registration.scroll_offset
1013                + registration.registration.bounds.origin,
1014        )
1015    }
1016
1017    fn entity_id(&self) -> Option<EntityId> {
1018        self.participant
1019            .as_ref()
1020            .map(|participant| participant.entity_id())
1021    }
1022}
1023
1024/// What a long press left behind: the handles and the edit menu.
1025///
1026/// The presentation layer draws both and reports their bounds each frame, so
1027/// that a press on a handle or a menu item is not taken for a press on the
1028/// text underneath, which would clear the very selection they belong to.
1029#[derive(Default)]
1030struct TouchSelection {
1031    /// The current selection was made by touch and carries handles.
1032    active: bool,
1033    menu_open: bool,
1034    drag: Option<EdgeDrag>,
1035    /// Where the handles and the menu were painted this frame, and the frame
1036    /// before: a press arrives between frames, and the surfaces may have
1037    /// moved in the one that has not painted yet.
1038    ui_bounds: Vec<Bounds<Pixels>>,
1039    previous_ui_bounds: Vec<Bounds<Pixels>>,
1040    /// The ends as last laid out: `(start, end, start_visible, end_visible)`.
1041    /// A frame in which no participant paints a selection — the cursor sits
1042    /// between two characters mid-drag — would otherwise lose the handle the
1043    /// finger holds, and with it the rest of the drag.
1044    last_edges: std::cell::Cell<Option<(Bounds<Pixels>, Bounds<Pixels>, bool, bool)>>,
1045}
1046
1047impl TouchSelection {
1048    fn covers(&self, position: Point<Pixels>) -> bool {
1049        self.active
1050            && self
1051                .ui_bounds
1052                .iter()
1053                .chain(&self.previous_ui_bounds)
1054                .any(|bounds| bounds.contains(&position))
1055    }
1056
1057    /// A new frame begins: what was painted last frame is kept one frame more.
1058    fn begin_frame(&mut self) {
1059        self.previous_ui_bounds = std::mem::take(&mut self.ui_bounds);
1060    }
1061
1062    /// Drops the handles and the menu; returns whether there were any.
1063    fn reset(&mut self) -> bool {
1064        let had = self.active;
1065        self.active = false;
1066        self.menu_open = false;
1067        self.drag = None;
1068        self.last_edges.set(None);
1069        had
1070    }
1071}
1072
1073/// Window-local generic text-selection state.
1074#[derive(Default)]
1075struct WindowSelectionState {
1076    participants: HashMap<EntityId, ParticipantRegistration>,
1077    active_scope: TextSelectionScopeId,
1078    anchor: Option<SelectionEndpoint>,
1079    cursor: Option<SelectionEndpoint>,
1080    pending_extension_anchor: Option<SelectionEndpoint>,
1081    is_selecting: bool,
1082    did_hit_text: bool,
1083    frame_generation: u64,
1084    finish_frame_scheduled: bool,
1085    refresh_held_cursor: bool,
1086    mouse_down_prepared: bool,
1087    auto_scroll: AutoScroll,
1088    /// Where the anchor's text was when the last synthetic wheel went out,
1089    /// and how many went out without moving it. A container at its end
1090    /// cannot scroll further; pushing it on would only make one that
1091    /// bounces stretch and snap back on every tick.
1092    auto_scroll_stall: (Option<(Bounds<Pixels>, Point<Pixels>)>, u8),
1093    touch: TouchSelection,
1094    /// This entity, so that touch changes can notify observers from paths that
1095    /// only hold an [`App`].
1096    entity_id: Option<EntityId>,
1097}
1098
1099impl WindowSelectionState {
1100    fn resolve_content_keys(state: &Entity<Self>, cx: &mut App) {
1101        let pending = state.update(cx, |state, _| {
1102            [
1103                state
1104                    .anchor
1105                    .as_ref()
1106                    .and_then(|endpoint| endpoint.content_key_resolver.clone()),
1107                state
1108                    .cursor
1109                    .as_ref()
1110                    .and_then(|endpoint| endpoint.content_key_resolver.clone()),
1111            ]
1112        });
1113        let resolved =
1114            pending.map(|pending| pending.and_then(|(callback, point)| callback(point, cx)));
1115        state.update(cx, |state, cx| {
1116            if let (Some(endpoint), Some(key)) = (state.anchor.as_mut(), resolved[0]) {
1117                endpoint.content_key = Some(key);
1118                endpoint.content_key_resolver = None;
1119            }
1120            if let (Some(endpoint), Some(key)) = (state.cursor.as_mut(), resolved[1]) {
1121                endpoint.content_key = Some(key);
1122                endpoint.content_key_resolver = None;
1123            }
1124            state.publish_snapshots(cx);
1125        });
1126    }
1127    fn acquire(window_id: gpui::WindowId, cx: &mut App) -> Entity<Self> {
1128        if !cx.has_global::<SelectionStateRegistry>() {
1129            cx.set_global(SelectionStateRegistry::default());
1130        }
1131        if let Some(state) = cx
1132            .global::<SelectionStateRegistry>()
1133            .0
1134            .get(&window_id)
1135            .and_then(WeakEntity::upgrade)
1136        {
1137            return state;
1138        }
1139
1140        let active_scope = if cx.has_global::<PendingTextSelectionScopes>() {
1141            cx.global_mut::<PendingTextSelectionScopes>()
1142                .0
1143                .remove(&window_id)
1144                .unwrap_or_default()
1145        } else {
1146            TextSelectionScopeId::default()
1147        };
1148
1149        let state = cx.new(move |cx| {
1150            let entity_id = cx.entity_id();
1151            cx.on_release(move |state: &mut WindowSelectionState, cx| {
1152                let handlers = state.clear_state(cx);
1153                if cx.has_global::<SelectionStateRegistry>() {
1154                    let registry = &mut cx.global_mut::<SelectionStateRegistry>().0;
1155                    if registry
1156                        .get(&window_id)
1157                        .is_some_and(|state| state.entity_id() == entity_id)
1158                    {
1159                        registry.remove(&window_id);
1160                    }
1161                }
1162                if !handlers.is_empty() {
1163                    cx.defer(move |cx| dispatch_clear_handlers(handlers, cx));
1164                }
1165            })
1166            .detach();
1167            Self {
1168                active_scope,
1169                entity_id: Some(entity_id),
1170                ..Self::default()
1171            }
1172        });
1173        cx.global_mut::<SelectionStateRegistry>()
1174            .0
1175            .insert(window_id, state.downgrade());
1176        state
1177    }
1178
1179    #[cfg(test)]
1180    fn ensure(window: &Window, cx: &mut App) -> Entity<Self> {
1181        Self::acquire(window.window_handle().window_id(), cx)
1182    }
1183
1184    fn existing(window: &Window, cx: &App) -> Option<Entity<Self>> {
1185        if !cx.has_global::<SelectionStateRegistry>() {
1186            return None;
1187        }
1188        cx.global::<SelectionStateRegistry>()
1189            .0
1190            .get(&window.window_handle().window_id())
1191            .and_then(WeakEntity::upgrade)
1192    }
1193
1194    /// Updates the active scope. Participants from other scopes cannot participate.
1195    #[cfg(test)]
1196    fn set_active_scope(&mut self, scope: TextSelectionScopeId, cx: &mut App) {
1197        let handlers = self.set_active_scope_state(scope, cx);
1198        dispatch_clear_handlers(handlers, cx);
1199    }
1200
1201    fn set_active_scope_state(
1202        &mut self,
1203        scope: TextSelectionScopeId,
1204        cx: &mut App,
1205    ) -> Vec<ClearHandler> {
1206        if self.active_scope == scope {
1207            return Vec::new();
1208        }
1209        let handlers = self.clear_state(cx);
1210        self.active_scope = scope;
1211        self.publish_snapshots(cx);
1212        handlers
1213    }
1214
1215    /// Sweeps participants after a rendered frame has completed.
1216    ///
1217    /// Registrations are stamped with the current generation while any sibling
1218    /// is painting. Sweeping only after paint makes registration independent of
1219    /// whether a participant or the lifecycle element paints first.
1220    ///
1221    /// A missed generation alone does not mean the participant left the window:
1222    /// a cached view replays its recorded frame, painting the same text at the
1223    /// same place without running any of its elements. Such a participant keeps
1224    /// the registration it last reported, which still describes what is on
1225    /// screen; only one whose element GPUI has dropped is swept.
1226    pub fn finish_frame(&mut self, cx: &mut App) -> Vec<ClearHandler> {
1227        self.finish_frame_scheduled = false;
1228        let stale = self
1229            .participants
1230            .iter()
1231            .filter_map(|(id, registration)| {
1232                (registration.generation != self.frame_generation
1233                    && !registration.registration.is_rendered())
1234                .then(|| (*id, registration.participant.clone()))
1235            })
1236            .collect::<Vec<_>>();
1237        let mut handlers = Vec::new();
1238        for (id, participant) in stale {
1239            self.participants.remove(&id);
1240            if let Some(participant) = participant.upgrade() {
1241                if let Some(handler) = participant.update(cx, |state, cx| state.clear_state(cx)) {
1242                    handlers.push(handler);
1243                }
1244            }
1245        }
1246        self.publish_snapshots(cx);
1247        self.frame_generation = self.frame_generation.wrapping_add(1);
1248        handlers
1249    }
1250
1251    fn schedule_finish_frame(&mut self) -> bool {
1252        if self.finish_frame_scheduled {
1253            return false;
1254        }
1255        self.finish_frame_scheduled = true;
1256        true
1257    }
1258
1259    /// Registers this frame's geometry for a participant.
1260    pub fn register_participant(
1261        &mut self,
1262        selection: TextSelectionHandle,
1263        registration: TextSelectionRegistration,
1264        cx: &mut App,
1265    ) {
1266        self.prune_dead_participants();
1267        if self.is_selecting
1268            && registration.self_scroll
1269            && self.anchor.as_ref().and_then(SelectionEndpoint::entity_id)
1270                == Some(selection.entity_id())
1271            && self
1272                .participants
1273                .get(&selection.entity_id())
1274                .is_some_and(|previous| {
1275                    previous.registration.scroll_offset != registration.scroll_offset
1276                        || previous.registration.bounds != registration.bounds
1277                })
1278        {
1279            self.refresh_held_cursor = true;
1280        }
1281        // The handles sit on the painted ends; when those moved — a scroll, a
1282        // reflow, a select-all — whoever draws the handles needs to know.
1283        let edges_moved = self.touch.active
1284            && self
1285                .participants
1286                .get(&selection.entity_id())
1287                .is_none_or(|previous| {
1288                    previous.registration.selection_edges != registration.selection_edges
1289                });
1290        self.participants.insert(
1291            selection.entity_id(),
1292            ParticipantRegistration {
1293                participant: selection.downgrade(),
1294                registration: Rc::new(registration),
1295                generation: self.frame_generation,
1296            },
1297        );
1298        self.publish_snapshots(cx);
1299        if edges_moved {
1300            self.touch_changed(cx);
1301        }
1302    }
1303
1304    /// Starts a selection gesture using bounds hit testing (useful to adapters/tests).
1305    #[cfg(test)]
1306    fn begin(&mut self, position: Point<Pixels>, extend: bool, cx: &mut App) {
1307        self.begin_impl(position, extend, false, None, cx);
1308    }
1309
1310    /// Updates the current gesture using bounds hit testing.
1311    #[cfg(test)]
1312    fn update(&mut self, position: Point<Pixels>, cx: &mut App) {
1313        self.update_impl(position, None, cx);
1314    }
1315
1316    /// Ends the current gesture and keeps its selection visible.
1317    pub fn end(&mut self, cx: &mut App) {
1318        self.pending_extension_anchor = None;
1319        if !self.is_selecting {
1320            return;
1321        }
1322        self.is_selecting = false;
1323        if !self.did_hit_text {
1324            self.anchor = None;
1325            self.cursor = None;
1326        }
1327        self.stop_anchor_auto_scroll(cx);
1328        self.publish_snapshots(cx);
1329    }
1330
1331    /// Clears both window selection and every participant's local selection.
1332    pub fn clear(&mut self, cx: &mut App) {
1333        let handlers = self.clear_state(cx);
1334        dispatch_clear_handlers(handlers, cx);
1335    }
1336
1337    fn clear_state(&mut self, cx: &mut App) -> Vec<ClearHandler> {
1338        self.stop_anchor_auto_scroll(cx);
1339        self.anchor = None;
1340        self.cursor = None;
1341        self.pending_extension_anchor = None;
1342        self.is_selecting = false;
1343        self.did_hit_text = false;
1344        if self.touch.reset() {
1345            self.touch_changed(cx);
1346        }
1347        self.prune_dead_participants();
1348        self.participants
1349            .values()
1350            .filter_map(|registration| registration.participant.upgrade())
1351            .filter_map(|participant| participant.update(cx, |state, cx| state.clear_state(cx)))
1352            .collect()
1353    }
1354
1355    /// Tells whoever draws the handles and the menu that they changed.
1356    ///
1357    /// Deferred, because the change may come from a participant painting its
1358    /// selection ends: a notification raised inside a draw marks the view
1359    /// dirty but starts no frame, and the handles would sit where they were
1360    /// until something else redrew the window.
1361    ///
1362    /// The participants in the selection hear it too: they paint the
1363    /// handles, and lay the handles' hitboxes out from the ends they painted
1364    /// last frame, so they render once more. A participant under a cached
1365    /// view would otherwise not, and the next frame would replay this one,
1366    /// with no hitbox where a handle is.
1367    fn touch_changed(&self, cx: &mut App) {
1368        let participants = self
1369            .participants
1370            .values()
1371            .filter_map(|registration| registration.participant.upgrade())
1372            .filter(|participant| participant.read(cx).snapshot.is_some())
1373            .collect::<Vec<_>>();
1374        let entity_id = self.entity_id;
1375        cx.defer(move |cx| {
1376            for participant in participants {
1377                participant.update(cx, |_, cx| {
1378                    cx.emit(TextSelectionEvent::TouchSelectionChanged)
1379                });
1380            }
1381            if let Some(entity_id) = entity_id {
1382                cx.notify(entity_id);
1383            }
1384        });
1385    }
1386
1387    fn copy_items(&self, cx: &App) -> Vec<CopyItem> {
1388        self.participants
1389            .values()
1390            .filter_map(|registration| {
1391                let participant = registration.participant.upgrade()?;
1392                participant
1393                    .read(cx)
1394                    .copy_item(registration.registration.document_order)
1395            })
1396            .collect()
1397    }
1398
1399    #[cfg(test)]
1400    fn selected_text(&self, cx: &mut App) -> String {
1401        resolve_copy_items(self.copy_items(cx), cx)
1402    }
1403
1404    /// Whether the current endpoints take in at least one character of some
1405    /// participant's painted text, as opposed to two points with nothing
1406    /// between them.
1407    fn selects_text(&self, cx: &App) -> bool {
1408        self.snapshot().is_some()
1409            && self.participants.values().any(|registration| {
1410                registration
1411                    .participant
1412                    .upgrade()
1413                    .is_some_and(|participant| {
1414                        let participant = participant.read(cx);
1415                        project_ranges(participant.snapshot, &participant.runs)
1416                            .ranges()
1417                            .iter()
1418                            .any(|range| range.as_ref().is_some_and(|range| !range.is_empty()))
1419                    })
1420            })
1421    }
1422
1423    /// Returns whether a drag or a participant-local selection is active.
1424    pub fn has_selection(&self, cx: &App) -> bool {
1425        self.snapshot().is_some()
1426            || self.participants.values().any(|registration| {
1427                registration
1428                    .participant
1429                    .upgrade()
1430                    .is_some_and(|participant| participant.read(cx).local_selection)
1431            })
1432    }
1433
1434    /// Returns the current resolved selection endpoints.
1435    pub fn snapshot(&self) -> Option<TextSelectionSnapshot> {
1436        if !self.did_hit_text {
1437            return None;
1438        }
1439        let anchor_endpoint = self.anchor.as_ref()?;
1440        let cursor_endpoint = self.cursor.as_ref()?;
1441        let anchor = anchor_endpoint.resolve(&self.participants)?;
1442        let cursor = cursor_endpoint.resolve(&self.participants)?;
1443        (anchor != cursor).then(|| {
1444            TextSelectionSnapshot::new(anchor_endpoint.snapshot(), cursor_endpoint.snapshot())
1445                .with_selecting(self.is_selecting)
1446                .with_window_points(Some(TextSelectionWindowPoints { anchor, cursor }))
1447        })
1448    }
1449
1450    /// Returns whether a drag is currently in progress.
1451    #[cfg(test)]
1452    fn is_selecting(&self) -> bool {
1453        self.is_selecting
1454    }
1455
1456    fn prepare_for_mouse_down(&mut self, extend: bool, cx: &mut App) -> Vec<ClearHandler> {
1457        let pending_extension_anchor = extend.then(|| self.anchor.clone()).flatten();
1458        self.stop_anchor_auto_scroll(cx);
1459        self.anchor = None;
1460        self.cursor = None;
1461        self.pending_extension_anchor = None;
1462        self.is_selecting = false;
1463        self.did_hit_text = false;
1464        if self.touch.reset() {
1465            self.touch_changed(cx);
1466        }
1467        self.prune_dead_participants();
1468        let handlers = self
1469            .participants
1470            .values()
1471            .filter_map(|registration| registration.participant.upgrade())
1472            .filter_map(|participant| participant.update(cx, |state, cx| state.clear_state(cx)))
1473            .collect();
1474        self.pending_extension_anchor = pending_extension_anchor;
1475        handlers
1476    }
1477
1478    /// The touch selection laid out for its handles and edit menu.
1479    ///
1480    /// The ends come from the participants: the first selected character of
1481    /// the earliest participant in document order and the last of the latest.
1482    /// A participant whose selection is entirely scrolled away paints no ends,
1483    /// so the handles disappear with the text they mark.
1484    fn touch_selection(&self) -> Option<TouchSelectionSnapshot> {
1485        if !self.touch.active {
1486            return None;
1487        }
1488        // Each end with its owner's viewport: an end scrolled out of its
1489        // participant gets no handle.
1490        let mut start: Option<(u64, Bounds<Pixels>, bool)> = None;
1491        let mut end: Option<(u64, Bounds<Pixels>, bool)> = None;
1492        for registration in self.participants.values() {
1493            let geometry = &registration.registration;
1494            if geometry.scope != self.active_scope || registration.participant.upgrade().is_none() {
1495                continue;
1496            }
1497            let Some((edge_start, edge_end)) = geometry.selection_edges else {
1498                continue;
1499            };
1500            let order = geometry.document_order;
1501            let viewport = geometry.hitbox.bounds;
1502            if start.is_none_or(|(best, ..)| order < best) {
1503                start = Some((order, edge_start, caret_in_view(edge_start, viewport)));
1504            }
1505            if end.is_none_or(|(best, ..)| order >= best) {
1506                end = Some((order, edge_end, caret_in_view(edge_end, viewport)));
1507            }
1508        }
1509        let edges = match (start, end) {
1510            (Some((_, start, start_visible)), Some((_, end, end_visible))) => {
1511                let edges = (start, end, start_visible, end_visible);
1512                self.touch.last_edges.set(Some(edges));
1513                edges
1514            }
1515            _ if self.touch.drag.is_some() => self.touch.last_edges.get()?,
1516            _ => return None,
1517        };
1518        let (start, end, start_visible, end_visible) = edges;
1519        Some(
1520            TouchSelectionSnapshot::new(start, end)
1521                .with_edge_visible(SelectionEdge::Start, start_visible)
1522                .with_edge_visible(SelectionEdge::End, end_visible)
1523                .with_menu_open(self.touch.menu_open)
1524                .with_dragging(self.touch.drag.map(|drag| drag.edge())),
1525        )
1526    }
1527
1528    /// The handles `participant` paints: the start when no participant
1529    /// earlier in document order has a selection end, the end when none
1530    /// later has. Participants paint in document order, so a later one that
1531    /// takes the end over has registered its ends by the time it asks.
1532    fn touch_handles_of(&self, participant: EntityId) -> Vec<(SelectionEdge, Bounds<Pixels>)> {
1533        if !self.touch.active {
1534            return Vec::new();
1535        }
1536        let Some(own) = self.participants.get(&participant) else {
1537            return Vec::new();
1538        };
1539        let Some((start, end)) = own.registration.selection_edges else {
1540            return Vec::new();
1541        };
1542        if start == end {
1543            return Vec::new();
1544        }
1545        let order = own.registration.document_order;
1546        let others = self.participants.iter().filter(|(id, registration)| {
1547            **id != participant
1548                && registration.registration.scope == self.active_scope
1549                && registration.registration.selection_edges.is_some()
1550                && registration.participant.upgrade().is_some()
1551        });
1552        let (mut earlier, mut later) = (false, false);
1553        for (_, registration) in others {
1554            let other = registration.registration.document_order;
1555            earlier |= other < order;
1556            later |= other > order;
1557        }
1558        let viewport = own.registration.hitbox.bounds;
1559        let mut handles = Vec::with_capacity(2);
1560        if !earlier && caret_in_view(start, viewport) {
1561            handles.push((SelectionEdge::Start, start));
1562        }
1563        if !later && caret_in_view(end, viewport) {
1564            handles.push((SelectionEdge::End, end));
1565        }
1566        handles
1567    }
1568
1569    /// Keeps the selection a long press made, and opens the edit menu over it.
1570    fn keep_touch_selection(&mut self, cx: &mut App) {
1571        self.touch.active = self.snapshot().is_some();
1572        self.touch.menu_open = self.touch.active;
1573        self.touch.drag = None;
1574        self.touch_changed(cx);
1575    }
1576
1577    /// Records where the handles and the menu are painted this frame.
1578    fn register_touch_ui(&mut self, bounds: Bounds<Pixels>) {
1579        self.touch.ui_bounds.push(bounds);
1580    }
1581
1582    fn close_edit_menu(&mut self, cx: &mut App) {
1583        if !self.touch.menu_open {
1584            return;
1585        }
1586        self.touch.menu_open = false;
1587        self.touch_changed(cx);
1588    }
1589
1590    /// The handles follow the text, but the menu would sit over whatever
1591    /// scrolls underneath it: it steps aside while a finger scrolls and comes
1592    /// back over the handles once the finger lifts.
1593    fn edit_menu_on_scroll(&mut self, phase: TouchPhase, cx: &mut App) {
1594        if !self.touch.active || self.touch.drag.is_some() {
1595            return;
1596        }
1597        match phase {
1598            TouchPhase::Ended | TouchPhase::Cancelled => {
1599                if !self.touch.menu_open {
1600                    self.touch.menu_open = true;
1601                    self.touch_changed(cx);
1602                }
1603            }
1604            _ => self.close_edit_menu(cx),
1605        }
1606    }
1607
1608    /// Selects all of the participant the touch selection started in.
1609    ///
1610    /// This stays a point selection — anchored on the participant's first
1611    /// line of text, ending on its last — rather than switching the
1612    /// participant to a local select-all: one selection, painted, reported
1613    /// and copied the one way, with handles that drag on from its ends.
1614    fn select_all_touched(&mut self, cx: &mut App) {
1615        if !self.touch.active {
1616            return;
1617        }
1618        let Some((participant, registration)) = self.anchor_registration() else {
1619            return;
1620        };
1621        // From the participant's text runs, not its painted line bounds:
1622        // those are clipped to the viewport, and a message taller than the
1623        // screen would only select what is on it.
1624        let (anchor, cursor) = {
1625            let runs = &participant.read(cx).runs;
1626            let (Some(first), Some(last)) = (
1627                runs.iter().min_by_key(|run| run.document_order),
1628                runs.iter().max_by_key(|run| run.document_order),
1629            ) else {
1630                return;
1631            };
1632            let (Some(start), Some(end)) = (
1633                first.layout.position_for_index(0),
1634                last.layout.position_for_index(last.text.len()),
1635            ) else {
1636                return;
1637            };
1638            // Just inside the first and the last glyph, mid-line, so both
1639            // land on text.
1640            let inset = px(1.);
1641            (
1642                point(start.x + inset, start.y + first.layout.line_height() / 2.),
1643                point(end.x - inset, end.y + last.layout.line_height() / 2.),
1644            )
1645        };
1646        let content_key_resolver = participant.read(cx).content_key_resolver.clone();
1647        let to_endpoint = |window_point: Point<Pixels>| {
1648            let content_point =
1649                window_point - registration.bounds.origin - registration.scroll_offset;
1650            SelectionEndpoint {
1651                participant: Some(participant.downgrade()),
1652                point: content_point,
1653                inside: true,
1654                inside_text: true,
1655                content_key: None,
1656                content_key_resolver: content_key_resolver
1657                    .clone()
1658                    .map(|resolver| (resolver, content_point)),
1659            }
1660        };
1661        self.anchor = Some(to_endpoint(anchor));
1662        self.cursor = Some(to_endpoint(cursor));
1663        self.did_hit_text = true;
1664        self.is_selecting = false;
1665        self.touch.menu_open = true;
1666        self.publish_snapshots(cx);
1667        self.touch_changed(cx);
1668    }
1669
1670    /// Starts dragging one end of the touch selection from `finger`.
1671    ///
1672    /// The selection is rebuilt from the painted ends, anchored at the end that
1673    /// stays: a select-all or a word selection becomes an ordinary point
1674    /// selection which the drag then extends.
1675    fn begin_edge_drag(
1676        &mut self,
1677        edge: SelectionEdge,
1678        finger: Point<Pixels>,
1679        window: &mut Window,
1680        cx: &mut App,
1681    ) {
1682        let Some(snapshot) = self.touch_selection() else {
1683            return;
1684        };
1685        let handlers = self.prepare_for_mouse_down(false, cx);
1686        dispatch_clear_handlers(handlers, cx);
1687        let held = snapshot.edge(edge.opposite());
1688        // Just inside the held end, so the anchor lands on the character it
1689        // marks rather than on the boundary between two participants.
1690        let nudge = px(1.);
1691        let anchor_point = match edge {
1692            SelectionEdge::Start => point(held.left() - nudge, held.center().y),
1693            SelectionEdge::End => point(held.left() + nudge, held.center().y),
1694        };
1695        let anchor = self.endpoint(anchor_point, None, cx);
1696        let drag = EdgeDrag::begin(edge, snapshot.edge(edge), finger);
1697        let cursor = self.endpoint(drag.text_position(finger), Some(window), cx);
1698        self.did_hit_text = anchor.inside_text || cursor.inside_text;
1699        self.anchor = Some(anchor);
1700        self.cursor = Some(cursor);
1701        self.is_selecting = true;
1702        self.touch.active = true;
1703        self.touch.menu_open = false;
1704        self.touch.drag = Some(drag);
1705        self.publish_snapshots(cx);
1706        self.touch_changed(cx);
1707    }
1708
1709    fn update_edge_drag(&mut self, finger: Point<Pixels>, window: &Window, cx: &mut Context<Self>) {
1710        let Some(drag) = self.touch.drag else {
1711            return;
1712        };
1713        let before = self.cursor.clone();
1714        self.update_in_window(drag.text_position(finger), window, cx);
1715        // A handle never collapses the selection: at the other end it stops,
1716        // and the finger has to pass that end, onto text, to swap the two.
1717        if !self.selects_text(cx) {
1718            self.cursor = before;
1719            self.publish_snapshots(cx);
1720            return;
1721        }
1722        // Dragging one end past the other swaps them: the cursor now lies
1723        // before the anchor, so the finger holds what became the start.
1724        if let Some(points) = self
1725            .snapshot()
1726            .and_then(|snapshot| snapshot.window_points())
1727        {
1728            let (anchor, cursor) = (points.anchor(), points.cursor());
1729            let cursor_first = cursor.y < anchor.y || (cursor.y == anchor.y && cursor.x < anchor.x);
1730            let edge = if cursor_first {
1731                SelectionEdge::Start
1732            } else {
1733                SelectionEdge::End
1734            };
1735            if let Some(drag) = self.touch.drag.as_mut() {
1736                drag.set_edge(edge);
1737            }
1738        }
1739        self.touch_changed(cx);
1740    }
1741
1742    fn end_edge_drag(&mut self, cx: &mut App) {
1743        if self.touch.drag.take().is_none() {
1744            return;
1745        }
1746        self.end(cx);
1747        self.keep_touch_selection(cx);
1748    }
1749
1750    fn begin_in_window(
1751        &mut self,
1752        position: Point<Pixels>,
1753        extend: bool,
1754        window: &mut Window,
1755        cx: &mut App,
1756    ) {
1757        self.begin_impl(position, extend, true, Some(window), cx);
1758    }
1759
1760    fn update_in_window(
1761        &mut self,
1762        position: Point<Pixels>,
1763        window: &Window,
1764        cx: &mut Context<Self>,
1765    ) {
1766        if !cx.has_active_drag() {
1767            self.update_impl(position, Some(window), cx);
1768            self.update_auto_scroll(position, window, cx);
1769        }
1770    }
1771
1772    fn select_at(
1773        &mut self,
1774        position: Point<Pixels>,
1775        click_count: usize,
1776        window: &mut Window,
1777        cx: &mut App,
1778    ) {
1779        GlobalState::init(cx);
1780        if GlobalState::is_text_selection_suppressed(cx) {
1781            return;
1782        }
1783        let hit = self.endpoint(position, Some(window), cx);
1784        if !hit.inside_text {
1785            return;
1786        }
1787        let Some(participant) = hit
1788            .participant
1789            .and_then(|participant| participant.upgrade())
1790        else {
1791            return;
1792        };
1793        let points = points_for_multi_click(&participant.read(cx).runs, position, click_count);
1794        let Some((anchor, cursor)) = points else {
1795            return;
1796        };
1797        let Some(registration) = self.participants.get(&participant.entity_id()) else {
1798            return;
1799        };
1800        let content_key_resolver = participant.read(cx).content_key_resolver.clone();
1801        let to_endpoint = |point: Point<Pixels>| {
1802            let content_point = point
1803                - registration.registration.bounds.origin
1804                - registration.registration.scroll_offset;
1805            SelectionEndpoint {
1806                participant: Some(participant.downgrade()),
1807                point: content_point,
1808                inside: true,
1809                inside_text: true,
1810                content_key: None,
1811                content_key_resolver: content_key_resolver
1812                    .clone()
1813                    .map(|resolver| (resolver, content_point)),
1814            }
1815        };
1816        self.anchor = Some(to_endpoint(anchor));
1817        self.cursor = Some(to_endpoint(cursor));
1818        self.did_hit_text = true;
1819        self.is_selecting = false;
1820        participant.update(cx, |state, cx| state.focus(window, cx));
1821        self.publish_snapshots(cx);
1822    }
1823
1824    #[cfg(test)]
1825    fn update_in_window_with_active_drag(
1826        &mut self,
1827        position: Point<Pixels>,
1828        active_drag: bool,
1829        window: &Window,
1830        cx: &mut App,
1831    ) {
1832        if !active_drag {
1833            self.update_impl(position, Some(window), cx);
1834        }
1835    }
1836
1837    fn begin_impl(
1838        &mut self,
1839        position: Point<Pixels>,
1840        extend: bool,
1841        already_prepared: bool,
1842        window: Option<&mut Window>,
1843        cx: &mut App,
1844    ) {
1845        GlobalState::init(cx);
1846        if GlobalState::is_text_selection_suppressed(cx) {
1847            self.pending_extension_anchor = None;
1848            return;
1849        }
1850        let previous_anchor = extend
1851            .then(|| {
1852                self.pending_extension_anchor
1853                    .take()
1854                    .or_else(|| self.anchor.clone())
1855            })
1856            .flatten()
1857            .filter(|anchor| anchor.resolve(&self.participants).is_some());
1858        if !extend && !already_prepared {
1859            self.clear(cx);
1860        }
1861        let endpoint = self.endpoint(position, window.as_deref(), cx);
1862        let focus_participant = endpoint
1863            .inside
1864            .then(|| endpoint.participant.clone())
1865            .flatten();
1866        let anchor = previous_anchor.unwrap_or_else(|| endpoint.clone());
1867        self.anchor = Some(anchor.clone());
1868        self.cursor = Some(endpoint.clone());
1869        self.did_hit_text = anchor.inside_text || endpoint.inside_text;
1870        self.is_selecting = true;
1871        if let Some(participant) = focus_participant.and_then(|participant| participant.upgrade()) {
1872            if let Some(window) = window {
1873                participant.update(cx, |state, cx| state.focus(window, cx));
1874            }
1875        }
1876        self.publish_snapshots(cx);
1877    }
1878
1879    fn update_impl(&mut self, position: Point<Pixels>, window: Option<&Window>, cx: &mut App) {
1880        if !self.is_selecting {
1881            return;
1882        }
1883        let endpoint = self.endpoint(position, window, cx);
1884        self.did_hit_text |= endpoint.inside_text;
1885        self.cursor = Some(endpoint);
1886        if window.is_none() {
1887            self.update_participant_auto_scroll(position, cx);
1888        }
1889        self.publish_snapshots(cx);
1890    }
1891
1892    fn endpoint(
1893        &mut self,
1894        position: Point<Pixels>,
1895        window: Option<&Window>,
1896        cx: &App,
1897    ) -> SelectionEndpoint {
1898        self.prune_dead_participants();
1899        let mut hit: Option<(
1900            WeakEntity<SelectableTextState>,
1901            Rc<TextSelectionRegistration>,
1902            f32,
1903        )> = None;
1904        let mut predecessor: Option<(
1905            WeakEntity<SelectableTextState>,
1906            Rc<TextSelectionRegistration>,
1907        )> = None;
1908        let mut first: Option<(
1909            WeakEntity<SelectableTextState>,
1910            Rc<TextSelectionRegistration>,
1911        )> = None;
1912
1913        for registration in self.participants.values() {
1914            if registration.registration.scope != self.active_scope
1915                || registration.participant.upgrade().is_none()
1916            {
1917                continue;
1918            }
1919            let participant_geometry = &registration.registration;
1920            let hovered = window.map_or_else(
1921                || participant_geometry.bounds.contains(&position),
1922                |window| participant_geometry.hitbox.is_hovered(window),
1923            );
1924            if hovered {
1925                let area = f32::from(participant_geometry.bounds.size.width)
1926                    * f32::from(participant_geometry.bounds.size.height);
1927                if hit.as_ref().is_none_or(|(_, best, best_area)| {
1928                    area < *best_area
1929                        || (area == *best_area
1930                            && participant_geometry.document_order < best.document_order)
1931                }) {
1932                    hit = Some((
1933                        registration.participant.clone(),
1934                        participant_geometry.clone(),
1935                        area,
1936                    ));
1937                }
1938            }
1939            if participant_geometry.bounds.top() <= position.y
1940                && predecessor.as_ref().is_none_or(|(_, best)| {
1941                    participant_geometry.bounds.top() > best.bounds.top()
1942                        || (participant_geometry.bounds.top() == best.bounds.top()
1943                            && participant_geometry.document_order < best.document_order)
1944                })
1945            {
1946                predecessor = Some((
1947                    registration.participant.clone(),
1948                    participant_geometry.clone(),
1949                ));
1950            }
1951            if first.as_ref().is_none_or(|(_, best)| {
1952                participant_geometry.bounds.top() < best.bounds.top()
1953                    || (participant_geometry.bounds.top() == best.bounds.top()
1954                        && participant_geometry.document_order < best.document_order)
1955            }) {
1956                first = Some((
1957                    registration.participant.clone(),
1958                    participant_geometry.clone(),
1959                ));
1960            }
1961        }
1962
1963        let selection = hit
1964            .map(|(participant, registration, _)| (participant, registration, true))
1965            .or_else(|| {
1966                predecessor
1967                    .or(first)
1968                    .map(|(participant, registration)| (participant, registration, false))
1969            });
1970        match selection {
1971            Some((participant, registration, inside)) => {
1972                let point = position - registration.bounds.origin - registration.scroll_offset;
1973                let content_key_resolver = participant.upgrade().and_then(|participant| {
1974                    participant
1975                        .read(cx)
1976                        .content_key_resolver
1977                        .clone()
1978                        .map(|callback| (callback, point))
1979                });
1980                SelectionEndpoint {
1981                    point,
1982                    participant: Some(participant),
1983                    inside,
1984                    inside_text: inside
1985                        && registration
1986                            .text_bounds
1987                            .iter()
1988                            .any(|bounds| bounds.contains(&position)),
1989                    content_key: None,
1990                    content_key_resolver,
1991                }
1992            }
1993            None => SelectionEndpoint {
1994                participant: None,
1995                point: position,
1996                inside: false,
1997                inside_text: false,
1998                content_key: None,
1999                content_key_resolver: None,
2000            },
2001        }
2002    }
2003
2004    fn publish_snapshots(&mut self, cx: &mut App) {
2005        self.prune_dead_participants();
2006        let snapshot = self.snapshot();
2007        let single_participant = self.single_participant();
2008        for (id, registration) in &self.participants {
2009            let Some(participant) = registration.participant.upgrade() else {
2010                continue;
2011            };
2012            let participant_snapshot = (registration.registration.scope == self.active_scope
2013                && self.participates(*id, registration)
2014                && single_participant.is_none_or(|single| single == *id))
2015            .then_some(snapshot)
2016            .flatten()
2017            .map(|mut snapshot| {
2018                snapshot.coverage = self.coverage_for(*id);
2019                snapshot
2020            });
2021            participant.update(cx, |state, cx| state.set_snapshot(participant_snapshot, cx));
2022        }
2023    }
2024
2025    fn coverage_for(&self, id: EntityId) -> TextSelectionCoverage {
2026        let Some(anchor) = self.anchor.as_ref().and_then(SelectionEndpoint::entity_id) else {
2027            return TextSelectionCoverage::Bounded;
2028        };
2029        let Some(cursor) = self.cursor.as_ref().and_then(SelectionEndpoint::entity_id) else {
2030            return TextSelectionCoverage::Bounded;
2031        };
2032        if anchor == cursor {
2033            return TextSelectionCoverage::Bounded;
2034        }
2035        let anchor_order = self.participants[&anchor].registration.document_order;
2036        let cursor_order = self.participants[&cursor].registration.document_order;
2037        if id != anchor && id != cursor {
2038            TextSelectionCoverage::Full
2039        } else if (id == anchor) == (anchor_order < cursor_order) {
2040            TextSelectionCoverage::ToEnd
2041        } else {
2042            TextSelectionCoverage::FromStart
2043        }
2044    }
2045
2046    fn single_participant(&self) -> Option<EntityId> {
2047        let anchor = self.anchor.as_ref()?.entity_id()?;
2048        let cursor = self.cursor.as_ref()?.entity_id()?;
2049        (anchor == cursor).then_some(anchor)
2050    }
2051
2052    fn participates(&self, id: EntityId, registration: &ParticipantRegistration) -> bool {
2053        let Some(anchor) = self.anchor.as_ref().and_then(SelectionEndpoint::entity_id) else {
2054            return false;
2055        };
2056        let Some(cursor) = self.cursor.as_ref().and_then(SelectionEndpoint::entity_id) else {
2057            return false;
2058        };
2059        let Some(anchor_registration) = self.participants.get(&anchor) else {
2060            return false;
2061        };
2062        let Some(cursor_registration) = self.participants.get(&cursor) else {
2063            return false;
2064        };
2065        let start = anchor_registration
2066            .registration
2067            .document_order
2068            .min(cursor_registration.registration.document_order);
2069        let end = anchor_registration
2070            .registration
2071            .document_order
2072            .max(cursor_registration.registration.document_order);
2073        (start..=end).contains(&registration.registration.document_order)
2074            || id == anchor
2075            || id == cursor
2076    }
2077
2078    fn update_auto_scroll(
2079        &mut self,
2080        position: Point<Pixels>,
2081        window: &Window,
2082        cx: &mut Context<Self>,
2083    ) {
2084        // A finished gesture keeps its anchor for shift-click extension; only
2085        // a live drag may scroll.
2086        if !self.is_selecting {
2087            return;
2088        }
2089        let Some((_, registration)) = self.anchor_registration() else {
2090            return;
2091        };
2092        // Exactly one writer per drag: a participant that scrolls its own
2093        // content is notified directly; anything else gets a synthetic wheel.
2094        if registration.self_scroll {
2095            self.auto_scroll.stop();
2096            self.update_participant_auto_scroll(position, cx);
2097            return;
2098        }
2099        // The content mask is the nearest clipping viewport established by a
2100        // scrollable ancestor. It remains stable as the participant itself
2101        // moves, so selection keeps scrolling the same related region even
2102        // after the anchor text has moved out of view.
2103        let visible_bounds = registration.hitbox.content_mask.bounds;
2104        // Keeps the synthesized wheel event hit-testing inside the mask.
2105        const HIT_TEST_INSET: Pixels = px(1.);
2106        // A collapsed mask leaves an empty clamp range below — stop.
2107        if visible_bounds.size.width < HIT_TEST_INSET * 2.
2108            || visible_bounds.size.height < HIT_TEST_INSET * 2.
2109        {
2110            self.stop_anchor_auto_scroll(cx);
2111            return;
2112        }
2113        let delta = AutoScroll::compute_delta(position.y, visible_bounds);
2114        let event_position = point(
2115            position.x.clamp(
2116                visible_bounds.left() + HIT_TEST_INSET,
2117                visible_bounds.right() - HIT_TEST_INSET,
2118            ),
2119            position.y.clamp(
2120                visible_bounds.top() + HIT_TEST_INSET,
2121                visible_bounds.bottom() - HIT_TEST_INSET,
2122            ),
2123        );
2124        self.auto_scroll.last_drag_position = Some(event_position);
2125        self.auto_scroll_stall = (None, 0);
2126        let window = window.window_handle();
2127        self.auto_scroll.set(delta, cx, move |delta, state, cx| {
2128            let Some(position) = state.auto_scroll.last_drag_position else {
2129                return;
2130            };
2131            // Hold off once the container has shown, over a few ticks, that
2132            // it has nowhere left to go; the next move of the finger asks
2133            // again.
2134            const STALLED_TICKS: u8 = 3;
2135            let geometry = state
2136                .anchor_registration()
2137                .map(|(_, registration)| (registration.bounds, registration.scroll_offset));
2138            let (last, stalled) = &mut state.auto_scroll_stall;
2139            if *last == geometry {
2140                *stalled = stalled.saturating_add(1);
2141                if *stalled >= STALLED_TICKS {
2142                    return;
2143                }
2144            } else {
2145                *last = geometry;
2146                *stalled = 0;
2147            }
2148            let window = window;
2149            cx.defer(move |cx| {
2150                _ = window.update(cx, |_, window, cx| {
2151                    window.dispatch_event(
2152                        ScrollWheelEvent {
2153                            position,
2154                            delta: ScrollDelta::Pixels(point(px(0.), -delta)),
2155                            ..Default::default()
2156                        }
2157                        .to_platform_input(),
2158                        cx,
2159                    );
2160                });
2161            });
2162        });
2163    }
2164
2165    /// Drives the anchor participant's own scrolling, measured against the
2166    /// visible portion of the participant's element bounds.
2167    fn update_participant_auto_scroll(&self, position: Point<Pixels>, cx: &mut App) {
2168        let Some((participant, registration)) = self.anchor_registration() else {
2169            return;
2170        };
2171        let visible_bounds = registration
2172            .bounds
2173            .intersect(&registration.hitbox.content_mask.bounds);
2174        let delta = if visible_bounds.size.width > px(0.) && visible_bounds.size.height > px(0.) {
2175            AutoScroll::compute_delta(position.y, visible_bounds)
2176        } else {
2177            None
2178        };
2179        participant.update(cx, |state, cx| state.set_auto_scroll(delta, cx));
2180    }
2181
2182    fn stop_anchor_auto_scroll(&mut self, cx: &mut App) {
2183        self.auto_scroll.stop();
2184        let Some(participant) = self.anchor_participant() else {
2185            return;
2186        };
2187        participant.update(cx, |state, cx| state.set_auto_scroll(None, cx));
2188    }
2189
2190    /// The live participant owning the anchor of the current gesture.
2191    fn anchor_participant(&self) -> Option<Entity<SelectableTextState>> {
2192        self.anchor
2193            .as_ref()
2194            .filter(|anchor| anchor.inside)?
2195            .participant
2196            .as_ref()?
2197            .upgrade()
2198    }
2199
2200    /// The anchor participant together with its current frame registration.
2201    fn anchor_registration(
2202        &self,
2203    ) -> Option<(Entity<SelectableTextState>, Rc<TextSelectionRegistration>)> {
2204        let participant = self.anchor_participant()?;
2205        let registration = self.participants.get(&participant.entity_id())?;
2206        Some((participant, registration.registration.clone()))
2207    }
2208
2209    fn prune_dead_participants(&mut self) {
2210        self.participants
2211            .retain(|_, registration| registration.participant.upgrade().is_some());
2212    }
2213}
2214
2215#[derive(Default)]
2216/// Non-owning window locator; retained [`TextSelection`] element state owns
2217/// each live selection entity.
2218struct SelectionStateRegistry(HashMap<gpui::WindowId, WeakEntity<WindowSelectionState>>);
2219
2220impl Global for SelectionStateRegistry {}
2221
2222#[derive(Default)]
2223struct PendingTextSelectionScopes(HashMap<gpui::WindowId, TextSelectionScopeId>);
2224
2225impl Global for PendingTextSelectionScopes {}
2226
2227#[derive(Default)]
2228struct TextSelectionScopeStacks(HashMap<gpui::WindowId, Vec<TextSelectionScopeId>>);
2229
2230impl Global for TextSelectionScopeStacks {}
2231
2232fn push_text_selection_scope(window_id: gpui::WindowId, scope: TextSelectionScopeId, cx: &mut App) {
2233    if !cx.has_global::<TextSelectionScopeStacks>() {
2234        cx.set_global(TextSelectionScopeStacks::default());
2235    }
2236    cx.global_mut::<TextSelectionScopeStacks>()
2237        .0
2238        .entry(window_id)
2239        .or_default()
2240        .push(scope);
2241}
2242
2243fn pop_text_selection_scope(window_id: gpui::WindowId, cx: &mut App) {
2244    let stacks = &mut cx.global_mut::<TextSelectionScopeStacks>().0;
2245    let remove_stack = stacks.get_mut(&window_id).is_some_and(|stack| {
2246        stack.pop();
2247        stack.is_empty()
2248    });
2249    if remove_stack {
2250        stacks.remove(&window_id);
2251    }
2252}
2253
2254fn current_text_selection_scope(
2255    window_id: gpui::WindowId,
2256    cx: &App,
2257) -> Option<TextSelectionScopeId> {
2258    cx.has_global::<TextSelectionScopeStacks>()
2259        .then(|| {
2260            cx.global::<TextSelectionScopeStacks>()
2261                .0
2262                .get(&window_id)
2263                .and_then(|stack| stack.last().copied())
2264        })
2265        .flatten()
2266}
2267
2268fn with_text_selection_scope<T>(
2269    window_id: gpui::WindowId,
2270    scope: TextSelectionScopeId,
2271    cx: &mut App,
2272    callback: impl FnOnce(&mut App) -> T,
2273) -> T {
2274    push_text_selection_scope(window_id, scope, cx);
2275    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| callback(cx)));
2276    pop_text_selection_scope(window_id, cx);
2277    match result {
2278        Ok(result) => result,
2279        Err(payload) => std::panic::resume_unwind(payload),
2280    }
2281}
2282
2283/// Window-level operations for text selection.
2284pub struct TextSelection;
2285
2286impl TextSelection {
2287    /// Returns the currently selected text in logical document order.
2288    pub fn selected_text(window: &mut Window, cx: &mut App) -> String {
2289        let Some(state) = live_text_selection_state(window, cx) else {
2290            return String::new();
2291        };
2292        let items = state.read(cx).copy_items(cx);
2293        resolve_copy_items(items, cx)
2294    }
2295
2296    /// Returns whether the window has a geometry selection or any participant
2297    /// has an active participant-local selection such as select-all.
2298    pub fn has_selection(window: &mut Window, cx: &mut App) -> bool {
2299        live_text_selection_state(window, cx).is_some_and(|state| state.read(cx).has_selection(cx))
2300    }
2301
2302    /// Clears window selection and every participant's local selection.
2303    pub fn clear(window: &mut Window, cx: &mut App) {
2304        if let Some(state) = live_text_selection_state(window, cx) {
2305            let handlers = state.update(cx, |state, cx| state.clear_state(cx));
2306            dispatch_clear_handlers(handlers, cx);
2307        }
2308    }
2309
2310    /// Clears selection for a known window identifier.
2311    ///
2312    /// Prefer [`Self::clear`] when a window reference is available. This
2313    /// narrow entry point supports hosts retiring deprecated window wrappers.
2314    pub fn clear_for_window(window_id: gpui::WindowId, cx: &mut App) {
2315        clear_window_text_selection(window_id, cx);
2316    }
2317
2318    /// Ends the current drag while leaving its selection visible.
2319    pub fn end(window: &mut Window, cx: &mut App) {
2320        if let Some(state) = live_text_selection_state(window, cx) {
2321            state.update(cx, |state, cx| state.end(cx));
2322        }
2323    }
2324
2325    /// Calls `callback` whenever the touch selection changes: it appears, its
2326    /// handles move, its menu opens or closes, or it goes away. Whoever draws
2327    /// the handles and the menu re-renders from here.
2328    pub fn observe_touch_selection(
2329        window: &Window,
2330        cx: &mut App,
2331        callback: impl Fn(&mut App) + 'static,
2332    ) -> Subscription {
2333        let state = WindowSelectionState::acquire(window.window_handle().window_id(), cx);
2334        cx.observe(&state, move |_, cx| callback(cx))
2335    }
2336
2337    /// Returns the selection a long press made, laid out for its handles and
2338    /// edit menu, or `None` when the selection was made with a pointer.
2339    pub fn touch_selection(window: &Window, cx: &App) -> Option<TouchSelectionSnapshot> {
2340        WindowSelectionState::existing(window, cx)?
2341            .read(cx)
2342            .touch_selection()
2343    }
2344
2345    /// Records where a touch handle or the edit menu is painted this frame, so
2346    /// that pressing it does not clear the selection it belongs to. Call from
2347    /// paint, every frame the surface is shown.
2348    pub fn register_touch_ui(bounds: Bounds<Pixels>, window: &Window, cx: &mut App) {
2349        if let Some(state) = WindowSelectionState::existing(window, cx) {
2350            state.update(cx, |state, _| state.register_touch_ui(bounds));
2351        }
2352    }
2353
2354    /// Closes the edit menu and keeps the selection with its handles.
2355    pub fn close_edit_menu(window: &mut Window, cx: &mut App) {
2356        if let Some(state) = live_text_selection_state(window, cx) {
2357            state.update(cx, |state, cx| state.close_edit_menu(cx));
2358        }
2359    }
2360
2361    /// Selects all of the text the touch selection started in, keeping the
2362    /// handles and the edit menu over the result.
2363    pub fn select_all(window: &mut Window, cx: &mut App) {
2364        if let Some(state) = live_text_selection_state(window, cx) {
2365            state.update(cx, |state, cx| state.select_all_touched(cx));
2366        }
2367    }
2368
2369    /// Starts dragging one end of the touch selection from `finger`. The other
2370    /// end stays; the menu closes until [`Self::end_edge_drag`].
2371    pub fn begin_edge_drag(
2372        edge: SelectionEdge,
2373        finger: Point<Pixels>,
2374        window: &mut Window,
2375        cx: &mut App,
2376    ) {
2377        if let Some(state) = live_text_selection_state(window, cx) {
2378            state.update(cx, |state, cx| {
2379                state.begin_edge_drag(edge, finger, window, cx)
2380            });
2381            WindowSelectionState::resolve_content_keys(&state, cx);
2382        }
2383    }
2384
2385    /// Moves the dragged end to the text under `finger`.
2386    pub fn update_edge_drag(finger: Point<Pixels>, window: &mut Window, cx: &mut App) {
2387        if let Some(state) = live_text_selection_state(window, cx) {
2388            state.update(cx, |state, cx| state.update_edge_drag(finger, window, cx));
2389            WindowSelectionState::resolve_content_keys(&state, cx);
2390        }
2391    }
2392
2393    /// Ends the handle drag and reopens the edit menu over the result.
2394    pub fn end_edge_drag(window: &mut Window, cx: &mut App) {
2395        if let Some(state) = live_text_selection_state(window, cx) {
2396            state.update(cx, |state, cx| state.end_edge_drag(cx));
2397        }
2398    }
2399
2400    /// Activates the opaque selection scope for this window.
2401    pub fn activate_scope(scope: TextSelectionScopeId, window: &mut Window, cx: &mut App) {
2402        let Some(state) = WindowSelectionState::existing(window, cx) else {
2403            if !cx.has_global::<PendingTextSelectionScopes>() {
2404                cx.set_global(PendingTextSelectionScopes::default());
2405            }
2406            cx.global_mut::<PendingTextSelectionScopes>()
2407                .0
2408                .insert(window.window_handle().window_id(), scope);
2409            return;
2410        };
2411        let handlers = state.update(cx, |state, cx| state.set_active_scope_state(scope, cx));
2412        dispatch_clear_handlers(handlers, cx);
2413    }
2414}
2415
2416/// A zero-sized root layer which enables text selection for a window.
2417///
2418/// Mount one as the root's first child. Its stable `"window-text-selection"`
2419/// element identity retains the window-local selection entity across frames.
2420pub struct TextSelectionLayer;
2421
2422pub(crate) fn text_selection_scope(
2423    scope: TextSelectionScopeId,
2424    element: impl IntoElement,
2425) -> impl IntoElement {
2426    TextSelectionScopeMarker {
2427        scope,
2428        element: element.into_element(),
2429    }
2430}
2431
2432struct TextSelectionScopeMarker<E> {
2433    scope: TextSelectionScopeId,
2434    element: E,
2435}
2436
2437impl<E: Element> IntoElement for TextSelectionScopeMarker<E> {
2438    type Element = Self;
2439
2440    fn into_element(self) -> Self::Element {
2441        self
2442    }
2443}
2444
2445impl<E: Element> Element for TextSelectionScopeMarker<E> {
2446    type RequestLayoutState = E::RequestLayoutState;
2447    type PrepaintState = E::PrepaintState;
2448
2449    fn id(&self) -> Option<ElementId> {
2450        self.element.id()
2451    }
2452
2453    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
2454        self.element.source_location()
2455    }
2456
2457    fn request_layout(
2458        &mut self,
2459        id: Option<&GlobalElementId>,
2460        inspector_id: Option<&InspectorElementId>,
2461        window: &mut Window,
2462        cx: &mut App,
2463    ) -> (LayoutId, Self::RequestLayoutState) {
2464        let window_id = window.window_handle().window_id();
2465        with_text_selection_scope(window_id, self.scope, cx, |cx| {
2466            self.element.request_layout(id, inspector_id, window, cx)
2467        })
2468    }
2469
2470    fn prepaint(
2471        &mut self,
2472        id: Option<&GlobalElementId>,
2473        inspector_id: Option<&InspectorElementId>,
2474        bounds: Bounds<Pixels>,
2475        request_layout: &mut Self::RequestLayoutState,
2476        window: &mut Window,
2477        cx: &mut App,
2478    ) -> Self::PrepaintState {
2479        let window_id = window.window_handle().window_id();
2480        with_text_selection_scope(window_id, self.scope, cx, |cx| {
2481            self.element
2482                .prepaint(id, inspector_id, bounds, request_layout, window, cx)
2483        })
2484    }
2485
2486    fn paint(
2487        &mut self,
2488        id: Option<&GlobalElementId>,
2489        inspector_id: Option<&InspectorElementId>,
2490        bounds: Bounds<Pixels>,
2491        request_layout: &mut Self::RequestLayoutState,
2492        prepaint: &mut Self::PrepaintState,
2493        window: &mut Window,
2494        cx: &mut App,
2495    ) {
2496        let window_id = window.window_handle().window_id();
2497        with_text_selection_scope(window_id, self.scope, cx, |cx| {
2498            self.element.paint(
2499                id,
2500                inspector_id,
2501                bounds,
2502                request_layout,
2503                prepaint,
2504                window,
2505                cx,
2506            );
2507        });
2508    }
2509}
2510
2511#[doc(hidden)]
2512pub struct TextSelectionLayerPrepaintState(Entity<WindowSelectionState>);
2513
2514impl IntoElement for TextSelectionLayer {
2515    type Element = Self;
2516
2517    fn into_element(self) -> Self::Element {
2518        self
2519    }
2520}
2521
2522impl Element for TextSelectionLayer {
2523    type RequestLayoutState = ();
2524    type PrepaintState = TextSelectionLayerPrepaintState;
2525
2526    fn id(&self) -> Option<ElementId> {
2527        Some("window-text-selection".into())
2528    }
2529
2530    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
2531        None
2532    }
2533
2534    fn request_layout(
2535        &mut self,
2536        _: Option<&GlobalElementId>,
2537        _: Option<&InspectorElementId>,
2538        window: &mut Window,
2539        cx: &mut App,
2540    ) -> (LayoutId, Self::RequestLayoutState) {
2541        (window.request_layout(Style::default(), [], cx), ())
2542    }
2543
2544    fn prepaint(
2545        &mut self,
2546        global_id: Option<&GlobalElementId>,
2547        _: Option<&InspectorElementId>,
2548        _: Bounds<Pixels>,
2549        _: &mut Self::RequestLayoutState,
2550        window: &mut Window,
2551        cx: &mut App,
2552    ) -> Self::PrepaintState {
2553        // Automatic participant order is paint order within this frame. Keep
2554        // this lifecycle in base so base-only applications do not need a
2555        // separate root component to reset it. Otherwise, registering the
2556        // first of two selected TextViews temporarily reverses their order
2557        // against the previous frame and alternates coverage forever.
2558        GlobalState::init(cx);
2559        GlobalState::global_mut(cx).begin_selection_frame();
2560        let state = retain_text_selection_state(global_id, window, cx);
2561        // The handles and the menu register again as they paint this frame.
2562        state.update(cx, |state, _| state.touch.begin_frame());
2563        TextSelectionLayerPrepaintState(state)
2564    }
2565
2566    fn paint(
2567        &mut self,
2568        _: Option<&GlobalElementId>,
2569        _: Option<&InspectorElementId>,
2570        _: Bounds<Pixels>,
2571        _: &mut Self::RequestLayoutState,
2572        state: &mut Self::PrepaintState,
2573        window: &mut Window,
2574        cx: &mut App,
2575    ) {
2576        paint_text_selection(&state.0, window, cx);
2577    }
2578}
2579
2580fn retain_text_selection_state(
2581    global_id: Option<&GlobalElementId>,
2582    window: &mut Window,
2583    cx: &mut App,
2584) -> Entity<WindowSelectionState> {
2585    let window_id = window.window_handle().window_id();
2586    let state = window.with_element_state::<Entity<WindowSelectionState>, _>(
2587        global_id.expect("TextSelection has a stable element id"),
2588        |retained, _| {
2589            let state = retained.unwrap_or_else(|| WindowSelectionState::acquire(window_id, cx));
2590            (state.clone(), state)
2591        },
2592    );
2593    if !cx.has_global::<SelectionStateRegistry>() {
2594        cx.set_global(SelectionStateRegistry::default());
2595    }
2596    cx.global_mut::<SelectionStateRegistry>()
2597        .0
2598        .insert(window_id, state.downgrade());
2599    state
2600}
2601
2602fn paint_text_selection(state: &Entity<WindowSelectionState>, window: &mut Window, cx: &mut App) {
2603    if state.update(cx, |state, _| state.schedule_finish_frame()) {
2604        let state = state.downgrade();
2605        window.defer(cx, move |window, cx| {
2606            let Some(state) = state.upgrade() else {
2607                return;
2608            };
2609            let handlers = state.update(cx, |state, cx| state.finish_frame(cx));
2610            dispatch_clear_handlers(handlers, cx);
2611            // Direct participant scrolling produces no wheel event. Refresh
2612            // the held cursor after paint registers the new scroll geometry.
2613            let refresh_cursor = state.update(cx, |state, cx| {
2614                if std::mem::take(&mut state.refresh_held_cursor) && state.is_selecting {
2615                    // A handle drag holds the finger off the text; keep the
2616                    // same offset, or the cursor would hop between the two.
2617                    let position = window.mouse_position();
2618                    let position = state
2619                        .touch
2620                        .drag
2621                        .map_or(position, |drag| drag.text_position(position));
2622                    state.update_in_window(position, window, cx);
2623                    true
2624                } else {
2625                    false
2626                }
2627            });
2628            if refresh_cursor {
2629                WindowSelectionState::resolve_content_keys(&state, cx);
2630            }
2631        });
2632    }
2633
2634    let mouse_down_state = state.downgrade();
2635    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2636        if event.button != MouseButton::Left {
2637            return;
2638        }
2639        let Some(state) = mouse_down_state.upgrade() else {
2640            return;
2641        };
2642        // A press on a handle or on the edit menu acts on the selection; it
2643        // must not clear it.
2644        if state.read(cx).touch.covers(event.position) {
2645            return;
2646        }
2647        if phase.capture() {
2648            GlobalState::init(cx);
2649            GlobalState::reset_text_selection_suppression(cx);
2650            let handlers = state.update(cx, |state, cx| {
2651                if state.mouse_down_prepared {
2652                    return Vec::new();
2653                }
2654                state.mouse_down_prepared = true;
2655                state.prepare_for_mouse_down(event.click_count == 1 && event.modifiers.shift, cx)
2656            });
2657            dispatch_clear_handlers(handlers, cx);
2658        } else if event.click_count == 1 {
2659            if GlobalState::is_text_selection_suppressed(cx) {
2660                state.update(cx, |state, _| state.pending_extension_anchor = None);
2661                return;
2662            }
2663            state.update(cx, |state, cx| {
2664                if !state.is_selecting {
2665                    state.begin_in_window(event.position, event.modifiers.shift, window, cx)
2666                }
2667            });
2668            WindowSelectionState::resolve_content_keys(&state, cx);
2669        } else if event.click_count >= 2 {
2670            if GlobalState::is_text_selection_suppressed(cx) {
2671                return;
2672            }
2673            let touch = GlobalState::is_touch_press(cx);
2674            state.update(cx, |state, cx| {
2675                state.select_at(event.position, event.click_count, window, cx);
2676                // A double tap is touch's other way to select a word, and it
2677                // gets the handles and the menu like a long press does.
2678                if touch {
2679                    state.keep_touch_selection(cx);
2680                }
2681            });
2682            WindowSelectionState::resolve_content_keys(&state, cx);
2683        }
2684    });
2685
2686    // A handle drag in progress follows the finger or the pointer wherever
2687    // it goes, whether or not the handle it took is laid out this frame.
2688    let drag_state = state.downgrade();
2689    window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2690        if phase.bubble()
2691            && event.pressed_button == Some(MouseButton::Left)
2692            && let Some(state) = drag_state.upgrade()
2693            && state.read(cx).touch.drag.is_some()
2694        {
2695            state.update(cx, |state, cx| {
2696                state.update_edge_drag(event.position, window, cx)
2697            });
2698            WindowSelectionState::resolve_content_keys(&state, cx);
2699        }
2700    });
2701    let drag_state = state.downgrade();
2702    window.on_mouse_event(move |event: &MouseUpEvent, phase, _, cx| {
2703        if phase.bubble()
2704            && event.button == MouseButton::Left
2705            && let Some(state) = drag_state.upgrade()
2706        {
2707            state.update(cx, |state, cx| state.end_edge_drag(cx));
2708        }
2709    });
2710
2711    let mouse_move_state = state.downgrade();
2712    window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2713        if phase.bubble()
2714            && let Some(state) = mouse_move_state.upgrade()
2715        {
2716            state.update(cx, |state, cx| {
2717                // A handle drag maps the pointer through the handle's offset;
2718                // the raw pointer must not fight it.
2719                if state.touch.drag.is_some() {
2720                    return;
2721                }
2722                state.update_in_window(event.position, window, cx)
2723            });
2724            WindowSelectionState::resolve_content_keys(&state, cx);
2725        }
2726    });
2727
2728    let mouse_up_state = state.downgrade();
2729    window.on_mouse_event(move |_: &MouseUpEvent, phase, _, cx| {
2730        if phase.bubble()
2731            && let Some(state) = mouse_up_state.upgrade()
2732        {
2733            state.update(cx, |state, cx| {
2734                state.mouse_down_prepared = false;
2735                state.end(cx)
2736            });
2737        }
2738    });
2739
2740    let scroll_state = state.downgrade();
2741    window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2742        let Some(state) = scroll_state.upgrade() else {
2743            return;
2744        };
2745        // On capture, before a scroll container can stop the event: one
2746        // stretched past its end swallows the whole stream, the lift
2747        // included, and the menu would never come back.
2748        if phase.capture() {
2749            state.update(cx, |state, cx| {
2750                state.edit_menu_on_scroll(event.touch_phase, cx)
2751            });
2752            return;
2753        }
2754        if phase.bubble() {
2755            let position = window.mouse_position();
2756            state.update(cx, |state, cx| {
2757                // A handle drag holds the finger off the text; keep its offset.
2758                let position = state
2759                    .touch
2760                    .drag
2761                    .map_or(position, |drag| drag.text_position(position));
2762                state.update_in_window(position, window, cx)
2763            });
2764            WindowSelectionState::resolve_content_keys(&state, cx);
2765        }
2766    });
2767}
2768
2769fn live_text_selection_state(
2770    window: &Window,
2771    cx: &mut App,
2772) -> Option<Entity<WindowSelectionState>> {
2773    WindowSelectionState::existing(window, cx)
2774}
2775
2776pub(crate) fn clear_window_text_selection(window_id: gpui::WindowId, cx: &mut App) {
2777    if !cx.has_global::<SelectionStateRegistry>() {
2778        return;
2779    }
2780    let Some(state) = cx
2781        .global::<SelectionStateRegistry>()
2782        .0
2783        .get(&window_id)
2784        .and_then(WeakEntity::upgrade)
2785    else {
2786        return;
2787    };
2788    let handlers = state.update(cx, |state, cx| state.clear_state(cx));
2789    dispatch_clear_handlers(handlers, cx);
2790}
2791
2792#[cfg(test)]
2793mod tests {
2794    use super::*;
2795    use crate::ElementExt as _;
2796    use gpui::{
2797        Bounds, ContentMask, Context, Hitbox, HitboxBehavior, HitboxId, InteractiveElement as _,
2798        IntoElement, ParentElement as _, Render, SharedString, Styled as _, StyledText,
2799        TestAppContext, TextLayout, Window, div, point, prelude::FluentBuilder as _, px, size,
2800    };
2801    use std::{
2802        cell::{Cell, RefCell},
2803        rc::Rc,
2804    };
2805
2806    struct FakeParticipant {
2807        selection: TextSelectionHandle,
2808    }
2809
2810    struct WindowSelectionView {
2811        selection: TextSelectionHandle,
2812    }
2813
2814    struct SelectionElementOnlyView;
2815    struct ToggleSelectionElementView {
2816        enabled: bool,
2817        selection: TextSelectionHandle,
2818    }
2819
2820    struct DoubleSelectionElementView {
2821        selection: TextSelectionHandle,
2822    }
2823
2824    struct WindowOwnedSelectionView {
2825        selection: TextSelectionHandle,
2826    }
2827
2828    struct FirstFrameScopedSelectionView {
2829        selection: TextSelectionHandle,
2830    }
2831
2832    struct PlainRunLayoutView {
2833        texts: Vec<SharedString>,
2834        layouts: Vec<TextLayout>,
2835    }
2836
2837    impl Render for WindowSelectionView {
2838        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2839            div()
2840        }
2841    }
2842
2843    impl Render for SelectionElementOnlyView {
2844        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2845            div()
2846                .size_full()
2847                .child(TextSelectionLayer)
2848                .child(
2849                    div()
2850                        .size_full()
2851                        .on_mouse_down(MouseButton::Left, |_, _, cx| {
2852                            GlobalState::suppress_text_selection(cx);
2853                        }),
2854                )
2855        }
2856    }
2857
2858    impl Render for ToggleSelectionElementView {
2859        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2860            let selection = self.selection.clone();
2861            div().when(self.enabled, |this| {
2862                this.child(TextSelectionLayer)
2863                    .child(div().size_full().on_prepaint(move |bounds, window, cx| {
2864                        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
2865                        selection.register(
2866                            TextSelectionRegistration::new(hitbox, bounds)
2867                                .with_text_bounds(vec![bounds]),
2868                            window,
2869                            cx,
2870                        );
2871                    }))
2872            })
2873        }
2874    }
2875
2876    impl Render for DoubleSelectionElementView {
2877        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2878            let selection = self.selection.clone();
2879            div()
2880                .size_full()
2881                .child(TextSelectionLayer)
2882                .child(TextSelectionLayer)
2883                .on_prepaint(move |bounds, window, cx| {
2884                    let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
2885                    selection.register(
2886                        TextSelectionRegistration::new(hitbox, bounds)
2887                            .with_text_bounds(vec![bounds]),
2888                        window,
2889                        cx,
2890                    );
2891                })
2892        }
2893    }
2894
2895    impl Render for WindowOwnedSelectionView {
2896        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2897            let selection = self.selection.clone();
2898            div()
2899                .size_full()
2900                .child(TextSelectionLayer)
2901                .child(div().size_full().on_prepaint(move |bounds, window, cx| {
2902                    let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
2903                    selection.register(
2904                        TextSelectionRegistration::new(hitbox, bounds)
2905                            .with_text_bounds(vec![bounds]),
2906                        window,
2907                        cx,
2908                    );
2909                }))
2910        }
2911    }
2912
2913    impl Render for FirstFrameScopedSelectionView {
2914        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2915            let scope = TextSelectionScopeId::from_raw(23);
2916            TextSelection::activate_scope(scope, window, cx);
2917            let selection = self.selection.clone();
2918
2919            div().child(TextSelectionLayer).child(
2920                div()
2921                    .size_full()
2922                    .on_prepaint(move |bounds, window, cx| {
2923                        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
2924                        selection.register(
2925                            TextSelectionRegistration::new(hitbox, bounds)
2926                                .with_text_bounds(vec![bounds]),
2927                            window,
2928                            cx,
2929                        );
2930                    })
2931                    .text_selection_scope(scope),
2932            )
2933        }
2934    }
2935
2936    impl Render for PlainRunLayoutView {
2937        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2938            self.layouts.clear();
2939            let children = self
2940                .texts
2941                .iter()
2942                .enumerate()
2943                .map(|(index, text)| {
2944                    let text = StyledText::new(text.clone());
2945                    self.layouts.push(text.layout().clone());
2946                    div()
2947                        .flex()
2948                        .absolute()
2949                        .top(px(index as f32 * 40.))
2950                        .child(text)
2951                })
2952                .collect::<Vec<_>>();
2953            div().size_full().children(children)
2954        }
2955    }
2956
2957    impl FakeParticipant {
2958        fn new(text: &str, cx: &mut gpui::App) -> Self {
2959            let selection = TextSelectionHandle::new(text, cx);
2960            Self { selection }
2961        }
2962
2963        fn register(
2964            &self,
2965            selection_state: &mut WindowSelectionState,
2966            y: f32,
2967            scope: TextSelectionScopeId,
2968            document_order: u64,
2969            cx: &mut gpui::App,
2970        ) {
2971            let bounds = Bounds::new(point(px(0.), px(y)), size(px(100.), px(10.)));
2972            selection_state.register_participant(
2973                self.selection.clone(),
2974                TextSelectionRegistration::new(
2975                    Hitbox {
2976                        fragments: None,
2977                        tags: Vec::new(),
2978                        id: HitboxId::placeholder(),
2979                        bounds,
2980                        content_mask: ContentMask {
2981                            fade_out: Default::default(),
2982                            bounds,
2983                        },
2984                        behavior: HitboxBehavior::Normal,
2985                    },
2986                    bounds,
2987                )
2988                .with_scope(scope)
2989                .with_document_order(document_order)
2990                .with_text_bounds(vec![bounds]),
2991                cx,
2992            );
2993        }
2994    }
2995
2996    fn laid_out_runs(texts: &[&str], cx: &mut TestAppContext) -> Vec<(SharedString, TextLayout)> {
2997        let texts = texts
2998            .iter()
2999            .map(|text| SharedString::from(*text))
3000            .collect::<Vec<_>>();
3001        let view = cx.add_window({
3002            let texts = texts.clone();
3003            move |_, _| PlainRunLayoutView {
3004                texts,
3005                layouts: Vec::new(),
3006            }
3007        });
3008        cx.update_window(*view, |_, window, cx| {
3009            let _ = window.draw(cx);
3010        })
3011        .unwrap();
3012        let layouts = cx.update(|cx| view.read(cx).unwrap().layouts.clone());
3013        texts.into_iter().zip(layouts).collect()
3014    }
3015
3016    fn plain_snapshot(anchor: Point<Pixels>, cursor: Point<Pixels>) -> TextSelectionSnapshot {
3017        TextSelectionSnapshot::new(
3018            TextSelectionEndpoint::new(None, anchor),
3019            TextSelectionEndpoint::new(None, cursor),
3020        )
3021        .with_window_points(Some(TextSelectionWindowPoints { anchor, cursor }))
3022    }
3023
3024    #[gpui::test]
3025    fn scope_stack_is_cleaned_after_panicking_subtree(cx: &mut TestAppContext) {
3026        let window_id = {
3027            let (_, window_cx) = cx.add_window_view(|_, _| SelectionElementOnlyView);
3028            window_cx.update(|window, _| window.window_handle().window_id())
3029        };
3030        let scope = TextSelectionScopeId::from_raw(41);
3031
3032        cx.update(|cx| {
3033            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3034                with_text_selection_scope(window_id, scope, cx, |_| panic!("subtree failed"));
3035            }));
3036
3037            assert!(result.is_err());
3038            assert_eq!(current_text_selection_scope(window_id, cx), None);
3039        });
3040    }
3041
3042    #[gpui::test]
3043    fn reentrant_scope_from_one_window_does_not_pollute_another(cx: &mut TestAppContext) {
3044        let first_window_id = {
3045            let (_, window_cx) = cx.add_window_view(|_, _| SelectionElementOnlyView);
3046            window_cx.update(|window, _| window.window_handle().window_id())
3047        };
3048        let second_window_id = {
3049            let (_, window_cx) = cx.add_window_view(|_, _| SelectionElementOnlyView);
3050            window_cx.update(|window, _| window.window_handle().window_id())
3051        };
3052        let scope = TextSelectionScopeId::from_raw(42);
3053
3054        cx.update(|cx| {
3055            with_text_selection_scope(first_window_id, scope, cx, |cx| {
3056                assert_eq!(current_text_selection_scope(second_window_id, cx), None);
3057                assert_eq!(
3058                    current_text_selection_scope(first_window_id, cx),
3059                    Some(scope)
3060                );
3061            });
3062        });
3063    }
3064
3065    #[gpui::test]
3066    fn selection_callback_can_reenter_its_selection_state(cx: &mut TestAppContext) {
3067        let called = Rc::new(Cell::new(false));
3068        let called_from_callback = called.clone();
3069        let (selection_state, participant) = cx.update(|cx| {
3070            let selection_state = cx.new(|_| WindowSelectionState::default());
3071            let selection_state_for_callback = selection_state.clone();
3072            let participant = FakeParticipant::new("participant", cx);
3073            participant
3074                .selection
3075                .subscribe(
3076                    move |event, cx| {
3077                        if matches!(event, TextSelectionEvent::SelectionChanged(Some(_))) {
3078                            selection_state_for_callback
3079                                .update(cx, |_, _| called_from_callback.set(true));
3080                        }
3081                    },
3082                    cx,
3083                )
3084                .detach();
3085            (selection_state, participant)
3086        });
3087        cx.run_until_parked();
3088        cx.update(|cx| {
3089            selection_state.update(cx, |selection_state, cx| {
3090                participant.register(selection_state, 0., TextSelectionScopeId::default(), 0, cx);
3091                selection_state.begin(point(px(1.), px(1.)), false, cx);
3092                selection_state.update(point(px(20.), px(1.)), cx);
3093            });
3094        });
3095        cx.run_until_parked();
3096        assert!(called.get());
3097    }
3098
3099    #[gpui::test]
3100    fn selection_events_preserve_snapshot_then_clear_order(cx: &mut TestAppContext) {
3101        let observed = Rc::new(RefCell::new(Vec::new()));
3102        let observed_for_callback = observed.clone();
3103        let selection = cx.update(|cx| {
3104            let selection = TextSelectionHandle::new("selection", cx);
3105            selection
3106                .subscribe(
3107                    move |event, _| {
3108                        if let TextSelectionEvent::SelectionChanged(snapshot) = event {
3109                            observed_for_callback.borrow_mut().push(snapshot.is_some());
3110                        }
3111                    },
3112                    cx,
3113                )
3114                .detach();
3115            selection
3116        });
3117        cx.run_until_parked();
3118        cx.update(|cx| {
3119            selection.0.update(cx, |state, cx| {
3120                state.set_snapshot(
3121                    Some(plain_snapshot(point(px(1.), px(1.)), point(px(8.), px(1.)))),
3122                    cx,
3123                );
3124                state.clear_state(cx);
3125            });
3126        });
3127        cx.run_until_parked();
3128        assert_eq!(&*observed.borrow(), &[true, false]);
3129    }
3130
3131    fn text_run(order: u64, text: SharedString, layout: TextLayout) -> TextSelectionRun {
3132        let bounds = layout.bounds();
3133        TextSelectionRun::new(text, layout, bounds).with_document_order(order)
3134    }
3135
3136    #[gpui::test]
3137    fn public_selection_data_uses_builders_and_readers(cx: &mut TestAppContext) {
3138        let bounds = Bounds::new(point(px(1.), px(2.)), size(px(30.), px(10.)));
3139        let hitbox = Hitbox {
3140            fragments: None,
3141            tags: Vec::new(),
3142            id: HitboxId::placeholder(),
3143            bounds,
3144            content_mask: ContentMask {
3145                fade_out: Default::default(),
3146                bounds,
3147            },
3148            behavior: HitboxBehavior::Normal,
3149        };
3150        let scope = TextSelectionScopeId::from_raw(7);
3151        let endpoint = TextSelectionEndpoint::new(None, bounds.origin)
3152            .with_content_key(TextSelectionContentKey::new(11));
3153        let snapshot = TextSelectionSnapshot::new(endpoint, endpoint)
3154            .with_selecting(true)
3155            .with_window_points(Some(TextSelectionWindowPoints {
3156                anchor: bounds.origin,
3157                cursor: bounds.bottom_right(),
3158            }))
3159            .with_coverage(TextSelectionCoverage::Full);
3160        let registration = TextSelectionRegistration::new(hitbox, bounds)
3161            .with_scroll_offset(point(px(3.), px(4.)))
3162            .with_scope(scope)
3163            .with_document_order(9)
3164            .with_text_bounds(vec![bounds]);
3165
3166        assert_eq!(endpoint.entity_id(), None);
3167        assert_eq!(endpoint.content_point(), bounds.origin);
3168        assert_eq!(
3169            endpoint.content_key(),
3170            Some(TextSelectionContentKey::new(11))
3171        );
3172        assert_eq!(snapshot.anchor(), endpoint);
3173        assert_eq!(snapshot.cursor(), endpoint);
3174        assert!(snapshot.is_selecting());
3175        assert_eq!(snapshot.coverage(), TextSelectionCoverage::Full);
3176        assert_eq!(
3177            snapshot.window_points(),
3178            Some(TextSelectionWindowPoints {
3179                anchor: bounds.origin,
3180                cursor: bounds.bottom_right(),
3181            })
3182        );
3183        assert_eq!(registration.bounds(), bounds);
3184        assert_eq!(registration.scroll_offset(), point(px(3.), px(4.)));
3185        assert_eq!(registration.scope(), scope);
3186        assert_eq!(registration.document_order(), 9);
3187        assert_eq!(registration.text_bounds(), &[bounds]);
3188
3189        let (text, layout) = laid_out_runs(&["aé"], cx).pop().unwrap();
3190        let text_run = TextSelectionRun::new(text.clone(), layout.clone(), layout.bounds())
3191            .with_document_order(3);
3192        assert_eq!(text_run.document_order(), 3);
3193        assert_eq!(text_run.text(), &text);
3194        assert_eq!(text_run.layout().len(), layout.len());
3195        assert_eq!(text_run.bounds(), layout.bounds());
3196
3197        let projection = TextSelectionProjection {
3198            ranges: vec![Some(1..3)],
3199            is_active: true,
3200        };
3201        assert_eq!(projection.ranges(), &[Some(1..3)]);
3202        assert!(projection.is_active());
3203    }
3204
3205    #[gpui::test]
3206    fn selection_handle_is_the_public_adapter_seam(cx: &mut TestAppContext) {
3207        let selected = Rc::new(Cell::new(false));
3208        let selected_from_callback = selected.clone();
3209        cx.update(|cx| {
3210            let selection = TextSelectionHandle::new("initial", cx);
3211            let entity_id = selection.entity_id();
3212            selection.set_fallback_copy_text("updated", cx);
3213            selection.set_local_selection(true, cx);
3214            selection
3215                .subscribe(
3216                    move |event, _| {
3217                        if let TextSelectionEvent::SelectionChanged(snapshot) = event {
3218                            selected_from_callback.set(snapshot.is_some());
3219                        }
3220                    },
3221                    cx,
3222                )
3223                .detach();
3224            selection.focus_with(|_, _| {}, cx);
3225            selection.copy_with(|_| "copied".to_string(), cx);
3226            selection.resolve_content_key_with(|_, _| Some(TextSelectionContentKey::new(3)), cx);
3227
3228            assert_eq!(selection.entity_id(), entity_id);
3229            assert_eq!(selection.snapshot(cx), None);
3230            assert_eq!(
3231                selection.update_runs(&[], cx),
3232                TextSelectionProjection::default()
3233            );
3234        });
3235        assert!(!selected.get());
3236    }
3237
3238    #[gpui::test]
3239    fn selection_handle_can_subscribe_its_window_to_refresh(cx: &mut TestAppContext) {
3240        let (_, cx) = cx.add_window_view(|_, cx| WindowSelectionView {
3241            selection: TextSelectionHandle::new("refresh", cx),
3242        });
3243        cx.update(|window, cx| {
3244            let selection = TextSelectionHandle::new("refresh", cx);
3245            selection.refresh_window_on_change(window, cx).detach();
3246        });
3247    }
3248
3249    #[gpui::test]
3250    fn plain_projection_preserves_forward_reversed_and_unicode_ranges(cx: &mut TestAppContext) {
3251        let (text, layout) = laid_out_runs(&["aé🙂z"], cx).pop().unwrap();
3252        let run = text_run(0, text, layout.clone());
3253        let start = layout.position_for_index(1).unwrap();
3254        let end = layout.position_for_index(7).unwrap();
3255
3256        let forward = project_ranges(Some(plain_snapshot(start, end)), std::slice::from_ref(&run));
3257        let reversed = project_ranges(Some(plain_snapshot(end, start)), &[run]);
3258
3259        assert_eq!(forward.ranges(), &[Some(1..7)]);
3260        assert_eq!(reversed.ranges(), &[Some(1..7)]);
3261        assert!(forward.is_active());
3262        assert!(reversed.is_active());
3263    }
3264
3265    #[gpui::test]
3266    fn double_click_expands_a_plain_run_to_the_input_word_boundary(cx: &mut TestAppContext) {
3267        let (text, layout) = laid_out_runs(&["one café, three"], cx).pop().unwrap();
3268        let run = text_run(0, text, layout.clone());
3269        let click = layout.position_for_index(6).unwrap();
3270
3271        let (anchor, cursor) =
3272            points_for_multi_click(std::slice::from_ref(&run), click, 2).unwrap();
3273        let states = project_ranges(Some(plain_snapshot(anchor, cursor)), &[run]);
3274
3275        assert_eq!(states.ranges(), &[Some(4..9)]);
3276    }
3277
3278    #[gpui::test]
3279    fn multi_click_uses_text_layout_window_coordinates_at_a_nonzero_origin(
3280        cx: &mut TestAppContext,
3281    ) {
3282        let mut runs = laid_out_runs(&["above", "alpha beta"], cx);
3283        let (text, layout) = runs.pop().unwrap();
3284        assert!(layout.bounds().origin.y > px(0.));
3285        let run = text_run(0, text, layout.clone());
3286        let click = layout.position_for_index(7).unwrap();
3287
3288        let (anchor, cursor) =
3289            points_for_multi_click(std::slice::from_ref(&run), click, 2).unwrap();
3290        let projection = project_ranges(Some(plain_snapshot(anchor, cursor)), &[run]);
3291
3292        assert_eq!(projection.ranges(), &[Some(6..10)]);
3293    }
3294
3295    #[gpui::test]
3296    fn triple_click_expands_to_the_input_logical_line_not_the_visual_row(cx: &mut TestAppContext) {
3297        let (text, layout) = laid_out_runs(&["second line"], cx).pop().unwrap();
3298        let run = text_run(0, text, layout.clone());
3299        let click = layout.position_for_index(4).unwrap();
3300
3301        let (anchor, cursor) =
3302            points_for_multi_click(std::slice::from_ref(&run), click, 4).unwrap();
3303        let states = project_ranges(Some(plain_snapshot(anchor, cursor)), &[run]);
3304
3305        assert_eq!(states.ranges(), &[Some(0..11)]);
3306        assert_eq!(line_range_at("first line\nsecond line\nthird", 15), 11..22);
3307    }
3308
3309    #[gpui::test]
3310    fn plain_projection_spans_multiple_runs_and_leaves_empty_gutters_unselected(
3311        cx: &mut TestAppContext,
3312    ) {
3313        let mut runs = laid_out_runs(&["first", "", "second"], cx);
3314        let (first_text, first_layout) = runs.remove(0);
3315        let (gutter_text, gutter_layout) = runs.remove(0);
3316        let (second_text, second_layout) = runs.remove(0);
3317        let start = first_layout.position_for_index(2).unwrap();
3318        let end = second_layout.position_for_index(3).unwrap();
3319        let states = project_ranges(
3320            Some(plain_snapshot(start, end)),
3321            &[
3322                text_run(2, second_text, second_layout),
3323                text_run(1, gutter_text, gutter_layout),
3324                text_run(0, first_text, first_layout),
3325            ],
3326        );
3327
3328        assert_eq!(states.ranges(), &[Some(0..3), None, Some(2..5)]);
3329        assert!(states.is_active());
3330    }
3331
3332    #[gpui::test]
3333    fn plain_projection_caches_multiple_participant_copies_in_document_order(
3334        cx: &mut TestAppContext,
3335    ) {
3336        let mut runs = laid_out_runs(&["one", "two"], cx);
3337        let (first_text, first_layout) = runs.remove(0);
3338        let (second_text, second_layout) = runs.remove(0);
3339        let snapshot = plain_snapshot(
3340            first_layout.position_for_index(1).unwrap(),
3341            second_layout.position_for_index(2).unwrap(),
3342        );
3343        cx.update(|cx| {
3344            let mut selection_state = WindowSelectionState::default();
3345            let first = FakeParticipant::new("", cx);
3346            let second = FakeParticipant::new("", cx);
3347            first.register(
3348                &mut selection_state,
3349                0.,
3350                TextSelectionScopeId::default(),
3351                1,
3352                cx,
3353            );
3354            second.register(
3355                &mut selection_state,
3356                20.,
3357                TextSelectionScopeId::default(),
3358                0,
3359                cx,
3360            );
3361
3362            first
3363                .selection
3364                .0
3365                .update(cx, |state, cx| state.set_snapshot(Some(snapshot), cx));
3366            let projection = first
3367                .selection
3368                .update_runs(&[text_run(0, first_text, first_layout)], cx);
3369            assert_eq!(projection.ranges(), &[Some(1..3)]);
3370            assert!(projection.is_active());
3371            second
3372                .selection
3373                .0
3374                .update(cx, |state, cx| state.set_snapshot(Some(snapshot), cx));
3375            let projection = second
3376                .selection
3377                .update_runs(&[text_run(0, second_text, second_layout)], cx);
3378            assert_eq!(projection.ranges(), &[Some(0..2)]);
3379            assert!(projection.is_active());
3380
3381            assert_eq!(selection_state.selected_text(cx), "tw\nne");
3382        });
3383    }
3384
3385    #[gpui::test]
3386    fn plain_projection_invalidates_cached_copy_when_the_snapshot_changes(cx: &mut TestAppContext) {
3387        let (text, layout) = laid_out_runs(&["first"], cx).pop().unwrap();
3388        let first_snapshot = plain_snapshot(
3389            layout.position_for_index(1).unwrap(),
3390            layout.position_for_index(3).unwrap(),
3391        );
3392        let changed_snapshot = plain_snapshot(
3393            layout.position_for_index(3).unwrap(),
3394            layout.position_for_index(5).unwrap(),
3395        );
3396        let run = text_run(0, text, layout);
3397        cx.update(|cx| {
3398            let mut selection_state = WindowSelectionState::default();
3399            let participant = FakeParticipant::new("", cx);
3400            participant.register(
3401                &mut selection_state,
3402                0.,
3403                TextSelectionScopeId::default(),
3404                0,
3405                cx,
3406            );
3407            participant.selection.0.update(cx, |state, cx| {
3408                state.set_snapshot(Some(first_snapshot), cx);
3409                state.update_runs(std::slice::from_ref(&run));
3410            });
3411            assert_eq!(selection_state.selected_text(cx), "ir");
3412
3413            participant.selection.0.update(cx, |state, cx| {
3414                state.set_snapshot(Some(changed_snapshot), cx);
3415            });
3416            assert_eq!(selection_state.selected_text(cx), "");
3417
3418            participant.selection.update_runs(&[run], cx);
3419            assert_eq!(selection_state.selected_text(cx), "st");
3420            selection_state.clear(cx);
3421            participant.selection.set_local_selection(true, cx);
3422            assert_eq!(selection_state.selected_text(cx), "");
3423        });
3424    }
3425
3426    #[gpui::test]
3427    fn plain_projection_orders_cached_runs_by_frame_order_not_input_order(cx: &mut TestAppContext) {
3428        let mut runs = laid_out_runs(&["one", "two"], cx);
3429        let (first_text, first_layout) = runs.remove(0);
3430        let (second_text, second_layout) = runs.remove(0);
3431        let snapshot = plain_snapshot(
3432            first_layout.position_for_index(1).unwrap(),
3433            second_layout.position_for_index(2).unwrap(),
3434        );
3435        cx.update(|cx| {
3436            let mut selection_state = WindowSelectionState::default();
3437            let participant = FakeParticipant::new("", cx);
3438            participant.register(
3439                &mut selection_state,
3440                0.,
3441                TextSelectionScopeId::default(),
3442                0,
3443                cx,
3444            );
3445            participant.selection.0.update(cx, |state, cx| {
3446                state.set_snapshot(Some(snapshot), cx);
3447                state.update_runs(&[
3448                    text_run(1, first_text, first_layout),
3449                    text_run(0, second_text, second_layout),
3450                ]);
3451            });
3452
3453            assert_eq!(selection_state.selected_text(cx), "twne");
3454        });
3455    }
3456
3457    #[gpui::test]
3458    fn plain_projection_safely_rejects_a_text_layout_length_mismatch(cx: &mut TestAppContext) {
3459        let (_, layout) = laid_out_runs(&["short"], cx).pop().unwrap();
3460        let start = layout.position_for_index(0).unwrap();
3461        let end = layout.position_for_index(5).unwrap();
3462        let states = project_ranges(
3463            Some(plain_snapshot(start, end)),
3464            &[text_run(0, SharedString::from("longer"), layout)],
3465        );
3466
3467        assert_eq!(states.ranges(), &[None]);
3468        assert!(states.is_active());
3469    }
3470
3471    #[gpui::test]
3472    fn begin_update_and_end_publish_a_cross_participant_selection(cx: &mut TestAppContext) {
3473        cx.update(|cx| {
3474            let mut selection_state = WindowSelectionState::default();
3475            let first = FakeParticipant::new("first", cx);
3476            let second = FakeParticipant::new("second", cx);
3477            first.register(
3478                &mut selection_state,
3479                0.,
3480                TextSelectionScopeId::default(),
3481                0,
3482                cx,
3483            );
3484            second.register(
3485                &mut selection_state,
3486                20.,
3487                TextSelectionScopeId::default(),
3488                1,
3489                cx,
3490            );
3491
3492            selection_state.begin(point(px(1.), px(1.)), false, cx);
3493            selection_state.update(point(px(1.), px(25.)), cx);
3494            assert!(selection_state.has_selection(cx));
3495            assert_eq!(selection_state.selected_text(cx), "first\nsecond");
3496
3497            selection_state.end(cx);
3498            assert!(!selection_state.is_selecting());
3499        });
3500    }
3501
3502    #[gpui::test]
3503    fn shift_extension_keeps_its_original_anchor_when_reversed(cx: &mut TestAppContext) {
3504        cx.update(|cx| {
3505            let mut selection_state = WindowSelectionState::default();
3506            let participant = FakeParticipant::new("participant", cx);
3507            participant.register(
3508                &mut selection_state,
3509                0.,
3510                TextSelectionScopeId::default(),
3511                0,
3512                cx,
3513            );
3514
3515            selection_state.begin(point(px(2.), px(2.)), false, cx);
3516            selection_state.end(cx);
3517            selection_state.begin(point(px(8.), px(2.)), true, cx);
3518            selection_state.end(cx);
3519            let first_anchor = selection_state.snapshot().unwrap().anchor();
3520
3521            selection_state.begin(point(px(0.), px(2.)), true, cx);
3522            selection_state.end(cx);
3523            let reversed = selection_state.snapshot().unwrap();
3524            assert_eq!(reversed.anchor(), first_anchor);
3525            assert!(reversed.cursor().content_point().x < reversed.anchor().content_point().x);
3526        });
3527    }
3528
3529    #[gpui::test]
3530    fn content_key_resolver_runs_outside_the_window_state_lease(cx: &mut TestAppContext) {
3531        cx.update(|cx| {
3532            let state = cx.new(|_| WindowSelectionState::default());
3533            let participant = FakeParticipant::new("virtual", cx);
3534            let state_for_callback = state.clone();
3535            participant.selection.resolve_content_key_with(
3536                move |_, cx| {
3537                    let _ = state_for_callback.read(cx).snapshot();
3538                    Some(TextSelectionContentKey::new(7))
3539                },
3540                cx,
3541            );
3542            state.update(cx, |state, cx| {
3543                participant.register(state, 0., TextSelectionScopeId::default(), 0, cx);
3544                state.begin(point(px(1.), px(1.)), false, cx);
3545                state.update(point(px(8.), px(1.)), cx);
3546            });
3547
3548            WindowSelectionState::resolve_content_keys(&state, cx);
3549
3550            assert_eq!(
3551                state.read(cx).snapshot().unwrap().cursor().content_key(),
3552                Some(TextSelectionContentKey::new(7))
3553            );
3554        });
3555    }
3556
3557    #[gpui::test]
3558    fn active_dnd_does_not_move_a_text_selection_cursor(cx: &mut TestAppContext) {
3559        let window = cx.add_window(|_, cx| WindowSelectionView {
3560            selection: TextSelectionHandle::new("unused", cx),
3561        });
3562        window
3563            .update(cx, |_, window, cx| {
3564                let mut state = WindowSelectionState::default();
3565                let participant = FakeParticipant::new("participant", cx);
3566                participant.register(&mut state, 0., TextSelectionScopeId::default(), 0, cx);
3567                state.begin(point(px(1.), px(1.)), false, cx);
3568                let before = state.cursor.as_ref().unwrap().point;
3569                state.update_in_window_with_active_drag(point(px(80.), px(1.)), true, window, cx);
3570                assert_eq!(state.cursor.as_ref().unwrap().point, before);
3571            })
3572            .unwrap();
3573    }
3574
3575    #[gpui::test]
3576    fn shift_extension_falls_back_when_the_anchor_participant_was_swept(cx: &mut TestAppContext) {
3577        cx.update(|cx| {
3578            let mut selection_state = WindowSelectionState::default();
3579            let first = FakeParticipant::new("first", cx);
3580            let second = FakeParticipant::new("second", cx);
3581            first.register(
3582                &mut selection_state,
3583                0.,
3584                TextSelectionScopeId::default(),
3585                0,
3586                cx,
3587            );
3588            selection_state.begin(point(px(1.), px(1.)), false, cx);
3589            selection_state.update(point(px(8.), px(1.)), cx);
3590            selection_state.end(cx);
3591
3592            selection_state.finish_frame(cx);
3593            selection_state.finish_frame(cx);
3594            second.register(
3595                &mut selection_state,
3596                20.,
3597                TextSelectionScopeId::default(),
3598                1,
3599                cx,
3600            );
3601            selection_state.begin(point(px(1.), px(21.)), true, cx);
3602            selection_state.update(point(px(8.), px(21.)), cx);
3603            selection_state.end(cx);
3604
3605            assert_eq!(selection_state.selected_text(cx), "second");
3606        });
3607    }
3608
3609    #[gpui::test]
3610    fn scope_and_suppression_prevent_unrelated_participants_from_participating(
3611        cx: &mut TestAppContext,
3612    ) {
3613        cx.update(|cx| {
3614            let mut selection_state = WindowSelectionState::default();
3615            let base = FakeParticipant::new("base", cx);
3616            let modal = FakeParticipant::new("modal", cx);
3617            base.register(
3618                &mut selection_state,
3619                0.,
3620                TextSelectionScopeId::default(),
3621                0,
3622                cx,
3623            );
3624            modal.register(&mut selection_state, 20., TextSelectionScopeId(1), 1, cx);
3625
3626            selection_state.set_active_scope(TextSelectionScopeId(1), cx);
3627            selection_state.begin(point(px(1.), px(21.)), false, cx);
3628            selection_state.update(point(px(8.), px(21.)), cx);
3629            selection_state.end(cx);
3630            assert_eq!(selection_state.selected_text(cx), "modal");
3631
3632            selection_state.clear(cx);
3633            GlobalState::init(cx);
3634            GlobalState::suppress_text_selection(cx);
3635            selection_state.begin(point(px(1.), px(21.)), false, cx);
3636            selection_state.update(point(px(8.), px(21.)), cx);
3637            assert!(!selection_state.has_selection(cx));
3638        });
3639    }
3640
3641    #[gpui::test]
3642    fn dead_participants_are_pruned_and_empty_selection_falls_back_safely(cx: &mut TestAppContext) {
3643        let selection_state = cx.update(|cx| {
3644            let selection_state = cx.new(|_| WindowSelectionState::default());
3645            let participant = FakeParticipant::new("gone", cx);
3646            selection_state.update(cx, |selection_state, cx| {
3647                participant.register(selection_state, 0., TextSelectionScopeId::default(), 0, cx)
3648            });
3649            selection_state
3650        });
3651        cx.update(|cx| {
3652            selection_state.update(cx, |selection_state, cx| {
3653                selection_state.begin(point(px(1.), px(1.)), false, cx);
3654                selection_state.update(point(px(8.), px(1.)), cx);
3655                selection_state.end(cx);
3656
3657                assert_eq!(selection_state.selected_text(cx), "");
3658                assert!(!selection_state.has_selection(cx));
3659            });
3660        });
3661    }
3662
3663    #[gpui::test]
3664    fn text_selection_namespace_reports_copies_ends_and_clears_selection(cx: &mut TestAppContext) {
3665        let (view, cx) = cx.add_window_view(|_, cx| WindowSelectionView {
3666            selection: TextSelectionHandle::new("copied", cx),
3667        });
3668        cx.update(|window, cx| {
3669            let selection = view.read(cx).selection.clone();
3670            let selection_state = WindowSelectionState::ensure(window, cx);
3671            selection_state.update(cx, |selection_state, cx| {
3672                FakeParticipant { selection }.register(
3673                    selection_state,
3674                    0.,
3675                    TextSelectionScopeId::default(),
3676                    0,
3677                    cx,
3678                );
3679                selection_state.begin(point(px(1.), px(1.)), false, cx);
3680                selection_state.update(point(px(8.), px(1.)), cx);
3681            });
3682
3683            assert!(TextSelection::has_selection(window, cx));
3684            assert_eq!(TextSelection::selected_text(window, cx), "copied");
3685            TextSelection::end(window, cx);
3686            assert!(TextSelection::has_selection(window, cx));
3687            TextSelection::clear(window, cx);
3688            assert!(!TextSelection::has_selection(window, cx));
3689            assert_eq!(TextSelection::selected_text(window, cx), "");
3690        });
3691    }
3692
3693    #[gpui::test]
3694    fn two_windows_isolate_selection_copy_clear_and_release_ownership(cx: &mut TestAppContext) {
3695        let first = cx.add_window(|_, cx| WindowOwnedSelectionView {
3696            selection: TextSelectionHandle::new("first", cx),
3697        });
3698        let second = cx.add_window(|_, cx| WindowOwnedSelectionView {
3699            selection: TextSelectionHandle::new("second", cx),
3700        });
3701        let first_selection = cx.update(|cx| first.read(cx).unwrap().selection.clone());
3702        let second_selection = cx.update(|cx| second.read(cx).unwrap().selection.clone());
3703
3704        let first_state = cx
3705            .update_window(*first, |_, window, cx| {
3706                let _ = window.draw(cx);
3707                first_selection.set_local_selection(true, cx);
3708                assert_eq!(TextSelection::selected_text(window, cx), "first");
3709                WindowSelectionState::existing(window, cx)
3710                    .unwrap()
3711                    .downgrade()
3712            })
3713            .unwrap();
3714        cx.update_window(*second, |_, window, cx| {
3715            let _ = window.draw(cx);
3716            second_selection.set_local_selection(true, cx);
3717            assert_eq!(TextSelection::selected_text(window, cx), "second");
3718        })
3719        .unwrap();
3720
3721        cx.update_window(*first, |_, window, cx| {
3722            TextSelection::clear(window, cx);
3723            assert_eq!(TextSelection::selected_text(window, cx), "");
3724        })
3725        .unwrap();
3726        cx.update_window(*second, |_, window, cx| {
3727            assert_eq!(TextSelection::selected_text(window, cx), "second");
3728        })
3729        .unwrap();
3730
3731        cx.update_window(*first, |_, window, _| window.remove_window())
3732            .unwrap();
3733        cx.run_until_parked();
3734
3735        assert!(first_state.upgrade().is_none());
3736        cx.update_window(*second, |_, window, cx| {
3737            assert_eq!(TextSelection::selected_text(window, cx), "second");
3738        })
3739        .unwrap();
3740        cx.update(|cx| {
3741            assert_eq!(cx.global::<SelectionStateRegistry>().0.len(), 1);
3742        });
3743    }
3744
3745    #[gpui::test]
3746    fn copy_callback_can_reenter_window_and_handle_selection(cx: &mut TestAppContext) {
3747        let (_, cx) = cx.add_window_view(|_, _| SelectionElementOnlyView);
3748        cx.update(|window, cx| {
3749            let _ = window.draw(cx);
3750            let state = WindowSelectionState::existing(window, cx).unwrap();
3751            let selection = TextSelectionHandle::new("fallback", cx);
3752            let state_for_copy = state.clone();
3753            let selection_for_copy = selection.clone();
3754            selection.copy_with(
3755                move |cx: &mut App| {
3756                    state_for_copy.update(cx, |state, _| {
3757                        assert!(state.snapshot().is_some());
3758                    });
3759                    assert!(selection_for_copy.snapshot(cx).is_some());
3760                    selection_for_copy.set_fallback_copy_text("reentered", cx);
3761                    "reentrant copy".to_string()
3762                },
3763                cx,
3764            );
3765            state.update(cx, |state, cx| {
3766                FakeParticipant {
3767                    selection: selection.clone(),
3768                }
3769                .register(state, 0., TextSelectionScopeId::default(), 0, cx);
3770                state.begin(point(px(1.), px(1.)), false, cx);
3771                state.update(point(px(8.), px(1.)), cx);
3772                state.end(cx);
3773            });
3774
3775            assert_eq!(TextSelection::selected_text(window, cx), "reentrant copy");
3776        });
3777    }
3778
3779    #[gpui::test]
3780    fn cross_participant_selection_excludes_participants_outside_its_document_interval(
3781        cx: &mut TestAppContext,
3782    ) {
3783        cx.update(|cx| {
3784            let mut selection_state = WindowSelectionState::default();
3785            let first = FakeParticipant::new("first", cx);
3786            let second = FakeParticipant::new("second", cx);
3787            let third = FakeParticipant::new("third", cx);
3788            first.register(
3789                &mut selection_state,
3790                0.,
3791                TextSelectionScopeId::default(),
3792                0,
3793                cx,
3794            );
3795            second.register(
3796                &mut selection_state,
3797                20.,
3798                TextSelectionScopeId::default(),
3799                1,
3800                cx,
3801            );
3802            third.register(
3803                &mut selection_state,
3804                40.,
3805                TextSelectionScopeId::default(),
3806                2,
3807                cx,
3808            );
3809
3810            selection_state.begin(point(px(1.), px(1.)), false, cx);
3811            selection_state.update(point(px(1.), px(25.)), cx);
3812            selection_state.end(cx);
3813
3814            assert_eq!(selection_state.selected_text(cx), "first\nsecond");
3815            assert!(third.selection.snapshot(cx).is_none());
3816        });
3817    }
3818
3819    #[gpui::test]
3820    fn changing_scope_clears_the_previous_scope_selection(cx: &mut TestAppContext) {
3821        cx.update(|cx| {
3822            let mut selection_state = WindowSelectionState::default();
3823            let base = FakeParticipant::new("base", cx);
3824            let modal = FakeParticipant::new("modal", cx);
3825            base.register(
3826                &mut selection_state,
3827                0.,
3828                TextSelectionScopeId::default(),
3829                0,
3830                cx,
3831            );
3832            modal.register(
3833                &mut selection_state,
3834                20.,
3835                TextSelectionScopeId::from_raw(1),
3836                1,
3837                cx,
3838            );
3839
3840            selection_state.begin(point(px(1.), px(1.)), false, cx);
3841            selection_state.update(point(px(8.), px(1.)), cx);
3842            selection_state.end(cx);
3843            selection_state.set_active_scope(TextSelectionScopeId::from_raw(1), cx);
3844
3845            assert!(!selection_state.has_selection(cx));
3846            assert!(base.selection.snapshot(cx).is_none());
3847        });
3848    }
3849
3850    #[gpui::test]
3851    fn blank_only_drag_never_publishes_or_copies_selection(cx: &mut TestAppContext) {
3852        cx.update(|cx| {
3853            let mut selection_state = WindowSelectionState::default();
3854            let participant = FakeParticipant::new("participant", cx);
3855            participant.register(
3856                &mut selection_state,
3857                0.,
3858                TextSelectionScopeId::default(),
3859                0,
3860                cx,
3861            );
3862
3863            selection_state.begin(point(px(200.), px(1.)), false, cx);
3864            selection_state.update(point(px(200.), px(8.)), cx);
3865            selection_state.end(cx);
3866
3867            assert!(!selection_state.has_selection(cx));
3868            assert_eq!(selection_state.selected_text(cx), "");
3869            assert!(participant.selection.snapshot(cx).is_none());
3870        });
3871    }
3872
3873    #[gpui::test]
3874    fn stale_live_participants_are_removed_when_the_next_frame_begins(cx: &mut TestAppContext) {
3875        cx.update(|cx| {
3876            let mut selection_state = WindowSelectionState::default();
3877            let participant = FakeParticipant::new("stale", cx);
3878            participant.register(
3879                &mut selection_state,
3880                0.,
3881                TextSelectionScopeId::default(),
3882                0,
3883                cx,
3884            );
3885            selection_state.begin(point(px(1.), px(1.)), false, cx);
3886            selection_state.update(point(px(8.), px(1.)), cx);
3887            selection_state.end(cx);
3888
3889            selection_state.finish_frame(cx);
3890            selection_state.finish_frame(cx);
3891            assert_eq!(selection_state.selected_text(cx), "");
3892            assert!(participant.selection.snapshot(cx).is_none());
3893        });
3894    }
3895
3896    #[gpui::test]
3897    fn clear_stops_anchor_auto_scroll_before_discarding_the_anchor(cx: &mut TestAppContext) {
3898        let commands = Rc::new(RefCell::new(Vec::new()));
3899        let observed = commands.clone();
3900        let (mut selection_state, participant) = cx.update(|cx| {
3901            let selection_state = WindowSelectionState::default();
3902            let participant = FakeParticipant::new("scroll", cx);
3903            participant
3904                .selection
3905                .subscribe(
3906                    move |event, _| {
3907                        if let TextSelectionEvent::AutoScroll(delta) = event {
3908                            observed.borrow_mut().push(*delta);
3909                        }
3910                    },
3911                    cx,
3912                )
3913                .detach();
3914            (selection_state, participant)
3915        });
3916        cx.run_until_parked();
3917        cx.update(|cx| {
3918            participant.register(
3919                &mut selection_state,
3920                0.,
3921                TextSelectionScopeId::default(),
3922                0,
3923                cx,
3924            );
3925
3926            selection_state.begin(point(px(1.), px(1.)), false, cx);
3927            selection_state.update(point(px(1.), px(25.)), cx);
3928            selection_state.clear(cx);
3929        });
3930        cx.run_until_parked();
3931        assert!(commands.borrow().iter().any(Option::is_some));
3932        assert_eq!(commands.borrow().last(), Some(&None));
3933    }
3934
3935    #[gpui::test]
3936    fn drag_auto_scroll_stops_when_the_content_mask_collapses(cx: &mut TestAppContext) {
3937        let window = cx.add_window(|_, cx| WindowSelectionView {
3938            selection: TextSelectionHandle::new("unused", cx),
3939        });
3940        window
3941            .update(cx, |_, window, cx| {
3942                let state = cx.new(|_| WindowSelectionState::default());
3943                let participant = FakeParticipant::new("participant", cx);
3944                state.update(cx, |state, cx| {
3945                    participant.register(state, 0., TextSelectionScopeId::default(), 0, cx);
3946                    state.begin(point(px(1.), px(1.)), false, cx);
3947                });
3948                // The scrollable ancestor got clipped away mid-drag, so the
3949                // refreshed registration carries a collapsed content mask.
3950                let collapsed = Bounds::new(point(px(0.), px(0.)), size(px(100.), px(0.)));
3951                state.update(cx, |state, cx| {
3952                    state.register_participant(
3953                        participant.selection.clone(),
3954                        TextSelectionRegistration::new(
3955                            Hitbox {
3956                                fragments: None,
3957                                tags: Vec::new(),
3958                                id: HitboxId::placeholder(),
3959                                bounds: collapsed,
3960                                content_mask: ContentMask {
3961                                    fade_out: Default::default(),
3962                                    bounds: collapsed,
3963                                },
3964                                behavior: HitboxBehavior::Normal,
3965                            },
3966                            collapsed,
3967                        )
3968                        .with_text_bounds(vec![collapsed]),
3969                        cx,
3970                    );
3971                    state.update_in_window(point(px(1.), px(50.)), window, cx);
3972                    assert!(!state.auto_scroll.is_active());
3973                    assert!(state.auto_scroll.last_drag_position.is_none());
3974                });
3975            })
3976            .unwrap();
3977    }
3978
3979    #[gpui::test]
3980    fn pointer_moves_after_a_click_do_not_auto_scroll(cx: &mut TestAppContext) {
3981        let window = cx.add_window(|_, cx| WindowSelectionView {
3982            selection: TextSelectionHandle::new("unused", cx),
3983        });
3984        window
3985            .update(cx, |_, window, cx| {
3986                let state = cx.new(|_| WindowSelectionState::default());
3987                let participant = FakeParticipant::new("participant", cx);
3988                state.update(cx, |state, cx| {
3989                    participant.register(state, 0., TextSelectionScopeId::default(), 0, cx);
3990                    // A click on text keeps its anchor so shift-click can extend it.
3991                    state.begin(point(px(1.), px(1.)), false, cx);
3992                    state.end(cx);
3993                    assert!(state.anchor.is_some());
3994
3995                    state.update_in_window(point(px(1.), px(50.)), window, cx);
3996                    assert!(!state.auto_scroll.is_active());
3997                });
3998            })
3999            .unwrap();
4000    }
4001
4002    #[gpui::test]
4003    fn proxy_endpoints_break_equal_position_ties_by_document_order(cx: &mut TestAppContext) {
4004        cx.update(|cx| {
4005            let mut selection_state = WindowSelectionState::default();
4006            let later = FakeParticipant::new("later", cx);
4007            let earlier = FakeParticipant::new("earlier", cx);
4008            later.register(
4009                &mut selection_state,
4010                0.,
4011                TextSelectionScopeId::default(),
4012                2,
4013                cx,
4014            );
4015            earlier.register(
4016                &mut selection_state,
4017                0.,
4018                TextSelectionScopeId::default(),
4019                1,
4020                cx,
4021            );
4022
4023            selection_state.begin(point(px(1.), px(1.)), false, cx);
4024            selection_state.update(point(px(200.), px(25.)), cx);
4025            let endpoint = selection_state.snapshot().unwrap().cursor();
4026
4027            assert_eq!(endpoint.entity_id(), Some(earlier.selection.entity_id()));
4028        });
4029    }
4030
4031    #[gpui::test]
4032    fn equal_area_hovered_participants_break_ties_by_document_order(cx: &mut TestAppContext) {
4033        cx.update(|cx| {
4034            for _ in 0..64 {
4035                let mut selection_state = WindowSelectionState::default();
4036                let later = FakeParticipant::new("later", cx);
4037                let earliest = FakeParticipant::new("earliest", cx);
4038                let middle = FakeParticipant::new("middle", cx);
4039                later.register(
4040                    &mut selection_state,
4041                    0.,
4042                    TextSelectionScopeId::default(),
4043                    30,
4044                    cx,
4045                );
4046                earliest.register(
4047                    &mut selection_state,
4048                    0.,
4049                    TextSelectionScopeId::default(),
4050                    10,
4051                    cx,
4052                );
4053                middle.register(
4054                    &mut selection_state,
4055                    0.,
4056                    TextSelectionScopeId::default(),
4057                    20,
4058                    cx,
4059                );
4060
4061                selection_state.begin(point(px(1.), px(1.)), false, cx);
4062                selection_state.update(point(px(8.), px(1.)), cx);
4063
4064                assert_eq!(
4065                    selection_state.snapshot().unwrap().anchor().entity_id(),
4066                    Some(earliest.selection.entity_id())
4067                );
4068            }
4069        });
4070    }
4071
4072    #[gpui::test]
4073    fn text_selection_namespace_is_a_safe_no_op_until_the_element_is_rendered(
4074        cx: &mut TestAppContext,
4075    ) {
4076        let (_, cx) = cx.add_window_view(|_, cx| WindowSelectionView {
4077            selection: TextSelectionHandle::new("not enabled", cx),
4078        });
4079        cx.update(|window, cx| {
4080            assert!(!TextSelection::has_selection(window, cx));
4081            assert_eq!(TextSelection::selected_text(window, cx), "");
4082            TextSelection::clear(window, cx);
4083            TextSelection::end(window, cx);
4084            assert!(!TextSelection::has_selection(window, cx));
4085        });
4086    }
4087
4088    #[gpui::test]
4089    fn unit_selection_element_supports_scope_and_registration_on_the_first_frame(
4090        cx: &mut TestAppContext,
4091    ) {
4092        let (view, cx) = cx.add_window_view(|_, cx| FirstFrameScopedSelectionView {
4093            selection: TextSelectionHandle::new("first frame", cx),
4094        });
4095        let selection = cx.update(|_, cx| view.read(cx).selection.clone());
4096
4097        cx.update(|window, cx| {
4098            let _ = window.draw(cx);
4099            let state = WindowSelectionState::existing(window, cx).unwrap();
4100            assert_eq!(
4101                state.read(cx).active_scope,
4102                TextSelectionScopeId::from_raw(23)
4103            );
4104            assert!(
4105                state
4106                    .read(cx)
4107                    .participants
4108                    .contains_key(&selection.entity_id())
4109            );
4110        });
4111    }
4112
4113    #[gpui::test]
4114    fn lazy_registration_does_not_enable_queries_without_the_element(cx: &mut TestAppContext) {
4115        let (_, cx) = cx.add_window_view(|_, cx| WindowSelectionView {
4116            selection: TextSelectionHandle::new("registered", cx),
4117        });
4118        cx.update(|window, cx| {
4119            let selection = TextSelectionHandle::new("registered", cx);
4120            selection.set_local_selection(true, cx);
4121            let bounds = Bounds::new(point(px(0.), px(0.)), size(px(100.), px(20.)));
4122            let hitbox = Hitbox {
4123                fragments: None,
4124                tags: Vec::new(),
4125                id: HitboxId::placeholder(),
4126                bounds,
4127                content_mask: ContentMask {
4128                    fade_out: Default::default(),
4129                    bounds,
4130                },
4131                behavior: HitboxBehavior::Normal,
4132            };
4133            selection.register(
4134                TextSelectionRegistration::new(hitbox, bounds).with_text_bounds(vec![bounds]),
4135                window,
4136                cx,
4137            );
4138            assert_eq!(TextSelection::selected_text(window, cx), "");
4139            assert!(!TextSelection::has_selection(window, cx));
4140            TextSelection::clear(window, cx);
4141            assert_eq!(TextSelection::selected_text(window, cx), "");
4142        });
4143    }
4144
4145    #[gpui::test]
4146    fn retained_selection_state_releases_and_does_not_resurrect_selection(cx: &mut TestAppContext) {
4147        let (view, cx) = cx.add_window_view(|_, cx| ToggleSelectionElementView {
4148            enabled: true,
4149            selection: TextSelectionHandle::new("local", cx),
4150        });
4151        let selection = cx.update(|_, cx| view.read(cx).selection.clone());
4152        cx.update(|window, cx| {
4153            let _ = window.draw(cx);
4154            selection.set_local_selection(true, cx);
4155            assert!(TextSelection::has_selection(window, cx));
4156
4157            window.simulate_next_frame(cx);
4158            assert!(TextSelection::has_selection(window, cx));
4159            let _ = window.draw(cx);
4160            assert!(TextSelection::has_selection(window, cx));
4161        });
4162        view.update(cx, |view, cx| {
4163            view.enabled = false;
4164            cx.notify();
4165        });
4166        cx.update(|window, cx| {
4167            let _ = window.draw(cx);
4168        });
4169        cx.update(|window, cx| {
4170            window.simulate_next_frame(cx);
4171        });
4172        cx.update(|window, cx| {
4173            window.simulate_next_frame(cx);
4174        });
4175        cx.run_until_parked();
4176        cx.update(|window, cx| {
4177            assert!(!TextSelection::has_selection(window, cx));
4178            assert_eq!(TextSelection::selected_text(window, cx), "");
4179            assert!(!selection.has_local_selection(cx));
4180            TextSelection::clear(window, cx);
4181        });
4182
4183        view.update(cx, |view, cx| {
4184            view.enabled = true;
4185            cx.notify();
4186        });
4187        cx.update(|window, cx| {
4188            let _ = window.draw(cx);
4189            assert!(!TextSelection::has_selection(window, cx));
4190            assert_eq!(TextSelection::selected_text(window, cx), "");
4191        });
4192    }
4193
4194    #[gpui::test]
4195    fn mounted_selection_element_does_not_keep_an_idle_frame_queue_alive(cx: &mut TestAppContext) {
4196        let (_, cx) = cx.add_window_view(|_, _| SelectionElementOnlyView);
4197        cx.update(|window, cx| {
4198            let _ = window.draw(cx);
4199            assert_eq!(window.simulate_next_frame(cx), 0);
4200            assert_eq!(window.simulate_next_frame(cx), 0);
4201            assert!(live_text_selection_state(window, cx).is_some());
4202        });
4203    }
4204
4205    #[gpui::test]
4206    fn selection_element_initializes_suppression_and_respects_bubble_suppression(
4207        cx: &mut TestAppContext,
4208    ) {
4209        let (_, cx) = cx.add_window_view(|_, _| SelectionElementOnlyView);
4210        cx.update(|window, cx| {
4211            let _ = window.draw(cx);
4212        });
4213        cx.simulate_mouse_down(
4214            point(px(1.), px(1.)),
4215            MouseButton::Left,
4216            gpui::Modifiers::default(),
4217        );
4218        cx.simulate_mouse_up(
4219            point(px(1.), px(1.)),
4220            MouseButton::Left,
4221            gpui::Modifiers::default(),
4222        );
4223        cx.update(|window, cx| {
4224            assert!(GlobalState::is_text_selection_suppressed(cx));
4225            assert!(!TextSelection::has_selection(window, cx));
4226        });
4227    }
4228
4229    #[gpui::test]
4230    fn frame_sweep_keeps_a_participant_registered_before_the_selection_element_paints(
4231        cx: &mut TestAppContext,
4232    ) {
4233        cx.update(|cx| {
4234            let mut selection_state = WindowSelectionState::default();
4235            let participant = FakeParticipant::new("painted first", cx);
4236            participant.register(
4237                &mut selection_state,
4238                0.,
4239                TextSelectionScopeId::default(),
4240                0,
4241                cx,
4242            );
4243            selection_state.begin(point(px(1.), px(1.)), false, cx);
4244            selection_state.update(point(px(8.), px(1.)), cx);
4245            selection_state.end(cx);
4246
4247            selection_state.finish_frame(cx);
4248
4249            assert_eq!(selection_state.selected_text(cx), "painted first");
4250            assert!(participant.selection.snapshot(cx).is_some());
4251        });
4252    }
4253
4254    #[gpui::test]
4255    fn two_selection_elements_schedule_only_one_post_frame_sweep(cx: &mut TestAppContext) {
4256        let (view, cx) = cx.add_window_view(|_, cx| DoubleSelectionElementView {
4257            selection: TextSelectionHandle::new("once", cx),
4258        });
4259        cx.update(|window, cx| {
4260            let selection_state = WindowSelectionState::ensure(window, cx);
4261            let selection = view.read(cx).selection.clone();
4262            selection_state.update(cx, |selection_state, cx| {
4263                FakeParticipant { selection }.register(
4264                    selection_state,
4265                    0.,
4266                    TextSelectionScopeId::default(),
4267                    0,
4268                    cx,
4269                );
4270                selection_state.begin(point(px(1.), px(1.)), false, cx);
4271                selection_state.update(point(px(8.), px(1.)), cx);
4272                selection_state.end(cx);
4273            });
4274
4275            let _ = window.draw(cx);
4276            window.simulate_next_frame(cx);
4277
4278            let items = selection_state.read(cx).copy_items(cx);
4279            assert_eq!(resolve_copy_items(items, cx), "once");
4280        });
4281    }
4282
4283    #[gpui::test]
4284    fn duplicate_selection_elements_gate_real_pointer_gestures_and_reentrant_clear(
4285        cx: &mut TestAppContext,
4286    ) {
4287        let (view, cx) = cx.add_window_view(|_, cx| DoubleSelectionElementView {
4288            selection: TextSelectionHandle::new("once", cx),
4289        });
4290        let clear_count = Rc::new(Cell::new(0));
4291        cx.update(|window, cx| {
4292            let state = WindowSelectionState::ensure(window, cx);
4293            let state_for_clear = state.clone();
4294            let count = clear_count.clone();
4295            let selection = view.read(cx).selection.clone();
4296            selection
4297                .subscribe(
4298                    move |event, cx| {
4299                        if matches!(event, TextSelectionEvent::Cleared) {
4300                            count.set(count.get() + 1);
4301                            let _ = state_for_clear.read(cx).snapshot();
4302                        }
4303                    },
4304                    cx,
4305                )
4306                .detach();
4307            let _ = window.draw(cx);
4308        });
4309
4310        cx.simulate_mouse_down(
4311            point(px(10.), px(10.)),
4312            MouseButton::Left,
4313            gpui::Modifiers::default(),
4314        );
4315        cx.simulate_mouse_up(
4316            point(px(10.), px(10.)),
4317            MouseButton::Left,
4318            gpui::Modifiers::default(),
4319        );
4320        cx.simulate_mouse_down(
4321            point(px(70.), px(10.)),
4322            MouseButton::Left,
4323            gpui::Modifiers {
4324                shift: true,
4325                ..Default::default()
4326            },
4327        );
4328        cx.simulate_mouse_up(
4329            point(px(70.), px(10.)),
4330            MouseButton::Left,
4331            gpui::Modifiers::default(),
4332        );
4333        cx.update(|window, cx| assert!(TextSelection::has_selection(window, cx)));
4334
4335        cx.simulate_mouse_down(
4336            point(px(15.), px(10.)),
4337            MouseButton::Left,
4338            gpui::Modifiers::default(),
4339        );
4340        cx.simulate_mouse_move(
4341            point(px(85.), px(10.)),
4342            Some(MouseButton::Left),
4343            gpui::Modifiers::default(),
4344        );
4345        cx.simulate_mouse_up(
4346            point(px(85.), px(10.)),
4347            MouseButton::Left,
4348            gpui::Modifiers::default(),
4349        );
4350        cx.update(|window, cx| assert!(TextSelection::has_selection(window, cx)));
4351        assert_eq!(clear_count.get(), 3);
4352    }
4353
4354    #[gpui::test]
4355    fn selection_layer_handles_real_double_and_triple_click_events(cx: &mut TestAppContext) {
4356        let (text, layout) = laid_out_runs(&["alpha beta"], cx).pop().unwrap();
4357        let (view, cx) = cx.add_window_view(|_, cx| DoubleSelectionElementView {
4358            selection: TextSelectionHandle::new("", cx),
4359        });
4360        cx.update(|window, cx| {
4361            let _ = window.draw(cx);
4362            let selection = view.read(cx).selection.clone();
4363            selection.resolve_content_key_with(|_, _| Some(TextSelectionContentKey::new(17)), cx);
4364            selection.update_runs(&[text_run(0, text.clone(), layout.clone())], cx);
4365        });
4366
4367        let position = layout.position_for_index(7).unwrap();
4368        cx.simulate_event(MouseDownEvent {
4369            position,
4370            modifiers: gpui::Modifiers::default(),
4371            button: MouseButton::Left,
4372            click_count: 2,
4373            first_mouse: false,
4374        });
4375        cx.simulate_event(MouseUpEvent {
4376            position,
4377            modifiers: gpui::Modifiers::default(),
4378            button: MouseButton::Left,
4379            click_count: 2,
4380        });
4381        cx.update(|window, cx| {
4382            let selection = view.read(cx).selection.clone();
4383            selection.update_runs(&[text_run(0, text.clone(), layout.clone())], cx);
4384            assert_eq!(TextSelection::selected_text(window, cx), "beta");
4385            let snapshot = selection.snapshot(cx).unwrap();
4386            assert_eq!(
4387                snapshot.anchor().content_key(),
4388                Some(TextSelectionContentKey::new(17))
4389            );
4390            assert_eq!(
4391                snapshot.cursor().content_key(),
4392                Some(TextSelectionContentKey::new(17))
4393            );
4394        });
4395
4396        cx.simulate_event(MouseDownEvent {
4397            position,
4398            modifiers: gpui::Modifiers::default(),
4399            button: MouseButton::Left,
4400            click_count: 3,
4401            first_mouse: false,
4402        });
4403        cx.simulate_event(MouseUpEvent {
4404            position,
4405            modifiers: gpui::Modifiers::default(),
4406            button: MouseButton::Left,
4407            click_count: 3,
4408        });
4409        cx.update(|window, cx| {
4410            let selection = view.read(cx).selection.clone();
4411            selection.update_runs(&[text_run(0, text, layout)], cx);
4412            assert_eq!(TextSelection::selected_text(window, cx), "alpha beta");
4413        });
4414    }
4415}