Skip to main content

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