Skip to main content

gpui_base/
text_selection.rs

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