BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-base / src / text / selection_adapter.rs

selection_adapter.rs

eef6c0a4 History
selection_adapter.rs 10.3 KiB Download Raw
1use std::{cell::RefCell, ops::RangeInclusive, rc::Rc};
2
3use crate::{
4 TextSelectionContentKey, TextSelectionCoverage, TextSelectionEndpoint, TextSelectionEvent,
5 TextSelectionHandle, TextSelectionRegistration, TextSelectionRun, TextSelectionSnapshot,
6};
7use gpui::{App, Bounds, EntityId, Hitbox, Pixels, Point, WeakEntity, Window};
8
9use super::TextViewState;
10
11#[derive(Clone, Copy, Debug, PartialEq)]
12struct CachedBlockEndpoint {
13 endpoint: TextSelectionEndpoint,
14 block_ix: Option<usize>,
15}
16
17#[derive(Default)]
18struct VirtualBlockSelection {
19 anchor: Option<CachedBlockEndpoint>,
20 cursor: Option<CachedBlockEndpoint>,
21 coverage: TextSelectionCoverage,
22}
23
24impl VirtualBlockSelection {
25 fn update(&mut self, snapshot: Option<TextSelectionSnapshot>, entity_id: EntityId) {
26 let Some(snapshot) = snapshot else {
27 *self = Self::default();
28 return;
29 };
30
31 self.coverage = snapshot.coverage();
32
33 Self::update_endpoint(&mut self.anchor, snapshot.anchor(), entity_id);
34 Self::update_endpoint(&mut self.cursor, snapshot.cursor(), entity_id);
35 }
36
37 fn update_endpoint(
38 cached: &mut Option<CachedBlockEndpoint>,
39 endpoint: TextSelectionEndpoint,
40 entity_id: EntityId,
41 ) {
42 if cached.is_some_and(|cached| cached.endpoint == endpoint) {
43 return;
44 }
45 let block_ix = (endpoint.entity_id() == Some(entity_id))
46 .then(|| endpoint.content_key().map(|key| key.value() as usize))
47 .flatten();
48 *cached = Some(CachedBlockEndpoint { endpoint, block_ix });
49 }
50
51 fn block_range(&self, entity_id: EntityId, last: usize) -> Option<RangeInclusive<usize>> {
52 let anchor = self.anchor?;
53 let cursor = self.cursor?;
54 match self.coverage {
55 TextSelectionCoverage::Full => Some(0..=last),
56 TextSelectionCoverage::FromStart => Some(0..=anchor.block_ix.or(cursor.block_ix)?),
57 TextSelectionCoverage::ToEnd => Some(anchor.block_ix.or(cursor.block_ix)?..=last),
58 TextSelectionCoverage::Bounded => {
59 if anchor.endpoint.entity_id() != Some(entity_id)
60 || cursor.endpoint.entity_id() != Some(entity_id)
61 {
62 return None;
63 }
64 let (anchor, cursor) = (anchor.block_ix?, cursor.block_ix?);
65 Some(anchor.min(cursor)..=anchor.max(cursor))
66 }
67 }
68 }
69}
70
71/// TextView's renderer-specific bridge to base-owned window selection.
72#[derive(Clone)]
73pub(super) struct TextViewSelectionAdapter {
74 selection: TextSelectionHandle,
75 text_bounds: Vec<Bounds<Pixels>>,
76 text_runs: Vec<TextSelectionRun>,
77 /// The caret boxes at the first and last selected character painted this
78 /// frame, where the touch handles go.
79 selection_edges: Option<(Bounds<Pixels>, Bounds<Pixels>)>,
80 layout_revision: Option<usize>,
81}
82
83impl TextViewSelectionAdapter {
84 pub(super) fn new(view: WeakEntity<TextViewState>, cx: &mut App) -> Self {
85 let selection = TextSelectionHandle::new("", cx);
86 let selection_id = selection.entity_id();
87 let virtual_blocks = Rc::new(RefCell::new(VirtualBlockSelection::default()));
88
89 let view_for_events = view.clone();
90 let blocks_for_events = virtual_blocks.clone();
91 selection
92 .subscribe(
93 move |event, cx| match event {
94 TextSelectionEvent::SelectionChanged(snapshot) => {
95 let snapshot = *snapshot;
96 let _ = view_for_events.update(cx, |state, cx| {
97 state.preserve_inline_selection = false;
98 blocks_for_events
99 .borrow_mut()
100 .update(snapshot, selection_id);
101 state.is_selecting =
102 snapshot.is_some_and(|snapshot| snapshot.is_selecting());
103 cx.notify();
104 });
105 }
106 TextSelectionEvent::AutoScroll(delta) => {
107 let delta = *delta;
108 let _ = view_for_events.update(cx, |state, cx| {
109 if state.scrollable {
110 state.set_auto_scroll(delta, cx);
111 } else if delta.is_none() {
112 state.stop_auto_scroll();
113 }
114 });
115 }
116 TextSelectionEvent::Cleared => {}
117 TextSelectionEvent::TouchSelectionChanged => {
118 let _ = view_for_events.update(cx, |_, cx| cx.notify());
119 }
120 },
121 cx,
122 )
123 .detach();
124
125 let view_for_clear = view.clone();
126 let blocks_for_clear = virtual_blocks.clone();
127 selection.clear_with(
128 move |cx| {
129 blocks_for_clear.replace(VirtualBlockSelection::default());
130 let _ = view_for_clear.update(cx, |state, cx| {
131 state.reset_selection();
132 cx.notify();
133 });
134 },
135 cx,
136 );
137
138 let view_for_copy = view.clone();
139 let blocks_for_copy = virtual_blocks.clone();
140 selection.copy_with(
141 move |cx| {
142 let Some(view) = view_for_copy.upgrade() else {
143 return String::new();
144 };
145 let state = view.read(cx);
146 let last = state.parsed_content.document.blocks.len().saturating_sub(1);
147 let blocks = blocks_for_copy.borrow().block_range(selection_id, last);
148 state.selected_text_in(blocks)
149 },
150 cx,
151 );
152
153 let view_for_content_key = view.clone();
154 selection.resolve_content_key_with(
155 move |point, cx| {
156 let view = view_for_content_key.upgrade()?;
157 view.read(cx)
158 .block_ix_at(point.y)
159 .map(|block| TextSelectionContentKey::new(block as u64))
160 },
161 cx,
162 );
163
164 selection.focus_with(
165 move |window, cx| {
166 let Some(view) = view.upgrade() else {
167 return;
168 };
169 let focus_handle = view.read(cx).focus_handle.clone();
170 view.update(cx, |state, _| state.is_selecting = true);
171 focus_handle.focus(window, cx);
172 },
173 cx,
174 );
175
176 Self {
177 selection,
178 text_bounds: Vec::new(),
179 text_runs: Vec::new(),
180 selection_edges: None,
181 layout_revision: None,
182 }
183 }
184
185 pub(super) fn update_layout_revision(&mut self, revision: usize, is_selecting: bool) -> bool {
186 let changed = self
187 .layout_revision
188 .is_some_and(|previous| previous != revision);
189 if !changed || !is_selecting {
190 self.layout_revision = Some(revision);
191 }
192 changed && !is_selecting
193 }
194
195 pub(super) fn begin_frame(&mut self) {
196 self.text_bounds.clear();
197 self.text_runs.clear();
198 self.selection_edges = None;
199 }
200
201 /// Records one inline's painted selection ends. Inlines paint in document
202 /// order, so the first start and the last end are the view's.
203 pub(super) fn register_selection_edges(&mut self, start: Bounds<Pixels>, end: Bounds<Pixels>) {
204 let first = self.selection_edges.map_or(start, |(first, _)| first);
205 self.selection_edges = Some((first, end));
206 }
207
208 pub(super) fn register_text_run(&mut self, run: TextSelectionRun) {
209 self.text_runs.push(run);
210 }
211
212 pub(super) fn register_inline(&mut self, bounds: Vec<Bounds<Pixels>>) {
213 self.text_bounds.extend(bounds);
214 }
215
216 #[allow(clippy::too_many_arguments)]
217 pub(super) fn register(
218 &self,
219 hitbox: Hitbox,
220 bounds: Bounds<Pixels>,
221 scroll_offset: Point<Pixels>,
222 document_order: u64,
223 self_scroll: bool,
224 window: &mut Window,
225 cx: &mut App,
226 ) {
227 self.selection.set_hit_test_runs(&self.text_runs, cx);
228 let registration = TextSelectionRegistration::new(hitbox, bounds)
229 .with_scroll_offset(scroll_offset)
230 .with_document_order(document_order)
231 .with_text_bounds(self.text_bounds.clone())
232 .with_self_scroll(self_scroll)
233 .with_rendered_element(&self.selection, window, cx);
234 let registration = match self.selection_edges {
235 Some((start, end)) => registration.with_selection_edges(start, end),
236 None => registration,
237 };
238 self.selection.register(registration, window, cx);
239 }
240
241 /// Lays out the touch handles this view owns; see
242 /// [`TextSelectionHandle::prepaint_touch_handles`].
243 pub(super) fn prepaint_touch_handles(
244 &self,
245 window: &mut Window,
246 cx: &App,
247 ) -> crate::TouchHandleLayout {
248 self.selection.prepaint_touch_handles(window, cx)
249 }
250
251 /// Paints the touch handles this view owns, after its content for the
252 /// frame; see [`TextSelectionHandle::paint_touch_handles`].
253 pub(super) fn paint_touch_handles(
254 &self,
255 layout: &crate::TouchHandleLayout,
256 color: gpui::Hsla,
257 window: &mut Window,
258 cx: &mut App,
259 ) {
260 self.selection
261 .paint_touch_handles(layout, color, window, cx);
262 }
263
264 pub(super) fn selection_points(&self, cx: &App) -> Option<(Point<Pixels>, Point<Pixels>)> {
265 let points = self.selection.snapshot(cx)?.window_points()?;
266 Some((points.anchor(), points.cursor()))
267 }
268
269 pub(super) fn set_local_selection(&self, active: bool, cx: &mut App) {
270 self.selection.set_local_selection(active, cx);
271 }
272
273 pub(super) fn is_part_of_window_selection(&self, cx: &App) -> bool {
274 let id = self.selection.entity_id();
275 self.selection.snapshot(cx).is_some_and(|snapshot| {
276 snapshot.anchor().entity_id() == Some(id) || snapshot.cursor().entity_id() == Some(id)
277 })
278 }
279
280 pub(super) fn has_selection_snapshot(&self, cx: &App) -> bool {
281 self.selection.snapshot(cx).is_some()
282 }
283
284 #[cfg(test)]
285 pub(super) fn text_bounds(&self) -> Vec<Bounds<Pixels>> {
286 self.text_bounds.clone()
287 }
288}