1use std::ops::Range;
2
3use gpui::{
4 App, BorderStyle, Bounds, Corners, Edges, Element, ElementId, GlobalElementId, HighlightStyle,
5 Hitbox, HitboxBehavior, Hsla, InspectorElementId, LayoutId, PaintQuad, Pixels, Point,
6 SharedString, StyledText, Subscription, TextStyleRefinement, Window, transparent_black,
7};
8
9use crate::{TextSelectionHandle, TextSelectionRegistration, TextSelectionRun};
10
11pub struct SelectableText {
20 id: ElementId,
21 handle: Option<TextSelectionHandle>,
22 text: SharedString,
23 styled_text: StyledText,
24 document_order: u64,
25 text_style: Option<TextStyleRefinement>,
26 selection_color: Option<Hsla>,
27}
28
29impl SelectableText {
30 pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
32 Self::build(id.into(), None, text.into())
33 }
34
35 pub fn with_handle(
37 id: impl Into<ElementId>,
38 handle: TextSelectionHandle,
39 text: impl Into<SharedString>,
40 ) -> Self {
41 Self::build(id.into(), Some(handle), text.into())
42 }
43
44 fn build(id: ElementId, handle: Option<TextSelectionHandle>, text: SharedString) -> Self {
45 Self {
46 id,
47 handle,
48 styled_text: StyledText::new(text.clone()),
49 text,
50 document_order: 0,
51 text_style: None,
52 selection_color: None,
53 }
54 }
55
56 pub fn document_order(mut self, order: u64) -> Self {
58 self.document_order = order;
59 self
60 }
61
62 pub fn text_style(mut self, style: TextStyleRefinement) -> Self {
64 self.text_style = Some(style);
65 self
66 }
67
68 pub fn highlights(
72 mut self,
73 highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
74 ) -> Self {
75 self.styled_text = self.styled_text.with_highlights(highlights);
76 self
77 }
78
79 pub fn selection_color(mut self, color: Hsla) -> Self {
82 self.selection_color = Some(color);
83 self
84 }
85
86 fn paint_selection(
87 layout: &gpui::TextLayout,
88 range: Range<usize>,
89 color: Hsla,
90 window: &mut Window,
91 ) {
92 let (Some(start), Some(end)) = (
93 layout.position_for_index(range.start),
94 layout.position_for_index(range.end),
95 ) else {
96 return;
97 };
98 for bounds in selection_quad_bounds(start, end, layout.bounds(), layout.line_height()) {
99 window.paint_quad(PaintQuad {
100 bounds,
101 background: color.into(),
102 corner_radii: Corners::default(),
103 border_widths: Edges::default(),
104 border_color: transparent_black(),
105 border_style: BorderStyle::default(),
106 });
107 }
108 }
109}
110
111struct OwnedSelection {
113 handle: TextSelectionHandle,
114 _refresh: Subscription,
116}
117
118fn selection_quad_bounds(
119 start: Point<Pixels>,
120 end: Point<Pixels>,
121 bounds: Bounds<Pixels>,
122 line_height: Pixels,
123) -> Vec<Bounds<Pixels>> {
124 if start.y == end.y {
125 return vec![Bounds::from_corners(
126 start,
127 Point::new(end.x, end.y + line_height),
128 )];
129 }
130
131 let mut quads = vec![Bounds::from_corners(
132 start,
133 Point::new(bounds.right(), start.y + line_height),
134 )];
135 if end.y > start.y + line_height {
136 quads.push(Bounds::from_corners(
137 Point::new(bounds.left(), start.y + line_height),
138 Point::new(bounds.right(), end.y),
139 ));
140 }
141 quads.push(Bounds::from_corners(
142 Point::new(bounds.left(), end.y),
143 Point::new(end.x, end.y + line_height),
144 ));
145 quads
146}
147
148#[cfg(not(feature = "gpui-fast"))]
149impl gpui::IntoElement for SelectableText {
150 type Element = Self;
151
152 fn into_element(self) -> Self::Element {
153 self
154 }
155}
156
157impl Element for SelectableText {
158 type RequestLayoutState = TextSelectionHandle;
159 type PrepaintState = Hitbox;
160
161 fn id(&self) -> Option<ElementId> {
162 Some(self.id.clone())
163 }
164
165 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
166 None
167 }
168
169 fn request_layout(
170 &mut self,
171 global_id: Option<&GlobalElementId>,
172 inspector_id: Option<&InspectorElementId>,
173 window: &mut Window,
174 cx: &mut App,
175 ) -> (LayoutId, Self::RequestLayoutState) {
176 let handle = self.handle.clone().unwrap_or_else(|| {
177 window.with_element_state(
178 global_id.expect("SelectableText must have a stable element id"),
179 |retained: Option<OwnedSelection>, window| {
180 let retained = retained.unwrap_or_else(|| {
181 let handle = TextSelectionHandle::new(self.text.clone(), cx);
182 let refresh = handle.refresh_window_on_change(window, cx);
183 OwnedSelection {
184 handle,
185 _refresh: refresh,
186 }
187 });
188 (retained.handle.clone(), retained)
189 },
190 )
191 });
192 let (layout_id, ()) = if let Some(style) = self.text_style.clone() {
193 window.with_text_style(Some(style), |window| {
194 self.styled_text
195 .request_layout(global_id, inspector_id, window, cx)
196 })
197 } else {
198 self.styled_text
199 .request_layout(global_id, inspector_id, window, cx)
200 };
201 (layout_id, handle)
202 }
203
204 fn prepaint(
205 &mut self,
206 global_id: Option<&GlobalElementId>,
207 inspector_id: Option<&InspectorElementId>,
208 bounds: Bounds<Pixels>,
209 handle: &mut Self::RequestLayoutState,
210 window: &mut Window,
211 cx: &mut App,
212 ) -> Self::PrepaintState {
213 self.styled_text
214 .prepaint(global_id, inspector_id, bounds, &mut (), window, cx);
215 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
216 let registration = TextSelectionRegistration::new(hitbox.clone(), bounds)
217 .with_document_order(self.document_order)
218 .with_text_bounds(vec![bounds])
219 .with_rendered_element(handle, window, cx);
220 handle.register(registration, window, cx);
221 hitbox
222 }
223
224 fn paint(
225 &mut self,
226 global_id: Option<&GlobalElementId>,
227 inspector_id: Option<&InspectorElementId>,
228 bounds: Bounds<Pixels>,
229 handle: &mut Self::RequestLayoutState,
230 _: &mut Self::PrepaintState,
231 window: &mut Window,
232 cx: &mut App,
233 ) {
234 let layout = self.styled_text.layout().clone();
235 let copy_text_before = handle.projected_copy_text(cx);
236 let projection = handle.update_runs(
237 &[
238 TextSelectionRun::new(self.text.clone(), layout.clone(), bounds)
239 .with_document_order(self.document_order),
240 ],
241 cx,
242 );
243 if copy_text_before != handle.projected_copy_text(cx) {
244 window.refresh();
245 }
246 let color = self
247 .selection_color
248 .unwrap_or_else(|| crate::Theme::global(cx).tokens.colors.selection);
249 for range in projection.ranges().iter().flatten().cloned() {
250 Self::paint_selection(&layout, range, color, window);
251 }
252 self.styled_text.paint(
253 global_id,
254 inspector_id,
255 bounds,
256 &mut (),
257 &mut (),
258 window,
259 cx,
260 );
261 }
262}
263
264#[cfg(test)]
265mod tests {
266 use std::{cell::Cell, rc::Rc};
267
268 use gpui::{
269 AppContext as _, Bounds, Context, IntoElement, Modifiers, MouseButton, ParentElement as _,
270 Render, Styled as _, TestAppContext, Window, div, point, px, size,
271 };
272
273 use super::SelectableText;
274 use crate::{TextSelection, TextSelectionHandle, TextSelectionLayer};
275
276 struct SelectableTextTestView;
277
278 impl Render for SelectableTextTestView {
279 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
280 div().size_full().child(TextSelectionLayer).child(
281 div()
282 .w(px(240.))
283 .h(px(32.))
284 .child(SelectableText::new("local", "alpha beta")),
285 )
286 }
287 }
288
289 #[gpui::test]
290 fn explicit_handle_constructor_preserves_document_contract(cx: &mut TestAppContext) {
291 cx.update(|cx| {
292 let handle = TextSelectionHandle::new("alpha beta", cx);
293 let _ = SelectableText::with_handle("plain", handle, "alpha beta").document_order(42);
294 });
295 }
296
297 #[gpui::test]
298 fn local_handle_participates_in_window_selection(cx: &mut TestAppContext) {
299 let (_, cx) = cx.add_window_view(|_, _| SelectableTextTestView);
300 cx.update(|window, cx| {
301 let _ = window.draw(cx);
302 });
303
304 cx.simulate_mouse_down(
305 gpui::point(px(1.), px(12.)),
306 MouseButton::Left,
307 Modifiers::default(),
308 );
309 cx.simulate_mouse_move(
310 gpui::point(px(220.), px(12.)),
311 Some(MouseButton::Left),
312 Modifiers::default(),
313 );
314 cx.simulate_mouse_up(
315 gpui::point(px(220.), px(12.)),
316 MouseButton::Left,
317 Modifiers::default(),
318 );
319 cx.update(|window, cx| {
320 let _ = window.draw(cx);
321 assert_eq!(TextSelection::selected_text(window, cx), "alpha beta");
322 });
323 }
324
325 struct HighlightedTestView;
326
327 impl Render for HighlightedTestView {
328 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
329 let mark = gpui::HighlightStyle {
330 background_color: Some(gpui::red()),
331 font_weight: Some(gpui::FontWeight::BOLD),
332 ..Default::default()
333 };
334 div().size_full().child(TextSelectionLayer).child(
335 div()
336 .w(px(240.))
337 .h(px(32.))
338 .child(SelectableText::new("local", "alpha beta").highlights([(6..10, mark)])),
339 )
340 }
341 }
342
343 #[gpui::test]
344 fn highlighted_text_selects_and_copies_as_plain_text(cx: &mut TestAppContext) {
345 let (_, cx) = cx.add_window_view(|_, _| HighlightedTestView);
346 cx.update(|window, cx| {
347 let _ = window.draw(cx);
348 });
349
350 cx.simulate_mouse_down(
351 gpui::point(px(1.), px(12.)),
352 MouseButton::Left,
353 Modifiers::default(),
354 );
355 cx.simulate_mouse_move(
356 gpui::point(px(220.), px(12.)),
357 Some(MouseButton::Left),
358 Modifiers::default(),
359 );
360 cx.simulate_mouse_up(
361 gpui::point(px(220.), px(12.)),
362 MouseButton::Left,
363 Modifiers::default(),
364 );
365 cx.update(|window, cx| {
366 let _ = window.draw(cx);
367 assert_eq!(TextSelection::selected_text(window, cx), "alpha beta");
368 });
369 }
370
371 struct CachedText {
372 renders: Rc<Cell<usize>>,
373 }
374
375 impl Render for CachedText {
376 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
377 self.renders.set(self.renders.get() + 1);
378 SelectableText::new("local", "alpha beta")
379 }
380 }
381
382 struct CachedTextParent {
383 text: gpui::Entity<CachedText>,
384 }
385
386 impl Render for CachedTextParent {
387 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
388 div().size_full().child(TextSelectionLayer).child(
389 gpui::AnyView::from(self.text.clone())
390 .cached(gpui::StyleRefinement::default().w(px(240.)).h(px(32.))),
391 )
392 }
393 }
394
395 #[gpui::test]
396 fn a_drag_redraws_the_text_before_the_button_is_released(cx: &mut TestAppContext) {
397 let renders = Rc::new(Cell::new(0));
398 let (_, cx) = cx.add_window_view({
399 let renders = renders.clone();
400 move |_, cx| CachedTextParent {
401 text: gpui::AppContext::new(cx, |_| CachedText { renders }),
402 }
403 });
404 let draw = |cx: &mut gpui::VisualTestContext| {
405 cx.update(|window, cx| {
406 let _ = window.draw(cx);
407 });
408 };
409 draw(cx);
410 let before = renders.get();
411 draw(cx);
412 assert_eq!(
413 renders.get(),
414 before,
415 "the text is cached while nothing changes"
416 );
417
418 cx.simulate_mouse_down(
419 gpui::point(px(1.), px(12.)),
420 MouseButton::Left,
421 Modifiers::default(),
422 );
423 draw(cx);
424 let pressed = renders.get();
425 cx.simulate_mouse_move(
426 gpui::point(px(220.), px(12.)),
427 Some(MouseButton::Left),
428 Modifiers::default(),
429 );
430 draw(cx);
431 assert!(
432 renders.get() > pressed,
433 "the selection is drawn as the pointer moves"
434 );
435 }
436
437 struct CopyCallbackTestView {
438 handle: TextSelectionHandle,
439 }
440
441 impl Render for CopyCallbackTestView {
442 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
443 div()
444 .size_full()
445 .child(TextSelectionLayer)
446 .child(SelectableText::new("local", "alpha beta"))
447 .child(SelectableText::with_handle(
448 "custom",
449 self.handle.clone(),
450 "gamma",
451 ))
452 }
453 }
454
455 #[gpui::test]
456 fn paint_does_not_resolve_window_selected_text(cx: &mut TestAppContext) {
457 let copies = Rc::new(Cell::new(0));
458 let handle = cx.update(|cx| {
459 let handle = TextSelectionHandle::new("gamma", cx);
460 let copies = copies.clone();
461 handle.copy_with(
462 move |_| {
463 copies.set(copies.get() + 1);
464 "gamma".into()
465 },
466 cx,
467 );
468 handle.set_local_selection(true, cx);
469 handle
470 });
471 let (_, cx) = cx.add_window_view(|_, _| CopyCallbackTestView { handle });
472 cx.update(|window, cx| {
473 let _ = window.draw(cx);
474 });
475 copies.set(0);
476
477 cx.update(|window, cx| {
478 let _ = window.draw(cx);
479 });
480
481 assert_eq!(copies.get(), 0);
482 }
483
484 #[test]
485 fn wrapped_selection_paints_full_width_middle_lines() {
486 let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(100.)));
487 let quads = super::selection_quad_bounds(
488 point(px(40.), px(20.)),
489 point(px(30.), px(80.)),
490 bounds,
491 px(20.),
492 );
493
494 assert_eq!(
495 quads,
496 vec![
497 Bounds::from_corners(point(px(40.), px(20.)), point(px(110.), px(40.))),
498 Bounds::from_corners(point(px(10.), px(40.)), point(px(110.), px(80.))),
499 Bounds::from_corners(point(px(10.), px(80.)), point(px(30.), px(100.))),
500 ]
501 );
502 }
503
504 struct ControlTestView {
507 control: gpui::Entity<ControlView>,
508 cached: bool,
509 }
510
511 struct ControlView {
512 renders: Rc<Cell<usize>>,
513 }
514
515 impl Render for ControlView {
516 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
517 use crate::ElementExt as _;
518 self.renders.set(self.renders.get() + 1);
519 div().w(px(60.)).h(px(20.)).keep_text_selection("control")
520 }
521 }
522
523 impl Render for ControlTestView {
524 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
525 let control = gpui::AnyView::from(self.control.clone());
526 let control = if self.cached {
527 control
528 .cached(gpui::StyleRefinement::default().w(px(60.)).h(px(20.)))
529 .into_any_element()
530 } else {
531 control.into_any_element()
532 };
533 div()
534 .size_full()
535 .child(TextSelectionLayer)
536 .child(
537 div()
538 .w(px(240.))
539 .h(px(32.))
540 .child(SelectableText::new("local", "alpha beta")),
541 )
542 .child(control)
543 }
544 }
545
546 fn press(position: gpui::Point<gpui::Pixels>, cx: &mut gpui::VisualTestContext) {
547 cx.simulate_mouse_down(position, MouseButton::Left, Modifiers::default());
548 cx.simulate_mouse_up(position, MouseButton::Left, Modifiers::default());
549 }
550
551 fn select_line(cx: &mut gpui::VisualTestContext) {
552 cx.simulate_mouse_down(
553 point(px(1.), px(12.)),
554 MouseButton::Left,
555 Modifiers::default(),
556 );
557 cx.simulate_mouse_move(
558 point(px(220.), px(12.)),
559 Some(MouseButton::Left),
560 Modifiers::default(),
561 );
562 cx.simulate_mouse_up(
563 point(px(220.), px(12.)),
564 MouseButton::Left,
565 Modifiers::default(),
566 );
567 cx.update(|window, cx| {
568 let _ = window.draw(cx);
569 assert_eq!(TextSelection::selected_text(window, cx), "alpha beta");
570 });
571 }
572
573 fn selected(cx: &mut gpui::VisualTestContext) -> String {
574 cx.update(|window, cx| {
575 let _ = window.draw(cx);
576 TextSelection::selected_text(window, cx)
577 })
578 }
579
580 #[gpui::test]
581 fn a_press_on_an_element_marked_keep_text_selection_keeps_it(cx: &mut TestAppContext) {
582 for cached in [false, true] {
583 let renders = Rc::new(Cell::new(0));
584 let (view, cx) = cx.add_window_view(|_, cx| ControlTestView {
585 control: cx.new(|_| ControlView {
586 renders: renders.clone(),
587 }),
588 cached,
589 });
590 cx.update(|window, cx| {
591 let _ = window.draw(cx);
592 });
593 select_line(cx);
594 let drawn = renders.get();
596 view.update(cx, |_, cx| cx.notify());
597 assert_eq!(selected(cx), "alpha beta");
598 assert_eq!(renders.get() == drawn, cached);
599
600 press(point(px(30.), px(42.)), cx);
601 assert_eq!(selected(cx), "alpha beta", "cached: {cached}");
602 press(point(px(120.), px(42.)), cx);
604 assert_eq!(selected(cx), "", "cached: {cached}");
605 }
606 }
607}