| use std::{ | |
| cell::{Cell, RefCell}, | |
| collections::HashMap, | |
| ops::Range, | |
| rc::Rc, | |
| sync::{ | |
| Arc, Weak, | |
| atomic::{AtomicU64, Ordering}, | |
| }, | |
| }; | |
| use gpui::{ | |
| App, AppContext as _, Bounds, Context, Element, ElementId, Entity, EntityId, EventEmitter, | |
| FocusHandle, FocusId, Global, GlobalElementId, Half, Hitbox, HitboxBehavior, HitboxId, Hsla, | |
| InputEvent as _, InspectorElementId, IntoElement, LayoutId, LongPressEvent, MouseButton, | |
| MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, ScrollDelta, ScrollWheelEvent, | |
| SharedString, Style, Subscription, TextLayout, TouchDragEvent, TouchPhase, WeakEntity, Window, | |
| point, px, | |
| }; | |
| use crate::text_boundary::{line_range_at, word_range_at}; | |
| use crate::touch_selection::{ | |
| EdgeDrag, SelectionEdge, TouchHandle, TouchSelectionSnapshot, caret_in_view, | |
| }; | |
| use crate::{AutoScroll, GlobalState}; | |
| /// An opaque selection layer identifier. | |
| #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] | |
| pub struct TextSelectionScopeId(u64); | |
| impl TextSelectionScopeId { | |
| /// Allocates a process-unique scope identifier. | |
| /// | |
| /// Keep the returned identifier for the semantic lifetime of the scope; | |
| /// do not allocate a new identifier on every frame. | |
| pub fn new() -> Self { | |
| static NEXT_SCOPE_ID: AtomicU64 = AtomicU64::new(1); | |
| let value = NEXT_SCOPE_ID | |
| .try_update(Ordering::Relaxed, Ordering::Relaxed, |value| { | |
| value.checked_add(1) | |
| }) | |
| .expect("text selection scope identifiers exhausted"); | |
| Self(value) | |
| } | |
| #[cfg(test)] | |
| const fn from_raw(value: u64) -> Self { | |
| Self(value) | |
| } | |
| } | |
| /// Stable participant-defined identity for virtualized participant content. | |
| #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | |
| pub struct TextSelectionContentKey(u64); | |
| impl TextSelectionContentKey { | |
| /// Creates a key from a participant-defined stable content identity. | |
| pub const fn new(value: u64) -> Self { | |
| Self(value) | |
| } | |
| /// Returns the participant-defined value. | |
| pub const fn value(self) -> u64 { | |
| self.0 | |
| } | |
| } | |
| /// A selection endpoint anchored to a participant's content coordinates. | |
| #[derive(Clone, Copy, Debug, PartialEq)] | |
| pub struct TextSelectionEndpoint { | |
| entity_id: Option<EntityId>, | |
| point: Point<Pixels>, | |
| content_key: Option<TextSelectionContentKey>, | |
| } | |
| impl TextSelectionEndpoint { | |
| /// Creates an endpoint at a participant-relative content point. | |
| pub(crate) const fn new(entity_id: Option<EntityId>, point: Point<Pixels>) -> Self { | |
| Self { | |
| entity_id, | |
| point, | |
| content_key: None, | |
| } | |
| } | |
| /// Sets participant-defined endpoint metadata. | |
| pub(crate) const fn with_content_key(mut self, content_key: TextSelectionContentKey) -> Self { | |
| self.content_key = Some(content_key); | |
| self | |
| } | |
| /// Returns the participant which owns this endpoint, when it hit one. | |
| pub const fn entity_id(&self) -> Option<EntityId> { | |
| self.entity_id | |
| } | |
| /// Returns the participant-relative content point. | |
| pub const fn content_point(&self) -> Point<Pixels> { | |
| self.point | |
| } | |
| /// Returns participant-defined endpoint metadata captured when it hit a participant. | |
| pub const fn content_key(&self) -> Option<TextSelectionContentKey> { | |
| self.content_key | |
| } | |
| } | |
| /// Window-coordinate anchor and cursor points for painting a selection. | |
| #[derive(Clone, Copy, Debug, PartialEq)] | |
| pub struct TextSelectionWindowPoints { | |
| anchor: Point<Pixels>, | |
| cursor: Point<Pixels>, | |
| } | |
| impl TextSelectionWindowPoints { | |
| /// Returns the stable anchor in window coordinates. | |
| pub const fn anchor(&self) -> Point<Pixels> { | |
| self.anchor | |
| } | |
| /// Returns the moving cursor in window coordinates. | |
| pub const fn cursor(&self) -> Point<Pixels> { | |
| self.cursor | |
| } | |
| } | |
| /// Participant-relative selection endpoints with an optional rendering projection. | |
| #[derive(Clone, Copy, Debug, PartialEq)] | |
| pub struct TextSelectionSnapshot { | |
| anchor: TextSelectionEndpoint, | |
| cursor: TextSelectionEndpoint, | |
| is_selecting: bool, | |
| window_points: Option<TextSelectionWindowPoints>, | |
| coverage: TextSelectionCoverage, | |
| } | |
| /// How much of one participant participates in a window selection. | |
| #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] | |
| pub enum TextSelectionCoverage { | |
| /// Only the interval between this participant's two endpoints is selected. | |
| #[default] | |
| Bounded, | |
| /// The participant is selected from its beginning through its endpoint. | |
| FromStart, | |
| /// The participant is selected from its endpoint through its end. | |
| ToEnd, | |
| /// The entire participant lies between endpoints in other participants. | |
| Full, | |
| } | |
| impl TextSelectionSnapshot { | |
| /// Creates a snapshot from stable participant-relative endpoints. | |
| pub(crate) const fn new(anchor: TextSelectionEndpoint, cursor: TextSelectionEndpoint) -> Self { | |
| Self { | |
| anchor, | |
| cursor, | |
| is_selecting: false, | |
| window_points: None, | |
| coverage: TextSelectionCoverage::Bounded, | |
| } | |
| } | |
| /// Sets whether the pointer gesture is still active. | |
| pub(crate) const fn with_selecting(mut self, is_selecting: bool) -> Self { | |
| self.is_selecting = is_selecting; | |
| self | |
| } | |
| /// Sets the current window-coordinate rendering projection. | |
| pub(crate) const fn with_window_points( | |
| mut self, | |
| window_points: Option<TextSelectionWindowPoints>, | |
| ) -> Self { | |
| self.window_points = window_points; | |
| self | |
| } | |
| /// Sets the portion of the receiving participant covered by this selection. | |
| #[cfg(test)] | |
| pub(crate) const fn with_coverage(mut self, coverage: TextSelectionCoverage) -> Self { | |
| self.coverage = coverage; | |
| self | |
| } | |
| /// Returns the stable anchor endpoint. | |
| pub const fn anchor(&self) -> TextSelectionEndpoint { | |
| self.anchor | |
| } | |
| /// Returns the moving cursor endpoint. | |
| pub const fn cursor(&self) -> TextSelectionEndpoint { | |
| self.cursor | |
| } | |
| /// Returns whether the pointer gesture is still active. | |
| pub const fn is_selecting(&self) -> bool { | |
| self.is_selecting | |
| } | |
| /// Returns the window-coordinate endpoints for participants that need them. | |
| pub const fn window_points(&self) -> Option<TextSelectionWindowPoints> { | |
| self.window_points | |
| } | |
| /// Returns the portion of the receiving participant covered by this selection. | |
| pub const fn coverage(&self) -> TextSelectionCoverage { | |
| self.coverage | |
| } | |
| } | |
| /// Retained element state proving a participant is still in the window. | |
| /// | |
| /// A participant reports its geometry from `paint`, which a cached view | |
| /// (`Entity::cached`) skips: GPUI replays the recorded frame instead. The | |
| /// element's retained state is replayed with it, so this marker outlives the | |
| /// frames whose paint never ran, and dies with the frame that drops the | |
| /// element for good. | |
| struct RenderedMarker; | |
| /// Per-frame geometry reported by a [`TextSelectionHandle`] participant. | |
| #[derive(Clone)] | |
| pub struct TextSelectionRegistration { | |
| hitbox: Hitbox, | |
| bounds: Bounds<Pixels>, | |
| scroll_offset: Point<Pixels>, | |
| scope: TextSelectionScopeId, | |
| document_order: u64, | |
| native_focus: Option<FocusHandle>, | |
| text_bounds: Vec<Bounds<Pixels>>, | |
| self_scroll: bool, | |
| selection_edges: Option<(Bounds<Pixels>, Bounds<Pixels>)>, | |
| rendered: Option<WeakEntity<RenderedMarker>>, | |
| } | |
| impl TextSelectionRegistration { | |
| /// Creates a registration with default scope, order, and scroll offset. | |
| pub fn new(hitbox: Hitbox, bounds: Bounds<Pixels>) -> Self { | |
| Self { | |
| hitbox, | |
| bounds, | |
| scroll_offset: Point::default(), | |
| scope: TextSelectionScopeId::default(), | |
| document_order: 0, | |
| native_focus: None, | |
| text_bounds: Vec::new(), | |
| self_scroll: false, | |
| selection_edges: None, | |
| rendered: None, | |
| } | |
| } | |
| /// Resolve order from the completed native tree, including replayed peers. | |
| pub(crate) fn with_native_focus(mut self, focus: FocusHandle, window: &Window) -> Self { | |
| self.document_order = window.focus_document_order(&focus).unwrap_or(0); | |
| self.native_focus = Some(focus); | |
| self | |
| } | |
| /// Ties this registration to the retained state of the element reporting | |
| /// it, so that a frame replayed from that element's cached view keeps it. | |
| /// | |
| /// Call this from the reporting element's `prepaint` or `paint`. A | |
| /// registration made outside a drawing element cannot be tied to one and | |
| /// is swept the first frame it misses, as every registration used to be. | |
| pub fn with_rendered_element( | |
| mut self, | |
| participant: &TextSelectionHandle, | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) -> Self { | |
| self.rendered = Some( | |
| window | |
| .use_keyed_state( | |
| ElementId::NamedInteger( | |
| "text-selection-participant".into(), | |
| participant.entity_id().as_u64(), | |
| ), | |
| cx, | |
| |_, _| RenderedMarker, | |
| ) | |
| .downgrade(), | |
| ); | |
| self | |
| } | |
| /// Whether the element that reported this registration is still part of | |
| /// the window, even if it did not paint the frame that just finished. | |
| fn is_rendered(&self) -> bool { | |
| self.rendered | |
| .as_ref() | |
| .is_some_and(|marker| marker.upgrade().is_some()) | |
| } | |
| /// Marks a participant that scrolls its own content in response to | |
| /// [`TextSelectionEvent::AutoScroll`]. Drag auto-scroll then drives it | |
| /// directly, measured against its own bounds, instead of synthesizing a | |
| /// wheel event for the nearest scrollable ancestor. | |
| pub(crate) fn with_self_scroll(mut self, self_scroll: bool) -> Self { | |
| self.self_scroll = self_scroll; | |
| self | |
| } | |
| /// Sets the participant's content scroll offset. | |
| pub fn with_scroll_offset(mut self, scroll_offset: Point<Pixels>) -> Self { | |
| self.scroll_offset = scroll_offset; | |
| self | |
| } | |
| /// Sets the opaque selection scope. | |
| pub fn with_scope(mut self, scope: TextSelectionScopeId) -> Self { | |
| self.scope = scope; | |
| self | |
| } | |
| /// Sets the stable logical document order. | |
| pub fn with_document_order(mut self, document_order: u64) -> Self { | |
| self.document_order = document_order; | |
| self | |
| } | |
| /// Sets the glyph-bearing bounds used to reject blank-only gestures. | |
| pub fn with_text_bounds(mut self, text_bounds: Vec<Bounds<Pixels>>) -> Self { | |
| self.text_bounds = text_bounds; | |
| self | |
| } | |
| /// Sets where the participant painted the two ends of its selection: the | |
| /// caret line box before its first selected character and the one after | |
| /// its last, in window coordinates. The touch handles are drawn there. | |
| pub fn with_selection_edges(mut self, start: Bounds<Pixels>, end: Bounds<Pixels>) -> Self { | |
| self.selection_edges = Some((start, end)); | |
| self | |
| } | |
| /// Returns the participant hitbox. | |
| pub fn hitbox(&self) -> &Hitbox { | |
| &self.hitbox | |
| } | |
| /// Returns the participant's window-coordinate bounds. | |
| pub const fn bounds(&self) -> Bounds<Pixels> { | |
| self.bounds | |
| } | |
| /// Returns the participant's content scroll offset. | |
| pub const fn scroll_offset(&self) -> Point<Pixels> { | |
| self.scroll_offset | |
| } | |
| /// Returns the opaque selection scope. | |
| pub const fn scope(&self) -> TextSelectionScopeId { | |
| self.scope | |
| } | |
| /// Returns the stable logical document order. | |
| pub const fn document_order(&self) -> u64 { | |
| self.document_order | |
| } | |
| /// Returns the glyph-bearing bounds used to reject blank-only gestures. | |
| pub fn text_bounds(&self) -> &[Bounds<Pixels>] { | |
| &self.text_bounds | |
| } | |
| /// Returns the caret line boxes at the participant's selection ends. | |
| pub const fn selection_edges(&self) -> Option<(Bounds<Pixels>, Bounds<Pixels>)> { | |
| self.selection_edges | |
| } | |
| } | |
| /// Laid-out text reported by a plain selection participant during paint. | |
| #[derive(Clone)] | |
| pub struct TextSelectionRun { | |
| /// Logical order within the containing participant. | |
| document_order: u64, | |
| /// The exact text used to produce `layout`. | |
| text: SharedString, | |
| /// Laid-out glyph geometry in window coordinates. | |
| layout: TextLayout, | |
| /// The run's window-coordinate paint bounds. | |
| bounds: Bounds<Pixels>, | |
| // Read-only retained-frame translation; the shared TextLayout is unchanged. | |
| translation: Point<Pixels>, | |
| } | |
| impl TextSelectionRun { | |
| /// Creates a laid-out text run. | |
| pub fn new(text: impl Into<SharedString>, layout: TextLayout, bounds: Bounds<Pixels>) -> Self { | |
| Self { | |
| document_order: 0, | |
| text: text.into(), | |
| layout, | |
| bounds, | |
| translation: Point::default(), | |
| } | |
| } | |
| pub(crate) fn reprojected(&self, translation: Point<Pixels>, mask: Bounds<Pixels>) -> Self { | |
| let mut projected = self.clone(); | |
| projected.translation = translation; | |
| projected.bounds = | |
| Bounds::new(self.bounds.origin + translation, self.bounds.size).intersect(&mask); | |
| projected | |
| } | |
| fn position_for_index(&self, index: usize) -> Option<Point<Pixels>> { | |
| self.layout | |
| .position_for_index(index) | |
| .map(|point| point + self.translation) | |
| } | |
| /// Sets the run's logical order within the participant. | |
| pub const fn with_document_order(mut self, document_order: u64) -> Self { | |
| self.document_order = document_order; | |
| self | |
| } | |
| /// Returns the run's logical order within its participant. | |
| pub const fn document_order(&self) -> u64 { | |
| self.document_order | |
| } | |
| /// Returns the exact text used to produce the layout. | |
| pub fn text(&self) -> &SharedString { | |
| &self.text | |
| } | |
| /// Returns the original shared glyph layout. Retained-frame translation | |
| /// is applied by the run's selection queries, without mutating this layout. | |
| pub fn layout(&self) -> &TextLayout { | |
| &self.layout | |
| } | |
| /// Returns the run's window-coordinate paint bounds. | |
| pub const fn bounds(&self) -> Bounds<Pixels> { | |
| self.bounds | |
| } | |
| } | |
| /// Selection projected onto a participant's laid-out text runs. | |
| #[derive(Clone, Debug, Default, PartialEq, Eq)] | |
| pub struct TextSelectionProjection { | |
| /// Selected UTF-8 byte ranges paired with the input runs. | |
| ranges: Vec<Option<Range<usize>>>, | |
| /// Whether the participant participates in the current selection. | |
| is_active: bool, | |
| } | |
| impl TextSelectionProjection { | |
| /// Returns selected UTF-8 byte ranges paired with the input runs. | |
| pub fn ranges(&self) -> &[Option<Range<usize>>] { | |
| &self.ranges | |
| } | |
| /// Returns whether the participant participates in the selection. | |
| pub const fn is_active(&self) -> bool { | |
| self.is_active | |
| } | |
| } | |
| /// Projects a participant selection snapshot onto laid-out plain-text runs. | |
| /// | |
| /// The returned states retain the input order so callers can pair every state | |
| /// with its run. The ranges are always character boundaries; `order` is used | |
| /// only when a participant caches selected text for copying. | |
| fn project_ranges( | |
| snapshot: Option<TextSelectionSnapshot>, | |
| runs: &[TextSelectionRun], | |
| ) -> TextSelectionProjection { | |
| let Some(snapshot) = snapshot else { | |
| return TextSelectionProjection { | |
| ranges: vec![None; runs.len()], | |
| is_active: false, | |
| }; | |
| }; | |
| let Some(window_points) = snapshot.window_points() else { | |
| return TextSelectionProjection { | |
| ranges: vec![None; runs.len()], | |
| is_active: true, | |
| }; | |
| }; | |
| TextSelectionProjection { | |
| ranges: runs | |
| .iter() | |
| .map(|run| selection_range_for_run(run, window_points.anchor, window_points.cursor)) | |
| .collect(), | |
| is_active: true, | |
| } | |
| } | |
| // A single literal run can retain original content-key byte endpoints through reflow. | |
| fn project_byte_ranges( | |
| owner: EntityId, | |
| snapshot: Option<TextSelectionSnapshot>, | |
| runs: &[TextSelectionRun], | |
| ) -> TextSelectionProjection { | |
| let Some(snapshot) = snapshot else { | |
| return project_ranges(None, runs); | |
| }; | |
| let [run] = runs else { | |
| return project_ranges(Some(snapshot), runs); | |
| }; | |
| let byte = |endpoint: TextSelectionEndpoint| { | |
| (endpoint.entity_id() == Some(owner)) | |
| .then(|| endpoint.content_key()) | |
| .flatten() | |
| .and_then(|key| usize::try_from(key.value()).ok()) | |
| .filter(|byte| *byte <= run.text.len() && run.text.is_char_boundary(*byte)) | |
| }; | |
| let own = || byte(snapshot.anchor()).or_else(|| byte(snapshot.cursor())); | |
| let range = match snapshot.coverage() { | |
| TextSelectionCoverage::Full => Some(0..run.text.len()), | |
| TextSelectionCoverage::FromStart => own().map(|end| 0..end), | |
| TextSelectionCoverage::ToEnd => own().map(|start| start..run.text.len()), | |
| TextSelectionCoverage::Bounded => byte(snapshot.anchor()) | |
| .zip(byte(snapshot.cursor())) | |
| .map(|(a, b)| a.min(b)..a.max(b)), | |
| }; | |
| if let Some(range) = range { | |
| TextSelectionProjection { | |
| ranges: vec![(!range.is_empty()).then_some(range)], | |
| is_active: true, | |
| } | |
| } else { | |
| project_ranges(Some(snapshot), runs) | |
| } | |
| } | |
| fn selection_range_for_run( | |
| run: &TextSelectionRun, | |
| selection_start: Point<Pixels>, | |
| selection_end: Point<Pixels>, | |
| ) -> Option<Range<usize>> { | |
| if run.text.len() != run.layout.len() { | |
| return None; | |
| } | |
| if run.text.is_empty() { | |
| return None; | |
| } | |
| let line_height = run.layout.line_height(); | |
| // Each character is tested with its row's top and height, so a run whose | |
| // rows all miss the band, or all lie strictly inside it with no endpoint | |
| // on any row, has the same answer for every character. Decide those | |
| // without the walk below, which scans the layout twice per character. | |
| let (rows_top, rows_bottom) = text_rows_extent(&run.layout, line_height); | |
| let (rows_top, rows_bottom) = ( | |
| rows_top + run.translation.y, | |
| rows_bottom + run.translation.y, | |
| ); | |
| let band_top = selection_start.y.min(selection_end.y); | |
| let band_bottom = selection_start.y.max(selection_end.y); | |
| if rows_bottom <= band_top || rows_top > band_bottom { | |
| return None; | |
| } | |
| if band_top < rows_top && band_bottom >= rows_bottom { | |
| return Some(0..run.text.len()); | |
| } | |
| let mut range = None; | |
| for (offset, character) in run.text.char_indices() { | |
| let next_offset = offset + character.len_utf8(); | |
| let Some(position) = run.position_for_index(offset) else { | |
| continue; | |
| }; | |
| let char_width = run | |
| .position_for_index(next_offset) | |
| .filter(|next| next.y == position.y) | |
| .map_or_else(|| line_height.half(), |next| next.x - position.x); | |
| if point_in_selection_band( | |
| position, | |
| char_width, | |
| selection_start, | |
| selection_end, | |
| line_height, | |
| ) { | |
| range.get_or_insert(offset..offset).end = next_offset; | |
| } | |
| } | |
| range | |
| } | |
| /// The top of the first laid-out row of `text_layout` and the bottom of its | |
| /// last one, each row `line_height` tall as a selection band test sees it. | |
| /// | |
| /// Both ends are accumulated the way [`TextLayout::position_for_index`] places | |
| /// rows, so comparisons against them agree with a per-character walk to the | |
| /// bit. The last laid-out row may hold no character such a walk tests (a | |
| /// trailing empty line, or a row whose only character is placed at the end of | |
| /// the row before it); callers treat the extent as covering, never as exact. | |
| pub(crate) fn text_rows_extent(text_layout: &TextLayout, line_height: Pixels) -> (Pixels, Pixels) { | |
| let top = text_layout.bounds().top(); | |
| let layout_line_height = text_layout.line_height(); | |
| let lines = text_layout.line_layouts(); | |
| let mut last_line_top = top; | |
| for line in lines.iter().take(lines.len().saturating_sub(1)) { | |
| last_line_top += line.size(layout_line_height).height; | |
| } | |
| let last_row_top = lines.last().map_or(top, |line| { | |
| last_line_top + line.wrap_boundaries.len() as f32 * layout_line_height | |
| }); | |
| (top, last_row_top + line_height) | |
| } | |
| fn points_for_multi_click( | |
| runs: &[TextSelectionRun], | |
| position: Point<Pixels>, | |
| click_count: usize, | |
| ) -> Option<(Point<Pixels>, Point<Pixels>)> { | |
| let run = runs.iter().find(|run| run.bounds.contains(&position))?; | |
| if run.text.len() != run.layout.len() { | |
| return None; | |
| } | |
| let offset = run | |
| .layout | |
| .index_for_position(position - run.translation) | |
| .ok()?; | |
| let range = match click_count { | |
| 2 => word_range_at(&run.text, offset)?, | |
| 3.. => line_range_at(&run.text, offset), | |
| _ => return None, | |
| }; | |
| if range.is_empty() { | |
| return None; | |
| } | |
| Some(( | |
| run.position_for_index(range.start)?, | |
| run.position_for_index(range.end)?, | |
| )) | |
| } | |
| fn point_in_selection_band( | |
| position: Point<Pixels>, | |
| char_width: Pixels, | |
| selection_start: Point<Pixels>, | |
| selection_end: Point<Pixels>, | |
| line_height: Pixels, | |
| ) -> bool { | |
| let point_in_line = | |
| |point: Point<Pixels>| point.y >= position.y && point.y < position.y + line_height; | |
| let top = selection_start.y.min(selection_end.y); | |
| let bottom = selection_start.y.max(selection_end.y); | |
| let x = position.x + char_width.half(); | |
| if position.y + line_height <= top || position.y > bottom { | |
| return false; | |
| } | |
| if point_in_line(selection_start) && point_in_line(selection_end) { | |
| let left = selection_start.x.min(selection_end.x); | |
| let right = selection_start.x.max(selection_end.x); | |
| return x >= left && x <= right; | |
| } | |
| let (top_point, bottom_point) = if selection_start.y < selection_end.y { | |
| (selection_start, selection_end) | |
| } else { | |
| (selection_end, selection_start) | |
| }; | |
| if point_in_line(top_point) { | |
| x >= top_point.x | |
| } else if point_in_line(bottom_point) { | |
| x <= bottom_point.x | |
| } else { | |
| true | |
| } | |
| } | |
| type FocusCallback = Rc<dyn Fn(&mut Window, &mut App)>; | |
| type ClearHandler = Rc<dyn Fn(&mut App)>; | |
| type CopyCallback = Rc<dyn Fn(&mut App) -> String>; | |
| type ContentKeyResolver = Rc<dyn Fn(Point<Pixels>, &App) -> Option<TextSelectionContentKey>>; | |
| /// Notifications emitted by a text-selection participant. | |
| #[derive(Clone, Debug, PartialEq)] | |
| pub enum TextSelectionEvent { | |
| /// The participant's window-selection projection changed. | |
| SelectionChanged(Option<TextSelectionSnapshot>), | |
| /// The active drag requests vertical auto-scroll, or `None` to stop. | |
| AutoScroll(Option<Pixels>, gpui::WeakInputGesture), | |
| /// Window selection cleared the participant's participant-local state. | |
| Cleared, | |
| /// The touch selection the participant takes part in changed: it | |
| /// appeared, its ends moved, a handle drag began or ended, or it went | |
| /// away. The participant paints the handles and lays their hitboxes out | |
| /// from the ends it painted last frame, so it renders once more. | |
| TouchSelectionChanged, | |
| } | |
| struct CopyItem { | |
| document_order: u64, | |
| callback: Option<CopyCallback>, | |
| fallback: String, | |
| } | |
| fn resolve_copy_items(mut items: Vec<CopyItem>, cx: &mut App) -> String { | |
| items.sort_by_key(|item| item.document_order); | |
| items | |
| .into_iter() | |
| .map(|item| { | |
| item.callback | |
| .map(|callback| callback(cx)) | |
| .unwrap_or(item.fallback) | |
| }) | |
| .filter(|text| !text.is_empty()) | |
| .collect::<Vec<_>>() | |
| .join("\n") | |
| } | |
| fn dispatch_clear_handlers(handlers: Vec<ClearHandler>, cx: &mut App) { | |
| for handler in handlers { | |
| handler(cx); | |
| } | |
| } | |
| type SelectionGroupKey = (gpui::WindowId, Option<FocusId>); | |
| fn placement_group(window: &Window) -> SelectionGroupKey { | |
| ( | |
| window.window_handle().window_id(), | |
| window.selection_group_context(), | |
| ) | |
| } | |
| fn physical_group(window: &Window) -> SelectionGroupKey { | |
| ( | |
| window.window_handle().window_id(), | |
| window.active_input_group(), | |
| ) | |
| } | |
| /// Weak observation of an original element-owned selection group. | |
| /// It does not retain selection, Window, or physical input permission. | |
| #[derive(Clone)] | |
| pub struct TextSelectionGroup { | |
| key: SelectionGroupKey, | |
| owner: WeakEntity<WindowSelectionState>, | |
| } | |
| impl TextSelectionGroup { | |
| pub fn same_owner(&self, other: &Self) -> bool { | |
| self.key == other.key && self.owner.entity_id() == other.owner.entity_id() | |
| } | |
| /// Missing ownership is unavailable evidence, rather than an empty selection. | |
| pub fn has_selection_in_scope(&self, scope: TextSelectionScopeId, cx: &App) -> Option<bool> { | |
| Some( | |
| self.owner | |
| .upgrade()? | |
| .read(cx) | |
| .has_selection_in_scope(scope, cx), | |
| ) | |
| } | |
| /// Whether this exact original owner is the physical group in this window. | |
| pub fn is_current(&self, window: &Window, cx: &App) -> bool { | |
| self.key.0 == window.window_handle().window_id() | |
| && window.input_group_is_admitted(self.key.1) | |
| && WindowSelectionState::existing(window, cx) | |
| .is_some_and(|owner| owner.entity_id() == self.owner.entity_id()) | |
| } | |
| /// Observe original touch presentation without retaining its selection owner. | |
| pub fn observe_touch_selection( | |
| &self, | |
| cx: &mut App, | |
| callback: impl Fn(&mut App) + 'static, | |
| ) -> Option<Subscription> { | |
| let owner = self.owner.upgrade()?; | |
| Some(cx.observe(&owner, move |_, cx| callback(cx))) | |
| } | |
| pub fn touch_selection(&self, cx: &App) -> Option<TouchSelectionSnapshot> { | |
| self.owner.upgrade()?.read(cx).touch_selection() | |
| } | |
| /// Read the exact original group's selected bytes. This grants no input. | |
| pub fn selected_text(&self, window: &Window, cx: &mut App) -> Option<String> { | |
| let owner = self.in_window(window)?; | |
| let items = owner.query(cx, |state, cx| state.copy_items(cx)); | |
| Some(resolve_copy_items(items, cx)) | |
| } | |
| /// Close only this original native menu, without resolving another group. | |
| pub fn close_edit_menu(&self, window: &Window, cx: &mut App) { | |
| if let Some(owner) = self.in_window(window) { | |
| owner.update(cx, |state, cx| state.close_edit_menu(cx)); | |
| } | |
| } | |
| fn in_window(&self, window: &Window) -> Option<Entity<WindowSelectionState>> { | |
| (self.key.0 == window.window_handle().window_id()) | |
| .then(|| self.owner.upgrade()) | |
| .flatten() | |
| } | |
| } | |
| struct SelectableTextState { | |
| group: Option<TextSelectionGroup>, | |
| enabled: bool, | |
| admission: Arc<()>, | |
| fallback_copy_text: String, | |
| /// The selected text as the participant last painted it. Painting | |
| /// projects it, which is not a change of the participant. | |
| projected_copy_text: RefCell<Option<String>>, | |
| /// The participant's text as it last painted it, for hit testing. | |
| runs: RefCell<Vec<TextSelectionRun>>, | |
| local_selection: bool, | |
| snapshot: Option<TextSelectionSnapshot>, | |
| on_focus: Option<FocusCallback>, | |
| clear: Option<ClearHandler>, | |
| copy: Option<CopyCallback>, | |
| content_key_resolver: Option<ContentKeyResolver>, | |
| byte_owner: Option<EntityId>, | |
| } | |
| impl EventEmitter<TextSelectionEvent> for SelectableTextState {} | |
| impl SelectableTextState { | |
| fn new(fallback_copy_text: impl Into<String>) -> Self { | |
| Self { | |
| group: None, | |
| enabled: true, | |
| admission: Arc::new(()), | |
| fallback_copy_text: fallback_copy_text.into(), | |
| projected_copy_text: RefCell::new(None), | |
| runs: RefCell::new(Vec::new()), | |
| local_selection: false, | |
| snapshot: None, | |
| on_focus: None, | |
| clear: None, | |
| copy: None, | |
| content_key_resolver: None, | |
| byte_owner: None, | |
| } | |
| } | |
| /// The current geometry selection snapshot for this participant. | |
| fn snapshot(&self) -> Option<TextSelectionSnapshot> { | |
| self.snapshot | |
| } | |
| /// Sets the text copied by this participant when it participates in selection. | |
| fn set_fallback_copy_text(&mut self, text: impl Into<String>) { | |
| self.fallback_copy_text = text.into(); | |
| *self.projected_copy_text.get_mut() = None; | |
| } | |
| /// Marks participant-local selection (for example select-all) as active. | |
| fn set_local_selection(&mut self, active: bool) { | |
| if self.local_selection != active { | |
| *self.projected_copy_text.get_mut() = None; | |
| } | |
| self.local_selection = active; | |
| } | |
| /// Projects this participant's current snapshot onto plain-text runs and caches | |
| /// their selected substrings for the window selection query. | |
| /// | |
| /// Call this once per painted run. A snapshot change or | |
| /// Clearing window selection invalidates the cache immediately, so copy | |
| /// never returns text from a previous projection while waiting to repaint. | |
| fn update_runs(&self, runs: &[TextSelectionRun]) -> TextSelectionProjection { | |
| *self.runs.borrow_mut() = runs.to_vec(); | |
| let states = if self.local_selection && !runs.is_empty() { | |
| TextSelectionProjection { | |
| ranges: runs.iter().map(|run| Some(0..run.text.len())).collect(), | |
| is_active: true, | |
| } | |
| } else if let Some(owner) = self.byte_owner { | |
| project_byte_ranges(owner, self.snapshot, runs) | |
| } else { | |
| project_ranges(self.snapshot, runs) | |
| }; | |
| let mut selected_runs = runs | |
| .iter() | |
| .zip(states.ranges()) | |
| .enumerate() | |
| .filter_map(|(index, (run, state))| { | |
| state.as_ref().map(|range| { | |
| debug_assert!(run.text.is_char_boundary(range.start)); | |
| debug_assert!(run.text.is_char_boundary(range.end)); | |
| ( | |
| run.document_order, | |
| index, | |
| run.text[range.clone()].to_string(), | |
| ) | |
| }) | |
| }) | |
| .collect::<Vec<_>>(); | |
| selected_runs.sort_by_key(|(order, index, _)| (*order, *index)); | |
| *self.projected_copy_text.borrow_mut() = | |
| Some(selected_runs.into_iter().map(|(_, _, text)| text).collect()); | |
| states | |
| } | |
| /// Installs the callback which focuses the participant when a drag begins in it. | |
| fn set_focus_handler(&mut self, callback: impl Fn(&mut Window, &mut App) + 'static) { | |
| self.on_focus = Some(Rc::new(callback)); | |
| } | |
| fn clear_with(&mut self, callback: impl Fn(&mut App) + 'static) { | |
| self.clear = Some(Rc::new(callback)); | |
| } | |
| /// Installs a participant-specific copy projection. | |
| fn copy_with(&mut self, callback: impl Fn(&mut App) -> String + 'static) { | |
| self.copy = Some(Rc::new(callback)); | |
| } | |
| /// Installs a participant-specific lookup for stable virtualized content keys. | |
| fn resolve_content_key_with( | |
| &mut self, | |
| callback: impl Fn(Point<Pixels>, &App) -> Option<TextSelectionContentKey> + 'static, | |
| ) { | |
| self.content_key_resolver = Some(Rc::new(callback)); | |
| } | |
| fn set_snapshot(&mut self, snapshot: Option<TextSelectionSnapshot>, cx: &mut Context<Self>) { | |
| let snapshot = snapshot.filter(|_| self.enabled); | |
| if self.snapshot == snapshot { | |
| return; | |
| } | |
| self.snapshot = snapshot; | |
| *self.projected_copy_text.get_mut() = None; | |
| cx.emit(TextSelectionEvent::SelectionChanged(snapshot)); | |
| } | |
| /// Whether clearing the participant would change anything: it is part | |
| /// of the window selection, or selected on its own. | |
| fn has_selection_to_clear(&self) -> bool { | |
| self.snapshot.is_some() || self.local_selection | |
| } | |
| fn clear_state(&mut self, cx: &mut Context<Self>) -> Option<ClearHandler> { | |
| self.snapshot = None; | |
| *self.projected_copy_text.get_mut() = None; | |
| self.local_selection = false; | |
| cx.emit(TextSelectionEvent::Cleared); | |
| cx.emit(TextSelectionEvent::SelectionChanged(None)); | |
| let callback = self.clear.clone()?; | |
| let owner = cx.entity().downgrade(); | |
| Some(Rc::new(move |cx| { | |
| // A deferred old clear cannot erase a newer participant selection. | |
| if owner.upgrade().is_some_and(|owner| { | |
| let owner = owner.read(cx); | |
| owner.snapshot.is_none() && !owner.local_selection | |
| }) { | |
| callback(cx); | |
| } | |
| })) | |
| } | |
| fn set_auto_scroll( | |
| &self, | |
| delta: Option<Pixels>, | |
| gesture: gpui::WeakInputGesture, | |
| cx: &mut Context<Self>, | |
| ) { | |
| let delta = delta.filter(|_| self.enabled); | |
| cx.emit(TextSelectionEvent::AutoScroll(delta, gesture)); | |
| } | |
| fn focus(&self, window: &mut Window, cx: &mut Context<Self>) { | |
| if self.enabled | |
| && let Some(callback) = self.on_focus.clone() | |
| { | |
| let owner = cx.entity().downgrade(); | |
| let admission = Arc::downgrade(&self.admission); | |
| let input = window.input_gesture(); | |
| window.defer(cx, move |window, cx| { | |
| if input.is_current() | |
| && admission.upgrade().is_some() | |
| && owner.upgrade().is_some_and(|owner| owner.read(cx).enabled) | |
| { | |
| callback(window, cx); | |
| } | |
| }); | |
| } | |
| } | |
| fn copy_item(&self, document_order: u64) -> Option<CopyItem> { | |
| (self.enabled && (self.snapshot.is_some() || self.local_selection)).then(|| CopyItem { | |
| document_order, | |
| callback: self.copy.clone(), | |
| fallback: self | |
| .projected_copy_text | |
| .borrow() | |
| .clone() | |
| .unwrap_or_else(|| self.fallback_copy_text.clone()), | |
| }) | |
| } | |
| } | |
| /// The touch handles a participant laid out for a frame, with their hitboxes. | |
| #[derive(Default)] | |
| pub struct TouchHandleLayout { | |
| hitboxes: Vec<(SelectionEdge, Hitbox)>, | |
| } | |
| /// A stable, participant-neutral handle for text that participates in window selection. | |
| #[derive(Clone)] | |
| pub struct TextSelectionHandle(Entity<SelectableTextState>); | |
| impl TextSelectionHandle { | |
| /// Creates a selection participant handle with fallback text for copying. | |
| pub fn new(fallback_copy_text: impl Into<String>, cx: &mut App) -> Self { | |
| Self(cx.new(|_| SelectableTextState::new(fallback_copy_text))) | |
| } | |
| /// Returns this participant's stable identity. | |
| pub fn entity_id(&self) -> EntityId { | |
| self.0.entity_id() | |
| } | |
| /// Returns the current geometry selection snapshot for this participant. | |
| pub fn snapshot(&self, cx: &App) -> Option<TextSelectionSnapshot> { | |
| self.0.read(cx).snapshot() | |
| } | |
| /// Revoke original participant admission synchronously, before another paint. | |
| pub fn set_enabled(&self, enabled: bool, cx: &mut App) { | |
| if self.0.read(cx).enabled == enabled { | |
| return; | |
| } | |
| let revoked = self.0.update(cx, |state, cx| { | |
| state.enabled = enabled; | |
| if !enabled { | |
| state.admission = Arc::new(()); | |
| state.local_selection = false; | |
| state.set_snapshot(None, cx); | |
| } | |
| !enabled | |
| }); | |
| if revoked { | |
| let group = self.0.read(cx).group.clone(); | |
| let handlers = group | |
| .and_then(|group| group.owner.upgrade()) | |
| .map(|owner| owner.update(cx, |owner, cx| owner.withdraw(self.entity_id(), cx))) | |
| .unwrap_or_default(); | |
| // The caller may still be borrowing the original TextViewState. | |
| cx.defer(move |cx| dispatch_clear_handlers(handlers, cx)); | |
| } | |
| } | |
| pub(crate) fn admission(&self, cx: &App) -> Weak<()> { | |
| Arc::downgrade(&self.0.read(cx).admission) | |
| } | |
| /// Sets the fallback text copied while this participant participates. | |
| pub fn set_fallback_copy_text(&self, text: impl Into<String>, cx: &mut App) { | |
| self.0 | |
| .update(cx, |state, _| state.set_fallback_copy_text(text)); | |
| } | |
| /// Marks participant-local selection, such as select-all, as active. | |
| pub fn set_local_selection(&self, active: bool, cx: &mut App) { | |
| self.0 | |
| .update(cx, |state, _| state.set_local_selection(active)); | |
| } | |
| /// Retain byte endpoints for one literal run using the original content-key path. | |
| pub fn preserve_byte_offsets(&self, cx: &mut App) { | |
| let owner = self.entity_id(); | |
| let weak = self.downgrade(); | |
| self.0.update(cx, |state, _| state.byte_owner = Some(owner)); | |
| self.resolve_content_key_with( | |
| move |position, cx| { | |
| let state = weak.upgrade()?; | |
| let state = state.read(cx); | |
| let runs = state.runs.borrow(); | |
| let [run] = runs.as_slice() else { | |
| return None; | |
| }; | |
| Some(TextSelectionContentKey::new( | |
| run.layout | |
| .index_for_position(position + run.bounds.origin - run.translation) | |
| .unwrap_or_else(|byte| byte) as u64, | |
| )) | |
| }, | |
| cx, | |
| ); | |
| } | |
| /// Copy the selected participants in this participant's original painted scope. | |
| /// Plain runs refresh from current native snapshots; rich callbacks stay original. | |
| pub fn selected_text_in_scope(&self, window: &Window, cx: &mut App) -> Option<String> { | |
| let state = self.group(cx)?.in_window(window)?; | |
| let participants = { | |
| let state = state.read(cx); | |
| let scope = state | |
| .participants | |
| .borrow() | |
| .get(&self.entity_id())? | |
| .registration | |
| .scope; | |
| state | |
| .participants | |
| .borrow() | |
| .values() | |
| .filter(|entry| entry.registration.scope == scope) | |
| .filter_map(|entry| { | |
| Some(( | |
| entry.participant.upgrade()?, | |
| entry.registration.document_order, | |
| )) | |
| }) | |
| .collect::<Vec<_>>() | |
| }; | |
| let mut items = participants | |
| .into_iter() | |
| .filter_map(|(participant, order)| { | |
| participant.query(cx, |participant, _| { | |
| if !participant.local_selection && participant.copy.is_none() { | |
| let runs = participant.runs.borrow().clone(); | |
| participant.update_runs(&runs); | |
| } | |
| participant.copy_item(order) | |
| }) | |
| }) | |
| .collect::<Vec<_>>(); | |
| if items.is_empty() { | |
| return None; | |
| } | |
| items.sort_by_key(|item| item.document_order); | |
| Some( | |
| items | |
| .into_iter() | |
| .map(|item| { | |
| item.callback | |
| .map(|callback| callback(cx)) | |
| .unwrap_or(item.fallback) | |
| }) | |
| .filter(|text| !text.is_empty()) | |
| .collect::<Vec<_>>() | |
| .join("\n"), | |
| ) | |
| } | |
| /// Activate the scope from this participant's actual painted registration. | |
| pub fn activate_scope(&self, window: &mut Window, cx: &mut App) -> bool { | |
| if !self.0.read(cx).enabled { | |
| return false; | |
| } | |
| let Some(state) = self.group(cx).and_then(|group| group.in_window(window)) else { | |
| return false; | |
| }; | |
| let scope = state | |
| .read(cx) | |
| .participants | |
| .borrow() | |
| .get(&self.entity_id()) | |
| .map(|entry| entry.registration.scope); | |
| let Some(scope) = scope else { | |
| return false; | |
| }; | |
| let handlers = state.update(cx, |state, cx| state.set_active_scope_state(scope, cx)); | |
| dispatch_clear_handlers(handlers, cx); | |
| true | |
| } | |
| pub fn group(&self, cx: &App) -> Option<TextSelectionGroup> { | |
| self.0.read(cx).group.clone() | |
| } | |
| /// Clear this participant's original group without changing foreground ownership. | |
| pub fn clear_group(&self, cx: &mut App) { | |
| if let Some(owner) = self.group(cx).and_then(|group| group.owner.upgrade()) { | |
| let handlers = owner.update(cx, |state, cx| state.clear_state(cx)); | |
| dispatch_clear_handlers(handlers, cx); | |
| } | |
| } | |
| /// Returns whether participant-local selection is active. | |
| pub fn has_local_selection(&self, cx: &App) -> bool { | |
| self.0.read(cx).local_selection | |
| } | |
| /// Registers this participant and its geometry for the current frame. | |
| pub fn register( | |
| &self, | |
| mut registration: TextSelectionRegistration, | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) { | |
| if let Some(scope) = current_text_selection_scope(window) { | |
| registration.scope = scope; | |
| } | |
| self.register_exact(registration, window, cx); | |
| } | |
| // Rich TextView captures its exact wrapper scope during request-layout; | |
| // a State-only native gap does not execute that wrapper again. | |
| pub(crate) fn register_exact( | |
| &self, | |
| registration: TextSelectionRegistration, | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) { | |
| if !self.0.read(cx).enabled { | |
| return; | |
| } | |
| let Some(state) = WindowSelectionState::at(placement_group(window), cx) else { | |
| return; | |
| }; | |
| schedule_selection_finish_frame(&state, window, cx); | |
| let Some(registration) = state.read(cx).register_quietly(self, registration, cx) else { | |
| return; | |
| }; | |
| state.query(cx, |state, cx| { | |
| state.register_participant(self.clone(), registration, cx) | |
| }); | |
| } | |
| // Plain text supplies its own original laid-out caret geometry. Preserve | |
| // preceding edges during registration, then update them once from the | |
| // projection after exact group binding, avoiding alternating None/Some | |
| // touch notifications on every paint. | |
| pub(crate) fn register_plain_text( | |
| &self, | |
| mut registration: TextSelectionRegistration, | |
| run: TextSelectionRun, | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) -> TextSelectionProjection { | |
| let placed = || { | |
| self.group(cx) | |
| .filter(|group| group.key == placement_group(window)) | |
| .and_then(|group| group.in_window(window)) | |
| }; | |
| registration.selection_edges = placed().and_then(|state| { | |
| state | |
| .read(cx) | |
| .participants | |
| .borrow() | |
| .get(&self.entity_id()) | |
| .and_then(|participant| participant.registration.selection_edges) | |
| }); | |
| self.register(registration, window, cx); | |
| let projection = self.update_runs(std::slice::from_ref(&run), cx); | |
| let edges = projection | |
| .ranges() | |
| .first() | |
| .and_then(|range| range.as_ref()) | |
| .and_then(|range| { | |
| let start = run.layout.position_for_index(range.start)?; | |
| let end = run.layout.position_for_index(range.end)?; | |
| let caret = gpui::Size::new(px(0.), run.layout.line_height()); | |
| Some((Bounds::new(start, caret), Bounds::new(end, caret))) | |
| }); | |
| if let Some(state) = self | |
| .group(cx) | |
| .filter(|group| group.key == placement_group(window)) | |
| .and_then(|group| group.in_window(window)) | |
| { | |
| state.query(cx, |state, cx| { | |
| if let Some(participant) = state.participants.get_mut().get_mut(&self.entity_id()) | |
| && participant.registration.selection_edges != edges | |
| { | |
| Rc::make_mut(&mut participant.registration).selection_edges = edges; | |
| if state.touch.active { | |
| state.touch_changed(cx); | |
| } | |
| } | |
| }); | |
| } | |
| projection | |
| } | |
| /// Projects the current snapshot onto plain-text runs and caches their copy text. | |
| pub fn update_runs(&self, runs: &[TextSelectionRun], cx: &mut App) -> TextSelectionProjection { | |
| self.0.read(cx).update_runs(runs) | |
| } | |
| // Rich text renders its own selection; retain geometry only for word hit testing. | |
| pub(crate) fn set_hit_test_runs(&self, runs: &[TextSelectionRun], cx: &mut App) { | |
| *self.0.read(cx).runs.borrow_mut() = runs.to_vec(); | |
| } | |
| /// Subscribes to participant selection notifications. | |
| pub fn subscribe( | |
| &self, | |
| mut callback: impl FnMut(&TextSelectionEvent, &mut App) + 'static, | |
| cx: &mut App, | |
| ) -> Subscription { | |
| cx.subscribe(&self.0, move |_, event, cx| callback(event, cx)) | |
| } | |
| /// Subscribes `window` to refresh whenever this participant's selection changes. | |
| #[must_use = "retain the subscription or explicitly detach it"] | |
| pub fn refresh_window_on_change(&self, window: &Window, cx: &mut App) -> Subscription { | |
| let window = window.window_handle(); | |
| self.subscribe( | |
| move |event, cx| { | |
| if matches!( | |
| event, | |
| TextSelectionEvent::SelectionChanged(_) | |
| | TextSelectionEvent::TouchSelectionChanged | |
| ) { | |
| _ = window.update(cx, |_, window, _| window.refresh()); | |
| } | |
| }, | |
| cx, | |
| ) | |
| } | |
| /// Sets the callback which focuses the participant when a drag begins in it. | |
| pub fn focus_with(&self, callback: impl Fn(&mut Window, &mut App) + 'static, cx: &mut App) { | |
| self.0 | |
| .update(cx, |state, _| state.set_focus_handler(callback)); | |
| } | |
| /// Sets the synchronous participant cleanup command used by window clear. | |
| pub fn clear_with(&self, callback: impl Fn(&mut App) + 'static, cx: &mut App) { | |
| self.0.update(cx, |state, _| state.clear_with(callback)); | |
| } | |
| /// Sets a participant-specific copy projection. | |
| pub fn copy_with(&self, callback: impl Fn(&mut App) -> String + 'static, cx: &mut App) { | |
| self.0.update(cx, |state, _| state.copy_with(callback)); | |
| } | |
| /// Lays out the touch handles at the ends of this participant's | |
| /// selection, as they were painted last frame, and gives each a hitbox | |
| /// where the finger takes it. Call during the participant's prepaint; | |
| /// hand the result to [`Self::paint_touch_handles`]. | |
| pub fn prepaint_touch_handles(&self, window: &mut Window, cx: &App) -> TouchHandleLayout { | |
| let Some(state) = self | |
| .group(cx) | |
| .filter(|group| group.key == placement_group(window)) | |
| .and_then(|group| group.in_window(window)) | |
| else { | |
| return TouchHandleLayout::default(); | |
| }; | |
| let hitboxes = state | |
| .read(cx) | |
| .touch_handles_of(self.entity_id()) | |
| .into_iter() | |
| .map(|(edge, caret)| { | |
| let hitbox = window.insert_hitbox( | |
| TouchHandle::hit_bounds(edge, caret), | |
| HitboxBehavior::BlockMouse, | |
| ); | |
| (edge, hitbox) | |
| }) | |
| .collect(); | |
| TouchHandleLayout { hitboxes } | |
| } | |
| /// Paints the touch handles at the ends of this participant's selection, | |
| /// in `color`, where the participant is in the paint order — so whatever | |
| /// is drawn over the text is drawn over its handles too. Call at the end | |
| /// of the participant's paint, after [`Self::register`] for the frame. | |
| /// | |
| /// The handles take the finger's drag from there; Base moves the | |
| /// selection with it. | |
| pub fn paint_touch_handles( | |
| &self, | |
| layout: &TouchHandleLayout, | |
| color: Hsla, | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) { | |
| let Some(state) = self | |
| .group(cx) | |
| .filter(|group| group.key == placement_group(window)) | |
| .and_then(|group| group.in_window(window)) | |
| else { | |
| return; | |
| }; | |
| for (edge, caret) in state.read(cx).touch_handles_of(self.entity_id()) { | |
| TouchHandle::paint(edge, caret, color, window); | |
| } | |
| for (edge, hitbox) in &layout.hitboxes { | |
| let edge = *edge; | |
| state.query(cx, |state, _| state.register_touch_ui(hitbox.id)); | |
| // Touch: the drag is offered on the first touch, before it can | |
| // become a tap, a long press or a pan. | |
| window.on_mouse_event({ | |
| let hitbox = hitbox.clone(); | |
| let state = state.downgrade(); | |
| move |event: &TouchDragEvent, phase, window, cx| { | |
| if !phase.bubble() | |
| || event.phase != TouchPhase::Started | |
| || window.default_prevented() | |
| || !hitbox.is_hovered(window) | |
| { | |
| return; | |
| } | |
| let Some(state) = state.upgrade() else { | |
| return; | |
| }; | |
| window.prevent_default(); | |
| cx.stop_propagation(); | |
| state.update(cx, |state, cx| { | |
| state.begin_edge_drag(edge, event.position, window, cx) | |
| }); | |
| WindowSelectionState::resolve_content_keys(&state, cx); | |
| } | |
| }); | |
| // Mouse: the same drag for a pointer. | |
| window.on_mouse_event({ | |
| let hitbox = hitbox.clone(); | |
| let state = state.downgrade(); | |
| move |event: &MouseDownEvent, phase, window, cx| { | |
| if !phase.bubble() | |
| || event.button != MouseButton::Left | |
| || !hitbox.is_hovered(window) | |
| { | |
| return; | |
| } | |
| let Some(state) = state.upgrade() else { | |
| return; | |
| }; | |
| cx.stop_propagation(); | |
| state.update(cx, |state, cx| { | |
| state.begin_edge_drag(edge, event.position, window, cx) | |
| }); | |
| WindowSelectionState::resolve_content_keys(&state, cx); | |
| } | |
| }); | |
| } | |
| } | |
| /// Sets a participant-specific lookup for stable virtualized content keys. | |
| pub fn resolve_content_key_with( | |
| &self, | |
| callback: impl Fn(Point<Pixels>, &App) -> Option<TextSelectionContentKey> + 'static, | |
| cx: &mut App, | |
| ) { | |
| self.0 | |
| .update(cx, |state, _| state.resolve_content_key_with(callback)); | |
| } | |
| fn downgrade(&self) -> WeakEntity<SelectableTextState> { | |
| self.0.downgrade() | |
| } | |
| } | |
| #[derive(Clone)] | |
| struct ParticipantRegistration { | |
| participant: WeakEntity<SelectableTextState>, | |
| registration: Rc<TextSelectionRegistration>, | |
| generation: u64, | |
| } | |
| #[derive(Clone)] | |
| struct SelectionEndpoint { | |
| participant: Option<WeakEntity<SelectableTextState>>, | |
| point: Point<Pixels>, | |
| inside: bool, | |
| inside_text: bool, | |
| content_key: Option<TextSelectionContentKey>, | |
| content_key_resolver: Option<(ContentKeyResolver, Point<Pixels>)>, | |
| } | |
| impl SelectionEndpoint { | |
| fn snapshot(&self) -> TextSelectionEndpoint { | |
| let snapshot = TextSelectionEndpoint::new(self.entity_id(), self.point); | |
| if let Some(content_key) = self.content_key { | |
| snapshot.with_content_key(content_key) | |
| } else { | |
| snapshot | |
| } | |
| } | |
| fn resolve( | |
| &self, | |
| participants: &HashMap<EntityId, ParticipantRegistration>, | |
| ) -> Option<Point<Pixels>> { | |
| let participant = self.participant.as_ref()?; | |
| let registration = participants.get(&participant.entity_id())?; | |
| participant.upgrade()?; | |
| Some( | |
| self.point | |
| + registration.registration.scroll_offset | |
| + registration.registration.bounds.origin, | |
| ) | |
| } | |
| fn entity_id(&self) -> Option<EntityId> { | |
| self.participant | |
| .as_ref() | |
| .map(|participant| participant.entity_id()) | |
| } | |
| } | |
| /// What a long press left behind: the handles and the edit menu. | |
| /// | |
| /// The presentation layer draws both and reports their bounds each frame, so | |
| /// that a press on a handle or a menu item is not taken for a press on the | |
| /// text underneath, which would clear the very selection they belong to. | |
| #[derive(Default)] | |
| struct TouchSelection { | |
| /// The current selection was made by touch and carries handles. | |
| active: bool, | |
| menu_open: bool, | |
| drag: Option<EdgeDrag>, | |
| /// Original handle/menu hitboxes, kept exactly while the native frame | |
| /// keeps them, including when only another participant repaints. | |
| ui_hitboxes: Vec<HitboxId>, | |
| /// The ends as last laid out: `(start, end, start_visible, end_visible)`. | |
| /// A frame in which no participant paints a selection — the cursor sits | |
| /// between two characters mid-drag — would otherwise lose the handle the | |
| /// finger holds, and with it the rest of the drag. | |
| last_edges: std::cell::Cell<Option<(Bounds<Pixels>, Bounds<Pixels>, bool, bool)>>, | |
| } | |
| impl TouchSelection { | |
| fn covers(&self, position: Point<Pixels>, window: &Window) -> bool { | |
| self.active | |
| && self | |
| .ui_hitboxes | |
| .iter() | |
| .any(|id| window.hitbox_contains(*id, &position)) | |
| } | |
| /// Drops the handles and the menu; returns whether there were any. | |
| fn reset(&mut self) -> bool { | |
| let had = self.active; | |
| self.active = false; | |
| self.menu_open = false; | |
| self.drag = None; | |
| self.last_edges.set(None); | |
| self.ui_hitboxes.clear(); | |
| had | |
| } | |
| } | |
| /// Window-local generic text-selection state. | |
| #[derive(Default)] | |
| struct WindowSelectionState { | |
| group: Option<SelectionGroupKey>, | |
| /// What each participant painted this frame, or last painted. Painting | |
| /// reports it without changing the selection: see | |
| /// [`WindowSelectionState::register_quietly`]. | |
| participants: RefCell<HashMap<EntityId, ParticipantRegistration>>, | |
| active_scope: TextSelectionScopeId, | |
| anchor: Option<SelectionEndpoint>, | |
| cursor: Option<SelectionEndpoint>, | |
| pending_extension_anchor: Option<SelectionEndpoint>, | |
| selecting: Option<gpui::InputGesture>, | |
| did_hit_text: bool, | |
| frame_generation: Cell<u64>, | |
| finish_frame_scheduled: Cell<bool>, | |
| refresh_held_cursor: bool, | |
| mouse_down_prepared: bool, | |
| auto_scroll: AutoScroll, | |
| /// Where the anchor's text was when the last synthetic wheel went out, | |
| /// and how many went out without moving it. A container at its end | |
| /// cannot scroll further; pushing it on would only make one that | |
| /// bounces stretch and snap back on every tick. | |
| auto_scroll_stall: (Option<(Bounds<Pixels>, Point<Pixels>)>, u8), | |
| touch: TouchSelection, | |
| /// This entity, so that touch changes can notify observers from paths that | |
| /// only hold an [`App`]. | |
| entity_id: Option<EntityId>, | |
| } | |
| impl WindowSelectionState { | |
| fn resolve_content_keys(state: &Entity<Self>, cx: &mut App) { | |
| let pending = state.read_with(cx, |state, _| { | |
| [ | |
| state | |
| .anchor | |
| .as_ref() | |
| .and_then(|endpoint| endpoint.content_key_resolver.clone()), | |
| state | |
| .cursor | |
| .as_ref() | |
| .and_then(|endpoint| endpoint.content_key_resolver.clone()), | |
| ] | |
| }); | |
| // Nothing to resolve and no selection to publish: an event that | |
| // changed nothing does not change the state either. | |
| if pending.iter().all(Option::is_none) && !state.read(cx).is_active() { | |
| return; | |
| } | |
| let resolved = | |
| pending.map(|pending| pending.and_then(|(callback, point)| callback(point, cx))); | |
| state.update(cx, |state, cx| { | |
| if let (Some(endpoint), Some(key)) = (state.anchor.as_mut(), resolved[0]) { | |
| endpoint.content_key = Some(key); | |
| endpoint.content_key_resolver = None; | |
| } | |
| if let (Some(endpoint), Some(key)) = (state.cursor.as_mut(), resolved[1]) { | |
| endpoint.content_key = Some(key); | |
| endpoint.content_key_resolver = None; | |
| } | |
| state.publish_snapshots(cx); | |
| }); | |
| } | |
| fn acquire(key: SelectionGroupKey, cx: &mut App) -> Entity<Self> { | |
| if !cx.has_global::<SelectionStateRegistry>() { | |
| cx.set_global(SelectionStateRegistry::default()); | |
| } | |
| if let Some(state) = cx | |
| .global::<SelectionStateRegistry>() | |
| .0 | |
| .get(&key) | |
| .and_then(WeakEntity::upgrade) | |
| { | |
| return state; | |
| } | |
| let state = cx.new(move |cx| { | |
| let entity_id = cx.entity_id(); | |
| cx.on_release(move |state: &mut WindowSelectionState, cx| { | |
| let handlers = state.clear_state(cx); | |
| if cx.has_global::<SelectionStateRegistry>() { | |
| let registry = &mut cx.global_mut::<SelectionStateRegistry>().0; | |
| if registry | |
| .get(&key) | |
| .is_some_and(|state| state.entity_id() == entity_id) | |
| { | |
| registry.remove(&key); | |
| } | |
| } | |
| if !handlers.is_empty() { | |
| cx.defer(move |cx| dispatch_clear_handlers(handlers, cx)); | |
| } | |
| }) | |
| .detach(); | |
| Self { | |
| group: Some(key), | |
| entity_id: Some(entity_id), | |
| ..Self::default() | |
| } | |
| }); | |
| cx.global_mut::<SelectionStateRegistry>() | |
| .0 | |
| .insert(key, state.downgrade()); | |
| state | |
| } | |
| #[cfg(test)] | |
| fn ensure(window: &Window, cx: &mut App) -> Entity<Self> { | |
| Self::acquire(physical_group(window), cx) | |
| } | |
| fn at(key: SelectionGroupKey, cx: &App) -> Option<Entity<Self>> { | |
| cx.try_global::<SelectionStateRegistry>()? | |
| .0 | |
| .get(&key)? | |
| .upgrade() | |
| } | |
| fn existing(window: &Window, cx: &App) -> Option<Entity<Self>> { | |
| Self::at(physical_group(window), cx) | |
| } | |
| /// Updates the active scope. Participants from other scopes cannot participate. | |
| #[cfg(test)] | |
| fn set_active_scope(&mut self, scope: TextSelectionScopeId, cx: &mut App) { | |
| let handlers = self.set_active_scope_state(scope, cx); | |
| dispatch_clear_handlers(handlers, cx); | |
| } | |
| fn set_active_scope_state( | |
| &mut self, | |
| scope: TextSelectionScopeId, | |
| cx: &mut App, | |
| ) -> Vec<ClearHandler> { | |
| if self.active_scope == scope { | |
| return Vec::new(); | |
| } | |
| let handlers = self.clear_state(cx); | |
| self.active_scope = scope; | |
| self.publish_snapshots(cx); | |
| handlers | |
| } | |
| // Resolve the original painted participant before changing scope. Container | |
| // ancestors must never clear an inner document's selection on its behalf. | |
| fn scope_at( | |
| &self, | |
| position: Point<Pixels>, | |
| window: &Window, | |
| cx: &App, | |
| glyph_required: bool, | |
| ) -> Option<TextSelectionScopeId> { | |
| self.participants | |
| .borrow() | |
| .values() | |
| .filter(|entry| { | |
| entry | |
| .participant | |
| .upgrade() | |
| .is_some_and(|participant| participant.read(cx).enabled) | |
| && entry.registration.hitbox.is_hovered_at(position, window) | |
| }) | |
| .min_by(|a, b| { | |
| let area = |entry: &ParticipantRegistration| { | |
| f32::from(entry.registration.bounds.size.width) | |
| * f32::from(entry.registration.bounds.size.height) | |
| }; | |
| area(a).total_cmp(&area(b)).then_with(|| { | |
| a.registration | |
| .document_order | |
| .cmp(&b.registration.document_order) | |
| }) | |
| }) | |
| .filter(|entry| { | |
| !glyph_required | |
| || entry | |
| .registration | |
| .text_bounds | |
| .iter() | |
| .any(|bounds| bounds.contains(&position)) | |
| }) | |
| .map(|entry| entry.registration.scope) | |
| } | |
| /// Sweeps participants after a rendered frame has completed. | |
| /// | |
| /// Registrations are stamped with the current generation while any sibling | |
| /// is painting. Sweeping only after paint makes registration independent of | |
| /// whether a participant or the lifecycle element paints first. | |
| /// | |
| /// A missed generation alone does not mean the participant left the window: | |
| /// a cached view replays its recorded frame, painting the same text at the | |
| /// same place without running any of its elements. Such a participant keeps | |
| /// the registration it last reported, which still describes what is on | |
| /// screen; only one whose element GPUI has dropped is swept. | |
| /// | |
| /// Removing an endpoint also retires the window's gesture. Clearing only | |
| /// the participant snapshot would restore that selection if its retained | |
| /// entity were registered again. | |
| pub fn finish_frame(&mut self, cx: &mut App) -> Vec<ClearHandler> { | |
| self.finish_frame_scheduled.set(false); | |
| let generation = self.frame_generation.get(); | |
| self.prune_dead_participants(cx); | |
| let stale = self | |
| .participants | |
| .get_mut() | |
| .iter() | |
| .filter_map(|(id, registration)| { | |
| (registration.generation != generation && !registration.registration.is_rendered()) | |
| .then(|| (*id, registration.participant.clone())) | |
| }) | |
| .collect::<Vec<_>>(); | |
| let endpoint_departed = stale.iter().any(|(id, _)| { | |
| [ | |
| self.anchor.as_ref(), | |
| self.cursor.as_ref(), | |
| self.pending_extension_anchor.as_ref(), | |
| ] | |
| .into_iter() | |
| .flatten() | |
| .any(|endpoint| endpoint.entity_id() == Some(*id)) | |
| }); | |
| let mut handlers = if endpoint_departed { | |
| self.clear_state(cx) | |
| } else { | |
| Vec::new() | |
| }; | |
| for (id, participant) in stale { | |
| self.participants.get_mut().remove(&id); | |
| if let Some(participant) = participant.upgrade() | |
| && participant.read(cx).has_selection_to_clear() | |
| { | |
| if let Some(handler) = participant.update(cx, |state, cx| state.clear_state(cx)) { | |
| handlers.push(handler); | |
| } | |
| } | |
| } | |
| self.publish_snapshots(cx); | |
| self.frame_generation.set(generation.wrapping_add(1)); | |
| handlers | |
| } | |
| fn schedule_finish_frame(&self) -> bool { | |
| !self.finish_frame_scheduled.replace(true) | |
| } | |
| /// Whether there is a selection, or a gesture or touch selection that | |
| /// may make one: what painting the participants reports can change it. | |
| fn is_active(&self) -> bool { | |
| self.anchor.is_some() | |
| || self.cursor.is_some() | |
| || self.pending_extension_anchor.is_some() | |
| || self.is_selecting() | |
| || self.refresh_held_cursor | |
| || self.touch.active | |
| } | |
| /// Records this frame's geometry for a participant without updating | |
| /// this state, when there is no selection for the geometry to change. | |
| /// Every participant paints its geometry on every frame; doing so through | |
| /// an update would mark the state, and every view that reads it, changed | |
| /// on every frame. Returns the registration when it has to go through | |
| /// [`Self::register_participant`]. | |
| fn register_quietly( | |
| &self, | |
| selection: &TextSelectionHandle, | |
| registration: TextSelectionRegistration, | |
| cx: &App, | |
| ) -> Option<TextSelectionRegistration> { | |
| let participant = selection.0.read(cx); | |
| // A first registration or a move between physical openings still has | |
| // to reconcile the original participant's revocable group custody. | |
| let same_group = participant | |
| .group | |
| .as_ref() | |
| .is_some_and(|group| Some(group.owner.entity_id()) == self.entity_id); | |
| if self.is_active() || !same_group || !participant.enabled { | |
| return Some(registration); | |
| } | |
| self.participants.borrow_mut().insert( | |
| selection.entity_id(), | |
| ParticipantRegistration { | |
| participant: selection.downgrade(), | |
| registration: Rc::new(registration), | |
| generation: self.frame_generation.get(), | |
| }, | |
| ); | |
| None | |
| } | |
| /// Ends the frame as [`Self::finish_frame`] does, without updating this | |
| /// state, when there is no selection and no participant that left the | |
| /// window has one to clear. Returns whether it could. | |
| fn finish_frame_quietly(&self, cx: &App) -> bool { | |
| if self.is_active() { | |
| return false; | |
| } | |
| let generation = self.frame_generation.get(); | |
| let mut participants = self.participants.borrow_mut(); | |
| let gone = |registration: &ParticipantRegistration| { | |
| registration.generation != generation && !registration.registration.is_rendered() | |
| }; | |
| if participants.values().any(|registration| { | |
| gone(registration) | |
| && registration | |
| .participant | |
| .upgrade() | |
| .is_some_and(|participant| participant.read(cx).has_selection_to_clear()) | |
| }) { | |
| return false; | |
| } | |
| participants.retain(|_, registration| { | |
| !gone(registration) && registration.participant.upgrade().is_some() | |
| }); | |
| drop(participants); | |
| self.finish_frame_scheduled.set(false); | |
| self.frame_generation.set(generation.wrapping_add(1)); | |
| true | |
| } | |
| /// Registers this frame's geometry for a participant. | |
| pub fn register_participant( | |
| &mut self, | |
| selection: TextSelectionHandle, | |
| registration: TextSelectionRegistration, | |
| cx: &mut App, | |
| ) { | |
| if let Some(key) = self.group { | |
| if let Some(owner) = Self::at(key, cx) { | |
| let group = TextSelectionGroup { | |
| key, | |
| owner: owner.downgrade(), | |
| }; | |
| let previous = selection | |
| .0 | |
| .query(cx, |state, _| state.group.replace(group.clone())); | |
| if let Some(previous) = previous.filter(|old| !old.same_owner(&group)) { | |
| let mut handlers = previous | |
| .owner | |
| .upgrade() | |
| .map(|old| { | |
| old.query(cx, |state, cx| state.withdraw(selection.entity_id(), cx)) | |
| }) | |
| .unwrap_or_default(); | |
| if let Some(handler) = selection.0.query(cx, |state, cx| { | |
| (state.local_selection | |
| || state.snapshot.is_some() | |
| || state.projected_copy_text.borrow().is_some()) | |
| .then(|| state.clear_state(cx)) | |
| .flatten() | |
| }) { | |
| handlers.push(handler); | |
| } | |
| cx.defer(move |cx| dispatch_clear_handlers(handlers, cx)); | |
| } | |
| } | |
| } | |
| if !selection.0.read(cx).enabled { | |
| return; | |
| } | |
| self.prune_dead_participants(cx); | |
| if self.is_selecting() | |
| && registration.self_scroll | |
| && self.anchor.as_ref().and_then(SelectionEndpoint::entity_id) | |
| == Some(selection.entity_id()) | |
| && self | |
| .participants | |
| .get_mut() | |
| .get(&selection.entity_id()) | |
| .is_some_and(|previous| { | |
| previous.registration.scroll_offset != registration.scroll_offset | |
| || previous.registration.bounds != registration.bounds | |
| }) | |
| { | |
| self.refresh_held_cursor = true; | |
| } | |
| // The handles sit on the painted ends; when those moved — a scroll, a | |
| // reflow, a select-all — whoever draws the handles needs to know. | |
| let edges_moved = self.touch.active | |
| && self | |
| .participants | |
| .get_mut() | |
| .get(&selection.entity_id()) | |
| .is_none_or(|previous| { | |
| previous.registration.selection_edges != registration.selection_edges | |
| }); | |
| self.participants.get_mut().insert( | |
| selection.entity_id(), | |
| ParticipantRegistration { | |
| participant: selection.downgrade(), | |
| registration: Rc::new(registration), | |
| generation: self.frame_generation.get(), | |
| }, | |
| ); | |
| self.publish_snapshots(cx); | |
| if edges_moved { | |
| self.touch_changed(cx); | |
| } | |
| } | |
| /// Starts a selection gesture using bounds hit testing (useful to adapters/tests). | |
| #[cfg(test)] | |
| fn begin(&mut self, position: Point<Pixels>, extend: bool, window: &Window, cx: &mut App) { | |
| self.begin_impl(position, extend, false, None, window.input_gesture(), cx); | |
| } | |
| /// Updates the current gesture using bounds hit testing. | |
| #[cfg(test)] | |
| fn update(&mut self, position: Point<Pixels>, cx: &mut App) { | |
| self.update_impl(position, None, cx); | |
| } | |
| fn retire_interrupted_gesture(&mut self, cx: &mut App) { | |
| if self | |
| .selecting | |
| .as_ref() | |
| .is_some_and(|gesture| !gesture.is_current()) | |
| { | |
| self.stop_anchor_auto_scroll(cx); | |
| self.selecting = None; | |
| self.pending_extension_anchor = None; | |
| self.refresh_held_cursor = false; | |
| self.mouse_down_prepared = false; | |
| if self.touch.drag.take().is_some() { | |
| self.touch_changed(cx); | |
| } | |
| self.publish_snapshots(cx); | |
| } | |
| } | |
| /// Ends the current gesture and keeps its selection visible. | |
| pub fn end(&mut self, cx: &mut App) { | |
| self.retire_interrupted_gesture(cx); | |
| self.pending_extension_anchor = None; | |
| if !self.is_selecting() { | |
| return; | |
| } | |
| self.stop_anchor_auto_scroll(cx); | |
| self.selecting = None; | |
| if !self.did_hit_text { | |
| self.anchor = None; | |
| self.cursor = None; | |
| } | |
| self.publish_snapshots(cx); | |
| } | |
| /// Clears both window selection and every participant's local selection. | |
| pub fn clear(&mut self, cx: &mut App) { | |
| let handlers = self.clear_state(cx); | |
| dispatch_clear_handlers(handlers, cx); | |
| } | |
| fn clear_state(&mut self, cx: &mut App) -> Vec<ClearHandler> { | |
| self.stop_anchor_auto_scroll(cx); | |
| self.anchor = None; | |
| self.cursor = None; | |
| self.pending_extension_anchor = None; | |
| self.selecting = None; | |
| self.did_hit_text = false; | |
| if self.touch.reset() { | |
| self.touch_changed(cx); | |
| } | |
| self.prune_dead_participants(cx); | |
| self.participants | |
| .borrow() | |
| .values() | |
| .filter_map(|registration| registration.participant.upgrade()) | |
| .filter_map(|participant| participant.update(cx, |state, cx| state.clear_state(cx))) | |
| .collect() | |
| } | |
| fn withdraw(&mut self, participant: EntityId, cx: &mut App) -> Vec<ClearHandler> { | |
| if !self.participants.borrow().contains_key(&participant) { | |
| return Vec::new(); | |
| } | |
| let depends = [&self.anchor, &self.cursor, &self.pending_extension_anchor] | |
| .into_iter() | |
| .flatten() | |
| .any(|endpoint| endpoint.entity_id() == Some(participant)); | |
| let handlers = if depends { | |
| self.clear_state(cx) | |
| } else { | |
| Vec::new() | |
| }; | |
| self.participants.get_mut().remove(&participant); | |
| if let Some(entity_id) = self.entity_id { | |
| cx.notify(entity_id); | |
| } | |
| handlers | |
| } | |
| /// Tells whoever draws the handles and the menu that they changed. | |
| /// | |
| /// Deferred, because the change may come from a participant painting its | |
| /// selection ends: a notification raised inside a draw marks the view | |
| /// dirty but starts no frame, and the handles would sit where they were | |
| /// until something else redrew the window. | |
| /// | |
| /// The participants in the selection hear it too: they paint the | |
| /// handles, and lay the handles' hitboxes out from the ends they painted | |
| /// last frame, so they render once more. A participant under a cached | |
| /// view would otherwise not, and the next frame would replay this one, | |
| /// with no hitbox where a handle is. | |
| fn touch_changed(&self, cx: &mut App) { | |
| let participants = self | |
| .participants | |
| .borrow() | |
| .values() | |
| .filter_map(|registration| registration.participant.upgrade()) | |
| .filter(|participant| participant.read(cx).snapshot.is_some()) | |
| .collect::<Vec<_>>(); | |
| let entity_id = self.entity_id; | |
| cx.defer(move |cx| { | |
| for participant in participants { | |
| participant.update(cx, |_, cx| { | |
| cx.emit(TextSelectionEvent::TouchSelectionChanged) | |
| }); | |
| } | |
| if let Some(entity_id) = entity_id { | |
| cx.notify(entity_id); | |
| } | |
| }); | |
| } | |
| fn copy_items(&self, cx: &App) -> Vec<CopyItem> { | |
| self.participants | |
| .borrow() | |
| .values() | |
| .filter_map(|registration| { | |
| let participant = registration.participant.upgrade()?; | |
| participant | |
| .read(cx) | |
| .copy_item(registration.registration.document_order) | |
| }) | |
| .collect() | |
| } | |
| #[cfg(test)] | |
| fn selected_text(&self, cx: &mut App) -> String { | |
| resolve_copy_items(self.copy_items(cx), cx) | |
| } | |
| /// Whether the current endpoints take in at least one character of some | |
| /// participant's painted text, as opposed to two points with nothing | |
| /// between them. | |
| fn selects_text(&self, cx: &App) -> bool { | |
| self.snapshot().is_some() | |
| && self.participants.borrow().values().any(|registration| { | |
| registration | |
| .participant | |
| .upgrade() | |
| .is_some_and(|participant| { | |
| let participant = participant.read(cx); | |
| project_ranges(participant.snapshot, &participant.runs.borrow()) | |
| .ranges() | |
| .iter() | |
| .any(|range| range.as_ref().is_some_and(|range| !range.is_empty())) | |
| }) | |
| }) | |
| } | |
| /// Returns whether a drag or a participant-local selection is active. | |
| pub fn has_selection(&self, cx: &App) -> bool { | |
| self.snapshot().is_some() | |
| || self.participants.borrow().values().any(|registration| { | |
| registration | |
| .participant | |
| .upgrade() | |
| .is_some_and(|participant| participant.read(cx).local_selection) | |
| }) | |
| } | |
| fn has_selection_in_scope(&self, scope: TextSelectionScopeId, cx: &App) -> bool { | |
| (self.active_scope == scope && (self.is_selecting() || self.snapshot().is_some())) | |
| || self.participants.borrow().values().any(|registration| { | |
| registration.registration.scope == scope | |
| && registration | |
| .participant | |
| .upgrade() | |
| .is_some_and(|participant| { | |
| let participant = participant.read(cx); | |
| participant.enabled && participant.local_selection | |
| }) | |
| }) | |
| } | |
| /// Returns the current resolved selection endpoints. | |
| pub fn snapshot(&self) -> Option<TextSelectionSnapshot> { | |
| if !self.did_hit_text { | |
| return None; | |
| } | |
| let anchor_endpoint = self.anchor.as_ref()?; | |
| let cursor_endpoint = self.cursor.as_ref()?; | |
| let anchor = anchor_endpoint.resolve(&self.participants.borrow())?; | |
| let cursor = cursor_endpoint.resolve(&self.participants.borrow())?; | |
| let different_content = anchor_endpoint.entity_id() == cursor_endpoint.entity_id() | |
| && anchor_endpoint | |
| .content_key | |
| .zip(cursor_endpoint.content_key) | |
| .is_some_and(|(a, b)| a != b); | |
| (anchor != cursor || different_content).then(|| { | |
| TextSelectionSnapshot::new(anchor_endpoint.snapshot(), cursor_endpoint.snapshot()) | |
| .with_selecting(self.is_selecting()) | |
| .with_window_points(Some(TextSelectionWindowPoints { anchor, cursor })) | |
| }) | |
| } | |
| /// Returns whether a drag is currently in progress. | |
| fn is_selecting(&self) -> bool { | |
| self.selecting | |
| .as_ref() | |
| .is_some_and(gpui::InputGesture::is_current) | |
| } | |
| fn prepare_for_mouse_down(&mut self, extend: bool, cx: &mut App) -> Vec<ClearHandler> { | |
| let pending_extension_anchor = extend.then(|| self.anchor.clone()).flatten(); | |
| self.stop_anchor_auto_scroll(cx); | |
| self.anchor = None; | |
| self.cursor = None; | |
| self.pending_extension_anchor = None; | |
| self.selecting = None; | |
| self.did_hit_text = false; | |
| if self.touch.reset() { | |
| self.touch_changed(cx); | |
| } | |
| self.prune_dead_participants(cx); | |
| let handlers = self | |
| .participants | |
| .borrow() | |
| .values() | |
| .filter_map(|registration| registration.participant.upgrade()) | |
| .filter_map(|participant| participant.update(cx, |state, cx| state.clear_state(cx))) | |
| .collect(); | |
| self.pending_extension_anchor = pending_extension_anchor; | |
| handlers | |
| } | |
| /// The touch selection laid out for its handles and edit menu. | |
| /// | |
| /// The ends come from the participants: the first selected character of | |
| /// the earliest participant in document order and the last of the latest. | |
| /// A participant whose selection is entirely scrolled away paints no ends, | |
| /// so the handles disappear with the text they mark. | |
| fn touch_selection(&self) -> Option<TouchSelectionSnapshot> { | |
| if !self.touch.active { | |
| return None; | |
| } | |
| // Each end with its owner's viewport: an end scrolled out of its | |
| // participant gets no handle. | |
| let mut start: Option<(u64, Bounds<Pixels>, bool)> = None; | |
| let mut end: Option<(u64, Bounds<Pixels>, bool)> = None; | |
| for registration in self.participants.borrow().values() { | |
| let geometry = ®istration.registration; | |
| if geometry.scope != self.active_scope || registration.participant.upgrade().is_none() { | |
| continue; | |
| } | |
| let Some((edge_start, edge_end)) = geometry.selection_edges else { | |
| continue; | |
| }; | |
| let order = geometry.document_order; | |
| let viewport = geometry.hitbox.bounds; | |
| if start.is_none_or(|(best, ..)| order < best) { | |
| start = Some((order, edge_start, caret_in_view(edge_start, viewport))); | |
| } | |
| if end.is_none_or(|(best, ..)| order >= best) { | |
| end = Some((order, edge_end, caret_in_view(edge_end, viewport))); | |
| } | |
| } | |
| let edges = match (start, end) { | |
| (Some((_, start, start_visible)), Some((_, end, end_visible))) => { | |
| let edges = (start, end, start_visible, end_visible); | |
| self.touch.last_edges.set(Some(edges)); | |
| edges | |
| } | |
| _ if self.touch.drag.is_some() => self.touch.last_edges.get()?, | |
| _ => return None, | |
| }; | |
| let (start, end, start_visible, end_visible) = edges; | |
| Some( | |
| TouchSelectionSnapshot::new(start, end) | |
| .with_edge_visible(SelectionEdge::Start, start_visible) | |
| .with_edge_visible(SelectionEdge::End, end_visible) | |
| .with_menu_open(self.touch.menu_open) | |
| .with_dragging( | |
| self.is_selecting() | |
| .then(|| self.touch.drag.map(|drag| drag.edge())) | |
| .flatten(), | |
| ), | |
| ) | |
| } | |
| /// The handles `participant` paints: the start when no participant | |
| /// earlier in document order has a selection end, the end when none | |
| /// later has. Participants paint in document order, so a later one that | |
| /// takes the end over has registered its ends by the time it asks. | |
| fn touch_handles_of(&self, participant: EntityId) -> Vec<(SelectionEdge, Bounds<Pixels>)> { | |
| if !self.touch.active { | |
| return Vec::new(); | |
| } | |
| let Some(own) = self.participants.borrow().get(&participant).cloned() else { | |
| return Vec::new(); | |
| }; | |
| let Some((start, end)) = own.registration.selection_edges else { | |
| return Vec::new(); | |
| }; | |
| if start == end { | |
| return Vec::new(); | |
| } | |
| let order = own.registration.document_order; | |
| let participants = self.participants.borrow(); | |
| let others = participants.iter().filter(|(id, registration)| { | |
| **id != participant | |
| && registration.registration.scope == self.active_scope | |
| && registration.registration.selection_edges.is_some() | |
| && registration.participant.upgrade().is_some() | |
| }); | |
| let (mut earlier, mut later) = (false, false); | |
| for (_, registration) in others { | |
| let other = registration.registration.document_order; | |
| earlier |= other < order; | |
| later |= other > order; | |
| } | |
| let viewport = own.registration.hitbox.bounds; | |
| let mut handles = Vec::with_capacity(2); | |
| if !earlier && caret_in_view(start, viewport) { | |
| handles.push((SelectionEdge::Start, start)); | |
| } | |
| if !later && caret_in_view(end, viewport) { | |
| handles.push((SelectionEdge::End, end)); | |
| } | |
| handles | |
| } | |
| /// Keeps the selection a long press made, and opens the edit menu over it. | |
| fn keep_touch_selection(&mut self, cx: &mut App) { | |
| self.touch.active = self.snapshot().is_some(); | |
| self.touch.menu_open = self.touch.active; | |
| self.touch.drag = None; | |
| self.touch_changed(cx); | |
| } | |
| /// Records where the handles and the menu are painted this frame. | |
| fn register_touch_ui(&mut self, hitbox: HitboxId) { | |
| if !self.touch.ui_hitboxes.contains(&hitbox) { | |
| self.touch.ui_hitboxes.push(hitbox); | |
| } | |
| } | |
| fn close_edit_menu(&mut self, cx: &mut App) { | |
| if !self.touch.menu_open { | |
| return; | |
| } | |
| self.touch.menu_open = false; | |
| self.touch_changed(cx); | |
| } | |
| /// The handles follow the text, but the menu would sit over whatever | |
| /// scrolls underneath it: it steps aside while a finger scrolls and comes | |
| /// back over the handles once the finger lifts. | |
| fn edit_menu_on_scroll(&mut self, phase: TouchPhase, cx: &mut App) { | |
| if !self.touch.active || self.touch.drag.is_some() { | |
| return; | |
| } | |
| match phase { | |
| TouchPhase::Ended | TouchPhase::Cancelled => { | |
| if !self.touch.menu_open { | |
| self.touch.menu_open = true; | |
| self.touch_changed(cx); | |
| } | |
| } | |
| _ => self.close_edit_menu(cx), | |
| } | |
| } | |
| /// Selects all of the participant the touch selection started in. | |
| /// | |
| /// This stays a point selection — anchored on the participant's first | |
| /// line of text, ending on its last — rather than switching the | |
| /// participant to a local select-all: one selection, painted, reported | |
| /// and copied the one way, with handles that drag on from its ends. | |
| fn select_all_touched(&mut self, cx: &mut App) { | |
| if !self.touch.active { | |
| return; | |
| } | |
| let Some((participant, registration)) = self.anchor_registration() else { | |
| return; | |
| }; | |
| // From the participant's text runs, not its painted line bounds: | |
| // those are clipped to the viewport, and a message taller than the | |
| // screen would only select what is on it. | |
| let (anchor, cursor) = { | |
| let runs = &participant.read(cx).runs.borrow(); | |
| let (Some(first), Some(last)) = ( | |
| runs.iter().min_by_key(|run| run.document_order), | |
| runs.iter().max_by_key(|run| run.document_order), | |
| ) else { | |
| return; | |
| }; | |
| let (Some(start), Some(end)) = ( | |
| first.position_for_index(0), | |
| last.position_for_index(last.text.len()), | |
| ) else { | |
| return; | |
| }; | |
| // Just inside the first and the last glyph, mid-line, so both | |
| // land on text. | |
| let inset = px(1.); | |
| ( | |
| point(start.x + inset, start.y + first.layout.line_height() / 2.), | |
| point(end.x - inset, end.y + last.layout.line_height() / 2.), | |
| ) | |
| }; | |
| let content_key_resolver = participant.read(cx).content_key_resolver.clone(); | |
| let to_endpoint = |window_point: Point<Pixels>| { | |
| let content_point = | |
| window_point - registration.bounds.origin - registration.scroll_offset; | |
| SelectionEndpoint { | |
| participant: Some(participant.downgrade()), | |
| point: content_point, | |
| inside: true, | |
| inside_text: true, | |
| content_key: None, | |
| content_key_resolver: content_key_resolver | |
| .clone() | |
| .map(|resolver| (resolver, content_point)), | |
| } | |
| }; | |
| self.anchor = Some(to_endpoint(anchor)); | |
| self.cursor = Some(to_endpoint(cursor)); | |
| self.did_hit_text = true; | |
| self.selecting = None; | |
| self.touch.menu_open = true; | |
| self.publish_snapshots(cx); | |
| self.touch_changed(cx); | |
| } | |
| /// Starts dragging one end of the touch selection from `finger`. | |
| /// | |
| /// The selection is rebuilt from the painted ends, anchored at the end that | |
| /// stays: a select-all or a word selection becomes an ordinary point | |
| /// selection which the drag then extends. | |
| fn begin_edge_drag( | |
| &mut self, | |
| edge: SelectionEdge, | |
| finger: Point<Pixels>, | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) { | |
| let gesture = window.input_gesture(); | |
| let Some(snapshot) = self.touch_selection() else { | |
| return; | |
| }; | |
| let handlers = self.prepare_for_mouse_down(false, cx); | |
| dispatch_clear_handlers(handlers, cx); | |
| if !gesture.is_current() { | |
| return; | |
| } | |
| let held = snapshot.edge(edge.opposite()); | |
| // Just inside the held end, so the anchor lands on the character it | |
| // marks rather than on the boundary between two participants. | |
| let nudge = px(1.); | |
| let anchor_point = match edge { | |
| SelectionEdge::Start => point(held.left() - nudge, held.center().y), | |
| SelectionEdge::End => point(held.left() + nudge, held.center().y), | |
| }; | |
| let anchor = self.endpoint(anchor_point, None, cx); | |
| let drag = EdgeDrag::begin(edge, snapshot.edge(edge), finger); | |
| let cursor = self.endpoint(drag.text_position(finger), Some(window), cx); | |
| self.did_hit_text = anchor.inside_text || cursor.inside_text; | |
| self.anchor = Some(anchor); | |
| self.cursor = Some(cursor); | |
| self.selecting = Some(gesture); | |
| self.touch.active = true; | |
| self.touch.menu_open = false; | |
| self.touch.drag = Some(drag); | |
| self.publish_snapshots(cx); | |
| self.touch_changed(cx); | |
| } | |
| fn update_edge_drag(&mut self, finger: Point<Pixels>, window: &Window, cx: &mut Context<Self>) { | |
| self.retire_interrupted_gesture(cx); | |
| let Some(drag) = self.touch.drag else { | |
| return; | |
| }; | |
| let before = self.cursor.clone(); | |
| self.update_in_window(drag.text_position(finger), window, cx); | |
| // A handle never collapses the selection: at the other end it stops, | |
| // and the finger has to pass that end, onto text, to swap the two. | |
| if !self.selects_text(cx) { | |
| self.cursor = before; | |
| self.publish_snapshots(cx); | |
| return; | |
| } | |
| // Dragging one end past the other swaps them: the cursor now lies | |
| // before the anchor, so the finger holds what became the start. | |
| if let Some(points) = self | |
| .snapshot() | |
| .and_then(|snapshot| snapshot.window_points()) | |
| { | |
| let (anchor, cursor) = (points.anchor(), points.cursor()); | |
| let cursor_first = cursor.y < anchor.y || (cursor.y == anchor.y && cursor.x < anchor.x); | |
| let edge = if cursor_first { | |
| SelectionEdge::Start | |
| } else { | |
| SelectionEdge::End | |
| }; | |
| if let Some(drag) = self.touch.drag.as_mut() { | |
| drag.set_edge(edge); | |
| } | |
| } | |
| self.touch_changed(cx); | |
| } | |
| fn end_edge_drag(&mut self, cx: &mut App) { | |
| if self.touch.drag.take().is_none() { | |
| return; | |
| } | |
| self.end(cx); | |
| self.keep_touch_selection(cx); | |
| } | |
| fn begin_in_window( | |
| &mut self, | |
| position: Point<Pixels>, | |
| extend: bool, | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) { | |
| let gesture = window.input_gesture(); | |
| self.begin_impl(position, extend, true, Some(window), gesture, cx); | |
| } | |
| fn update_in_window( | |
| &mut self, | |
| position: Point<Pixels>, | |
| window: &Window, | |
| cx: &mut Context<Self>, | |
| ) { | |
| self.retire_interrupted_gesture(cx); | |
| if !cx.has_active_drag() { | |
| self.update_impl(position, Some(window), cx); | |
| self.update_auto_scroll(position, window, cx); | |
| } | |
| } | |
| fn select_at( | |
| &mut self, | |
| position: Point<Pixels>, | |
| click_count: usize, | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) { | |
| GlobalState::init(cx); | |
| if GlobalState::is_text_selection_suppressed(cx) { | |
| return; | |
| } | |
| let hit = self.endpoint(position, Some(window), cx); | |
| if !hit.inside_text { | |
| return; | |
| } | |
| let Some(participant) = hit | |
| .participant | |
| .and_then(|participant| participant.upgrade()) | |
| else { | |
| return; | |
| }; | |
| let points = | |
| points_for_multi_click(&participant.read(cx).runs.borrow(), position, click_count); | |
| let Some((anchor, cursor)) = points else { | |
| return; | |
| }; | |
| let Some(registration) = self | |
| .participants | |
| .borrow() | |
| .get(&participant.entity_id()) | |
| .cloned() | |
| else { | |
| return; | |
| }; | |
| let content_key_resolver = participant.read(cx).content_key_resolver.clone(); | |
| let to_endpoint = |point: Point<Pixels>| { | |
| let content_point = point | |
| - registration.registration.bounds.origin | |
| - registration.registration.scroll_offset; | |
| SelectionEndpoint { | |
| participant: Some(participant.downgrade()), | |
| point: content_point, | |
| inside: true, | |
| inside_text: true, | |
| content_key: None, | |
| content_key_resolver: content_key_resolver | |
| .clone() | |
| .map(|resolver| (resolver, content_point)), | |
| } | |
| }; | |
| self.anchor = Some(to_endpoint(anchor)); | |
| self.cursor = Some(to_endpoint(cursor)); | |
| self.did_hit_text = true; | |
| self.selecting = None; | |
| participant.update(cx, |state, cx| state.focus(window, cx)); | |
| self.publish_snapshots(cx); | |
| } | |
| #[cfg(test)] | |
| fn update_in_window_with_active_drag( | |
| &mut self, | |
| position: Point<Pixels>, | |
| active_drag: bool, | |
| window: &Window, | |
| cx: &mut App, | |
| ) { | |
| if !active_drag { | |
| self.update_impl(position, Some(window), cx); | |
| } | |
| } | |
| fn begin_impl( | |
| &mut self, | |
| position: Point<Pixels>, | |
| extend: bool, | |
| already_prepared: bool, | |
| window: Option<&mut Window>, | |
| gesture: gpui::InputGesture, | |
| cx: &mut App, | |
| ) { | |
| GlobalState::init(cx); | |
| if GlobalState::is_text_selection_suppressed(cx) { | |
| self.pending_extension_anchor = None; | |
| return; | |
| } | |
| let previous_anchor = extend | |
| .then(|| { | |
| self.pending_extension_anchor | |
| .take() | |
| .or_else(|| self.anchor.clone()) | |
| }) | |
| .flatten() | |
| .filter(|anchor| anchor.resolve(&self.participants.borrow()).is_some()); | |
| if !extend && !already_prepared { | |
| self.clear(cx); | |
| } | |
| if !gesture.is_current() { | |
| return; | |
| } | |
| let endpoint = self.endpoint(position, window.as_deref(), cx); | |
| let focus_participant = endpoint | |
| .inside | |
| .then(|| endpoint.participant.clone()) | |
| .flatten(); | |
| let anchor = previous_anchor.unwrap_or_else(|| endpoint.clone()); | |
| self.anchor = Some(anchor.clone()); | |
| self.cursor = Some(endpoint.clone()); | |
| self.did_hit_text = anchor.inside_text || endpoint.inside_text; | |
| self.selecting = Some(gesture); | |
| if let Some(participant) = focus_participant.and_then(|participant| participant.upgrade()) { | |
| if let Some(window) = window { | |
| participant.update(cx, |state, cx| state.focus(window, cx)); | |
| } | |
| } | |
| self.publish_snapshots(cx); | |
| } | |
| fn update_impl(&mut self, position: Point<Pixels>, window: Option<&Window>, cx: &mut App) { | |
| if !self.is_selecting() { | |
| return; | |
| } | |
| let endpoint = self.endpoint(position, window, cx); | |
| self.did_hit_text |= endpoint.inside_text; | |
| self.cursor = Some(endpoint); | |
| if window.is_none() { | |
| self.update_participant_auto_scroll(position, cx); | |
| } | |
| self.publish_snapshots(cx); | |
| } | |
| fn endpoint( | |
| &mut self, | |
| position: Point<Pixels>, | |
| window: Option<&Window>, | |
| cx: &App, | |
| ) -> SelectionEndpoint { | |
| self.prune_dead_participants(cx); | |
| let mut hit: Option<( | |
| WeakEntity<SelectableTextState>, | |
| Rc<TextSelectionRegistration>, | |
| f32, | |
| )> = None; | |
| let mut predecessor: Option<( | |
| WeakEntity<SelectableTextState>, | |
| Rc<TextSelectionRegistration>, | |
| )> = None; | |
| let mut first: Option<( | |
| WeakEntity<SelectableTextState>, | |
| Rc<TextSelectionRegistration>, | |
| )> = None; | |
| for registration in self.participants.borrow().values() { | |
| if registration | |
| .participant | |
| .upgrade() | |
| .is_none_or(|participant| !participant.read(cx).enabled) | |
| { | |
| continue; | |
| } | |
| if registration.registration.scope != self.active_scope | |
| || registration.participant.upgrade().is_none() | |
| { | |
| continue; | |
| } | |
| let participant_geometry = ®istration.registration; | |
| let hovered = window.map_or_else( | |
| || participant_geometry.bounds.contains(&position), | |
| |window| participant_geometry.hitbox.is_hovered(window), | |
| ); | |
| if hovered { | |
| let area = f32::from(participant_geometry.bounds.size.width) | |
| * f32::from(participant_geometry.bounds.size.height); | |
| if hit.as_ref().is_none_or(|(_, best, best_area)| { | |
| area < *best_area | |
| || (area == *best_area | |
| && participant_geometry.document_order < best.document_order) | |
| }) { | |
| hit = Some(( | |
| registration.participant.clone(), | |
| participant_geometry.clone(), | |
| area, | |
| )); | |
| } | |
| } | |
| if participant_geometry.bounds.top() <= position.y | |
| && predecessor.as_ref().is_none_or(|(_, best)| { | |
| participant_geometry.bounds.top() > best.bounds.top() | |
| || (participant_geometry.bounds.top() == best.bounds.top() | |
| && participant_geometry.document_order < best.document_order) | |
| }) | |
| { | |
| predecessor = Some(( | |
| registration.participant.clone(), | |
| participant_geometry.clone(), | |
| )); | |
| } | |
| if first.as_ref().is_none_or(|(_, best)| { | |
| participant_geometry.bounds.top() < best.bounds.top() | |
| || (participant_geometry.bounds.top() == best.bounds.top() | |
| && participant_geometry.document_order < best.document_order) | |
| }) { | |
| first = Some(( | |
| registration.participant.clone(), | |
| participant_geometry.clone(), | |
| )); | |
| } | |
| } | |
| let selection = hit | |
| .map(|(participant, registration, _)| (participant, registration, true)) | |
| .or_else(|| { | |
| predecessor | |
| .or(first) | |
| .map(|(participant, registration)| (participant, registration, false)) | |
| }); | |
| match selection { | |
| Some((participant, registration, inside)) => { | |
| let point = position - registration.bounds.origin - registration.scroll_offset; | |
| let content_key_resolver = participant.upgrade().and_then(|participant| { | |
| participant | |
| .read(cx) | |
| .content_key_resolver | |
| .clone() | |
| .map(|callback| (callback, point)) | |
| }); | |
| SelectionEndpoint { | |
| point, | |
| participant: Some(participant), | |
| inside, | |
| inside_text: inside | |
| && registration | |
| .text_bounds | |
| .iter() | |
| .any(|bounds| bounds.contains(&position)), | |
| content_key: None, | |
| content_key_resolver, | |
| } | |
| } | |
| None => SelectionEndpoint { | |
| participant: None, | |
| point: position, | |
| inside: false, | |
| inside_text: false, | |
| content_key: None, | |
| content_key_resolver: None, | |
| }, | |
| } | |
| } | |
| fn publish_snapshots(&mut self, cx: &mut App) { | |
| self.prune_dead_participants(cx); | |
| let snapshot = self.snapshot(); | |
| let single_participant = self.single_participant(); | |
| for (id, registration) in self.participants.borrow().iter() { | |
| let Some(participant) = registration.participant.upgrade() else { | |
| continue; | |
| }; | |
| let participant_snapshot = (registration.registration.scope == self.active_scope | |
| && self.participates(*id, registration) | |
| && single_participant.is_none_or(|single| single == *id)) | |
| .then_some(snapshot) | |
| .flatten() | |
| .map(|mut snapshot| { | |
| snapshot.coverage = self.coverage_for(*id); | |
| snapshot | |
| }); | |
| let current = participant.read(cx); | |
| let participant_snapshot = current.enabled.then_some(participant_snapshot).flatten(); | |
| if current.snapshot != participant_snapshot { | |
| participant.update(cx, |state, cx| state.set_snapshot(participant_snapshot, cx)); | |
| } | |
| } | |
| } | |
| fn coverage_for(&self, id: EntityId) -> TextSelectionCoverage { | |
| let Some(anchor) = self.anchor.as_ref().and_then(SelectionEndpoint::entity_id) else { | |
| return TextSelectionCoverage::Bounded; | |
| }; | |
| let Some(cursor) = self.cursor.as_ref().and_then(SelectionEndpoint::entity_id) else { | |
| return TextSelectionCoverage::Bounded; | |
| }; | |
| if anchor == cursor { | |
| return TextSelectionCoverage::Bounded; | |
| } | |
| let anchor_order = self.participants.borrow()[&anchor] | |
| .registration | |
| .document_order; | |
| let cursor_order = self.participants.borrow()[&cursor] | |
| .registration | |
| .document_order; | |
| if id != anchor && id != cursor { | |
| TextSelectionCoverage::Full | |
| } else if (id == anchor) == (anchor_order < cursor_order) { | |
| TextSelectionCoverage::ToEnd | |
| } else { | |
| TextSelectionCoverage::FromStart | |
| } | |
| } | |
| fn single_participant(&self) -> Option<EntityId> { | |
| let anchor = self.anchor.as_ref()?.entity_id()?; | |
| let cursor = self.cursor.as_ref()?.entity_id()?; | |
| (anchor == cursor).then_some(anchor) | |
| } | |
| fn participates(&self, id: EntityId, registration: &ParticipantRegistration) -> bool { | |
| let Some(anchor) = self.anchor.as_ref().and_then(SelectionEndpoint::entity_id) else { | |
| return false; | |
| }; | |
| let Some(cursor) = self.cursor.as_ref().and_then(SelectionEndpoint::entity_id) else { | |
| return false; | |
| }; | |
| let Some(anchor_registration) = self.participants.borrow().get(&anchor).cloned() else { | |
| return false; | |
| }; | |
| let Some(cursor_registration) = self.participants.borrow().get(&cursor).cloned() else { | |
| return false; | |
| }; | |
| let start = anchor_registration | |
| .registration | |
| .document_order | |
| .min(cursor_registration.registration.document_order); | |
| let end = anchor_registration | |
| .registration | |
| .document_order | |
| .max(cursor_registration.registration.document_order); | |
| (start..=end).contains(®istration.registration.document_order) | |
| || id == anchor | |
| || id == cursor | |
| } | |
| fn update_auto_scroll( | |
| &mut self, | |
| position: Point<Pixels>, | |
| window: &Window, | |
| cx: &mut Context<Self>, | |
| ) { | |
| // A finished gesture keeps its anchor for shift-click extension; only | |
| // a live drag may scroll. | |
| if !self.is_selecting() { | |
| return; | |
| } | |
| let Some((_, registration)) = self.anchor_registration() else { | |
| return; | |
| }; | |
| // Exactly one writer per drag: a participant that scrolls its own | |
| // content is notified directly; anything else gets a synthetic wheel. | |
| if registration.self_scroll { | |
| self.auto_scroll.stop(); | |
| self.update_participant_auto_scroll(position, cx); | |
| return; | |
| } | |
| // The content mask is the nearest clipping viewport established by a | |
| // scrollable ancestor. It remains stable as the participant itself | |
| // moves, so selection keeps scrolling the same related region even | |
| // after the anchor text has moved out of view. | |
| let visible_bounds = registration.hitbox.content_mask.bounds; | |
| // Keeps the synthesized wheel event hit-testing inside the mask. | |
| const HIT_TEST_INSET: Pixels = px(1.); | |
| // A collapsed mask leaves an empty clamp range below — stop. | |
| if visible_bounds.size.width < HIT_TEST_INSET * 2. | |
| || visible_bounds.size.height < HIT_TEST_INSET * 2. | |
| { | |
| self.stop_anchor_auto_scroll(cx); | |
| return; | |
| } | |
| let delta = AutoScroll::compute_delta(position.y, visible_bounds); | |
| let event_position = point( | |
| position.x.clamp( | |
| visible_bounds.left() + HIT_TEST_INSET, | |
| visible_bounds.right() - HIT_TEST_INSET, | |
| ), | |
| position.y.clamp( | |
| visible_bounds.top() + HIT_TEST_INSET, | |
| visible_bounds.bottom() - HIT_TEST_INSET, | |
| ), | |
| ); | |
| self.auto_scroll.last_drag_position = Some(event_position); | |
| self.auto_scroll_stall = (None, 0); | |
| let window = window.window_handle(); | |
| let Some(anchor) = self.anchor_participant() else { | |
| return; | |
| }; | |
| let admission = Arc::downgrade(&anchor.read(cx).admission); | |
| let gesture = self.selecting.as_ref().unwrap().downgrade(); | |
| let deferred_gesture = gesture.clone(); | |
| self.auto_scroll | |
| .set(delta, gesture, cx, move |delta, state, cx| { | |
| if admission.upgrade().is_none() || !state.is_selecting() { | |
| return; | |
| } | |
| let Some(position) = state.auto_scroll.last_drag_position else { | |
| return; | |
| }; | |
| // Hold off once the container has shown, over a few ticks, that | |
| // it has nowhere left to go; the next move of the finger asks | |
| // again. | |
| const STALLED_TICKS: u8 = 3; | |
| let geometry = state | |
| .anchor_registration() | |
| .map(|(_, registration)| (registration.bounds, registration.scroll_offset)); | |
| let (last, stalled) = &mut state.auto_scroll_stall; | |
| if *last == geometry { | |
| *stalled = stalled.saturating_add(1); | |
| if *stalled >= STALLED_TICKS { | |
| return; | |
| } | |
| } else { | |
| *last = geometry; | |
| *stalled = 0; | |
| } | |
| let window = window; | |
| let admission = admission.clone(); | |
| let gesture = deferred_gesture.clone(); | |
| cx.defer(move |cx| { | |
| if admission.upgrade().is_none() || !gesture.is_current() { | |
| return; | |
| } | |
| _ = window.update(cx, |_, window, cx| { | |
| if !gesture.is_current() { | |
| return; | |
| } | |
| window.dispatch_event( | |
| ScrollWheelEvent { | |
| position, | |
| delta: ScrollDelta::Pixels(point(px(0.), -delta)), | |
| ..Default::default() | |
| } | |
| .to_platform_input(), | |
| cx, | |
| ); | |
| }); | |
| }); | |
| }); | |
| } | |
| /// Drives the anchor participant's own scrolling, measured against the | |
| /// visible portion of the participant's element bounds. | |
| fn update_participant_auto_scroll(&self, position: Point<Pixels>, cx: &mut App) { | |
| let Some((participant, registration)) = self.anchor_registration() else { | |
| return; | |
| }; | |
| let visible_bounds = registration | |
| .bounds | |
| .intersect(®istration.hitbox.content_mask.bounds); | |
| let delta = if visible_bounds.size.width > px(0.) && visible_bounds.size.height > px(0.) { | |
| AutoScroll::compute_delta(position.y, visible_bounds) | |
| } else { | |
| None | |
| }; | |
| let Some(gesture) = self | |
| .selecting | |
| .as_ref() | |
| .filter(|gesture| gesture.is_current()) | |
| .map(gpui::InputGesture::downgrade) | |
| else { | |
| return; | |
| }; | |
| participant.update(cx, |state, cx| state.set_auto_scroll(delta, gesture, cx)); | |
| } | |
| fn stop_anchor_auto_scroll(&mut self, cx: &mut App) { | |
| self.auto_scroll.stop(); | |
| let Some(participant) = self.anchor_participant() else { | |
| return; | |
| }; | |
| if let Some(gesture) = self.selecting.as_ref().map(gpui::InputGesture::downgrade) { | |
| participant.update(cx, |state, cx| state.set_auto_scroll(None, gesture, cx)); | |
| } | |
| } | |
| /// The live participant owning the anchor of the current gesture. | |
| fn anchor_participant(&self) -> Option<Entity<SelectableTextState>> { | |
| self.anchor | |
| .as_ref() | |
| .filter(|anchor| anchor.inside)? | |
| .participant | |
| .as_ref()? | |
| .upgrade() | |
| } | |
| /// The anchor participant together with its current frame registration. | |
| fn anchor_registration( | |
| &self, | |
| ) -> Option<(Entity<SelectableTextState>, Rc<TextSelectionRegistration>)> { | |
| let participant = self.anchor_participant()?; | |
| let registration = self | |
| .participants | |
| .borrow() | |
| .get(&participant.entity_id())? | |
| .clone(); | |
| Some((participant, registration.registration.clone())) | |
| } | |
| fn prune_dead_participants(&mut self, cx: &App) { | |
| let owner = self.entity_id; | |
| self.participants.get_mut().retain(|_, registration| { | |
| registration | |
| .participant | |
| .upgrade() | |
| .is_some_and(|participant| { | |
| owner.is_none_or(|owner| { | |
| participant | |
| .read(cx) | |
| .group | |
| .as_ref() | |
| .is_some_and(|group| group.owner.entity_id() == owner) | |
| }) | |
| }) | |
| }); | |
| } | |
| } | |
| #[derive(Default)] | |
| /// Non-owning window locator; retained [`TextSelection`] element state owns | |
| /// each live selection entity. | |
| struct SelectionStateRegistry(HashMap<SelectionGroupKey, WeakEntity<WindowSelectionState>>); | |
| impl Global for SelectionStateRegistry {} | |
| // One inherited scope in the original Window, also restored for retained gaps. | |
| // Actual selection ownership stays in the original window/participant state. | |
| pub(crate) fn current_text_selection_scope(window: &Window) -> Option<TextSelectionScopeId> { | |
| window | |
| .text_selection_scope_context() | |
| .map(TextSelectionScopeId) | |
| } | |
| /// Window-level operations for text selection. | |
| pub struct TextSelection; | |
| impl TextSelection { | |
| /// Returns whether `position` hits selectable text in the active scope. | |
| /// | |
| /// Uses the current frame's registered text geometry and hitboxes without | |
| /// starting or changing a selection. Blank space and text outside the active | |
| /// selection scope do not match. A containing control can yield a long press | |
| /// to the window's text selection before claiming the gesture itself. | |
| /// Call during pointer dispatch with the event's position, so the hitboxes | |
| /// reflect the point being queried. Touch-selection controls do not match. | |
| pub fn is_selectable_at(position: Point<Pixels>, window: &Window, cx: &mut App) -> bool { | |
| live_text_selection_state(window, cx).is_some_and(|state| { | |
| state.update(cx, |state, cx| { | |
| !state.touch.covers(position, window) | |
| && state.endpoint(position, Some(window), cx).inside_text | |
| }) | |
| }) | |
| } | |
| /// Returns the currently selected text in logical document order. | |
| pub fn selected_text(window: &mut Window, cx: &mut App) -> String { | |
| let Some(state) = live_text_selection_state(window, cx) else { | |
| return String::new(); | |
| }; | |
| let items = state.read(cx).copy_items(cx); | |
| resolve_copy_items(items, cx) | |
| } | |
| /// Returns whether the window has a geometry selection or any participant | |
| /// has an active participant-local selection such as select-all. | |
| pub fn has_selection(window: &mut Window, cx: &mut App) -> bool { | |
| live_text_selection_state(window, cx).is_some_and(|state| state.read(cx).has_selection(cx)) | |
| } | |
| /// Whether this original scope has a geometry selection, an active selection | |
| /// gesture (including its initial collapsed range), or local selection. | |
| /// Unrelated window scopes do not participate. Reads the original registered | |
| /// participants; does not copy text, dispatch input or create selection state. | |
| pub fn has_selection_in_scope( | |
| scope: TextSelectionScopeId, | |
| window: &Window, | |
| cx: &mut App, | |
| ) -> bool { | |
| live_text_selection_state(window, cx) | |
| .is_some_and(|state| state.read(cx).has_selection_in_scope(scope, cx)) | |
| } | |
| /// Observe the already painted owner for this element's original native placement. | |
| pub fn group_for_element(window: &Window, cx: &App) -> Option<TextSelectionGroup> { | |
| let key = placement_group(window); | |
| Some(TextSelectionGroup { | |
| key, | |
| owner: WindowSelectionState::at(key, cx)?.downgrade(), | |
| }) | |
| } | |
| /// Clears window selection and every participant's local selection. | |
| pub fn clear(window: &mut Window, cx: &mut App) { | |
| if let Some(state) = live_text_selection_state(window, cx) { | |
| let handlers = state.update(cx, |state, cx| state.clear_state(cx)); | |
| dispatch_clear_handlers(handlers, cx); | |
| } | |
| } | |
| /// Ends the current drag while leaving its selection visible. | |
| pub fn end(window: &mut Window, cx: &mut App) { | |
| if let Some(state) = live_text_selection_state(window, cx) { | |
| state.update(cx, |state, cx| state.end(cx)); | |
| } | |
| } | |
| /// Calls `callback` whenever the touch selection changes: it appears, its | |
| /// handles move, its menu opens or closes, or it goes away. Whoever draws | |
| /// the handles and the menu re-renders from here. | |
| pub fn observe_touch_selection( | |
| window: &Window, | |
| cx: &mut App, | |
| callback: impl Fn(&mut App) + 'static, | |
| ) -> Option<Subscription> { | |
| let state = WindowSelectionState::existing(window, cx)?; | |
| Some(cx.observe(&state, move |_, cx| callback(cx))) | |
| } | |
| /// Returns the selection a long press made, laid out for its handles and | |
| /// edit menu, or `None` when the selection was made with a pointer. | |
| pub fn touch_selection(window: &Window, cx: &App) -> Option<TouchSelectionSnapshot> { | |
| WindowSelectionState::existing(window, cx)? | |
| .read(cx) | |
| .touch_selection() | |
| } | |
| /// Reports the actual touch handle/menu hitbox so a press preserves its | |
| /// selection. Native retained frame custody determines its geometry and | |
| /// lifetime; old rectangles cannot protect unrelated text after a reflow. | |
| pub fn register_touch_ui(hitbox: &Hitbox, window: &Window, cx: &mut App) { | |
| if let Some(state) = WindowSelectionState::existing(window, cx) { | |
| state.query(cx, |state, _| state.register_touch_ui(hitbox.id)); | |
| } | |
| } | |
| /// Closes the edit menu and keeps the selection with its handles. | |
| pub fn close_edit_menu(window: &mut Window, cx: &mut App) { | |
| if let Some(state) = live_text_selection_state(window, cx) { | |
| state.update(cx, |state, cx| state.close_edit_menu(cx)); | |
| } | |
| } | |
| /// Selects all of the text the touch selection started in, keeping the | |
| /// handles and the edit menu over the result. | |
| pub fn select_all(window: &mut Window, cx: &mut App) { | |
| if let Some(state) = live_text_selection_state(window, cx) { | |
| state.update(cx, |state, cx| state.select_all_touched(cx)); | |
| } | |
| } | |
| /// Starts dragging one end of the touch selection from `finger`. The other | |
| /// end stays; the menu closes until [`Self::end_edge_drag`]. | |
| pub fn begin_edge_drag( | |
| edge: SelectionEdge, | |
| finger: Point<Pixels>, | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) { | |
| if let Some(state) = live_text_selection_state(window, cx) { | |
| state.update(cx, |state, cx| { | |
| state.begin_edge_drag(edge, finger, window, cx) | |
| }); | |
| WindowSelectionState::resolve_content_keys(&state, cx); | |
| } | |
| } | |
| /// Moves the dragged end to the text under `finger`. | |
| pub fn update_edge_drag(finger: Point<Pixels>, window: &mut Window, cx: &mut App) { | |
| if let Some(state) = live_text_selection_state(window, cx) { | |
| state.update(cx, |state, cx| state.update_edge_drag(finger, window, cx)); | |
| WindowSelectionState::resolve_content_keys(&state, cx); | |
| } | |
| } | |
| /// Ends the handle drag and reopens the edit menu over the result. | |
| pub fn end_edge_drag(window: &mut Window, cx: &mut App) { | |
| if let Some(state) = live_text_selection_state(window, cx) { | |
| state.update(cx, |state, cx| state.end_edge_drag(cx)); | |
| } | |
| } | |
| /// Activates the opaque selection scope for this window. | |
| pub fn activate_scope(scope: TextSelectionScopeId, window: &mut Window, cx: &mut App) { | |
| let Some(state) = WindowSelectionState::existing(window, cx) else { | |
| return; | |
| }; | |
| if state.read(cx).active_scope == scope { | |
| return; | |
| } | |
| let handlers = state.update(cx, |state, cx| state.set_active_scope_state(scope, cx)); | |
| dispatch_clear_handlers(handlers, cx); | |
| } | |
| } | |
| /// A zero-sized root layer which enables text selection for a window. | |
| /// | |
| /// Mount one as the root's first child. Its stable `"window-text-selection"` | |
| /// element identity retains the window-local selection entity across frames. | |
| pub struct TextSelectionLayer; | |
| pub(crate) fn text_selection_scope( | |
| scope: TextSelectionScopeId, | |
| element: impl IntoElement, | |
| ) -> impl IntoElement { | |
| TextSelectionScopeMarker { | |
| scope, | |
| element: element.into_element(), | |
| } | |
| } | |
| struct TextSelectionScopeMarker<E> { | |
| scope: TextSelectionScopeId, | |
| element: E, | |
| } | |
| impl<E: Element> IntoElement for TextSelectionScopeMarker<E> { | |
| type Element = Self; | |
| fn into_element(self) -> Self::Element { | |
| self | |
| } | |
| } | |
| impl<E: Element> Element for TextSelectionScopeMarker<E> { | |
| type RequestLayoutState = E::RequestLayoutState; | |
| type PrepaintState = E::PrepaintState; | |
| fn id(&self) -> Option<ElementId> { | |
| self.element.id() | |
| } | |
| fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { | |
| self.element.source_location() | |
| } | |
| fn request_layout( | |
| &mut self, | |
| id: Option<&GlobalElementId>, | |
| inspector_id: Option<&InspectorElementId>, | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) -> (LayoutId, Self::RequestLayoutState) { | |
| window.with_text_selection_scope_context(Some(self.scope.0), |window| { | |
| self.element.request_layout(id, inspector_id, window, cx) | |
| }) | |
| } | |
| fn prepaint( | |
| &mut self, | |
| id: Option<&GlobalElementId>, | |
| inspector_id: Option<&InspectorElementId>, | |
| bounds: Bounds<Pixels>, | |
| request_layout: &mut Self::RequestLayoutState, | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) -> Self::PrepaintState { | |
| window.with_text_selection_scope_context(Some(self.scope.0), |window| { | |
| self.element | |
| .prepaint(id, inspector_id, bounds, request_layout, window, cx) | |
| }) | |
| } | |
| fn paint( | |
| &mut self, | |
| id: Option<&GlobalElementId>, | |
| inspector_id: Option<&InspectorElementId>, | |
| bounds: Bounds<Pixels>, | |
| request_layout: &mut Self::RequestLayoutState, | |
| prepaint: &mut Self::PrepaintState, | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) { | |
| window.with_text_selection_scope_context(Some(self.scope.0), |window| { | |
| self.element.paint( | |
| id, | |
| inspector_id, | |
| bounds, | |
| request_layout, | |
| prepaint, | |
| window, | |
| cx, | |
| ); | |
| }); | |
| } | |
| } | |
| #[doc(hidden)] | |
| pub struct TextSelectionLayerPrepaintState(SelectionGroupKey); | |
| impl IntoElement for TextSelectionLayer { | |
| type Element = Self; | |
| fn into_element(self) -> Self::Element { | |
| self | |
| } | |
| } | |
| impl Element for TextSelectionLayer { | |
| type RequestLayoutState = (); | |
| type PrepaintState = TextSelectionLayerPrepaintState; | |
| fn id(&self) -> Option<ElementId> { | |
| Some("window-text-selection".into()) | |
| } | |
| fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { | |
| None | |
| } | |
| fn request_layout( | |
| &mut self, | |
| _: Option<&GlobalElementId>, | |
| _: Option<&InspectorElementId>, | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) -> (LayoutId, Self::RequestLayoutState) { | |
| (window.request_layout(Style::default(), [], cx), ()) | |
| } | |
| fn prepaint( | |
| &mut self, | |
| _: Option<&GlobalElementId>, | |
| _: Option<&InspectorElementId>, | |
| _: Bounds<Pixels>, | |
| _: &mut (), | |
| window: &mut Window, | |
| _: &mut App, | |
| ) -> Self::PrepaintState { | |
| TextSelectionLayerPrepaintState(placement_group(window)) | |
| } | |
| fn paint( | |
| &mut self, | |
| _: Option<&GlobalElementId>, | |
| _: Option<&InspectorElementId>, | |
| _: Bounds<Pixels>, | |
| _: &mut (), | |
| state: &mut Self::PrepaintState, | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) { | |
| let key = state.0; | |
| let namespace = key | |
| .1 | |
| .map(ElementId::FocusHandle) | |
| .unwrap_or_else(|| "background-selection".into()); | |
| let owner = window.with_global_id(namespace, |slot, window| { | |
| window.with_element_state::<Entity<WindowSelectionState>, _>(slot, |retained, _| { | |
| let owner = retained.unwrap_or_else(|| WindowSelectionState::acquire(key, cx)); | |
| (owner.clone(), owner) | |
| }) | |
| }); | |
| paint_text_selection(&owner, window, cx); | |
| } | |
| } | |
| fn schedule_selection_finish_frame( | |
| state: &Entity<WindowSelectionState>, | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) { | |
| if state.read(cx).schedule_finish_frame() { | |
| let state = state.downgrade(); | |
| window.defer(cx, move |window, cx| { | |
| let Some(state) = state.upgrade() else { | |
| return; | |
| }; | |
| let handlers = state.query(cx, |state, cx| { | |
| let live: std::collections::HashSet<_> = window | |
| .rendered_hitboxes() | |
| .iter() | |
| .map(|hitbox| hitbox.id) | |
| .collect(); | |
| state.touch.ui_hitboxes.retain(|id| live.contains(id)); | |
| // Dispatch IDs are frame-local: resolve the original stable | |
| // handles only after the native tree has completed/replayed. | |
| for participant in state.participants.get_mut().values_mut() { | |
| if let Some(order) = participant | |
| .registration | |
| .native_focus | |
| .as_ref() | |
| .and_then(|focus| window.focus_document_order(focus)) | |
| { | |
| Rc::make_mut(&mut participant.registration).document_order = order; | |
| } | |
| } | |
| state.prune_dead_participants(cx); | |
| if state.finish_frame_quietly(cx) { | |
| Vec::new() | |
| } else { | |
| state.finish_frame(cx) | |
| } | |
| }); | |
| dispatch_clear_handlers(handlers, cx); | |
| // Direct participant scrolling produces no wheel event. Refresh | |
| // the held cursor after paint registers the new scroll geometry. | |
| let refresh_cursor = state.read(cx).refresh_held_cursor; | |
| let refresh_cursor = refresh_cursor | |
| && state.update(cx, |state, cx| { | |
| if std::mem::take(&mut state.refresh_held_cursor) && state.is_selecting() { | |
| // A handle drag holds the finger off the text; keep the | |
| // same offset, or the cursor would hop between the two. | |
| let position = window.mouse_position(); | |
| let position = state | |
| .touch | |
| .drag | |
| .map_or(position, |drag| drag.text_position(position)); | |
| state.update_in_window(position, window, cx); | |
| true | |
| } else { | |
| false | |
| } | |
| }); | |
| if refresh_cursor { | |
| WindowSelectionState::resolve_content_keys(&state, cx); | |
| } | |
| }); | |
| } | |
| } | |
| fn paint_text_selection(state: &Entity<WindowSelectionState>, window: &mut Window, cx: &mut App) { | |
| state.query(cx, |state, cx| state.retire_interrupted_gesture(cx)); | |
| schedule_selection_finish_frame(state, window, cx); | |
| let mouse_down_state = state.downgrade(); | |
| window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| { | |
| if event.button != MouseButton::Left { | |
| return; | |
| } | |
| let Some(state) = mouse_down_state.upgrade() else { | |
| return; | |
| }; | |
| // A press on a handle or on the edit menu acts on the selection; it | |
| // must not clear it. | |
| if state.read(cx).touch.covers(event.position, window) { | |
| return; | |
| } | |
| if phase.capture() { | |
| let gesture = window.input_gesture(); | |
| GlobalState::init(cx); | |
| GlobalState::reset_text_selection_suppression(cx); | |
| let handlers = state.update(cx, |state, cx| { | |
| state | |
| .scope_at(event.position, window, cx, false) | |
| .map_or_else(Vec::new, |scope| state.set_active_scope_state(scope, cx)) | |
| }); | |
| dispatch_clear_handlers(handlers, cx); | |
| if !gesture.is_current() { | |
| return; | |
| } | |
| let handlers = state.update(cx, |state, cx| { | |
| if state.mouse_down_prepared { | |
| return Vec::new(); | |
| } | |
| state.mouse_down_prepared = true; | |
| state.prepare_for_mouse_down(event.click_count == 1 && event.modifiers.shift, cx) | |
| }); | |
| dispatch_clear_handlers(handlers, cx); | |
| } else if event.click_count == 1 { | |
| if GlobalState::is_text_selection_suppressed(cx) { | |
| state.update(cx, |state, _| state.pending_extension_anchor = None); | |
| return; | |
| } | |
| state.update(cx, |state, cx| { | |
| if !state.is_selecting() { | |
| state.begin_in_window(event.position, event.modifiers.shift, window, cx) | |
| } | |
| }); | |
| WindowSelectionState::resolve_content_keys(&state, cx); | |
| } else if event.click_count >= 2 { | |
| if GlobalState::is_text_selection_suppressed(cx) { | |
| return; | |
| } | |
| let touch = GlobalState::is_touch_press(cx); | |
| state.update(cx, |state, cx| { | |
| state.select_at(event.position, event.click_count, window, cx); | |
| // A double tap is touch's other way to select a word, and it | |
| // gets the handles and the menu like a long press does. | |
| if touch { | |
| state.keep_touch_selection(cx); | |
| } | |
| }); | |
| WindowSelectionState::resolve_content_keys(&state, cx); | |
| } | |
| }); | |
| // Every touch is offered as a drag first; that is how a tap's mouse | |
| // events are later told apart from a mouse's. | |
| window.on_mouse_event(move |event: &TouchDragEvent, phase, _, cx| { | |
| if phase.capture() && event.phase == TouchPhase::Started { | |
| GlobalState::note_touch(cx); | |
| } | |
| }); | |
| // Touch panning remains scrolling until a long press actually hits text. | |
| // Claiming the gesture keeps subsequent moves out of the pan recognizer. | |
| let long_press_state = state.downgrade(); | |
| window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| { | |
| if !phase.bubble() { | |
| return; | |
| } | |
| let Some(state) = long_press_state.upgrade() else { | |
| return; | |
| }; | |
| if event.phase == TouchPhase::Started { | |
| let gesture = window.input_gesture(); | |
| if window.default_prevented() | |
| || state.read(cx).touch.covers(event.start_position, window) | |
| { | |
| return; | |
| } | |
| let Some(scope) = state | |
| .read(cx) | |
| .scope_at(event.start_position, window, cx, true) | |
| else { | |
| return; | |
| }; | |
| let handlers = state.update(cx, |state, cx| state.set_active_scope_state(scope, cx)); | |
| dispatch_clear_handlers(handlers, cx); | |
| if !gesture.is_current() { | |
| return; | |
| } | |
| if !state.update(cx, |state, cx| { | |
| state | |
| .endpoint(event.start_position, Some(window), cx) | |
| .inside_text | |
| }) { | |
| return; | |
| } | |
| GlobalState::init(cx); | |
| GlobalState::reset_text_selection_suppression(cx); | |
| let handlers = state.update(cx, |state, cx| state.prepare_for_mouse_down(false, cx)); | |
| dispatch_clear_handlers(handlers, cx); | |
| if !gesture.is_current() { | |
| return; | |
| } | |
| let selected = state.update(cx, |state, cx| { | |
| state.select_at(event.start_position, 2, window, cx); | |
| if state.anchor.is_some() && gesture.is_current() { | |
| state.selecting = Some(gesture); | |
| state.publish_snapshots(cx); | |
| true | |
| } else { | |
| false | |
| } | |
| }); | |
| if !selected { | |
| return; | |
| } | |
| window.capture_long_press(&state); | |
| } else if !window.has_long_press_capture(&state) { | |
| return; | |
| } else { | |
| state.update(cx, |state, cx| match event.phase { | |
| TouchPhase::Moved => { | |
| state.update_in_window(event.position, window, cx); | |
| } | |
| TouchPhase::Ended | TouchPhase::Cancelled => { | |
| state.end(cx); | |
| // The finger is up; the selection it made gets its | |
| // handles and the edit menu. | |
| state.keep_touch_selection(cx); | |
| } | |
| _ => {} | |
| }); | |
| } | |
| window.prevent_default(); | |
| cx.stop_propagation(); | |
| WindowSelectionState::resolve_content_keys(&state, cx); | |
| }); | |
| // A handle drag in progress follows the finger or the pointer wherever | |
| // it goes, whether or not the handle it took is laid out this frame. | |
| let drag_state = state.downgrade(); | |
| window.on_mouse_event(move |event: &TouchDragEvent, phase, window, cx| { | |
| if !phase.bubble() || event.phase == TouchPhase::Started { | |
| return; | |
| } | |
| let Some(state) = drag_state.upgrade() else { | |
| return; | |
| }; | |
| if state.read(cx).touch.drag.is_none() { | |
| return; | |
| } | |
| cx.stop_propagation(); | |
| state.update(cx, |state, cx| match event.phase { | |
| TouchPhase::Moved => state.update_edge_drag(event.position, window, cx), | |
| _ => state.end_edge_drag(cx), | |
| }); | |
| WindowSelectionState::resolve_content_keys(&state, cx); | |
| }); | |
| let drag_state = state.downgrade(); | |
| window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| { | |
| if phase.bubble() | |
| && event.pressed_button == Some(MouseButton::Left) | |
| && let Some(state) = drag_state.upgrade() | |
| && state.read(cx).touch.drag.is_some() | |
| { | |
| state.update(cx, |state, cx| { | |
| state.update_edge_drag(event.position, window, cx) | |
| }); | |
| WindowSelectionState::resolve_content_keys(&state, cx); | |
| } | |
| }); | |
| let drag_state = state.downgrade(); | |
| window.on_mouse_event(move |event: &MouseUpEvent, phase, _, cx| { | |
| if phase.bubble() | |
| && event.button == MouseButton::Left | |
| && let Some(state) = drag_state.upgrade() | |
| { | |
| state.update(cx, |state, cx| state.end_edge_drag(cx)); | |
| } | |
| }); | |
| let mouse_move_state = state.downgrade(); | |
| window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| { | |
| if phase.bubble() | |
| && let Some(state) = mouse_move_state.upgrade() | |
| && state.read(cx).is_selecting() | |
| && state.read(cx).touch.drag.is_none() | |
| { | |
| state.update(cx, |state, cx| { | |
| state.update_in_window(event.position, window, cx) | |
| }); | |
| WindowSelectionState::resolve_content_keys(&state, cx); | |
| } | |
| }); | |
| let mouse_up_state = state.downgrade(); | |
| window.on_mouse_event(move |_: &MouseUpEvent, phase, _, cx| { | |
| if phase.bubble() | |
| && let Some(state) = mouse_up_state.upgrade() | |
| { | |
| state.update(cx, |state, cx| { | |
| state.mouse_down_prepared = false; | |
| state.end(cx) | |
| }); | |
| } | |
| }); | |
| let scroll_state = state.downgrade(); | |
| window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| { | |
| let Some(state) = scroll_state.upgrade() else { | |
| return; | |
| }; | |
| // On capture, before a scroll container can stop the event: one | |
| // stretched past its end swallows the whole stream, the lift | |
| // included, and the menu would never come back. | |
| if phase.capture() { | |
| if state.read(cx).touch.active && state.read(cx).touch.drag.is_none() { | |
| state.update(cx, |state, cx| { | |
| state.edit_menu_on_scroll(event.touch_phase, cx) | |
| }); | |
| } | |
| return; | |
| } | |
| if phase.bubble() && state.read(cx).is_selecting() { | |
| let position = window.mouse_position(); | |
| state.update(cx, |state, cx| { | |
| // A handle drag holds the finger off the text; keep its offset. | |
| let position = state | |
| .touch | |
| .drag | |
| .map_or(position, |drag| drag.text_position(position)); | |
| state.update_in_window(position, window, cx) | |
| }); | |
| WindowSelectionState::resolve_content_keys(&state, cx); | |
| } | |
| }); | |
| } | |
| fn live_text_selection_state( | |
| window: &Window, | |
| cx: &mut App, | |
| ) -> Option<Entity<WindowSelectionState>> { | |
| WindowSelectionState::existing(window, cx) | |
| } | |
| #[cfg(test)] | |
| mod tests { | |
| use super::*; | |
| use crate::ElementExt as _; | |
| use gpui::{ | |
| Bounds, ContentMask, Context, Hitbox, HitboxBehavior, HitboxId, InteractiveElement as _, | |
| IntoElement, ParentElement as _, Render, SharedString, Styled as _, StyledText, | |
| TestAppContext, TextLayout, Window, div, point, prelude::FluentBuilder as _, px, size, | |
| }; | |
| use std::{ | |
| cell::{Cell, RefCell}, | |
| rc::Rc, | |
| }; | |
| struct FakeParticipant { | |
| selection: TextSelectionHandle, | |
| } | |
| struct WindowSelectionView { | |
| selection: TextSelectionHandle, | |
| } | |
| struct SelectionElementOnlyView; | |
| struct ToggleSelectionElementView { | |
| enabled: bool, | |
| selection: TextSelectionHandle, | |
| } | |
| struct DoubleSelectionElementView { | |
| selection: TextSelectionHandle, | |
| } | |
| struct WindowOwnedSelectionView { | |
| selection: TextSelectionHandle, | |
| } | |
| struct FirstFrameScopedSelectionView { | |
| selection: TextSelectionHandle, | |
| } | |
| struct PlainRunLayoutView { | |
| texts: Vec<SharedString>, | |
| layouts: Vec<TextLayout>, | |
| } | |
| struct GroupDocument { | |
| handle: TextSelectionHandle, | |
| focus: FocusHandle, | |
| text: SharedString, | |
| renders: Rc<Cell<usize>>, | |
| } | |
| impl Render for GroupDocument { | |
| fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { | |
| self.renders.set(self.renders.get() + 1); | |
| let handle = self.handle.clone(); | |
| let select = handle.clone(); | |
| div() | |
| .id("group-document") | |
| .track_focus(&self.focus) | |
| .key_context("TextView") | |
| .w(px(400.)) | |
| .h(px(80.)) | |
| .on_action(move |_: &crate::input::Copy, window, cx| { | |
| if let Some(text) = handle.selected_text_in_scope(window, cx) { | |
| cx.write_to_clipboard(gpui::ClipboardItem::new_string(text)); | |
| } | |
| }) | |
| .on_action(move |_: &crate::input::SelectAll, window, cx| { | |
| if select.activate_scope(window, cx) { | |
| select.clear_group(cx); | |
| select.set_local_selection(true, cx); | |
| window.refresh(); | |
| } | |
| }) | |
| .child( | |
| crate::SelectableText::with_handle( | |
| "run", | |
| self.handle.clone(), | |
| self.text.clone(), | |
| ) | |
| .focus_handle(&self.focus), | |
| ) | |
| } | |
| } | |
| struct GroupRoot { | |
| background: Entity<GroupDocument>, | |
| foreground: Entity<GroupDocument>, | |
| group_focus: FocusHandle, | |
| scope: Option<gpui::InputScope>, | |
| } | |
| impl Render for GroupRoot { | |
| fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { | |
| let mut root = div() | |
| .w(px(400.)) | |
| .h(px(200.)) | |
| .child(TextSelectionLayer) | |
| .child(self.background.clone()); | |
| if let Some(scope) = &self.scope { | |
| // Deliberately same parent/id namespace as background Layer. | |
| root = | |
| root.child(scope.element(TextSelectionLayer)).child( | |
| scope.element( | |
| div() | |
| .id("foreground-container") | |
| .track_focus(&self.group_focus) | |
| .child(TextSelectionLayer) | |
| .child(self.foreground.clone().cached( | |
| gpui::StyleRefinement::default().w(px(400.)).h(px(80.)), | |
| )), | |
| ), | |
| ); | |
| } | |
| root | |
| } | |
| } | |
| fn group_document(text: &'static str, cx: &mut App) -> Entity<GroupDocument> { | |
| cx.new(|cx| { | |
| let focus = cx.focus_handle(); | |
| let handle = TextSelectionHandle::new(text, cx); | |
| let target = focus.clone(); | |
| handle.focus_with(move |window, cx| target.focus(window, cx), cx); | |
| GroupDocument { | |
| handle, | |
| focus, | |
| text: text.into(), | |
| renders: Rc::new(Cell::new(0)), | |
| } | |
| }) | |
| } | |
| #[gpui::test] | |
| fn original_background_and_foreground_selection_layers_isolate_real_pointer_copy_and_namespace( | |
| cx: &mut TestAppContext, | |
| ) { | |
| cx.update(crate::init); | |
| let (root, cx) = cx.add_window_view(|_, cx| GroupRoot { | |
| background: group_document("background original words", cx), | |
| foreground: group_document("foreground independent words", cx), | |
| group_focus: cx.focus_handle().tab_stop(false), | |
| scope: None, | |
| }); | |
| let draw = |cx: &mut gpui::VisualTestContext| { | |
| cx.run_until_parked(); | |
| cx.update(|window, cx| window.draw(cx).clear(cx)); | |
| }; | |
| draw(cx); | |
| cx.simulate_mouse_down( | |
| point(px(2.), px(8.)), | |
| MouseButton::Left, | |
| gpui::Modifiers::default(), | |
| ); | |
| cx.simulate_mouse_move( | |
| point(px(95.), px(8.)), | |
| Some(MouseButton::Left), | |
| gpui::Modifiers::default(), | |
| ); | |
| cx.simulate_mouse_up( | |
| point(px(95.), px(8.)), | |
| MouseButton::Left, | |
| gpui::Modifiers::default(), | |
| ); | |
| draw(cx); | |
| let background = root.read_with(cx, |root, cx| root.background.read(cx).handle.clone()); | |
| let foreground = root.read_with(cx, |root, cx| root.foreground.read(cx).handle.clone()); | |
| let kept = cx.update(|window, cx| background.selected_text_in_scope(window, cx).unwrap()); | |
| assert!(!kept.is_empty()); | |
| cx.update(|window, cx| { | |
| root.update(cx, |root, cx| { | |
| root.scope = Some(window.input_scope(&root.group_focus, cx)); | |
| cx.notify(); | |
| }) | |
| }); | |
| draw(cx); | |
| cx.simulate_mouse_down( | |
| point(px(2.), px(88.)), | |
| MouseButton::Left, | |
| gpui::Modifiers::default(), | |
| ); | |
| cx.simulate_mouse_move( | |
| point(px(135.), px(88.)), | |
| Some(MouseButton::Left), | |
| gpui::Modifiers::default(), | |
| ); | |
| cx.simulate_mouse_up( | |
| point(px(135.), px(88.)), | |
| MouseButton::Left, | |
| gpui::Modifiers::default(), | |
| ); | |
| draw(cx); | |
| cx.update(|window, cx| { | |
| let fore = foreground.selected_text_in_scope(window, cx).unwrap(); | |
| assert!(!fore.is_empty()); | |
| assert!(fore.starts_with("foreground")); | |
| assert_eq!(background.selected_text_in_scope(window, cx).unwrap(), kept); | |
| assert!( | |
| !background | |
| .group(cx) | |
| .unwrap() | |
| .same_owner(&foreground.group(cx).unwrap()) | |
| ); | |
| }); | |
| cx.dispatch_action(crate::input::Copy); | |
| cx.update(|_, cx| { | |
| assert!( | |
| cx.read_from_clipboard() | |
| .unwrap() | |
| .text() | |
| .unwrap() | |
| .starts_with("foreground") | |
| ) | |
| }); | |
| let reopening = cx.update(|window, cx| { | |
| let group = foreground.group(cx).unwrap(); | |
| let text = foreground.selected_text_in_scope(window, cx).unwrap(); | |
| let gesture = window.input_gesture(); | |
| root.update(cx, |root, cx| { | |
| root.scope.take(); | |
| root.scope = Some(window.input_scope(&root.group_focus, cx)); | |
| cx.notify(); | |
| }); | |
| assert!(!gesture.is_current()); | |
| (group, text) | |
| }); | |
| draw(cx); | |
| cx.update(|_, cx| { | |
| cx.write_to_clipboard(gpui::ClipboardItem::new_string("sentinel".into())) | |
| }); | |
| cx.dispatch_action(crate::input::Copy); | |
| cx.update(|window, cx| { | |
| assert_eq!( | |
| cx.read_from_clipboard().unwrap().text().unwrap(), | |
| reopening.1 | |
| ); | |
| assert!(reopening.0.same_owner(&foreground.group(cx).unwrap())); | |
| assert_eq!( | |
| foreground.selected_text_in_scope(window, cx).unwrap(), | |
| reopening.1 | |
| ); | |
| assert_eq!(background.selected_text_in_scope(window, cx).unwrap(), kept); | |
| }); | |
| cx.update(|window, cx| { | |
| root.update(cx, |root, cx| { | |
| root.scope.take(); | |
| let focus = root.background.read(cx).focus.clone(); | |
| window.focus(&focus, cx); | |
| cx.notify(); | |
| }) | |
| }); | |
| draw(cx); | |
| cx.dispatch_action(crate::input::Copy); | |
| cx.update(|window, cx| { | |
| assert_eq!(background.selected_text_in_scope(window, cx).unwrap(), kept); | |
| assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), kept); | |
| }); | |
| cx.simulate_mouse_down( | |
| point(px(180.), px(8.)), | |
| MouseButton::Left, | |
| gpui::Modifiers { | |
| shift: true, | |
| ..Default::default() | |
| }, | |
| ); | |
| cx.simulate_mouse_up( | |
| point(px(180.), px(8.)), | |
| MouseButton::Left, | |
| gpui::Modifiers { | |
| shift: true, | |
| ..Default::default() | |
| }, | |
| ); | |
| draw(cx); | |
| cx.update(|window, cx| { | |
| let extended = background.selected_text_in_scope(window, cx).unwrap(); | |
| assert!( | |
| extended.len() > kept.len(), | |
| "original anchor supports shift extension after closing foreground" | |
| ); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn original_background_paint_does_not_resolve_foreground_copy_callbacks( | |
| cx: &mut TestAppContext, | |
| ) { | |
| cx.with_paused_automatic_drawing(|cx| { | |
| cx.update(crate::init); | |
| let (root, cx) = cx.add_window_view(|window, cx| { | |
| let group_focus = cx.focus_handle().tab_stop(false); | |
| GroupRoot { | |
| background: group_document("background original words", cx), | |
| foreground: group_document("foreground independent words", cx), | |
| scope: Some(window.input_scope(&group_focus, cx)), | |
| group_focus, | |
| } | |
| }); | |
| cx.update(|window, cx| window.draw(cx).clear(cx)); | |
| let background = root.read_with(cx, |root, _| root.background.clone()); | |
| let foreground = root.read_with(cx, |root, _| root.foreground.clone()); | |
| let copies = Rc::new(Cell::new(0)); | |
| let out = copies.clone(); | |
| cx.update(|window, cx| { | |
| let handle = foreground.read(cx).handle.clone(); | |
| handle.copy_with( | |
| move |_| { | |
| out.set(out.get() + 1); | |
| "foreground independent words".into() | |
| }, | |
| cx, | |
| ); | |
| handle.set_local_selection(true, cx); | |
| window.refresh(); | |
| }); | |
| cx.update(|window, cx| window.draw(cx).clear(cx)); | |
| cx.run_until_parked(); | |
| cx.update(|window, cx| { | |
| assert_eq!( | |
| TextSelection::selected_text(window, cx), | |
| "foreground independent words" | |
| ); | |
| }); | |
| let calls = copies.get(); | |
| let foreground_renders = foreground.read_with(cx, |doc, _| doc.renders.get()); | |
| let background_renders = background.read_with(cx, |doc, _| doc.renders.get()); | |
| cx.update(|_, cx| background.update(cx, |_, cx| cx.notify())); | |
| cx.update(|window, cx| window.draw(cx).clear(cx)); | |
| assert!(background.read_with(cx, |doc, _| doc.renders.get()) > background_renders); | |
| assert_eq!( | |
| foreground.read_with(cx, |doc, _| doc.renders.get()), | |
| foreground_renders, | |
| "original foreground remains retained while background alone rebuilds" | |
| ); | |
| assert_eq!( | |
| copies.get(), | |
| calls, | |
| "background paint must not execute foreground copy code" | |
| ); | |
| }); | |
| } | |
| struct ReparentRoot { | |
| document: Entity<GroupDocument>, | |
| first: gpui::InputScope, | |
| first_focus: FocusHandle, | |
| second: gpui::InputScope, | |
| second_focus: FocusHandle, | |
| moved: bool, | |
| absent: bool, | |
| } | |
| impl Render for ReparentRoot { | |
| fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { | |
| if self.absent { | |
| return div().into_any_element(); | |
| } | |
| // Same container namespace and geometry; only original group context changes. | |
| let content = div().id("group-container").w(px(400.)).h(px(80.)).child( | |
| self.document | |
| .clone() | |
| .cached(gpui::StyleRefinement::default().w(px(400.)).h(px(80.))), | |
| ); | |
| let content = if self.moved { | |
| self.second | |
| .element(content.track_focus(&self.second_focus)) | |
| .into_any_element() | |
| } else { | |
| self.first | |
| .element(content.track_focus(&self.first_focus)) | |
| .into_any_element() | |
| }; | |
| div() | |
| .child( | |
| self.first | |
| .element(div().id("first-layer").child(TextSelectionLayer)), | |
| ) | |
| .child( | |
| self.second | |
| .element(div().id("second-layer").child(TextSelectionLayer)), | |
| ) | |
| .child(content) | |
| .into_any_element() | |
| } | |
| } | |
| #[gpui::test] | |
| fn original_cached_participant_moves_groups_without_carrying_local_select_all( | |
| cx: &mut TestAppContext, | |
| ) { | |
| cx.update(crate::init); | |
| let (root, cx) = cx.add_window_view(|window, cx| { | |
| let first_focus = cx.focus_handle().tab_stop(false); | |
| let second_focus = cx.focus_handle().tab_stop(false); | |
| ReparentRoot { | |
| document: group_document("original cached selection", cx), | |
| first: window.input_scope(&first_focus, cx), | |
| first_focus, | |
| second: window.input_scope(&second_focus, cx), | |
| second_focus, | |
| moved: false, | |
| absent: false, | |
| } | |
| }); | |
| let draw = |cx: &mut gpui::VisualTestContext| { | |
| cx.run_until_parked(); | |
| cx.update(|window, cx| window.draw(cx).clear(cx)); | |
| }; | |
| draw(cx); | |
| let document = root.read_with(cx, |root, _| root.document.clone()); | |
| let handle = document.read_with(cx, |doc, _| doc.handle.clone()); | |
| cx.update(|window, cx| { | |
| let focus = document.read(cx).focus.clone(); | |
| window.focus(&focus, cx); | |
| }); | |
| draw(cx); | |
| cx.dispatch_action(crate::input::SelectAll); | |
| draw(cx); | |
| let old = cx.update(|_, cx| handle.group(cx).unwrap()); | |
| let renders = document.read_with(cx, |doc, _| doc.renders.get()); | |
| cx.update(|window, cx| { | |
| assert_eq!( | |
| handle.selected_text_in_scope(window, cx).unwrap(), | |
| "original cached selection" | |
| ) | |
| }); | |
| // Prove unchanged group really uses the original cached subtree first. | |
| cx.update(|_, cx| root.update(cx, |_, cx| cx.notify())); | |
| draw(cx); | |
| assert_eq!(document.read_with(cx, |doc, _| doc.renders.get()), renders); | |
| cx.update(|_, cx| { | |
| root.update(cx, |root, cx| { | |
| root.moved = true; | |
| cx.notify(); | |
| }) | |
| }); | |
| draw(cx); | |
| assert!(document.read_with(cx, |doc, _| doc.renders.get()) > renders); | |
| cx.update(|window, cx| { | |
| let current = handle.group(cx).unwrap(); | |
| assert!(!old.same_owner(¤t)); | |
| assert_eq!( | |
| old.has_selection_in_scope(TextSelectionScopeId::default(), cx), | |
| Some(false) | |
| ); | |
| assert!(!handle.has_local_selection(cx)); | |
| assert!(handle.selected_text_in_scope(window, cx).is_none()); | |
| let focus = document.read(cx).focus.clone(); | |
| window.focus(&focus, cx); | |
| }); | |
| draw(cx); | |
| cx.dispatch_action(crate::input::SelectAll); | |
| draw(cx); | |
| cx.update(|window, cx| { | |
| assert_eq!( | |
| handle.selected_text_in_scope(window, cx).unwrap(), | |
| "original cached selection" | |
| ) | |
| }); | |
| } | |
| #[gpui::test] | |
| fn released_group_cannot_clear_repainted_participant_selection(cx: &mut TestAppContext) { | |
| cx.update(crate::init); | |
| let (root, cx) = cx.add_window_view(|window, cx| { | |
| let first_focus = cx.focus_handle().tab_stop(false); | |
| let second_focus = cx.focus_handle().tab_stop(false); | |
| ReparentRoot { | |
| document: group_document("original fresh selection", cx), | |
| first: window.input_scope(&first_focus, cx), | |
| first_focus, | |
| second: window.input_scope(&second_focus, cx), | |
| second_focus, | |
| moved: false, | |
| absent: false, | |
| } | |
| }); | |
| cx.run_until_parked(); | |
| cx.update(|window, cx| window.draw(cx).clear(cx)); | |
| let handle = root.read_with(cx, |root, cx| root.document.read(cx).handle.clone()); | |
| let old = cx.update(|_, cx| handle.group(cx).unwrap()); | |
| cx.update(|window, cx| { | |
| handle.set_local_selection(true, cx); | |
| root.update(cx, |root, cx| { | |
| root.absent = true; | |
| cx.notify(); | |
| }); | |
| window.draw(cx).clear(cx); | |
| assert!( | |
| old.owner.upgrade().is_none(), | |
| "original layer has dropped before its queued release" | |
| ); | |
| root.update(cx, |root, cx| { | |
| root.absent = false; | |
| root.moved = true; | |
| cx.notify(); | |
| }); | |
| window.draw(cx).clear(cx); | |
| assert!(!old.same_owner(&handle.group(cx).unwrap())); | |
| assert!(!handle.has_local_selection(cx)); | |
| handle.set_local_selection(true, cx); | |
| assert!(handle.has_local_selection(cx)); | |
| }); | |
| cx.run_until_parked(); | |
| cx.update(|window, cx| { | |
| assert!( | |
| handle.has_local_selection(cx), | |
| "old queued release cannot clear the new group's selection" | |
| ); | |
| assert_eq!( | |
| handle.selected_text_in_scope(window, cx).unwrap(), | |
| "original fresh selection" | |
| ); | |
| }); | |
| } | |
| struct DiscardPrepaint { | |
| child: gpui::AnyElement, | |
| attempts: Rc<Cell<usize>>, | |
| } | |
| impl IntoElement for DiscardPrepaint { | |
| type Element = Self; | |
| fn into_element(self) -> Self { | |
| self | |
| } | |
| } | |
| impl Element for DiscardPrepaint { | |
| type RequestLayoutState = (); | |
| type PrepaintState = (); | |
| fn id(&self) -> Option<ElementId> { | |
| None | |
| } | |
| fn source_location(&self) -> Option<&'static core::panic::Location<'static>> { | |
| None | |
| } | |
| fn request_layout( | |
| &mut self, | |
| _: Option<&GlobalElementId>, | |
| _: Option<&InspectorElementId>, | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) -> (LayoutId, ()) { | |
| (self.child.request_layout(window, cx), ()) | |
| } | |
| fn prepaint( | |
| &mut self, | |
| _: Option<&GlobalElementId>, | |
| _: Option<&InspectorElementId>, | |
| _: Bounds<Pixels>, | |
| _: &mut (), | |
| window: &mut Window, | |
| cx: &mut App, | |
| ) { | |
| let result: Result<(), ()> = window.transact(|window| { | |
| self.child.prepaint(window, cx); | |
| Err(()) | |
| }); | |
| assert!(result.is_err()); | |
| self.attempts.set(self.attempts.get() + 1); | |
| } | |
| fn paint( | |
| &mut self, | |
| _: Option<&GlobalElementId>, | |
| _: Option<&InspectorElementId>, | |
| _: Bounds<Pixels>, | |
| _: &mut (), | |
| _: &mut (), | |
| _: &mut Window, | |
| _: &mut App, | |
| ) { | |
| } | |
| } | |
| struct FailedRichRoot { | |
| document: Entity<crate::text::TextViewState>, | |
| first: gpui::InputScope, | |
| first_focus: FocusHandle, | |
| second: gpui::InputScope, | |
| second_focus: FocusHandle, | |
| attempt: bool, | |
| attempts: Rc<Cell<usize>>, | |
| } | |
| impl Render for FailedRichRoot { | |
| fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { | |
| let failed = div() | |
| .w(px(140.)) | |
| .h(px(80.)) | |
| .track_focus(&self.second_focus) | |
| .child(TextSelectionLayer) | |
| .child(crate::text::TextView::new(&self.document).selectable(true)); | |
| let failed = DiscardPrepaint { | |
| child: self.second.element(failed).into_any_element(), | |
| attempts: self.attempts.clone(), | |
| }; | |
| let first = div() | |
| .w(px(400.)) | |
| .h(px(80.)) | |
| .track_focus(&self.first_focus) | |
| .child(TextSelectionLayer) | |
| .child(crate::text::TextView::new(&self.document).selectable(true)); | |
| div() | |
| .when(self.attempt, |this| this.child(failed)) | |
| .child(self.first.element(first)) | |
| } | |
| } | |
| #[gpui::test] | |
| fn discarded_rich_prepaint_preserves_published_group_and_completed_selection( | |
| cx: &mut TestAppContext, | |
| ) { | |
| cx.update(crate::init); | |
| let (root, cx) = cx.add_window_view(|window, cx| { | |
| let first_focus = cx.focus_handle().tab_stop(false); | |
| let second_focus = cx.focus_handle().tab_stop(false); | |
| FailedRichRoot { | |
| document: cx.new(|cx| { | |
| crate::text::TextViewState::markdown("**Original** rich selected text 䏿–‡", cx) | |
| }), | |
| first: window.input_scope(&first_focus, cx), | |
| first_focus, | |
| second: window.input_scope(&second_focus, cx), | |
| second_focus, | |
| attempt: false, | |
| attempts: Rc::new(Cell::new(0)), | |
| } | |
| }); | |
| let draw = |cx: &mut gpui::VisualTestContext| { | |
| cx.run_until_parked(); | |
| cx.update(|window, cx| window.draw(cx).clear(cx)); | |
| }; | |
| draw(cx); | |
| cx.simulate_mouse_down( | |
| point(px(2.), px(8.)), | |
| MouseButton::Left, | |
| gpui::Modifiers::default(), | |
| ); | |
| cx.simulate_mouse_move( | |
| point(px(160.), px(8.)), | |
| Some(MouseButton::Left), | |
| gpui::Modifiers::default(), | |
| ); | |
| cx.simulate_mouse_up( | |
| point(px(160.), px(8.)), | |
| MouseButton::Left, | |
| gpui::Modifiers::default(), | |
| ); | |
| draw(cx); | |
| let kept = cx.update(|window, cx| { | |
| let selection = WindowSelectionState::existing(window, cx).unwrap(); | |
| assert!(selection.read(cx).snapshot().is_some()); | |
| assert!(!selection.read(cx).is_selecting()); | |
| let kept = TextSelection::selected_text(window, cx); | |
| assert!(!kept.is_empty()); | |
| kept | |
| }); | |
| let old = cx.update(|window, cx| TextSelectionGroup { | |
| key: physical_group(window), | |
| owner: WindowSelectionState::existing(window, cx) | |
| .unwrap() | |
| .downgrade(), | |
| }); | |
| cx.update(|_, cx| { | |
| root.update(cx, |root, cx| { | |
| root.attempt = true; | |
| cx.notify(); | |
| }) | |
| }); | |
| draw(cx); | |
| cx.update(|window, cx| { | |
| assert!(root.read(cx).attempts.get() > 0); | |
| assert_eq!( | |
| old.has_selection_in_scope(TextSelectionScopeId::default(), cx), | |
| Some(true) | |
| ); | |
| assert_eq!(TextSelection::selected_text(window, cx), kept); | |
| assert_eq!( | |
| cx.global::<SelectionStateRegistry>().0.len(), | |
| 1, | |
| "discarded layer never publishes its weak locator" | |
| ); | |
| }); | |
| } | |
| fn painted_participant(selection: TextSelectionHandle) -> impl IntoElement { | |
| gpui::canvas( | |
| |bounds, window, _| { | |
| let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal); | |
| TextSelectionRegistration::new(hitbox, bounds).with_text_bounds(vec![bounds]) | |
| }, | |
| move |_, registration, window, cx| selection.register(registration, window, cx), | |
| ) | |
| .size_full() | |
| } | |
| impl Render for WindowSelectionView { | |
| fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { | |
| div() | |
| } | |
| } | |
| impl Render for SelectionElementOnlyView { | |
| fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { | |
| div() | |
| .size_full() | |
| .child(TextSelectionLayer) | |
| .child( | |
| div() | |
| .size_full() | |
| .on_mouse_down(MouseButton::Left, |_, _, cx| { | |
| GlobalState::suppress_text_selection(cx); | |
| }), | |
| ) | |
| } | |
| } | |
| impl Render for ToggleSelectionElementView { | |
| fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { | |
| let selection = self.selection.clone(); | |
| div().when(self.enabled, |this| { | |
| this.child(TextSelectionLayer) | |
| .child(painted_participant(selection)) | |
| }) | |
| } | |
| } | |
| impl Render for DoubleSelectionElementView { | |
| fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { | |
| let selection = self.selection.clone(); | |
| div() | |
| .size_full() | |
| .child(TextSelectionLayer) | |
| .child(TextSelectionLayer) | |
| .child(painted_participant(selection)) | |
| } | |
| } | |
| impl Render for WindowOwnedSelectionView { | |
| fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { | |
| let selection = self.selection.clone(); | |
| div() | |
| .size_full() | |
| .child(TextSelectionLayer) | |
| .child(painted_participant(selection)) | |
| } | |
| } | |
| impl Render for FirstFrameScopedSelectionView { | |
| fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { | |
| let scope = TextSelectionScopeId::from_raw(23); | |
| div() | |
| .child(TextSelectionLayer) | |
| .child(painted_participant(self.selection.clone()).text_selection_scope(scope)) | |
| } | |
| } | |
| impl Render for PlainRunLayoutView { | |
| fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { | |
| self.layouts.clear(); | |
| let children = self | |
| .texts | |
| .iter() | |
| .enumerate() | |
| .map(|(index, text)| { | |
| let text = StyledText::new(text.clone()); | |
| self.layouts.push(text.layout().clone()); | |
| div().absolute().top(px(index as f32 * 40.)).child(text) | |
| }) | |
| .collect::<Vec<_>>(); | |
| div().size_full().children(children) | |
| } | |
| } | |
| fn with_selection_window<R>( | |
| cx: &mut TestAppContext, | |
| run: impl FnOnce(&mut Window, &mut App) -> R, | |
| ) -> R { | |
| let window = match cx.windows().first().copied() { | |
| Some(window) => window, | |
| None => { | |
| let window = cx.add_window(|_, _| gpui::EmptyView); | |
| (*window).into() | |
| } | |
| }; | |
| cx.update_window(window, |_, window, cx| run(window, cx)) | |
| .unwrap() | |
| } | |
| impl FakeParticipant { | |
| fn new(text: &str, cx: &mut gpui::App) -> Self { | |
| let selection = TextSelectionHandle::new(text, cx); | |
| Self { selection } | |
| } | |
| fn register( | |
| &self, | |
| selection_state: &mut WindowSelectionState, | |
| y: f32, | |
| scope: TextSelectionScopeId, | |
| document_order: u64, | |
| cx: &mut gpui::App, | |
| ) { | |
| let bounds = Bounds::new(point(px(0.), px(y)), size(px(100.), px(10.))); | |
| selection_state.register_participant( | |
| self.selection.clone(), | |
| TextSelectionRegistration::new( | |
| Hitbox { | |
| dispatch_node: None, | |
| regions: None, | |
| id: HitboxId::placeholder(), | |
| bounds, | |
| content_mask: ContentMask { bounds }, | |
| behavior: HitboxBehavior::Normal, | |
| }, | |
| bounds, | |
| ) | |
| .with_scope(scope) | |
| .with_document_order(document_order) | |
| .with_text_bounds(vec![bounds]), | |
| cx, | |
| ); | |
| } | |
| } | |
| fn laid_out_runs(texts: &[&str], cx: &mut TestAppContext) -> Vec<(SharedString, TextLayout)> { | |
| let texts = texts | |
| .iter() | |
| .map(|text| SharedString::from(*text)) | |
| .collect::<Vec<_>>(); | |
| let view = cx.add_window({ | |
| let texts = texts.clone(); | |
| move |_, _| PlainRunLayoutView { | |
| texts, | |
| layouts: Vec::new(), | |
| } | |
| }); | |
| cx.update_window(*view, |_, window, cx| { | |
| let _ = window.draw(cx); | |
| }) | |
| .unwrap(); | |
| let layouts = cx.update(|cx| view.read(cx).unwrap().layouts.clone()); | |
| texts.into_iter().zip(layouts).collect() | |
| } | |
| fn plain_snapshot(anchor: Point<Pixels>, cursor: Point<Pixels>) -> TextSelectionSnapshot { | |
| TextSelectionSnapshot::new( | |
| TextSelectionEndpoint::new(None, anchor), | |
| TextSelectionEndpoint::new(None, cursor), | |
| ) | |
| .with_window_points(Some(TextSelectionWindowPoints { anchor, cursor })) | |
| } | |
| #[gpui::test] | |
| fn scope_context_is_cleaned_after_panicking_subtree(cx: &mut TestAppContext) { | |
| let handle = cx.add_window(|_, _| SelectionElementOnlyView); | |
| cx.update_window(*handle, |_, window, _| { | |
| let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { | |
| window.with_text_selection_scope_context(Some(41), |_| panic!("subtree failed")); | |
| })); | |
| assert!(result.is_err()); | |
| assert_eq!(current_text_selection_scope(window), None); | |
| }) | |
| .unwrap(); | |
| } | |
| #[gpui::test] | |
| fn reentrant_scope_from_one_window_does_not_pollute_another(cx: &mut TestAppContext) { | |
| let first = cx.add_window(|_, _| SelectionElementOnlyView); | |
| let second = cx.add_window(|_, _| SelectionElementOnlyView); | |
| cx.update_window(*first, |_, window, cx| { | |
| window.with_text_selection_scope_context(Some(42), |window| { | |
| assert_eq!( | |
| current_text_selection_scope(window), | |
| Some(TextSelectionScopeId::from_raw(42)) | |
| ); | |
| second | |
| .update(cx, |_, window, _| { | |
| assert_eq!(current_text_selection_scope(window), None) | |
| }) | |
| .unwrap(); | |
| }); | |
| assert_eq!(current_text_selection_scope(window), None); | |
| }) | |
| .unwrap(); | |
| } | |
| #[gpui::test] | |
| fn selection_callback_can_reenter_its_selection_state(cx: &mut TestAppContext) { | |
| let called = Rc::new(Cell::new(false)); | |
| let called_from_callback = called.clone(); | |
| let (selection_state, participant) = cx.update(|cx| { | |
| let selection_state = cx.new(|_| WindowSelectionState::default()); | |
| let selection_state_for_callback = selection_state.clone(); | |
| let participant = FakeParticipant::new("participant", cx); | |
| participant | |
| .selection | |
| .subscribe( | |
| move |event, cx| { | |
| if matches!(event, TextSelectionEvent::SelectionChanged(Some(_))) { | |
| selection_state_for_callback | |
| .update(cx, |_, _| called_from_callback.set(true)); | |
| } | |
| }, | |
| cx, | |
| ) | |
| .detach(); | |
| (selection_state, participant) | |
| }); | |
| cx.run_until_parked(); | |
| with_selection_window(cx, |window, cx| { | |
| selection_state.update(cx, |selection_state, cx| { | |
| participant.register(selection_state, 0., TextSelectionScopeId::default(), 0, cx); | |
| selection_state.begin(point(px(1.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(20.), px(1.)), cx); | |
| }); | |
| }); | |
| cx.run_until_parked(); | |
| assert!(called.get()); | |
| } | |
| #[gpui::test] | |
| fn selection_events_preserve_snapshot_then_clear_order(cx: &mut TestAppContext) { | |
| let observed = Rc::new(RefCell::new(Vec::new())); | |
| let observed_for_callback = observed.clone(); | |
| let selection = cx.update(|cx| { | |
| let selection = TextSelectionHandle::new("selection", cx); | |
| selection | |
| .subscribe( | |
| move |event, _| { | |
| if let TextSelectionEvent::SelectionChanged(snapshot) = event { | |
| observed_for_callback.borrow_mut().push(snapshot.is_some()); | |
| } | |
| }, | |
| cx, | |
| ) | |
| .detach(); | |
| selection | |
| }); | |
| cx.run_until_parked(); | |
| cx.update(|cx| { | |
| selection.0.update(cx, |state, cx| { | |
| state.set_snapshot( | |
| Some(plain_snapshot(point(px(1.), px(1.)), point(px(8.), px(1.)))), | |
| cx, | |
| ); | |
| state.clear_state(cx); | |
| }); | |
| }); | |
| cx.run_until_parked(); | |
| assert_eq!(&*observed.borrow(), &[true, false]); | |
| } | |
| fn text_run(order: u64, text: SharedString, layout: TextLayout) -> TextSelectionRun { | |
| let bounds = layout.bounds(); | |
| TextSelectionRun::new(text, layout, bounds).with_document_order(order) | |
| } | |
| #[gpui::test] | |
| fn public_selection_data_uses_builders_and_readers(cx: &mut TestAppContext) { | |
| let bounds = Bounds::new(point(px(1.), px(2.)), size(px(30.), px(10.))); | |
| let hitbox = Hitbox { | |
| dispatch_node: None, | |
| regions: None, | |
| id: HitboxId::placeholder(), | |
| bounds, | |
| content_mask: ContentMask { bounds }, | |
| behavior: HitboxBehavior::Normal, | |
| }; | |
| let scope = TextSelectionScopeId::from_raw(7); | |
| let endpoint = TextSelectionEndpoint::new(None, bounds.origin) | |
| .with_content_key(TextSelectionContentKey::new(11)); | |
| let snapshot = TextSelectionSnapshot::new(endpoint, endpoint) | |
| .with_selecting(true) | |
| .with_window_points(Some(TextSelectionWindowPoints { | |
| anchor: bounds.origin, | |
| cursor: bounds.bottom_right(), | |
| })) | |
| .with_coverage(TextSelectionCoverage::Full); | |
| let registration = TextSelectionRegistration::new(hitbox, bounds) | |
| .with_scroll_offset(point(px(3.), px(4.))) | |
| .with_scope(scope) | |
| .with_document_order(9) | |
| .with_text_bounds(vec![bounds]); | |
| assert_eq!(endpoint.entity_id(), None); | |
| assert_eq!(endpoint.content_point(), bounds.origin); | |
| assert_eq!( | |
| endpoint.content_key(), | |
| Some(TextSelectionContentKey::new(11)) | |
| ); | |
| assert_eq!(snapshot.anchor(), endpoint); | |
| assert_eq!(snapshot.cursor(), endpoint); | |
| assert!(snapshot.is_selecting()); | |
| assert_eq!(snapshot.coverage(), TextSelectionCoverage::Full); | |
| assert_eq!( | |
| snapshot.window_points(), | |
| Some(TextSelectionWindowPoints { | |
| anchor: bounds.origin, | |
| cursor: bounds.bottom_right(), | |
| }) | |
| ); | |
| assert_eq!(registration.bounds(), bounds); | |
| assert_eq!(registration.scroll_offset(), point(px(3.), px(4.))); | |
| assert_eq!(registration.scope(), scope); | |
| assert_eq!(registration.document_order(), 9); | |
| assert_eq!(registration.text_bounds(), &[bounds]); | |
| let (text, layout) = laid_out_runs(&["aé"], cx).pop().unwrap(); | |
| let text_run = TextSelectionRun::new(text.clone(), layout.clone(), layout.bounds()) | |
| .with_document_order(3); | |
| assert_eq!(text_run.document_order(), 3); | |
| assert_eq!(text_run.text(), &text); | |
| assert_eq!(text_run.layout().len(), layout.len()); | |
| assert_eq!(text_run.bounds(), layout.bounds()); | |
| let projection = TextSelectionProjection { | |
| ranges: vec![Some(1..3)], | |
| is_active: true, | |
| }; | |
| assert_eq!(projection.ranges(), &[Some(1..3)]); | |
| assert!(projection.is_active()); | |
| } | |
| #[gpui::test] | |
| fn selection_handle_is_the_public_adapter_seam(cx: &mut TestAppContext) { | |
| let selected = Rc::new(Cell::new(false)); | |
| let selected_from_callback = selected.clone(); | |
| cx.update(|cx| { | |
| let selection = TextSelectionHandle::new("initial", cx); | |
| let entity_id = selection.entity_id(); | |
| selection.set_fallback_copy_text("updated", cx); | |
| selection.set_local_selection(true, cx); | |
| selection | |
| .subscribe( | |
| move |event, _| { | |
| if let TextSelectionEvent::SelectionChanged(snapshot) = event { | |
| selected_from_callback.set(snapshot.is_some()); | |
| } | |
| }, | |
| cx, | |
| ) | |
| .detach(); | |
| selection.focus_with(|_, _| {}, cx); | |
| selection.copy_with(|_| "copied".to_string(), cx); | |
| selection.resolve_content_key_with(|_, _| Some(TextSelectionContentKey::new(3)), cx); | |
| assert_eq!(selection.entity_id(), entity_id); | |
| assert_eq!(selection.snapshot(cx), None); | |
| assert_eq!( | |
| selection.update_runs(&[], cx), | |
| TextSelectionProjection::default() | |
| ); | |
| }); | |
| assert!(!selected.get()); | |
| } | |
| #[gpui::test] | |
| fn disabling_original_participant_withdraws_gesture_geometry_and_queued_focus( | |
| cx: &mut TestAppContext, | |
| ) { | |
| let focused = Rc::new(Cell::new(0)); | |
| let cleared = Rc::new(Cell::new(0)); | |
| let initial_clear = Rc::new(Cell::new(0)); | |
| let (view, cx) = cx.add_window_view(|_, cx| WindowOwnedSelectionView { | |
| selection: TextSelectionHandle::new("first", cx), | |
| }); | |
| cx.update(|window, cx| window.draw(cx).clear(cx)); | |
| cx.update(|window, cx| { | |
| let first = view.read(cx).selection.clone(); | |
| let seen = focused.clone(); | |
| first.focus_with(move |_, _| seen.set(seen.get() + 1), cx); | |
| let seen = cleared.clone(); | |
| first.clear_with(move |_| seen.set(seen.get() + 1), cx); | |
| let second = FakeParticipant::new("second", cx); | |
| let state = WindowSelectionState::ensure(window, cx); | |
| state.update(cx, |state, cx| { | |
| FakeParticipant { | |
| selection: first.clone(), | |
| } | |
| .register(state, 0., TextSelectionScopeId::default(), 0, cx); | |
| second.register(state, 20., TextSelectionScopeId::default(), 1, cx); | |
| state.begin(point(px(1.), px(1.)), false, window, cx); | |
| state.update(point(px(8.), px(1.)), cx); | |
| }); | |
| assert!(state.read(cx).is_selecting()); | |
| initial_clear.set(cleared.get()); | |
| first.0.update(cx, |state, cx| state.focus(window, cx)); | |
| first.set_enabled(false, cx); | |
| first.set_enabled(true, cx); | |
| state.update(cx, |state, cx| { | |
| assert!(!state.is_selecting()); | |
| assert!(state.anchor.is_none()); | |
| assert!(state.cursor.is_none()); | |
| assert!(!state.participants.borrow().contains_key(&first.entity_id())); | |
| state.update(point(px(8.), px(21.)), cx); | |
| assert_eq!(state.selected_text(cx), ""); | |
| }); | |
| assert!(second.selection.snapshot(cx).is_none()); | |
| // Explicit new selection survives the old deferred clear. | |
| first.set_local_selection(true, cx); | |
| }); | |
| cx.run_until_parked(); | |
| assert_eq!(focused.get(), 0, "a revoked deferred focus cannot revive"); | |
| assert_eq!( | |
| cleared.get(), | |
| initial_clear.get(), | |
| "old clear cannot erase a newer local selection" | |
| ); | |
| cx.update(|window, cx| { | |
| let first = view.read(cx).selection.clone(); | |
| let state = WindowSelectionState::existing(window, cx).unwrap(); | |
| state.update(cx, |state, cx| { | |
| FakeParticipant { | |
| selection: first.clone(), | |
| } | |
| .register(state, 0., TextSelectionScopeId::default(), 0, cx); | |
| state.begin(point(px(1.), px(1.)), false, window, cx); | |
| state.update(point(px(8.), px(1.)), cx); | |
| assert_eq!(state.selected_text(cx), "first"); | |
| }); | |
| first.0.update(cx, |state, cx| state.focus(window, cx)); | |
| }); | |
| cx.run_until_parked(); | |
| assert_eq!( | |
| focused.get(), | |
| 1, | |
| "a newly registered original owner can focus" | |
| ); | |
| } | |
| #[gpui::test] | |
| fn selection_handle_can_subscribe_its_window_to_refresh(cx: &mut TestAppContext) { | |
| let (_, cx) = cx.add_window_view(|_, cx| WindowSelectionView { | |
| selection: TextSelectionHandle::new("refresh", cx), | |
| }); | |
| cx.update(|window, cx| { | |
| let selection = TextSelectionHandle::new("refresh", cx); | |
| selection.refresh_window_on_change(window, cx).detach(); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn plain_projection_preserves_forward_reversed_and_unicode_ranges(cx: &mut TestAppContext) { | |
| let (text, layout) = laid_out_runs(&["aé🙂z"], cx).pop().unwrap(); | |
| let run = text_run(0, text, layout.clone()); | |
| let start = layout.position_for_index(1).unwrap(); | |
| let end = layout.position_for_index(7).unwrap(); | |
| let forward = project_ranges(Some(plain_snapshot(start, end)), std::slice::from_ref(&run)); | |
| let reversed = project_ranges(Some(plain_snapshot(end, start)), &[run]); | |
| assert_eq!(forward.ranges(), &[Some(1..7)]); | |
| assert_eq!(reversed.ranges(), &[Some(1..7)]); | |
| assert!(forward.is_active()); | |
| assert!(reversed.is_active()); | |
| } | |
| #[gpui::test] | |
| fn double_click_expands_a_plain_run_to_the_input_word_boundary(cx: &mut TestAppContext) { | |
| let (text, layout) = laid_out_runs(&["one café, three"], cx).pop().unwrap(); | |
| let run = text_run(0, text, layout.clone()); | |
| let click = layout.position_for_index(6).unwrap(); | |
| let (anchor, cursor) = | |
| points_for_multi_click(std::slice::from_ref(&run), click, 2).unwrap(); | |
| let states = project_ranges(Some(plain_snapshot(anchor, cursor)), &[run]); | |
| assert_eq!(states.ranges(), &[Some(4..9)]); | |
| } | |
| #[gpui::test] | |
| fn multi_click_uses_text_layout_window_coordinates_at_a_nonzero_origin( | |
| cx: &mut TestAppContext, | |
| ) { | |
| let mut runs = laid_out_runs(&["above", "alpha beta"], cx); | |
| let (text, layout) = runs.pop().unwrap(); | |
| assert!(layout.bounds().origin.y > px(0.)); | |
| let run = text_run(0, text, layout.clone()); | |
| let click = layout.position_for_index(7).unwrap(); | |
| let (anchor, cursor) = | |
| points_for_multi_click(std::slice::from_ref(&run), click, 2).unwrap(); | |
| let projection = project_ranges(Some(plain_snapshot(anchor, cursor)), &[run]); | |
| assert_eq!(projection.ranges(), &[Some(6..10)]); | |
| } | |
| #[gpui::test] | |
| fn translated_runs_keep_word_and_unicode_range_queries_in_window_coordinates( | |
| cx: &mut TestAppContext, | |
| ) { | |
| let (text, layout) = laid_out_runs(&["one café, three"], cx).pop().unwrap(); | |
| let original_bounds = layout.bounds(); | |
| let original_click = layout.position_for_index(6).unwrap(); | |
| let original_start = layout.position_for_index(4).unwrap(); | |
| let original_end = layout.position_for_index(9).unwrap(); | |
| let original = text_run(0, text, layout.clone()); | |
| let mask = Bounds::new( | |
| point(px(-200.), px(-200.)), | |
| gpui::size(px(1000.), px(1000.)), | |
| ); | |
| for delta in [point(px(80.), px(-30.)), point(px(-50.), px(60.))] { | |
| let run = original.reprojected(delta, mask); | |
| let (anchor, cursor) = | |
| points_for_multi_click(std::slice::from_ref(&run), original_click + delta, 2) | |
| .unwrap(); | |
| assert_eq!(anchor, original_start + delta); | |
| assert_eq!(cursor, original_end + delta); | |
| for (start, end) in [(anchor, cursor), (cursor, anchor)] { | |
| let projection = | |
| project_ranges(Some(plain_snapshot(start, end)), std::slice::from_ref(&run)); | |
| assert_eq!(projection.ranges(), &[Some(4..9)]); | |
| } | |
| assert_eq!( | |
| layout.bounds(), | |
| original_bounds, | |
| "retained projection must never mutate the shared native layout" | |
| ); | |
| assert_eq!(layout.position_for_index(6).unwrap(), original_click); | |
| } | |
| } | |
| #[gpui::test] | |
| fn triple_click_expands_to_the_input_logical_line_not_the_visual_row(cx: &mut TestAppContext) { | |
| let (text, layout) = laid_out_runs(&["second line"], cx).pop().unwrap(); | |
| let run = text_run(0, text, layout.clone()); | |
| let click = layout.position_for_index(4).unwrap(); | |
| let (anchor, cursor) = | |
| points_for_multi_click(std::slice::from_ref(&run), click, 4).unwrap(); | |
| let states = project_ranges(Some(plain_snapshot(anchor, cursor)), &[run]); | |
| assert_eq!(states.ranges(), &[Some(0..11)]); | |
| assert_eq!(line_range_at("first line\nsecond line\nthird", 15), 11..22); | |
| } | |
| #[gpui::test] | |
| fn plain_projection_spans_multiple_runs_and_leaves_empty_gutters_unselected( | |
| cx: &mut TestAppContext, | |
| ) { | |
| let mut runs = laid_out_runs(&["first", "", "second"], cx); | |
| let (first_text, first_layout) = runs.remove(0); | |
| let (gutter_text, gutter_layout) = runs.remove(0); | |
| let (second_text, second_layout) = runs.remove(0); | |
| let start = first_layout.position_for_index(2).unwrap(); | |
| let end = second_layout.position_for_index(3).unwrap(); | |
| let states = project_ranges( | |
| Some(plain_snapshot(start, end)), | |
| &[ | |
| text_run(2, second_text, second_layout), | |
| text_run(1, gutter_text, gutter_layout), | |
| text_run(0, first_text, first_layout), | |
| ], | |
| ); | |
| assert_eq!(states.ranges(), &[Some(0..3), None, Some(2..5)]); | |
| assert!(states.is_active()); | |
| } | |
| #[gpui::test] | |
| fn plain_projection_caches_multiple_participant_copies_in_document_order( | |
| cx: &mut TestAppContext, | |
| ) { | |
| let mut runs = laid_out_runs(&["one", "two"], cx); | |
| let (first_text, first_layout) = runs.remove(0); | |
| let (second_text, second_layout) = runs.remove(0); | |
| let snapshot = plain_snapshot( | |
| first_layout.position_for_index(1).unwrap(), | |
| second_layout.position_for_index(2).unwrap(), | |
| ); | |
| cx.update(|cx| { | |
| let mut selection_state = WindowSelectionState::default(); | |
| let first = FakeParticipant::new("", cx); | |
| let second = FakeParticipant::new("", cx); | |
| first.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 1, | |
| cx, | |
| ); | |
| second.register( | |
| &mut selection_state, | |
| 20., | |
| TextSelectionScopeId::default(), | |
| 0, | |
| cx, | |
| ); | |
| first | |
| .selection | |
| .0 | |
| .update(cx, |state, cx| state.set_snapshot(Some(snapshot), cx)); | |
| let projection = first | |
| .selection | |
| .update_runs(&[text_run(0, first_text, first_layout)], cx); | |
| assert_eq!(projection.ranges(), &[Some(1..3)]); | |
| assert!(projection.is_active()); | |
| second | |
| .selection | |
| .0 | |
| .update(cx, |state, cx| state.set_snapshot(Some(snapshot), cx)); | |
| let projection = second | |
| .selection | |
| .update_runs(&[text_run(0, second_text, second_layout)], cx); | |
| assert_eq!(projection.ranges(), &[Some(0..2)]); | |
| assert!(projection.is_active()); | |
| assert_eq!(selection_state.selected_text(cx), "tw\nne"); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn plain_projection_invalidates_cached_copy_when_the_snapshot_changes(cx: &mut TestAppContext) { | |
| let (text, layout) = laid_out_runs(&["first"], cx).pop().unwrap(); | |
| let first_snapshot = plain_snapshot( | |
| layout.position_for_index(1).unwrap(), | |
| layout.position_for_index(3).unwrap(), | |
| ); | |
| let changed_snapshot = plain_snapshot( | |
| layout.position_for_index(3).unwrap(), | |
| layout.position_for_index(5).unwrap(), | |
| ); | |
| let run = text_run(0, text, layout); | |
| cx.update(|cx| { | |
| let mut selection_state = WindowSelectionState::default(); | |
| let participant = FakeParticipant::new("", cx); | |
| participant.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 0, | |
| cx, | |
| ); | |
| participant.selection.0.update(cx, |state, cx| { | |
| state.set_snapshot(Some(first_snapshot), cx); | |
| state.update_runs(std::slice::from_ref(&run)); | |
| }); | |
| assert_eq!(selection_state.selected_text(cx), "ir"); | |
| participant.selection.0.update(cx, |state, cx| { | |
| state.set_snapshot(Some(changed_snapshot), cx); | |
| }); | |
| assert_eq!(selection_state.selected_text(cx), ""); | |
| participant.selection.update_runs(&[run], cx); | |
| assert_eq!(selection_state.selected_text(cx), "st"); | |
| selection_state.clear(cx); | |
| participant.selection.set_local_selection(true, cx); | |
| assert_eq!(selection_state.selected_text(cx), ""); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn plain_projection_orders_cached_runs_by_frame_order_not_input_order(cx: &mut TestAppContext) { | |
| let mut runs = laid_out_runs(&["one", "two"], cx); | |
| let (first_text, first_layout) = runs.remove(0); | |
| let (second_text, second_layout) = runs.remove(0); | |
| let snapshot = plain_snapshot( | |
| first_layout.position_for_index(1).unwrap(), | |
| second_layout.position_for_index(2).unwrap(), | |
| ); | |
| cx.update(|cx| { | |
| let mut selection_state = WindowSelectionState::default(); | |
| let participant = FakeParticipant::new("", cx); | |
| participant.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 0, | |
| cx, | |
| ); | |
| participant.selection.0.update(cx, |state, cx| { | |
| state.set_snapshot(Some(snapshot), cx); | |
| state.update_runs(&[ | |
| text_run(1, first_text, first_layout), | |
| text_run(0, second_text, second_layout), | |
| ]); | |
| }); | |
| assert_eq!(selection_state.selected_text(cx), "twne"); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn plain_projection_safely_rejects_a_text_layout_length_mismatch(cx: &mut TestAppContext) { | |
| let (_, layout) = laid_out_runs(&["short"], cx).pop().unwrap(); | |
| let start = layout.position_for_index(0).unwrap(); | |
| let end = layout.position_for_index(5).unwrap(); | |
| let states = project_ranges( | |
| Some(plain_snapshot(start, end)), | |
| &[text_run(0, SharedString::from("longer"), layout)], | |
| ); | |
| assert_eq!(states.ranges(), &[None]); | |
| assert!(states.is_active()); | |
| } | |
| #[gpui::test] | |
| fn begin_update_and_end_publish_a_cross_participant_selection(cx: &mut TestAppContext) { | |
| with_selection_window(cx, |window, cx| { | |
| let mut selection_state = WindowSelectionState::default(); | |
| let first = FakeParticipant::new("first", cx); | |
| let second = FakeParticipant::new("second", cx); | |
| first.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 0, | |
| cx, | |
| ); | |
| second.register( | |
| &mut selection_state, | |
| 20., | |
| TextSelectionScopeId::default(), | |
| 1, | |
| cx, | |
| ); | |
| selection_state.begin(point(px(1.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(1.), px(25.)), cx); | |
| assert!(selection_state.has_selection(cx)); | |
| assert_eq!(selection_state.selected_text(cx), "first\nsecond"); | |
| selection_state.end(cx); | |
| assert!(!selection_state.is_selecting()); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn shift_extension_keeps_its_original_anchor_when_reversed(cx: &mut TestAppContext) { | |
| with_selection_window(cx, |window, cx| { | |
| let mut selection_state = WindowSelectionState::default(); | |
| let participant = FakeParticipant::new("participant", cx); | |
| participant.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 0, | |
| cx, | |
| ); | |
| selection_state.begin(point(px(2.), px(2.)), false, window, cx); | |
| selection_state.end(cx); | |
| selection_state.begin(point(px(8.), px(2.)), true, window, cx); | |
| selection_state.end(cx); | |
| let first_anchor = selection_state.snapshot().unwrap().anchor(); | |
| selection_state.begin(point(px(0.), px(2.)), true, window, cx); | |
| selection_state.end(cx); | |
| let reversed = selection_state.snapshot().unwrap(); | |
| assert_eq!(reversed.anchor(), first_anchor); | |
| assert!(reversed.cursor().content_point().x < reversed.anchor().content_point().x); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn content_key_resolver_runs_outside_the_window_state_lease(cx: &mut TestAppContext) { | |
| with_selection_window(cx, |window, cx| { | |
| let state = cx.new(|_| WindowSelectionState::default()); | |
| let participant = FakeParticipant::new("virtual", cx); | |
| let state_for_callback = state.clone(); | |
| participant.selection.resolve_content_key_with( | |
| move |_, cx| { | |
| let _ = state_for_callback.read(cx).snapshot(); | |
| Some(TextSelectionContentKey::new(7)) | |
| }, | |
| cx, | |
| ); | |
| state.update(cx, |state, cx| { | |
| participant.register(state, 0., TextSelectionScopeId::default(), 0, cx); | |
| state.begin(point(px(1.), px(1.)), false, window, cx); | |
| state.update(point(px(8.), px(1.)), cx); | |
| }); | |
| WindowSelectionState::resolve_content_keys(&state, cx); | |
| assert_eq!( | |
| state.read(cx).snapshot().unwrap().cursor().content_key(), | |
| Some(TextSelectionContentKey::new(7)) | |
| ); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn active_dnd_does_not_move_a_text_selection_cursor(cx: &mut TestAppContext) { | |
| let window = cx.add_window(|_, cx| WindowSelectionView { | |
| selection: TextSelectionHandle::new("unused", cx), | |
| }); | |
| window | |
| .update(cx, |_, window, cx| { | |
| let mut state = WindowSelectionState::default(); | |
| let participant = FakeParticipant::new("participant", cx); | |
| participant.register(&mut state, 0., TextSelectionScopeId::default(), 0, cx); | |
| state.begin(point(px(1.), px(1.)), false, window, cx); | |
| let before = state.cursor.as_ref().unwrap().point; | |
| state.update_in_window_with_active_drag(point(px(80.), px(1.)), true, window, cx); | |
| assert_eq!(state.cursor.as_ref().unwrap().point, before); | |
| }) | |
| .unwrap(); | |
| } | |
| #[gpui::test] | |
| fn shift_extension_falls_back_when_the_anchor_participant_was_swept(cx: &mut TestAppContext) { | |
| with_selection_window(cx, |window, cx| { | |
| let mut selection_state = WindowSelectionState::default(); | |
| let first = FakeParticipant::new("first", cx); | |
| let second = FakeParticipant::new("second", cx); | |
| first.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 0, | |
| cx, | |
| ); | |
| selection_state.begin(point(px(1.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(8.), px(1.)), cx); | |
| selection_state.end(cx); | |
| selection_state.finish_frame(cx); | |
| selection_state.finish_frame(cx); | |
| second.register( | |
| &mut selection_state, | |
| 20., | |
| TextSelectionScopeId::default(), | |
| 1, | |
| cx, | |
| ); | |
| selection_state.begin(point(px(1.), px(21.)), true, window, cx); | |
| selection_state.update(point(px(8.), px(21.)), cx); | |
| selection_state.end(cx); | |
| assert_eq!(selection_state.selected_text(cx), "second"); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn scope_and_suppression_prevent_unrelated_participants_from_participating( | |
| cx: &mut TestAppContext, | |
| ) { | |
| with_selection_window(cx, |window, cx| { | |
| let mut selection_state = WindowSelectionState::default(); | |
| let base = FakeParticipant::new("base", cx); | |
| let modal = FakeParticipant::new("modal", cx); | |
| base.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 0, | |
| cx, | |
| ); | |
| modal.register(&mut selection_state, 20., TextSelectionScopeId(1), 1, cx); | |
| selection_state.set_active_scope(TextSelectionScopeId(1), cx); | |
| selection_state.begin(point(px(1.), px(21.)), false, window, cx); | |
| selection_state.update(point(px(8.), px(21.)), cx); | |
| selection_state.end(cx); | |
| assert_eq!(selection_state.selected_text(cx), "modal"); | |
| selection_state.clear(cx); | |
| GlobalState::init(cx); | |
| GlobalState::suppress_text_selection(cx); | |
| selection_state.begin(point(px(1.), px(21.)), false, window, cx); | |
| selection_state.update(point(px(8.), px(21.)), cx); | |
| assert!(!selection_state.has_selection(cx)); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn dead_participants_are_pruned_and_empty_selection_falls_back_safely(cx: &mut TestAppContext) { | |
| let selection_state = cx.update(|cx| { | |
| let selection_state = cx.new(|_| WindowSelectionState::default()); | |
| let participant = FakeParticipant::new("gone", cx); | |
| selection_state.update(cx, |selection_state, cx| { | |
| participant.register(selection_state, 0., TextSelectionScopeId::default(), 0, cx) | |
| }); | |
| selection_state | |
| }); | |
| with_selection_window(cx, |window, cx| { | |
| selection_state.update(cx, |selection_state, cx| { | |
| selection_state.begin(point(px(1.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(8.), px(1.)), cx); | |
| selection_state.end(cx); | |
| assert_eq!(selection_state.selected_text(cx), ""); | |
| assert!(!selection_state.has_selection(cx)); | |
| }); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn text_selection_namespace_reports_copies_ends_and_clears_selection(cx: &mut TestAppContext) { | |
| let (view, cx) = cx.add_window_view(|_, cx| WindowSelectionView { | |
| selection: TextSelectionHandle::new("copied", cx), | |
| }); | |
| cx.update(|window, cx| { | |
| let selection = view.read(cx).selection.clone(); | |
| let selection_state = WindowSelectionState::ensure(window, cx); | |
| selection_state.update(cx, |selection_state, cx| { | |
| FakeParticipant { selection }.register( | |
| selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 0, | |
| cx, | |
| ); | |
| selection_state.begin(point(px(1.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(8.), px(1.)), cx); | |
| }); | |
| assert!(TextSelection::has_selection(window, cx)); | |
| assert_eq!(TextSelection::selected_text(window, cx), "copied"); | |
| TextSelection::end(window, cx); | |
| assert!(TextSelection::has_selection(window, cx)); | |
| TextSelection::clear(window, cx); | |
| assert!(!TextSelection::has_selection(window, cx)); | |
| assert_eq!(TextSelection::selected_text(window, cx), ""); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn two_windows_isolate_selection_copy_clear_and_release_ownership(cx: &mut TestAppContext) { | |
| let first = cx.add_window(|_, cx| WindowOwnedSelectionView { | |
| selection: TextSelectionHandle::new("first", cx), | |
| }); | |
| let second = cx.add_window(|_, cx| WindowOwnedSelectionView { | |
| selection: TextSelectionHandle::new("second", cx), | |
| }); | |
| let first_selection = cx.update(|cx| first.read(cx).unwrap().selection.clone()); | |
| let second_selection = cx.update(|cx| second.read(cx).unwrap().selection.clone()); | |
| let first_state = cx | |
| .update_window(*first, |_, window, cx| { | |
| let _ = window.draw(cx); | |
| first_selection.set_local_selection(true, cx); | |
| assert_eq!(TextSelection::selected_text(window, cx), "first"); | |
| WindowSelectionState::existing(window, cx) | |
| .unwrap() | |
| .downgrade() | |
| }) | |
| .unwrap(); | |
| cx.update_window(*second, |_, window, cx| { | |
| let _ = window.draw(cx); | |
| second_selection.set_local_selection(true, cx); | |
| assert_eq!(TextSelection::selected_text(window, cx), "second"); | |
| }) | |
| .unwrap(); | |
| cx.update_window(*first, |_, window, cx| { | |
| TextSelection::clear(window, cx); | |
| assert_eq!(TextSelection::selected_text(window, cx), ""); | |
| }) | |
| .unwrap(); | |
| cx.update_window(*second, |_, window, cx| { | |
| assert_eq!(TextSelection::selected_text(window, cx), "second"); | |
| }) | |
| .unwrap(); | |
| cx.update_window(*first, |_, window, _| window.remove_window()) | |
| .unwrap(); | |
| cx.run_until_parked(); | |
| assert!(first_state.upgrade().is_none()); | |
| cx.update_window(*second, |_, window, cx| { | |
| assert_eq!(TextSelection::selected_text(window, cx), "second"); | |
| }) | |
| .unwrap(); | |
| cx.update(|cx| { | |
| assert_eq!(cx.global::<SelectionStateRegistry>().0.len(), 1); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn copy_callback_can_reenter_window_and_handle_selection(cx: &mut TestAppContext) { | |
| let (_, cx) = cx.add_window_view(|_, _| SelectionElementOnlyView); | |
| cx.update(|window, cx| { | |
| let _ = window.draw(cx); | |
| let state = WindowSelectionState::existing(window, cx).unwrap(); | |
| let selection = TextSelectionHandle::new("fallback", cx); | |
| let state_for_copy = state.clone(); | |
| let selection_for_copy = selection.clone(); | |
| selection.copy_with( | |
| move |cx: &mut App| { | |
| state_for_copy.update(cx, |state, _| { | |
| assert!(state.snapshot().is_some()); | |
| }); | |
| assert!(selection_for_copy.snapshot(cx).is_some()); | |
| selection_for_copy.set_fallback_copy_text("reentered", cx); | |
| "reentrant copy".to_string() | |
| }, | |
| cx, | |
| ); | |
| state.update(cx, |state, cx| { | |
| FakeParticipant { | |
| selection: selection.clone(), | |
| } | |
| .register(state, 0., TextSelectionScopeId::default(), 0, cx); | |
| state.begin(point(px(1.), px(1.)), false, window, cx); | |
| state.update(point(px(8.), px(1.)), cx); | |
| state.end(cx); | |
| }); | |
| assert_eq!(TextSelection::selected_text(window, cx), "reentrant copy"); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn cross_participant_selection_excludes_participants_outside_its_document_interval( | |
| cx: &mut TestAppContext, | |
| ) { | |
| with_selection_window(cx, |window, cx| { | |
| let mut selection_state = WindowSelectionState::default(); | |
| let first = FakeParticipant::new("first", cx); | |
| let second = FakeParticipant::new("second", cx); | |
| let third = FakeParticipant::new("third", cx); | |
| first.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 0, | |
| cx, | |
| ); | |
| second.register( | |
| &mut selection_state, | |
| 20., | |
| TextSelectionScopeId::default(), | |
| 1, | |
| cx, | |
| ); | |
| third.register( | |
| &mut selection_state, | |
| 40., | |
| TextSelectionScopeId::default(), | |
| 2, | |
| cx, | |
| ); | |
| selection_state.begin(point(px(1.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(1.), px(25.)), cx); | |
| selection_state.end(cx); | |
| assert_eq!(selection_state.selected_text(cx), "first\nsecond"); | |
| assert!(third.selection.snapshot(cx).is_none()); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn changing_scope_clears_the_previous_scope_selection(cx: &mut TestAppContext) { | |
| with_selection_window(cx, |window, cx| { | |
| let mut selection_state = WindowSelectionState::default(); | |
| let base = FakeParticipant::new("base", cx); | |
| let modal = FakeParticipant::new("modal", cx); | |
| base.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 0, | |
| cx, | |
| ); | |
| modal.register( | |
| &mut selection_state, | |
| 20., | |
| TextSelectionScopeId::from_raw(1), | |
| 1, | |
| cx, | |
| ); | |
| selection_state.begin(point(px(1.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(8.), px(1.)), cx); | |
| selection_state.end(cx); | |
| selection_state.set_active_scope(TextSelectionScopeId::from_raw(1), cx); | |
| assert!(!selection_state.has_selection(cx)); | |
| assert!(base.selection.snapshot(cx).is_none()); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn blank_only_drag_never_publishes_or_copies_selection(cx: &mut TestAppContext) { | |
| with_selection_window(cx, |window, cx| { | |
| let mut selection_state = WindowSelectionState::default(); | |
| let participant = FakeParticipant::new("participant", cx); | |
| participant.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 0, | |
| cx, | |
| ); | |
| selection_state.begin(point(px(200.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(200.), px(8.)), cx); | |
| selection_state.end(cx); | |
| assert!(!selection_state.has_selection(cx)); | |
| assert_eq!(selection_state.selected_text(cx), ""); | |
| assert!(participant.selection.snapshot(cx).is_none()); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn unmounted_selection_does_not_revive_when_the_participant_returns(cx: &mut TestAppContext) { | |
| with_selection_window(cx, |window, cx| { | |
| let mut selection_state = WindowSelectionState::default(); | |
| let participant = FakeParticipant::new("stale", cx); | |
| participant.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 0, | |
| cx, | |
| ); | |
| selection_state.begin(point(px(1.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(8.), px(1.)), cx); | |
| selection_state.end(cx); | |
| assert_eq!(selection_state.selected_text(cx), "stale"); | |
| selection_state.finish_frame(cx); | |
| selection_state.finish_frame(cx); | |
| assert_eq!(selection_state.selected_text(cx), ""); | |
| assert!(participant.selection.snapshot(cx).is_none()); | |
| participant.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 0, | |
| cx, | |
| ); | |
| assert_eq!(selection_state.selected_text(cx), ""); | |
| assert!(participant.selection.snapshot(cx).is_none()); | |
| selection_state.begin(point(px(1.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(8.), px(1.)), cx); | |
| selection_state.end(cx); | |
| assert_eq!(selection_state.selected_text(cx), "stale"); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn removing_an_unselected_participant_preserves_the_current_selection(cx: &mut TestAppContext) { | |
| with_selection_window(cx, |window, cx| { | |
| let mut selection_state = WindowSelectionState::default(); | |
| let selected = FakeParticipant::new("selected", cx); | |
| let unrelated = FakeParticipant::new("unrelated", cx); | |
| let scope = TextSelectionScopeId::default(); | |
| selected.register(&mut selection_state, 0., scope, 0, cx); | |
| unrelated.register(&mut selection_state, 20., scope, 1, cx); | |
| selection_state.begin(point(px(1.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(8.), px(1.)), cx); | |
| selection_state.end(cx); | |
| assert_eq!(selection_state.selected_text(cx), "selected"); | |
| selection_state.finish_frame(cx); | |
| selected.register(&mut selection_state, 0., scope, 0, cx); | |
| selection_state.finish_frame(cx); | |
| assert_eq!(selection_state.selected_text(cx), "selected"); | |
| unrelated.register(&mut selection_state, 20., scope, 1, cx); | |
| assert_eq!(selection_state.selected_text(cx), "selected"); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn removing_either_range_endpoint_discards_the_shared_selection(cx: &mut TestAppContext) { | |
| for remove_anchor in [true, false] { | |
| with_selection_window(cx, |window, cx| { | |
| let mut selection_state = WindowSelectionState::default(); | |
| let anchor = FakeParticipant::new("anchor", cx); | |
| let cursor = FakeParticipant::new("cursor", cx); | |
| let scope = TextSelectionScopeId::default(); | |
| anchor.register(&mut selection_state, 0., scope, 0, cx); | |
| cursor.register(&mut selection_state, 20., scope, 1, cx); | |
| selection_state.begin(point(px(1.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(8.), px(21.)), cx); | |
| selection_state.end(cx); | |
| assert_eq!(selection_state.selected_text(cx), "anchor\ncursor"); | |
| selection_state.finish_frame(cx); | |
| if remove_anchor { | |
| cursor.register(&mut selection_state, 20., scope, 1, cx); | |
| } else { | |
| anchor.register(&mut selection_state, 0., scope, 0, cx); | |
| } | |
| selection_state.finish_frame(cx); | |
| assert_eq!(selection_state.selected_text(cx), ""); | |
| anchor.register(&mut selection_state, 0., scope, 0, cx); | |
| cursor.register(&mut selection_state, 20., scope, 1, cx); | |
| assert_eq!(selection_state.selected_text(cx), ""); | |
| }); | |
| } | |
| } | |
| #[gpui::test] | |
| fn clear_or_unmount_stops_auto_scroll_before_discarding_the_anchor(cx: &mut TestAppContext) { | |
| for unmount in [false, true] { | |
| let commands = Rc::new(RefCell::new(Vec::new())); | |
| let observed = commands.clone(); | |
| let (mut selection_state, participant) = cx.update(|cx| { | |
| let selection_state = WindowSelectionState::default(); | |
| let participant = FakeParticipant::new("scroll", cx); | |
| participant | |
| .selection | |
| .subscribe( | |
| move |event, _| { | |
| if let TextSelectionEvent::AutoScroll(delta, _) = event { | |
| observed.borrow_mut().push(*delta); | |
| } | |
| }, | |
| cx, | |
| ) | |
| .detach(); | |
| (selection_state, participant) | |
| }); | |
| cx.run_until_parked(); | |
| with_selection_window(cx, |window, cx| { | |
| participant.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 0, | |
| cx, | |
| ); | |
| selection_state.begin(point(px(1.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(1.), px(25.)), cx); | |
| if unmount { | |
| selection_state.finish_frame(cx); | |
| selection_state.finish_frame(cx); | |
| } else { | |
| selection_state.clear(cx); | |
| } | |
| }); | |
| cx.run_until_parked(); | |
| assert!(commands.borrow().iter().any(Option::is_some)); | |
| assert_eq!(commands.borrow().last(), Some(&None)); | |
| } | |
| } | |
| #[gpui::test] | |
| fn original_clear_callback_cannot_rearm_an_interrupted_selection_begin( | |
| cx: &mut TestAppContext, | |
| ) { | |
| with_selection_window(cx, |window, cx| { | |
| let focus = cx.focus_handle(); | |
| let scope = window.input_scope(&focus, cx); | |
| let participant = FakeParticipant::new("original", cx); | |
| participant | |
| .selection | |
| .clear_with(move |_| scope.revoke(), cx); | |
| let mut state = WindowSelectionState::default(); | |
| participant.register(&mut state, 0., TextSelectionScopeId::default(), 0, cx); | |
| state.begin(point(px(1.), px(1.)), false, window, cx); | |
| assert!(state.selecting.is_none()); | |
| assert!(state.anchor.is_none()); | |
| state.update(point(px(80.), px(8.)), cx); | |
| assert!(participant.selection.snapshot(cx).is_none()); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn original_deferred_focus_callback_is_withdrawn_before_user_code_after_interruption( | |
| cx: &mut TestAppContext, | |
| ) { | |
| let called = Rc::new(Cell::new(0)); | |
| let observed = called.clone(); | |
| let participant = with_selection_window(cx, |window, cx| { | |
| let participant = FakeParticipant::new("focus", cx); | |
| participant | |
| .selection | |
| .focus_with(move |_, _| observed.set(observed.get() + 1), cx); | |
| let focus = cx.focus_handle(); | |
| let scope = window.input_scope(&focus, cx); | |
| window.defer(cx, move |_, _| scope.revoke()); | |
| participant | |
| .selection | |
| .0 | |
| .update(cx, |state, cx| state.focus(window, cx)); | |
| // Keep the actual participant alive until both original defers run. | |
| let fresh = participant.selection.clone(); | |
| window.defer(cx, move |window, cx| { | |
| fresh.0.update(cx, |state, cx| state.focus(window, cx)) | |
| }); | |
| participant | |
| }); | |
| cx.run_until_parked(); | |
| assert_eq!( | |
| called.get(), | |
| 1, | |
| "old native focus callback is refused; a new one still executes" | |
| ); | |
| drop(participant); | |
| } | |
| #[gpui::test] | |
| fn drag_auto_scroll_stops_when_the_content_mask_collapses(cx: &mut TestAppContext) { | |
| let window = cx.add_window(|_, cx| WindowSelectionView { | |
| selection: TextSelectionHandle::new("unused", cx), | |
| }); | |
| window | |
| .update(cx, |_, window, cx| { | |
| let state = cx.new(|_| WindowSelectionState::default()); | |
| let participant = FakeParticipant::new("participant", cx); | |
| state.update(cx, |state, cx| { | |
| participant.register(state, 0., TextSelectionScopeId::default(), 0, cx); | |
| state.begin(point(px(1.), px(1.)), false, window, cx); | |
| }); | |
| // The scrollable ancestor got clipped away mid-drag, so the | |
| // refreshed registration carries a collapsed content mask. | |
| let collapsed = Bounds::new(point(px(0.), px(0.)), size(px(100.), px(0.))); | |
| state.update(cx, |state, cx| { | |
| state.register_participant( | |
| participant.selection.clone(), | |
| TextSelectionRegistration::new( | |
| Hitbox { | |
| dispatch_node: None, | |
| regions: None, | |
| id: HitboxId::placeholder(), | |
| bounds: collapsed, | |
| content_mask: ContentMask { bounds: collapsed }, | |
| behavior: HitboxBehavior::Normal, | |
| }, | |
| collapsed, | |
| ) | |
| .with_text_bounds(vec![collapsed]), | |
| cx, | |
| ); | |
| state.update_in_window(point(px(1.), px(50.)), window, cx); | |
| assert!(!state.auto_scroll.is_active()); | |
| assert!(state.auto_scroll.last_drag_position.is_none()); | |
| }); | |
| }) | |
| .unwrap(); | |
| } | |
| #[gpui::test] | |
| fn pointer_moves_after_a_click_do_not_auto_scroll(cx: &mut TestAppContext) { | |
| let window = cx.add_window(|_, cx| WindowSelectionView { | |
| selection: TextSelectionHandle::new("unused", cx), | |
| }); | |
| window | |
| .update(cx, |_, window, cx| { | |
| let state = cx.new(|_| WindowSelectionState::default()); | |
| let participant = FakeParticipant::new("participant", cx); | |
| state.update(cx, |state, cx| { | |
| participant.register(state, 0., TextSelectionScopeId::default(), 0, cx); | |
| // A click on text keeps its anchor so shift-click can extend it. | |
| state.begin(point(px(1.), px(1.)), false, window, cx); | |
| state.end(cx); | |
| assert!(state.anchor.is_some()); | |
| state.update_in_window(point(px(1.), px(50.)), window, cx); | |
| assert!(!state.auto_scroll.is_active()); | |
| }); | |
| }) | |
| .unwrap(); | |
| } | |
| #[gpui::test] | |
| fn proxy_endpoints_break_equal_position_ties_by_document_order(cx: &mut TestAppContext) { | |
| with_selection_window(cx, |window, cx| { | |
| let mut selection_state = WindowSelectionState::default(); | |
| let later = FakeParticipant::new("later", cx); | |
| let earlier = FakeParticipant::new("earlier", cx); | |
| later.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 2, | |
| cx, | |
| ); | |
| earlier.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 1, | |
| cx, | |
| ); | |
| selection_state.begin(point(px(1.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(200.), px(25.)), cx); | |
| let endpoint = selection_state.snapshot().unwrap().cursor(); | |
| assert_eq!(endpoint.entity_id(), Some(earlier.selection.entity_id())); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn equal_area_hovered_participants_break_ties_by_document_order(cx: &mut TestAppContext) { | |
| with_selection_window(cx, |window, cx| { | |
| for _ in 0..64 { | |
| let mut selection_state = WindowSelectionState::default(); | |
| let later = FakeParticipant::new("later", cx); | |
| let earliest = FakeParticipant::new("earliest", cx); | |
| let middle = FakeParticipant::new("middle", cx); | |
| later.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 30, | |
| cx, | |
| ); | |
| earliest.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 10, | |
| cx, | |
| ); | |
| middle.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 20, | |
| cx, | |
| ); | |
| selection_state.begin(point(px(1.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(8.), px(1.)), cx); | |
| assert_eq!( | |
| selection_state.snapshot().unwrap().anchor().entity_id(), | |
| Some(earliest.selection.entity_id()) | |
| ); | |
| } | |
| }); | |
| } | |
| #[gpui::test] | |
| fn text_selection_namespace_is_a_safe_no_op_until_the_element_is_rendered( | |
| cx: &mut TestAppContext, | |
| ) { | |
| let (_, cx) = cx.add_window_view(|_, cx| WindowSelectionView { | |
| selection: TextSelectionHandle::new("not enabled", cx), | |
| }); | |
| cx.update(|window, cx| { | |
| assert!(!TextSelection::has_selection(window, cx)); | |
| assert_eq!(TextSelection::selected_text(window, cx), ""); | |
| TextSelection::clear(window, cx); | |
| TextSelection::end(window, cx); | |
| assert!(!TextSelection::has_selection(window, cx)); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn unit_selection_element_supports_scope_and_registration_on_the_first_frame( | |
| cx: &mut TestAppContext, | |
| ) { | |
| let (view, cx) = cx.add_window_view(|_, cx| FirstFrameScopedSelectionView { | |
| selection: TextSelectionHandle::new("first frame", cx), | |
| }); | |
| let selection = cx.update(|_, cx| view.read(cx).selection.clone()); | |
| cx.update(|window, cx| { | |
| let _ = window.draw(cx); | |
| let state = WindowSelectionState::existing(window, cx).unwrap(); | |
| assert_eq!( | |
| state.read(cx).participants.borrow()[&selection.entity_id()] | |
| .registration | |
| .scope, | |
| TextSelectionScopeId::from_raw(23) | |
| ); | |
| assert!( | |
| state | |
| .read(cx) | |
| .participants | |
| .borrow() | |
| .contains_key(&selection.entity_id()) | |
| ); | |
| }); | |
| cx.simulate_mouse_down( | |
| point(px(1.), px(1.)), | |
| MouseButton::Left, | |
| gpui::Modifiers::default(), | |
| ); | |
| cx.simulate_mouse_move( | |
| point(px(8.), px(1.)), | |
| Some(MouseButton::Left), | |
| gpui::Modifiers::default(), | |
| ); | |
| cx.update(|window, cx| { | |
| assert!(TextSelection::has_selection_in_scope( | |
| TextSelectionScopeId::from_raw(23), | |
| window, | |
| cx | |
| )); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn lazy_registration_does_not_enable_queries_without_the_element(cx: &mut TestAppContext) { | |
| let (_, cx) = cx.add_window_view(|_, cx| WindowSelectionView { | |
| selection: TextSelectionHandle::new("registered", cx), | |
| }); | |
| cx.update(|window, cx| { | |
| let selection = TextSelectionHandle::new("registered", cx); | |
| selection.set_local_selection(true, cx); | |
| let bounds = Bounds::new(point(px(0.), px(0.)), size(px(100.), px(20.))); | |
| let hitbox = Hitbox { | |
| dispatch_node: None, | |
| regions: None, | |
| id: HitboxId::placeholder(), | |
| bounds, | |
| content_mask: ContentMask { bounds }, | |
| behavior: HitboxBehavior::Normal, | |
| }; | |
| selection.register( | |
| TextSelectionRegistration::new(hitbox, bounds).with_text_bounds(vec![bounds]), | |
| window, | |
| cx, | |
| ); | |
| assert_eq!(TextSelection::selected_text(window, cx), ""); | |
| assert!(!TextSelection::has_selection(window, cx)); | |
| TextSelection::clear(window, cx); | |
| assert_eq!(TextSelection::selected_text(window, cx), ""); | |
| }); | |
| } | |
| /// A view reading the window's selection state, beside selectable text, | |
| /// counting its renders. | |
| #[cfg(feature = "gpui-fast")] | |
| struct SelectionStateReader { | |
| renders: Rc<Cell<usize>>, | |
| } | |
| #[cfg(feature = "gpui-fast")] | |
| impl Render for SelectionStateReader { | |
| fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { | |
| self.renders.set(self.renders.get() + 1); | |
| if let Some(state) = WindowSelectionState::existing(window, cx) { | |
| let _ = state.read(cx).participants.borrow().len(); | |
| } | |
| div().size_full() | |
| } | |
| } | |
| /// The selectable text of a [`ToggleSelectionElementView`] beside a | |
| /// [`SelectionStateReader`]. | |
| #[cfg(feature = "gpui-fast")] | |
| struct ReaderBesideSelectionView { | |
| text: gpui::Entity<ToggleSelectionElementView>, | |
| reader: gpui::Entity<SelectionStateReader>, | |
| } | |
| #[cfg(feature = "gpui-fast")] | |
| impl Render for ReaderBesideSelectionView { | |
| fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { | |
| div() | |
| .size_full() | |
| .child(self.reader.clone()) | |
| .child(self.text.clone()) | |
| } | |
| } | |
| /// Selectable text drawn again, nothing about its selection changed, | |
| /// writes neither the window's selection state nor its own: a view | |
| /// reading them is retained, as it would not be had they changed. | |
| #[cfg(feature = "gpui-fast")] | |
| #[gpui::test] | |
| fn redrawing_selectable_text_leaves_its_readers_retained(cx: &mut TestAppContext) { | |
| let renders = Rc::new(Cell::new(0)); | |
| let (view, cx) = cx.add_window_view(|_, cx| ReaderBesideSelectionView { | |
| text: cx.new(|cx| ToggleSelectionElementView { | |
| enabled: true, | |
| selection: TextSelectionHandle::new("text", cx), | |
| }), | |
| reader: cx.new(|_| SelectionStateReader { | |
| renders: renders.clone(), | |
| }), | |
| }); | |
| let text = cx.update(|_, cx| view.read(cx).text.clone()); | |
| let redraw = |cx: &mut gpui::VisualTestContext| { | |
| text.update(cx, |_, cx| cx.notify()); | |
| cx.update(|window, cx| { | |
| let _ = window.draw(cx); | |
| window.simulate_next_frame(cx); | |
| }); | |
| cx.run_until_parked(); | |
| }; | |
| redraw(cx); | |
| redraw(cx); | |
| let before = renders.get(); | |
| for _ in 0..4 { | |
| redraw(cx); | |
| } | |
| assert_eq!(renders.get(), before, "the reader rendered again"); | |
| } | |
| #[gpui::test] | |
| fn retained_selection_state_releases_and_does_not_resurrect_selection(cx: &mut TestAppContext) { | |
| let (view, cx) = cx.add_window_view(|_, cx| ToggleSelectionElementView { | |
| enabled: true, | |
| selection: TextSelectionHandle::new("local", cx), | |
| }); | |
| let selection = cx.update(|_, cx| view.read(cx).selection.clone()); | |
| cx.update(|window, cx| { | |
| let _ = window.draw(cx); | |
| selection.set_local_selection(true, cx); | |
| assert!(TextSelection::has_selection(window, cx)); | |
| window.simulate_next_frame(cx); | |
| assert!(TextSelection::has_selection(window, cx)); | |
| let _ = window.draw(cx); | |
| assert!(TextSelection::has_selection(window, cx)); | |
| }); | |
| view.update(cx, |view, cx| { | |
| view.enabled = false; | |
| cx.notify(); | |
| }); | |
| cx.update(|window, cx| { | |
| let _ = window.draw(cx); | |
| }); | |
| cx.update(|window, cx| { | |
| window.simulate_next_frame(cx); | |
| }); | |
| cx.update(|window, cx| { | |
| window.simulate_next_frame(cx); | |
| }); | |
| cx.run_until_parked(); | |
| cx.update(|window, cx| { | |
| assert!(!TextSelection::has_selection(window, cx)); | |
| assert_eq!(TextSelection::selected_text(window, cx), ""); | |
| assert!(!selection.has_local_selection(cx)); | |
| }); | |
| view.update(cx, |view, cx| { | |
| view.enabled = true; | |
| cx.notify(); | |
| }); | |
| cx.update(|window, cx| { | |
| let _ = window.draw(cx); | |
| assert!(!TextSelection::has_selection(window, cx)); | |
| assert_eq!(TextSelection::selected_text(window, cx), ""); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn mounted_selection_element_does_not_keep_an_idle_frame_queue_alive(cx: &mut TestAppContext) { | |
| let (_, cx) = cx.add_window_view(|_, _| SelectionElementOnlyView); | |
| cx.update(|window, cx| { | |
| let _ = window.draw(cx); | |
| assert_eq!(window.simulate_next_frame(cx), 0); | |
| assert_eq!(window.simulate_next_frame(cx), 0); | |
| assert!(live_text_selection_state(window, cx).is_some()); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn selection_element_initializes_suppression_and_respects_bubble_suppression( | |
| cx: &mut TestAppContext, | |
| ) { | |
| let (_, cx) = cx.add_window_view(|_, _| SelectionElementOnlyView); | |
| cx.update(|window, cx| { | |
| let _ = window.draw(cx); | |
| }); | |
| cx.simulate_mouse_down( | |
| point(px(1.), px(1.)), | |
| MouseButton::Left, | |
| gpui::Modifiers::default(), | |
| ); | |
| cx.simulate_mouse_up( | |
| point(px(1.), px(1.)), | |
| MouseButton::Left, | |
| gpui::Modifiers::default(), | |
| ); | |
| cx.update(|window, cx| { | |
| assert!(GlobalState::is_text_selection_suppressed(cx)); | |
| assert!(!TextSelection::has_selection(window, cx)); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn frame_sweep_keeps_a_participant_registered_before_the_selection_element_paints( | |
| cx: &mut TestAppContext, | |
| ) { | |
| with_selection_window(cx, |window, cx| { | |
| let mut selection_state = WindowSelectionState::default(); | |
| let participant = FakeParticipant::new("painted first", cx); | |
| participant.register( | |
| &mut selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 0, | |
| cx, | |
| ); | |
| selection_state.begin(point(px(1.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(8.), px(1.)), cx); | |
| selection_state.end(cx); | |
| selection_state.finish_frame(cx); | |
| assert_eq!(selection_state.selected_text(cx), "painted first"); | |
| assert!(participant.selection.snapshot(cx).is_some()); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn two_selection_elements_schedule_only_one_post_frame_sweep(cx: &mut TestAppContext) { | |
| let (view, cx) = cx.add_window_view(|_, cx| DoubleSelectionElementView { | |
| selection: TextSelectionHandle::new("once", cx), | |
| }); | |
| cx.update(|window, cx| { | |
| let selection_state = WindowSelectionState::ensure(window, cx); | |
| let selection = view.read(cx).selection.clone(); | |
| selection_state.update(cx, |selection_state, cx| { | |
| FakeParticipant { selection }.register( | |
| selection_state, | |
| 0., | |
| TextSelectionScopeId::default(), | |
| 0, | |
| cx, | |
| ); | |
| selection_state.begin(point(px(1.), px(1.)), false, window, cx); | |
| selection_state.update(point(px(8.), px(1.)), cx); | |
| selection_state.end(cx); | |
| }); | |
| let _ = window.draw(cx); | |
| window.simulate_next_frame(cx); | |
| let items = selection_state.read(cx).copy_items(cx); | |
| assert_eq!(resolve_copy_items(items, cx), "once"); | |
| }); | |
| } | |
| #[gpui::test] | |
| fn duplicate_selection_elements_gate_real_pointer_gestures_and_reentrant_clear( | |
| cx: &mut TestAppContext, | |
| ) { | |
| let (view, cx) = cx.add_window_view(|_, cx| DoubleSelectionElementView { | |
| selection: TextSelectionHandle::new("once", cx), | |
| }); | |
| let clear_count = Rc::new(Cell::new(0)); | |
| cx.update(|window, cx| { | |
| let state = WindowSelectionState::ensure(window, cx); | |
| let state_for_clear = state.clone(); | |
| let count = clear_count.clone(); | |
| let selection = view.read(cx).selection.clone(); | |
| selection | |
| .subscribe( | |
| move |event, cx| { | |
| if matches!(event, TextSelectionEvent::Cleared) { | |
| count.set(count.get() + 1); | |
| let _ = state_for_clear.read(cx).snapshot(); | |
| } | |
| }, | |
| cx, | |
| ) | |
| .detach(); | |
| let _ = window.draw(cx); | |
| }); | |
| cx.simulate_mouse_down( | |
| point(px(10.), px(10.)), | |
| MouseButton::Left, | |
| gpui::Modifiers::default(), | |
| ); | |
| cx.simulate_mouse_up( | |
| point(px(10.), px(10.)), | |
| MouseButton::Left, | |
| gpui::Modifiers::default(), | |
| ); | |
| cx.simulate_mouse_down( | |
| point(px(70.), px(10.)), | |
| MouseButton::Left, | |
| gpui::Modifiers { | |
| shift: true, | |
| ..Default::default() | |
| }, | |
| ); | |
| cx.simulate_mouse_up( | |
| point(px(70.), px(10.)), | |
| MouseButton::Left, | |
| gpui::Modifiers::default(), | |
| ); | |
| cx.update(|window, cx| assert!(TextSelection::has_selection(window, cx))); | |
| cx.simulate_mouse_down( | |
| point(px(15.), px(10.)), | |
| MouseButton::Left, | |
| gpui::Modifiers::default(), | |
| ); | |
| cx.simulate_mouse_move( | |
| point(px(85.), px(10.)), | |
| Some(MouseButton::Left), | |
| gpui::Modifiers::default(), | |
| ); | |
| cx.simulate_mouse_up( | |
| point(px(85.), px(10.)), | |
| MouseButton::Left, | |
| gpui::Modifiers::default(), | |
| ); | |
| cx.update(|window, cx| assert!(TextSelection::has_selection(window, cx))); | |
| assert_eq!(clear_count.get(), 3); | |
| } | |
| #[gpui::test] | |
| fn selection_layer_handles_real_double_and_triple_click_events(cx: &mut TestAppContext) { | |
| let (text, layout) = laid_out_runs(&["alpha beta"], cx).pop().unwrap(); | |
| let (view, cx) = cx.add_window_view(|_, cx| DoubleSelectionElementView { | |
| selection: TextSelectionHandle::new("", cx), | |
| }); | |
| cx.update(|window, cx| { | |
| let _ = window.draw(cx); | |
| let selection = view.read(cx).selection.clone(); | |
| selection.resolve_content_key_with(|_, _| Some(TextSelectionContentKey::new(17)), cx); | |
| selection.update_runs(&[text_run(0, text.clone(), layout.clone())], cx); | |
| }); | |
| let position = layout.position_for_index(7).unwrap(); | |
| cx.simulate_event(MouseDownEvent { | |
| position, | |
| modifiers: gpui::Modifiers::default(), | |
| button: MouseButton::Left, | |
| click_count: 2, | |
| first_mouse: false, | |
| }); | |
| cx.simulate_event(MouseUpEvent { | |
| position, | |
| modifiers: gpui::Modifiers::default(), | |
| button: MouseButton::Left, | |
| click_count: 2, | |
| }); | |
| cx.update(|window, cx| { | |
| let selection = view.read(cx).selection.clone(); | |
| selection.update_runs(&[text_run(0, text.clone(), layout.clone())], cx); | |
| assert_eq!(TextSelection::selected_text(window, cx), "beta"); | |
| let snapshot = selection.snapshot(cx).unwrap(); | |
| assert_eq!( | |
| snapshot.anchor().content_key(), | |
| Some(TextSelectionContentKey::new(17)) | |
| ); | |
| assert_eq!( | |
| snapshot.cursor().content_key(), | |
| Some(TextSelectionContentKey::new(17)) | |
| ); | |
| }); | |
| cx.simulate_event(MouseDownEvent { | |
| position, | |
| modifiers: gpui::Modifiers::default(), | |
| button: MouseButton::Left, | |
| click_count: 3, | |
| first_mouse: false, | |
| }); | |
| cx.simulate_event(MouseUpEvent { | |
| position, | |
| modifiers: gpui::Modifiers::default(), | |
| button: MouseButton::Left, | |
| click_count: 3, | |
| }); | |
| cx.update(|window, cx| { | |
| let selection = view.read(cx).selection.clone(); | |
| selection.update_runs(&[text_run(0, text, layout)], cx); | |
| assert_eq!(TextSelection::selected_text(window, cx), "alpha beta"); | |
| }); | |
| } | |
| } |