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