BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / text / window_selection.rs

window_selection.rs

window_selection.rs 81.0 KiB Download Raw
1#[cfg(test)]
2mod tests {
3 use crate::global_state::GlobalState;
4 use crate::{
5 Placement, Root,
6 text::{TextView, TextViewState},
7 };
8 use gpui::{
9 App, AppContext as _, Bounds, Context, Element, ElementId, Entity, FocusHandle,
10 GlobalElementId, Hitbox, InspectorElementId, InteractiveElement as _, IntoElement,
11 LayoutId, Modifiers, MouseButton, MouseDownEvent, MouseUpEvent, ParentElement as _, Pixels,
12 Render, SharedString, Styled as _, StyledText, TestAppContext, VisualTestContext, Window,
13 div, point, px, relative,
14 };
15 use gpui_base::{
16 AutoScroll, TextSelection, TextSelectionHandle, TextSelectionRegistration, TextSelectionRun,
17 };
18 use std::cell::{Cell, RefCell};
19 use std::rc::Rc;
20 use std::time::Duration;
21
22 struct PlainSelectableText {
23 selection: TextSelectionHandle,
24 text: SharedString,
25 styled_text: StyledText,
26 document_order: u64,
27 }
28
29 impl PlainSelectableText {
30 fn new(selection: TextSelectionHandle, text: impl Into<SharedString>) -> Self {
31 let text = text.into();
32 Self {
33 selection,
34 styled_text: StyledText::new(text.clone()),
35 text,
36 document_order: 0,
37 }
38 }
39
40 fn document_order(mut self, document_order: u64) -> Self {
41 self.document_order = document_order;
42 self
43 }
44 }
45
46 impl IntoElement for PlainSelectableText {
47 type Element = Self;
48
49 fn into_element(self) -> Self::Element {
50 self
51 }
52 }
53
54 impl Element for PlainSelectableText {
55 type RequestLayoutState = ();
56 type PrepaintState = Hitbox;
57
58 fn id(&self) -> Option<ElementId> {
59 None
60 }
61
62 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
63 None
64 }
65
66 fn request_layout(
67 &mut self,
68 id: Option<&GlobalElementId>,
69 inspector_id: Option<&InspectorElementId>,
70 window: &mut Window,
71 cx: &mut App,
72 ) -> (LayoutId, Self::RequestLayoutState) {
73 self.styled_text
74 .request_layout(id, inspector_id, window, cx)
75 }
76
77 fn prepaint(
78 &mut self,
79 id: Option<&GlobalElementId>,
80 inspector_id: Option<&InspectorElementId>,
81 bounds: Bounds<Pixels>,
82 _: &mut Self::RequestLayoutState,
83 window: &mut Window,
84 cx: &mut App,
85 ) -> Self::PrepaintState {
86 self.styled_text
87 .prepaint(id, inspector_id, bounds, &mut (), window, cx);
88 let hitbox = window.insert_hitbox(bounds, gpui::HitboxBehavior::Normal);
89 self.selection.register(
90 TextSelectionRegistration::new(hitbox.clone(), bounds)
91 .with_document_order(self.document_order)
92 .with_text_bounds(vec![bounds]),
93 window,
94 cx,
95 );
96 hitbox
97 }
98
99 fn paint(
100 &mut self,
101 id: Option<&GlobalElementId>,
102 inspector_id: Option<&InspectorElementId>,
103 bounds: Bounds<Pixels>,
104 _: &mut Self::RequestLayoutState,
105 _: &mut Self::PrepaintState,
106 window: &mut Window,
107 cx: &mut App,
108 ) {
109 let layout = self.styled_text.layout().clone();
110 self.selection.update_runs(
111 &[TextSelectionRun::new(self.text.clone(), layout, bounds).with_document_order(0)],
112 cx,
113 );
114 self.styled_text
115 .paint(id, inspector_id, bounds, &mut (), &mut (), window, cx);
116 }
117 }
118
119 struct MixedAdapterView {
120 plain_selection: TextSelectionHandle,
121 text_view: Entity<TextViewState>,
122 }
123
124 impl MixedAdapterView {
125 fn new(cx: &mut Context<Self>) -> Self {
126 Self {
127 plain_selection: TextSelectionHandle::new("", cx),
128 text_view: cx.new(|cx| TextViewState::markdown("TextView adapter", cx)),
129 }
130 }
131 }
132
133 impl Render for MixedAdapterView {
134 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
135 div()
136 .size_full()
137 .pt(px(10.))
138 .child(div().h(px(40.)).child(PlainSelectableText::new(
139 self.plain_selection.clone(),
140 "Plain adapter",
141 )))
142 .child(
143 div()
144 .h(px(40.))
145 .child(TextView::new(&self.text_view).selectable(true)),
146 )
147 }
148 }
149
150 struct BaseOwnedTextViewSelection {
151 text_view: Entity<TextViewState>,
152 }
153
154 struct CrossRendererVirtualView {
155 top_selection: TextSelectionHandle,
156 bottom_selection: TextSelectionHandle,
157 text_view: Entity<TextViewState>,
158 format: crate::text::SelectionFormat,
159 }
160
161 impl CrossRendererVirtualView {
162 fn new(format: crate::text::SelectionFormat, cx: &mut Context<Self>) -> Self {
163 let source = (0..20)
164 .map(|ix| format!("**Paragraph{ix}**"))
165 .collect::<Vec<_>>()
166 .join("\n\n");
167 Self {
168 top_selection: TextSelectionHandle::new("", cx),
169 bottom_selection: TextSelectionHandle::new("", cx),
170 text_view: cx.new(|cx| TextViewState::markdown(&source, cx)),
171 format,
172 }
173 }
174 }
175
176 impl Render for CrossRendererVirtualView {
177 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
178 div()
179 .size_full()
180 .pt(px(10.))
181 .child(
182 div().h(px(40.)).child(
183 PlainSelectableText::new(self.top_selection.clone(), "Top plain")
184 .document_order(0),
185 ),
186 )
187 .child(
188 div().h(px(80.)).child(
189 TextView::new(&self.text_view)
190 .selectable(true)
191 .scrollable(true)
192 .selection_format(self.format),
193 ),
194 )
195 .child(
196 div().h(px(40.)).child(
197 PlainSelectableText::new(self.bottom_selection.clone(), "Bottom plain")
198 .document_order(2),
199 ),
200 )
201 }
202 }
203
204 enum CrossRendererVirtualScenario {
205 PlainToVirtualTail,
206 VirtualHeadToPlain,
207 VirtualInMiddle,
208 }
209
210 fn assert_cross_renderer_virtual_export(
211 format: crate::text::SelectionFormat,
212 scenario: CrossRendererVirtualScenario,
213 cx: &mut TestAppContext,
214 ) {
215 use gpui::ListOffset;
216
217 cx.update(crate::init);
218 let (root, cx) = cx.add_window_view(move |window, cx| {
219 let content = cx.new(|cx| CrossRendererVirtualView::new(format, cx));
220 Root::new(content, window, cx)
221 });
222 let content = root.read_with(cx, |root, _| {
223 root.view()
224 .clone()
225 .downcast::<CrossRendererVirtualView>()
226 .unwrap()
227 });
228 let cx: &mut VisualTestContext = cx;
229 cx.run_until_parked();
230 cx.update(|window, cx| {
231 let _ = window.draw(cx);
232 });
233 let (bounds, list_state) = content.read_with(cx, |content, cx| {
234 let state = content.text_view.read(cx);
235 (state.bounds(), state.list_state().clone())
236 });
237 let top_plain = point(px(1.), bounds.origin.y - px(20.));
238 let bottom_plain = point(px(1.), bounds.bottom() + px(20.));
239
240 match scenario {
241 CrossRendererVirtualScenario::PlainToVirtualTail => {
242 list_state.scroll_to(ListOffset {
243 item_ix: 19,
244 offset_in_item: px(0.),
245 });
246 cx.update(|window, cx| {
247 let _ = window.draw(cx);
248 });
249 drag(
250 cx,
251 top_plain,
252 point(bounds.right() - px(1.), bounds.bottom() - px(1.)),
253 );
254 }
255 CrossRendererVirtualScenario::VirtualHeadToPlain => {
256 drag(cx, bounds.origin + point(px(1.), px(1.)), bottom_plain);
257 }
258 CrossRendererVirtualScenario::VirtualInMiddle => {
259 drag(cx, top_plain, bottom_plain);
260 }
261 }
262
263 let text = window_selected_text(cx);
264 for ix in 0..20 {
265 let expected = if format == crate::text::SelectionFormat::Source {
266 format!("**Paragraph{ix}**")
267 } else {
268 format!("Paragraph{ix}")
269 };
270 assert!(
271 text.contains(&expected),
272 "missing {expected:?} for cross-selection virtual selection: {text:?}"
273 );
274 }
275 }
276
277 #[gpui::test]
278 fn plain_to_virtual_tail_exports_unpainted_plain_blocks(cx: &mut TestAppContext) {
279 assert_cross_renderer_virtual_export(
280 crate::text::SelectionFormat::Plain,
281 CrossRendererVirtualScenario::PlainToVirtualTail,
282 cx,
283 );
284 }
285
286 #[gpui::test]
287 fn plain_to_virtual_tail_exports_unpainted_source_blocks(cx: &mut TestAppContext) {
288 assert_cross_renderer_virtual_export(
289 crate::text::SelectionFormat::Source,
290 CrossRendererVirtualScenario::PlainToVirtualTail,
291 cx,
292 );
293 }
294
295 #[gpui::test]
296 fn virtual_head_to_plain_exports_unpainted_plain_blocks(cx: &mut TestAppContext) {
297 assert_cross_renderer_virtual_export(
298 crate::text::SelectionFormat::Plain,
299 CrossRendererVirtualScenario::VirtualHeadToPlain,
300 cx,
301 );
302 }
303
304 #[gpui::test]
305 fn virtual_head_to_plain_exports_unpainted_source_blocks(cx: &mut TestAppContext) {
306 assert_cross_renderer_virtual_export(
307 crate::text::SelectionFormat::Source,
308 CrossRendererVirtualScenario::VirtualHeadToPlain,
309 cx,
310 );
311 }
312
313 #[gpui::test]
314 fn middle_virtual_renderer_exports_all_plain_blocks(cx: &mut TestAppContext) {
315 assert_cross_renderer_virtual_export(
316 crate::text::SelectionFormat::Plain,
317 CrossRendererVirtualScenario::VirtualInMiddle,
318 cx,
319 );
320 }
321
322 #[gpui::test]
323 fn middle_virtual_renderer_exports_all_source_blocks(cx: &mut TestAppContext) {
324 assert_cross_renderer_virtual_export(
325 crate::text::SelectionFormat::Source,
326 CrossRendererVirtualScenario::VirtualInMiddle,
327 cx,
328 );
329 }
330
331 impl BaseOwnedTextViewSelection {
332 fn new(cx: &mut Context<Self>) -> Self {
333 Self {
334 text_view: cx.new(|cx| TextViewState::markdown("Single authority", cx)),
335 }
336 }
337 }
338
339 impl Render for BaseOwnedTextViewSelection {
340 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
341 div().size_full().pt(px(10.)).child(
342 div()
343 .h(px(40.))
344 .child(TextView::new(&self.text_view).selectable(true)),
345 )
346 }
347 }
348
349 struct ChatTestView {
350 focus_handle: FocusHandle,
351 first: Entity<TextViewState>,
352 second: Entity<TextViewState>,
353 second_selectable: bool,
354 /// Top padding above the views. Bumping it shifts the whole content
355 /// down, which is the layout-level equivalent of an outer container
356 /// scrolling (see `selection_follows_content_when_layout_shifts`).
357 top_offset: gpui::Pixels,
358 /// Blank gap between the two views, used to anchor a selection in blank
359 /// space (the proxy-anchored endpoint path).
360 mid_gap: gpui::Pixels,
361 first_style: crate::text::TextViewStyle,
362 }
363
364 impl ChatTestView {
365 fn new(second_selectable: bool, cx: &mut Context<Self>) -> Self {
366 Self {
367 focus_handle: cx.focus_handle(),
368 first: cx.new(|cx| TextViewState::markdown("Hello world", cx)),
369 second: cx.new(|cx| TextViewState::markdown("Second message", cx)),
370 second_selectable,
371 top_offset: px(10.),
372 mid_gap: px(0.),
373 first_style: crate::text::TextViewStyle::default(),
374 }
375 }
376 }
377
378 impl Render for ChatTestView {
379 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
380 // `track_focus` makes the root a focusable container, so GPUI's
381 // focus-on-mouse-down marks every press inside it default-prevented.
382 // Selection must still start from blank space here (regression
383 // guard for `drag_from_blank_space_selects_views_below`), which the
384 // `suppress_text_selection` mechanism guarantees because blank-space
385 // presses never set that flag.
386 div()
387 .track_focus(&self.focus_handle)
388 .size_full()
389 .pt(self.top_offset)
390 .child(
391 div().h(px(40.)).child(
392 TextView::new(&self.first)
393 .selectable(true)
394 .style(self.first_style.clone()),
395 ),
396 )
397 // A blank gap between the two views. It is not over any
398 // TextView hitbox, so a press here exercises the blank-space
399 // (proxy-anchored) endpoint path.
400 .child(div().h(self.mid_gap))
401 .child(
402 div()
403 .h(px(40.))
404 .child(TextView::new(&self.second).selectable(self.second_selectable)),
405 )
406 // A 20px selection below the views that owns its press the way
407 // Input/Button do: its bubble-phase handler sets the suppress
408 // flag, so a press starting here must not start a selection.
409 .child(
410 div()
411 .h(px(20.))
412 .on_mouse_down(MouseButton::Left, |_, _, cx| {
413 GlobalState::suppress_text_selection(cx);
414 }),
415 )
416 }
417 }
418
419 fn setup(
420 second_selectable: bool,
421 cx: &mut TestAppContext,
422 ) -> (Entity<ChatTestView>, &mut VisualTestContext) {
423 cx.update(crate::init);
424 let (root, cx) = cx.add_window_view(|window, cx| {
425 let chat = cx.new(|cx| ChatTestView::new(second_selectable, cx));
426 Root::new(chat, window, cx)
427 });
428 let chat = root.read_with(cx, |root, _| {
429 root.view().clone().downcast::<ChatTestView>().unwrap()
430 });
431 cx.run_until_parked();
432 cx.update(|window, cx| {
433 let _ = window.draw(cx);
434 });
435 (chat, cx)
436 }
437
438 #[gpui::test]
439 fn base_plain_selection_and_text_view_share_one_cross_renderer_selection(
440 cx: &mut TestAppContext,
441 ) {
442 cx.update(crate::init);
443 let (_, cx) = cx.add_window_view(|window, cx| {
444 let content = cx.new(MixedAdapterView::new);
445 Root::new(content, window, cx)
446 });
447 let cx: &mut VisualTestContext = cx;
448 cx.run_until_parked();
449 cx.update(|window, cx| {
450 let _ = window.draw(cx);
451 });
452
453 cx.simulate_mouse_down(
454 point(px(1.), px(15.)),
455 MouseButton::Left,
456 Modifiers::default(),
457 );
458 cx.simulate_mouse_move(
459 point(px(300.), px(70.)),
460 Some(MouseButton::Left),
461 Modifiers::default(),
462 );
463 cx.simulate_mouse_up(
464 point(px(300.), px(70.)),
465 MouseButton::Left,
466 Modifiers::default(),
467 );
468 cx.update(|window, cx| {
469 let _ = window.draw(cx);
470 });
471
472 let selected = cx.update(|window, cx| TextSelection::selected_text(window, cx));
473 assert_eq!(selected.trim(), "Plain adapter\nTextView adapter");
474 }
475
476 #[gpui::test]
477 fn clearing_base_state_leaves_no_root_owned_text_view_selection(cx: &mut TestAppContext) {
478 cx.update(crate::init);
479 let (root, cx) = cx.add_window_view(|window, cx| {
480 let content = cx.new(BaseOwnedTextViewSelection::new);
481 Root::new(content, window, cx)
482 });
483 let content = root.read_with(cx, |root, _| {
484 root.view()
485 .clone()
486 .downcast::<BaseOwnedTextViewSelection>()
487 .unwrap()
488 });
489 let cx: &mut VisualTestContext = cx;
490 cx.run_until_parked();
491 cx.update(|window, cx| {
492 let _ = window.draw(cx);
493 });
494
495 cx.simulate_mouse_down(
496 point(px(1.), px(15.)),
497 MouseButton::Left,
498 Modifiers::default(),
499 );
500 cx.simulate_mouse_move(
501 point(px(300.), px(15.)),
502 Some(MouseButton::Left),
503 Modifiers::default(),
504 );
505 cx.simulate_mouse_up(
506 point(px(300.), px(15.)),
507 MouseButton::Left,
508 Modifiers::default(),
509 );
510 cx.update(|window, cx| {
511 let _ = window.draw(cx);
512 });
513 assert_eq!(
514 content
515 .read_with(cx, |view, cx| view.text_view.read(cx).selected_text())
516 .trim(),
517 "Single authority"
518 );
519
520 cx.update(|window, cx| {
521 TextSelection::clear(window, cx);
522 let _ = window.draw(cx);
523 });
524
525 let selected = content.read_with(cx, |view, cx| view.text_view.read(cx).selected_text());
526 assert!(
527 selected.is_empty(),
528 "TextView retained selection outside the window selection state: {selected:?}"
529 );
530 }
531
532 #[gpui::test]
533 fn base_clear_resets_text_view_before_returning(cx: &mut TestAppContext) {
534 cx.update(crate::init);
535 let (root, cx) = cx.add_window_view(|window, cx| {
536 let content = cx.new(BaseOwnedTextViewSelection::new);
537 Root::new(content, window, cx)
538 });
539 let content = root.read_with(cx, |root, _| {
540 root.view()
541 .clone()
542 .downcast::<BaseOwnedTextViewSelection>()
543 .unwrap()
544 });
545 let text_view = content.read_with(cx, |content, _| content.text_view.clone());
546 let cx: &mut VisualTestContext = cx;
547 cx.run_until_parked();
548 cx.update(|window, cx| {
549 let _ = window.draw(cx);
550 text_view.update(cx, |state, cx| state.select_all(cx));
551 TextSelection::clear(window, cx);
552 assert_eq!(text_view.read(cx).selected_text(), "");
553 });
554 }
555
556 #[gpui::test]
557 fn base_clear_then_select_all_in_one_effect_keeps_the_new_selection(cx: &mut TestAppContext) {
558 cx.update(crate::init);
559 let (root, cx) = cx.add_window_view(|window, cx| {
560 let content = cx.new(BaseOwnedTextViewSelection::new);
561 Root::new(content, window, cx)
562 });
563 let content = root.read_with(cx, |root, _| {
564 root.view()
565 .clone()
566 .downcast::<BaseOwnedTextViewSelection>()
567 .unwrap()
568 });
569 let text_view = content.read_with(cx, |content, _| content.text_view.clone());
570 let cx: &mut VisualTestContext = cx;
571 cx.run_until_parked();
572 cx.update(|window, cx| {
573 let _ = window.draw(cx);
574 text_view.update(cx, |state, cx| state.select_all(cx));
575 TextSelection::clear(window, cx);
576 text_view.update(cx, |state, cx| state.select_all(cx));
577 });
578 cx.run_until_parked();
579
580 let (has_selection, selected) = cx.update(|window, cx| {
581 (
582 TextSelection::has_selection(window, cx),
583 TextSelection::selected_text(window, cx),
584 )
585 });
586 assert!(has_selection);
587 assert_eq!(selected.trim(), "Single authority");
588 }
589
590 /// A `scrollable(true)` TextView virtualizes its blocks, so a block only
591 /// learns its selection once it has been painted. Pressing at the top,
592 /// scrolling with the wheel and releasing at the bottom leaves every block
593 /// in between unpainted — copying used to drop all of them.
594 struct ScrollableTextViewTest {
595 text_view: Entity<TextViewState>,
596 }
597
598 struct AutoScrollTextViewTest {
599 text_view: Entity<TextViewState>,
600 }
601
602 struct PaddedReaderAutoScrollTest {
603 text_view: Entity<TextViewState>,
604 }
605
606 struct PaddedScrollableTextViewTest {
607 text_view: Entity<TextViewState>,
608 }
609
610 /// Same as [`ScrollableTextViewTest`], but copying yields source.
611 struct SourceTextViewTest {
612 text_view: Entity<TextViewState>,
613 }
614
615 impl Render for SourceTextViewTest {
616 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
617 div().size_full().child(
618 div().h(px(60.)).child(
619 TextView::new(&self.text_view)
620 .selectable(true)
621 .scrollable(true)
622 .selection_format(crate::text::SelectionFormat::Source),
623 ),
624 )
625 }
626 }
627
628 impl Render for ScrollableTextViewTest {
629 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
630 div().size_full().child(
631 div().h(px(60.)).child(
632 TextView::new(&self.text_view)
633 .selectable(true)
634 .scrollable(true),
635 ),
636 )
637 }
638 }
639
640 impl Render for AutoScrollTextViewTest {
641 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
642 div().size_full().child(
643 div()
644 .debug_selector(|| "scrollable-text-view".into())
645 .h(px(300.))
646 .overflow_hidden()
647 .child(
648 TextView::new(&self.text_view)
649 .flex_none()
650 .px_5()
651 .selectable(true)
652 .scrollable(true),
653 ),
654 )
655 }
656 }
657
658 /// Scroll offset in pixels from the top of the list (positive = scrolled down).
659 fn list_scroll_px(text_view: &Entity<TextViewState>, cx: &mut VisualTestContext) -> Pixels {
660 text_view.read_with(cx, |state, _| {
661 -state.list_state().scroll_px_offset_for_scrollbar().y
662 })
663 }
664
665 /// Drags from `start` to `edge`, holds for `ticks` auto-scroll frames, and
666 /// returns how far the list moved. One 16 ms timer drives the list, so the
667 /// distance is bounded by `ticks` times the per-frame delta; a second
668 /// writer shows up as an overshoot.
669 fn drag_and_hold(
670 text_view: &Entity<TextViewState>,
671 start: gpui::Point<Pixels>,
672 edge: gpui::Point<Pixels>,
673 ticks: u32,
674 cx: &mut VisualTestContext,
675 ) -> Pixels {
676 let before = list_scroll_px(text_view, cx);
677 cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
678 cx.simulate_mouse_move(edge, Some(MouseButton::Left), Modifiers::default());
679 cx.executor()
680 .advance_clock(Duration::from_millis(16 * u64::from(ticks)));
681 cx.run_until_parked();
682 let after = list_scroll_px(text_view, cx);
683 cx.simulate_mouse_up(edge, MouseButton::Left, Modifiers::default());
684 after - before
685 }
686
687 fn assert_auto_scroll_magnitude(moved: Pixels, per_tick: Pixels, ticks: u32, label: &str) {
688 let max = per_tick * ticks as f32;
689 if per_tick > px(0.) {
690 assert!(
691 moved > px(0.) && moved <= max,
692 "{label}: moved {moved:?}, expected within (0, {max:?}] for {ticks} ticks of {per_tick:?}"
693 );
694 } else {
695 assert!(
696 moved < px(0.) && moved >= max,
697 "{label}: moved {moved:?}, expected within [{max:?}, 0) for {ticks} ticks of {per_tick:?}"
698 );
699 }
700 }
701
702 #[gpui::test]
703 fn held_text_view_drag_auto_scroll_extends_selection(cx: &mut TestAppContext) {
704 let source = (0..100)
705 .map(|ix| format!("Paragraph {ix} with enough text to select"))
706 .collect::<Vec<_>>()
707 .join("\n\n");
708 cx.update(crate::init);
709 let (root, cx) = cx.add_window_view(|window, cx| {
710 let view = cx.new(|cx| AutoScrollTextViewTest {
711 text_view: cx.new(|cx| TextViewState::markdown(&source, cx)),
712 });
713 Root::new(view, window, cx)
714 });
715 let text_view = root.read_with(cx, |root, cx| {
716 root.view()
717 .clone()
718 .downcast::<AutoScrollTextViewTest>()
719 .unwrap()
720 .read(cx)
721 .text_view
722 .clone()
723 });
724 let cx: &mut VisualTestContext = cx;
725 cx.run_until_parked();
726 cx.update(|window, cx| {
727 let _ = window.draw(cx);
728 });
729
730 let bounds = cx
731 .debug_bounds("scrollable-text-view")
732 .expect("scrollable TextView bounds");
733 let start = point(bounds.left() + px(30.), bounds.top() + px(30.));
734 let edge = point(bounds.left() + px(60.), bounds.bottom() - px(2.));
735 cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
736 cx.simulate_mouse_move(edge, Some(MouseButton::Left), Modifiers::default());
737 cx.update(|window, cx| {
738 let _ = window.draw(cx);
739 });
740 let before = window_selected_text(cx);
741 assert!(!before.is_empty(), "the drag must start a text selection");
742 // Each tick paints the newly scrolled blocks, with no further mouse moves.
743 for _ in 0..12 {
744 cx.executor().advance_clock(Duration::from_millis(16));
745 cx.run_until_parked();
746 cx.update(|window, cx| {
747 let _ = window.draw(cx);
748 });
749 }
750 let after = window_selected_text(cx);
751 cx.simulate_mouse_up(edge, MouseButton::Left, Modifiers::default());
752 assert!(
753 after.len() > before.len(),
754 "holding at edge must expand selection: before={before:?}, after={after:?}"
755 );
756 let stopped_at = list_scroll_px(&text_view, cx);
757 cx.executor().advance_clock(Duration::from_millis(64));
758 cx.run_until_parked();
759 cx.update(|window, cx| {
760 let _ = window.draw(cx);
761 });
762 assert_eq!(list_scroll_px(&text_view, cx), stopped_at);
763 assert_eq!(window_selected_text(cx), after);
764 }
765
766 #[gpui::test]
767 fn compatibility_text_view_drag_selection_auto_scrolls_both_directions(
768 cx: &mut TestAppContext,
769 ) {
770 use gpui::ListOffset;
771
772 let source = (0..100)
773 .map(|ix| format!("Paragraph {ix} with enough text to select"))
774 .collect::<Vec<_>>()
775 .join("\n\n");
776 cx.update(crate::init);
777 let (root, cx) = cx.add_window_view(|window, cx| {
778 let view = cx.new(|cx| AutoScrollTextViewTest {
779 text_view: cx.new(|cx| TextViewState::markdown(&source, cx)),
780 });
781 Root::new(view, window, cx)
782 });
783 let view = root.read_with(cx, |root, _| {
784 root.view()
785 .clone()
786 .downcast::<AutoScrollTextViewTest>()
787 .unwrap()
788 });
789 let cx: &mut VisualTestContext = cx;
790 cx.run_until_parked();
791 cx.update(|window, cx| {
792 let _ = window.draw(cx);
793 });
794
795 let bounds = cx
796 .debug_bounds("scrollable-text-view")
797 .expect("scrollable TextView bounds");
798 // The TextView fills the viewport, so the per-frame delta the drag
799 // requests is the one measured against the viewport edge.
800 const TICKS: u32 = 4;
801 let start = point(bounds.left() + px(30.), bounds.top() + px(30.));
802 let edge = point(bounds.left() + px(60.), bounds.bottom() - px(2.));
803 let per_tick = AutoScroll::compute_delta(edge.y, bounds).expect("edge zone");
804 let text_view = view.read_with(cx, |view, _| view.text_view.clone());
805 let moved = drag_and_hold(&text_view, start, edge, TICKS, cx);
806 assert_auto_scroll_magnitude(moved, per_tick, TICKS, "downward");
807
808 let list_state = text_view.read_with(cx, |state, _| state.list_state().clone());
809 list_state.scroll_to(ListOffset {
810 item_ix: 99,
811 offset_in_item: px(0.),
812 });
813 cx.update(|window, cx| {
814 let _ = window.draw(cx);
815 });
816 let start = point(bounds.left() + px(30.), bounds.bottom() - px(30.));
817 let edge = point(bounds.left() + px(60.), bounds.top() + px(2.));
818 let per_tick = AutoScroll::compute_delta(edge.y, bounds).expect("edge zone");
819 let moved = drag_and_hold(&text_view, start, edge, TICKS, cx);
820 assert_auto_scroll_magnitude(moved, per_tick, TICKS, "upward");
821 }
822
823 /// The reader layout from the field report: a clipping row that centers a
824 /// vertically padded, full-height scrollable TextView. The list's edges
825 /// sit inside the padding, so a wheel event synthesized at the clipping
826 /// ancestor's edge misses the list hitbox; only the participant path
827 /// scrolls it.
828 impl Render for PaddedReaderAutoScrollTest {
829 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
830 div().size_full().child(
831 div()
832 .debug_selector(|| "reader".into())
833 .flex()
834 .flex_row()
835 .h(px(300.))
836 .min_w(px(0.))
837 .overflow_hidden()
838 .justify_center()
839 .child(
840 TextView::new(&self.text_view)
841 .scrollable(true)
842 .selectable(true)
843 .px_5()
844 .py_3()
845 .h_full()
846 .w_full()
847 .max_w(relative(0.85))
848 .mx_auto(),
849 ),
850 )
851 }
852 }
853
854 #[gpui::test]
855 fn padded_reader_text_view_auto_scrolls_at_the_clipping_edge(cx: &mut TestAppContext) {
856 let source = (0..100)
857 .map(|ix| format!("Paragraph {ix} with enough text to select"))
858 .collect::<Vec<_>>()
859 .join("\n\n");
860 cx.update(crate::init);
861 let (root, cx) = cx.add_window_view(|window, cx| {
862 let view = cx.new(|cx| PaddedReaderAutoScrollTest {
863 text_view: cx.new(|cx| TextViewState::markdown(&source, cx)),
864 });
865 Root::new(view, window, cx)
866 });
867 let view = root.read_with(cx, |root, _| {
868 root.view()
869 .clone()
870 .downcast::<PaddedReaderAutoScrollTest>()
871 .unwrap()
872 });
873 let cx: &mut VisualTestContext = cx;
874 cx.run_until_parked();
875 cx.update(|window, cx| {
876 let _ = window.draw(cx);
877 });
878
879 let reader = cx.debug_bounds("reader").expect("reader bounds");
880 let text_view = view.read_with(cx, |view, _| view.text_view.clone());
881 let list_bounds = text_view.read_with(cx, |state, _| state.list_state().viewport_bounds());
882 assert!(
883 list_bounds.bottom() < reader.bottom() - px(2.),
884 "the list must end inside the padding: list {list_bounds:?}, reader {reader:?}"
885 );
886
887 // Below the list but inside the clipping ancestor: the synthetic wheel
888 // is clamped to this band and misses the list hitbox.
889 let start = point(reader.center().x, reader.top() + px(40.));
890 let edge = point(reader.center().x, reader.bottom() - px(2.));
891 let moved = drag_and_hold(&text_view, start, edge, 4, cx);
892 assert!(
893 moved > px(0.),
894 "dragging to the clipping edge must scroll the padded list, moved {moved:?}"
895 );
896 }
897
898 struct ClippedReaderAutoScrollTest {
899 text_view: Entity<TextViewState>,
900 }
901
902 // A TextView taller than its clipping ancestor.
903 impl Render for ClippedReaderAutoScrollTest {
904 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
905 div().size_full().child(
906 div()
907 .debug_selector(|| "reader".into())
908 .flex()
909 .flex_row()
910 .h(px(300.))
911 .min_w(px(0.))
912 .overflow_hidden()
913 .justify_center()
914 .child(
915 TextView::new(&self.text_view)
916 .scrollable(true)
917 .selectable(true)
918 .h(px(600.))
919 .flex_none()
920 .w_full()
921 .max_w(relative(0.85))
922 .mx_auto(),
923 ),
924 )
925 }
926 }
927
928 #[gpui::test]
929 fn clipped_reader_text_view_auto_scrolls_at_the_visible_edge(cx: &mut TestAppContext) {
930 let source = (0..100)
931 .map(|ix| format!("Paragraph {ix} with enough text to select"))
932 .collect::<Vec<_>>()
933 .join("\n\n");
934 cx.update(crate::init);
935 let (root, cx) = cx.add_window_view(|window, cx| {
936 let view = cx.new(|cx| ClippedReaderAutoScrollTest {
937 text_view: cx.new(|cx| TextViewState::markdown(&source, cx)),
938 });
939 Root::new(view, window, cx)
940 });
941 let view = root.read_with(cx, |root, _| {
942 root.view()
943 .clone()
944 .downcast::<ClippedReaderAutoScrollTest>()
945 .unwrap()
946 });
947 let cx: &mut VisualTestContext = cx;
948 cx.run_until_parked();
949 cx.update(|window, cx| {
950 let _ = window.draw(cx);
951 });
952
953 let reader = cx.debug_bounds("reader").expect("reader bounds");
954 let text_view = view.read_with(cx, |view, _| view.text_view.clone());
955 let list_bounds = text_view.read_with(cx, |state, _| state.list_state().viewport_bounds());
956 assert!(list_bounds.bottom() > reader.bottom() + px(100.));
957
958 // The visible edge is well above the TextView's own bottom.
959 let start = point(reader.center().x, reader.top() + px(40.));
960 let edge = point(reader.center().x, reader.bottom() - px(2.));
961 let moved = drag_and_hold(&text_view, start, edge, 4, cx);
962 assert!(
963 moved > px(0.),
964 "dragging to the clipping edge must scroll the clipped list, moved {moved:?}"
965 );
966 }
967
968 impl Render for PaddedScrollableTextViewTest {
969 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
970 div().size_full().child(
971 TextView::new(&self.text_view)
972 .selectable(true)
973 .scrollable(true)
974 .h(px(300.))
975 .p(px(100.)),
976 )
977 }
978 }
979
980 #[gpui::test]
981 fn padded_scrollable_text_view_uses_content_origin_for_virtual_blocks(cx: &mut TestAppContext) {
982 use gpui::ListOffset;
983
984 const BLOCKS: usize = 20;
985 let source = (0..BLOCKS)
986 .map(|ix| format!("Paragraph{ix}"))
987 .collect::<Vec<_>>()
988 .join("\n\n");
989 cx.update(crate::init);
990 let (root, cx) = cx.add_window_view(|window, cx| {
991 let view = cx.new(|cx| PaddedScrollableTextViewTest {
992 text_view: cx.new(|cx| TextViewState::markdown(&source, cx)),
993 });
994 Root::new(view, window, cx)
995 });
996 let view = root.read_with(cx, |root, _| {
997 root.view()
998 .clone()
999 .downcast::<PaddedScrollableTextViewTest>()
1000 .unwrap()
1001 });
1002 let cx: &mut VisualTestContext = cx;
1003 cx.run_until_parked();
1004 cx.update(|window, cx| {
1005 let _ = window.draw(cx);
1006 });
1007 let (text_view, bounds) = view.read_with(cx, |view, cx| {
1008 let state = view.text_view.read(cx);
1009 (view.text_view.clone(), state.bounds())
1010 });
1011
1012 cx.simulate_mouse_down(
1013 bounds.origin + point(px(1.), px(1.)),
1014 MouseButton::Left,
1015 Modifiers::default(),
1016 );
1017 let list_state = text_view.read_with(cx, |state, _| state.list_state().clone());
1018 list_state.scroll_to(ListOffset {
1019 item_ix: BLOCKS - 1,
1020 offset_in_item: px(0.),
1021 });
1022 cx.update(|window, cx| {
1023 let _ = window.draw(cx);
1024 });
1025 cx.simulate_mouse_move(
1026 point(bounds.right() - px(1.), bounds.bottom() - px(1.)),
1027 Some(MouseButton::Left),
1028 Modifiers::default(),
1029 );
1030 cx.simulate_mouse_up(
1031 point(bounds.right() - px(1.), bounds.bottom() - px(1.)),
1032 MouseButton::Left,
1033 Modifiers::default(),
1034 );
1035 cx.update(|window, cx| {
1036 let _ = window.draw(cx);
1037 });
1038
1039 let text = window_selected_text(cx);
1040 assert!(
1041 text.contains("Paragraph0"),
1042 "first block was skipped: {text:?}"
1043 );
1044 assert!(
1045 text.contains("Paragraph18"),
1046 "drag did not reach the tail: {text:?}"
1047 );
1048 }
1049
1050 /// [`Paragraph::render`] stores one `InlineState` per run of children
1051 /// between inline images, so selection offsets belong to a run, not to a
1052 /// single child. Mapping them against every child made the text before an
1053 /// image show up again as if it were the text after it.
1054 struct InlineImageSourceTestView {
1055 text_view: Entity<TextViewState>,
1056 }
1057
1058 impl Render for InlineImageSourceTestView {
1059 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1060 div().size_full().pt(px(10.)).child(
1061 div().h(px(80.)).child(
1062 TextView::new(&self.text_view)
1063 .selectable(true)
1064 .selection_format(crate::text::SelectionFormat::Source),
1065 ),
1066 )
1067 }
1068 }
1069
1070 #[gpui::test]
1071 fn selection_spans_blocks_scrolled_past(cx: &mut TestAppContext) {
1072 use gpui::{ScrollDelta, ScrollWheelEvent};
1073
1074 const BLOCKS: usize = 20;
1075
1076 cx.update(crate::init);
1077 let source = (0..BLOCKS)
1078 .map(|ix| format!("Paragraph{ix}"))
1079 .collect::<Vec<_>>()
1080 .join("\n\n");
1081 let (_, cx) = cx.add_window_view(|window, cx| {
1082 let view = cx.new(|cx| ScrollableTextViewTest {
1083 text_view: cx.new(|cx| TextViewState::markdown(&source, cx)),
1084 });
1085 Root::new(view, window, cx)
1086 });
1087 let cx: &mut VisualTestContext = cx;
1088 cx.run_until_parked();
1089 cx.update(|window, cx| {
1090 let _ = window.draw(cx);
1091 });
1092
1093 // Press inside the first block, then wheel-scroll to the end. The
1094 // blocks scrolled past are never painted while the drag is active.
1095 cx.simulate_mouse_down(
1096 point(px(0.), px(1.)),
1097 MouseButton::Left,
1098 Modifiers::default(),
1099 );
1100 cx.update(|window, cx| {
1101 let _ = window.draw(cx);
1102 });
1103 for _ in 0..BLOCKS {
1104 cx.simulate_event(ScrollWheelEvent {
1105 position: point(px(10.), px(30.)),
1106 delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
1107 ..Default::default()
1108 });
1109 cx.update(|window, cx| {
1110 let _ = window.draw(cx);
1111 });
1112 }
1113
1114 // Release over the last visible block.
1115 cx.simulate_mouse_move(
1116 point(px(150.), px(58.)),
1117 Some(MouseButton::Left),
1118 Modifiers::default(),
1119 );
1120 cx.update(|window, cx| {
1121 let _ = window.draw(cx);
1122 });
1123 cx.simulate_mouse_up(
1124 point(px(150.), px(58.)),
1125 MouseButton::Left,
1126 Modifiers::default(),
1127 );
1128 cx.update(|window, cx| {
1129 let _ = window.draw(cx);
1130 });
1131
1132 let text = window_selected_text(cx);
1133 let missing = (0..BLOCKS)
1134 .filter(|ix| !text.contains(&format!("Paragraph{ix}")))
1135 .collect::<Vec<_>>();
1136 assert!(
1137 missing.is_empty(),
1138 "blocks scrolled past were dropped: {missing:?} in {text:?}"
1139 );
1140 }
1141
1142 /// Source mode has the same gap to bridge as plain text: a block the
1143 /// selection spans but that scrolled past without painting reports no
1144 /// selection of its own, and must still be copied — with its markup.
1145 #[gpui::test]
1146 fn source_selection_spans_blocks_scrolled_past(cx: &mut TestAppContext) {
1147 use gpui::{ScrollDelta, ScrollWheelEvent};
1148
1149 const BLOCKS: usize = 20;
1150
1151 cx.update(crate::init);
1152 let source = (0..BLOCKS)
1153 .map(|ix| format!("**Paragraph{ix}**"))
1154 .collect::<Vec<_>>()
1155 .join("\n\n");
1156 let (_, cx) = cx.add_window_view(|window, cx| {
1157 let view = cx.new(|cx| SourceTextViewTest {
1158 text_view: cx.new(|cx| TextViewState::markdown(&source, cx)),
1159 });
1160 Root::new(view, window, cx)
1161 });
1162 let cx: &mut VisualTestContext = cx;
1163 cx.run_until_parked();
1164 cx.update(|window, cx| {
1165 let _ = window.draw(cx);
1166 });
1167
1168 cx.simulate_mouse_down(
1169 point(px(0.), px(1.)),
1170 MouseButton::Left,
1171 Modifiers::default(),
1172 );
1173 cx.update(|window, cx| {
1174 let _ = window.draw(cx);
1175 });
1176 // Jump the whole document in one go, so the blocks in between never
1177 // paint at all and cannot leave a stale selection behind.
1178 cx.simulate_event(ScrollWheelEvent {
1179 position: point(px(10.), px(30.)),
1180 delta: ScrollDelta::Pixels(point(px(0.), px(-40.) * BLOCKS as f32)),
1181 ..Default::default()
1182 });
1183 cx.update(|window, cx| {
1184 let _ = window.draw(cx);
1185 });
1186
1187 cx.simulate_mouse_move(
1188 point(px(150.), px(58.)),
1189 Some(MouseButton::Left),
1190 Modifiers::default(),
1191 );
1192 cx.update(|window, cx| {
1193 let _ = window.draw(cx);
1194 });
1195 cx.simulate_mouse_up(
1196 point(px(150.), px(58.)),
1197 MouseButton::Left,
1198 Modifiers::default(),
1199 );
1200 cx.update(|window, cx| {
1201 let _ = window.draw(cx);
1202 });
1203
1204 let text = window_selected_text(cx);
1205 let missing = (0..BLOCKS)
1206 .filter(|ix| !text.contains(&format!("**Paragraph{ix}**")))
1207 .collect::<Vec<_>>();
1208 assert!(
1209 missing.is_empty(),
1210 "blocks scrolled past were dropped or lost their markup: {missing:?} in {text:?}"
1211 );
1212 }
1213
1214 #[gpui::test]
1215 fn shrinking_virtual_selection_drops_blocks_beyond_the_new_cursor(cx: &mut TestAppContext) {
1216 use gpui::ListOffset;
1217
1218 const BLOCKS: usize = 20;
1219 let source = (0..BLOCKS)
1220 .map(|ix| format!("Paragraph{ix}"))
1221 .collect::<Vec<_>>()
1222 .join("\n\n");
1223 cx.update(crate::init);
1224 let (root, cx) = cx.add_window_view(|window, cx| {
1225 let view = cx.new(|cx| ScrollableTextViewTest {
1226 text_view: cx.new(|cx| TextViewState::markdown(&source, cx)),
1227 });
1228 Root::new(view, window, cx)
1229 });
1230 let view = root.read_with(cx, |root, _| {
1231 root.view()
1232 .clone()
1233 .downcast::<ScrollableTextViewTest>()
1234 .unwrap()
1235 });
1236 let cx: &mut VisualTestContext = cx;
1237 cx.run_until_parked();
1238 cx.update(|window, cx| {
1239 let _ = window.draw(cx);
1240 });
1241
1242 cx.simulate_mouse_down(
1243 point(px(0.), px(1.)),
1244 MouseButton::Left,
1245 Modifiers::default(),
1246 );
1247 let list_state =
1248 view.read_with(cx, |view, cx| view.text_view.read(cx).list_state().clone());
1249 list_state.scroll_to(ListOffset {
1250 item_ix: BLOCKS - 1,
1251 offset_in_item: px(0.),
1252 });
1253 cx.update(|window, cx| {
1254 let _ = window.draw(cx);
1255 });
1256 cx.simulate_mouse_move(
1257 point(px(150.), px(30.)),
1258 Some(MouseButton::Left),
1259 Modifiers::default(),
1260 );
1261 cx.update(|window, cx| {
1262 let _ = window.draw(cx);
1263 });
1264 let expanded = window_selected_text(cx);
1265 assert!(
1266 expanded.contains("Paragraph18"),
1267 "failed to expand near the last block: {expanded:?}"
1268 );
1269
1270 list_state.scroll_to(ListOffset {
1271 item_ix: 5,
1272 offset_in_item: px(0.),
1273 });
1274 cx.update(|window, cx| {
1275 let _ = window.draw(cx);
1276 });
1277 cx.simulate_mouse_move(
1278 point(px(150.), px(10.)),
1279 Some(MouseButton::Left),
1280 Modifiers::default(),
1281 );
1282 cx.simulate_mouse_up(
1283 point(px(150.), px(10.)),
1284 MouseButton::Left,
1285 Modifiers::default(),
1286 );
1287 cx.update(|window, cx| {
1288 let _ = window.draw(cx);
1289 });
1290
1291 let text = window_selected_text(cx);
1292 assert!(text.contains("Paragraph5"), "got: {text:?}");
1293 assert!(
1294 !text.contains("Paragraph18"),
1295 "stale blocks beyond the new cursor were copied: {text:?}"
1296 );
1297 }
1298
1299 /// A multi-click selection has to come back as source too. The click stores
1300 /// the plain word it selected as a shortcut, which has lost its markup.
1301 #[gpui::test]
1302 fn source_multi_click_selection_keeps_its_markup(cx: &mut TestAppContext) {
1303 cx.update(crate::init);
1304 let (_, cx) = cx.add_window_view(|window, cx| {
1305 let view = cx.new(|cx| SourceTextViewTest {
1306 text_view: cx.new(|cx| TextViewState::markdown("**Hello** world", cx)),
1307 });
1308 Root::new(view, window, cx)
1309 });
1310 let cx: &mut VisualTestContext = cx;
1311 cx.run_until_parked();
1312 cx.update(|window, cx| {
1313 let _ = window.draw(cx);
1314 });
1315
1316 let position = point(px(10.), px(10.));
1317 cx.simulate_event(MouseDownEvent {
1318 position,
1319 modifiers: Modifiers::default(),
1320 button: MouseButton::Left,
1321 click_count: 2,
1322 first_mouse: false,
1323 });
1324 cx.simulate_event(MouseUpEvent {
1325 position,
1326 modifiers: Modifiers::default(),
1327 button: MouseButton::Left,
1328 click_count: 2,
1329 });
1330 cx.update(|window, cx| {
1331 let _ = window.draw(cx);
1332 });
1333
1334 let text = window_selected_text(cx);
1335 assert_eq!(text.trim(), "**Hello**", "got: {text:?}");
1336 }
1337
1338 #[gpui::test]
1339 fn selection_inside_one_block_leaves_the_rest(cx: &mut TestAppContext) {
1340 cx.update(crate::init);
1341 let source = (0..20)
1342 .map(|ix| format!("Paragraph{ix}"))
1343 .collect::<Vec<_>>()
1344 .join("\n\n");
1345 let (_, cx) = cx.add_window_view(|window, cx| {
1346 let view = cx.new(|cx| ScrollableTextViewTest {
1347 text_view: cx.new(|cx| TextViewState::markdown(&source, cx)),
1348 });
1349 Root::new(view, window, cx)
1350 });
1351 let cx: &mut VisualTestContext = cx;
1352 cx.run_until_parked();
1353 cx.update(|window, cx| {
1354 let _ = window.draw(cx);
1355 });
1356
1357 // Stay inside the first block. The blocks below are on screen and
1358 // simply not selected, so none of them may be filled in.
1359 drag(cx, point(px(2.), px(4.)), point(px(40.), px(4.)));
1360
1361 let text = window_selected_text(cx);
1362 assert!(!text.trim().is_empty(), "nothing selected");
1363 assert!(
1364 !text.contains("Paragraph1"),
1365 "unselected block was filled in: {text:?}"
1366 );
1367 }
1368
1369 #[gpui::test]
1370 fn source_format_maps_offsets_per_rendered_run(cx: &mut TestAppContext) {
1371 cx.update(crate::init);
1372 let (_, cx) = cx.add_window_view(|window, cx| {
1373 let view = cx.new(|cx| InlineImageSourceTestView {
1374 text_view: cx.new(|cx| {
1375 TextViewState::markdown(
1376 "Build **status** ![img](https://example.com/i.svg) after text",
1377 cx,
1378 )
1379 }),
1380 });
1381 Root::new(view, window, cx)
1382 });
1383 let cx: &mut VisualTestContext = cx;
1384 cx.run_until_parked();
1385 cx.update(|window, cx| {
1386 let _ = window.draw(cx);
1387 });
1388
1389 drag(cx, point(px(0.), px(11.)), point(px(600.), px(80.)));
1390
1391 let text = window_selected_text(cx);
1392 assert_eq!(
1393 text.trim(),
1394 "Build **status** ![img](https://example.com/i.svg) after text"
1395 );
1396 }
1397
1398 fn drag(
1399 cx: &mut VisualTestContext,
1400 from: gpui::Point<gpui::Pixels>,
1401 to: gpui::Point<gpui::Pixels>,
1402 ) {
1403 drag_through(cx, &[from, to]);
1404 }
1405
1406 fn drag_through(cx: &mut VisualTestContext, points: &[gpui::Point<gpui::Pixels>]) {
1407 assert!(points.len() >= 2);
1408 let from = points[0];
1409 let to = *points.last().unwrap();
1410
1411 cx.simulate_mouse_down(from, MouseButton::Left, Modifiers::default());
1412 cx.update(|window, cx| {
1413 let _ = window.draw(cx);
1414 });
1415
1416 for point in &points[1..] {
1417 cx.simulate_mouse_move(*point, Some(MouseButton::Left), Modifiers::default());
1418 cx.update(|window, cx| {
1419 let _ = window.draw(cx);
1420 });
1421 }
1422
1423 cx.simulate_mouse_up(to, MouseButton::Left, Modifiers::default());
1424 cx.update(|window, cx| {
1425 let _ = window.draw(cx);
1426 });
1427 }
1428
1429 fn window_selected_text(cx: &mut VisualTestContext) -> String {
1430 cx.update(|window, cx| TextSelection::selected_text(window, cx))
1431 }
1432
1433 fn click(
1434 cx: &mut VisualTestContext,
1435 position: gpui::Point<gpui::Pixels>,
1436 modifiers: Modifiers,
1437 ) {
1438 cx.simulate_mouse_down(position, MouseButton::Left, modifiers);
1439 cx.simulate_mouse_up(position, MouseButton::Left, modifiers);
1440 cx.update(|window, cx| {
1441 let _ = window.draw(cx);
1442 });
1443 }
1444
1445 fn shift_modifiers() -> Modifiers {
1446 Modifiers {
1447 shift: true,
1448 ..Modifiers::default()
1449 }
1450 }
1451
1452 struct CachedPanelRoot {
1453 inner: Entity<CachedInnerPanel>,
1454 }
1455
1456 /// Samples, from inside the panel and before the TextView paints, whether
1457 /// the window still holds the selection the TextView is about to draw from.
1458 /// That is exactly what its inlines read, so a `false` sample is a frame
1459 /// painted without the highlight.
1460 struct SelectionPaintProbe {
1461 samples: Rc<RefCell<Vec<bool>>>,
1462 }
1463
1464 impl IntoElement for SelectionPaintProbe {
1465 type Element = Self;
1466
1467 fn into_element(self) -> Self::Element {
1468 self
1469 }
1470 }
1471
1472 impl Element for SelectionPaintProbe {
1473 type RequestLayoutState = ();
1474 type PrepaintState = ();
1475
1476 fn id(&self) -> Option<ElementId> {
1477 None
1478 }
1479
1480 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
1481 None
1482 }
1483
1484 fn request_layout(
1485 &mut self,
1486 _: Option<&GlobalElementId>,
1487 _: Option<&InspectorElementId>,
1488 window: &mut Window,
1489 cx: &mut App,
1490 ) -> (LayoutId, Self::RequestLayoutState) {
1491 (window.request_layout(gpui::Style::default(), None, cx), ())
1492 }
1493
1494 fn prepaint(
1495 &mut self,
1496 _: Option<&GlobalElementId>,
1497 _: Option<&InspectorElementId>,
1498 _: Bounds<Pixels>,
1499 _: &mut Self::RequestLayoutState,
1500 _: &mut Window,
1501 _: &mut App,
1502 ) -> Self::PrepaintState {
1503 }
1504
1505 fn paint(
1506 &mut self,
1507 _: Option<&GlobalElementId>,
1508 _: Option<&InspectorElementId>,
1509 _: Bounds<Pixels>,
1510 _: &mut Self::RequestLayoutState,
1511 _: &mut Self::PrepaintState,
1512 window: &mut Window,
1513 cx: &mut App,
1514 ) {
1515 let has_selection = TextSelection::has_selection(window, cx);
1516 self.samples.borrow_mut().push(has_selection);
1517 }
1518 }
1519
1520 struct CachedInnerPanel {
1521 text_view: Entity<TextViewState>,
1522 renders: Rc<Cell<usize>>,
1523 samples: Rc<RefCell<Vec<bool>>>,
1524 }
1525
1526 impl Render for CachedInnerPanel {
1527 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1528 self.renders.set(self.renders.get() + 1);
1529 div()
1530 .size_full()
1531 .debug_selector(|| "cached-text-view".into())
1532 .child(SelectionPaintProbe {
1533 samples: self.samples.clone(),
1534 })
1535 .child(TextView::new(&self.text_view).selectable(true))
1536 }
1537 }
1538
1539 impl Render for CachedPanelRoot {
1540 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1541 div().size_full().child(
1542 self.inner
1543 .clone()
1544 .cached(gpui::StyleRefinement::default().size_full()),
1545 )
1546 }
1547 }
1548
1549 /// A dock panel renders its content through `Entity::cached`, which replays
1550 /// the recorded frame whenever nothing in it changed: the TextView paints
1551 /// the same text at the same place without any of its elements running.
1552 /// Sweeping the participant for the generation it could not stamp cleared
1553 /// the selection it had just painted, and re-registering it on the next
1554 /// frame brought the selection back — it blinked, and the window never
1555 /// stopped redrawing.
1556 #[gpui::test]
1557 fn selection_inside_a_cached_view_survives_replayed_frames(cx: &mut TestAppContext) {
1558 let source = (0..20)
1559 .map(|ix| format!("Paragraph {ix} with enough text to select"))
1560 .collect::<Vec<_>>()
1561 .join("\n\n");
1562 cx.update(crate::init);
1563 let renders = Rc::new(Cell::new(0));
1564 let samples: Rc<RefCell<Vec<bool>>> = Rc::default();
1565 let panel_renders = renders.clone();
1566 let panel_samples = samples.clone();
1567 let (_, cx) = cx.add_window_view(|window, cx| {
1568 let view = cx.new(|cx| CachedPanelRoot {
1569 inner: cx.new(|cx| CachedInnerPanel {
1570 text_view: cx.new(|cx| TextViewState::markdown(&source, cx)),
1571 renders: panel_renders,
1572 samples: panel_samples,
1573 }),
1574 });
1575 Root::new(view, window, cx)
1576 });
1577 let cx: &mut VisualTestContext = cx;
1578 cx.run_until_parked();
1579 cx.update(|window, cx| {
1580 let _ = window.draw(cx);
1581 });
1582 let bounds = cx
1583 .debug_bounds("cached-text-view")
1584 .expect("cached TextView bounds");
1585
1586 let start = bounds.origin + point(px(30.), px(8.));
1587 drag(cx, start, start + point(px(60.), px(40.)));
1588 cx.run_until_parked();
1589
1590 let selected = window_selected_text(cx);
1591 assert!(!selected.is_empty(), "the drag must select text");
1592 let settled = renders.get();
1593 samples.borrow_mut().clear();
1594
1595 for frame in 0..8 {
1596 cx.update(|window, cx| {
1597 let _ = window.draw(cx);
1598 });
1599 cx.run_until_parked();
1600 assert_eq!(
1601 window_selected_text(cx),
1602 selected,
1603 "frame {frame} lost the selection painted inside the cached panel"
1604 );
1605 }
1606 // Every frame the panel did repaint must have had the selection to
1607 // paint; a `false` here is the blink itself.
1608 assert!(
1609 samples.borrow().iter().all(|has_selection| *has_selection),
1610 "the panel repainted without a selection: {:?}",
1611 samples.borrow()
1612 );
1613 assert_eq!(
1614 renders.get(),
1615 settled,
1616 "a settled selection must let the cached panel stay cached"
1617 );
1618 }
1619
1620 #[gpui::test]
1621 fn shift_click_extends_from_previous_plain_click(cx: &mut TestAppContext) {
1622 let (_, cx) = setup(true, cx);
1623
1624 click(cx, point(px(0.), px(15.)), Modifiers::default());
1625 click(cx, point(px(300.), px(15.)), shift_modifiers());
1626
1627 assert_eq!(window_selected_text(cx).trim(), "Hello world");
1628 }
1629
1630 #[gpui::test]
1631 fn shift_click_reuses_anchor_for_repeated_extension(cx: &mut TestAppContext) {
1632 let (_, cx) = setup(true, cx);
1633 let anchor = point(px(0.), px(15.));
1634
1635 click(cx, anchor, Modifiers::default());
1636 click(cx, point(px(300.), px(15.)), shift_modifiers());
1637 assert_eq!(window_selected_text(cx).trim(), "Hello world");
1638
1639 click(cx, anchor, shift_modifiers());
1640 assert_eq!(window_selected_text(cx), "");
1641 }
1642
1643 #[gpui::test]
1644 fn shift_click_keeps_anchor_when_cursor_crosses_it(cx: &mut TestAppContext) {
1645 let (_, cx) = setup(true, cx);
1646 let anchor = point(px(20.), px(15.));
1647
1648 click(cx, anchor, Modifiers::default());
1649 click(cx, point(px(300.), px(15.)), shift_modifiers());
1650 assert_eq!(window_selected_text(cx).trim(), "llo world");
1651
1652 click(cx, point(px(0.), px(15.)), shift_modifiers());
1653 assert_eq!(window_selected_text(cx).trim(), "He");
1654 }
1655
1656 #[gpui::test]
1657 fn shift_drag_keeps_previous_plain_click_as_anchor(cx: &mut TestAppContext) {
1658 let (_, cx) = setup(true, cx);
1659 let modifiers = shift_modifiers();
1660
1661 click(cx, point(px(0.), px(15.)), Modifiers::default());
1662 cx.simulate_mouse_down(point(px(20.), px(15.)), MouseButton::Left, modifiers);
1663 cx.simulate_mouse_move(point(px(300.), px(70.)), Some(MouseButton::Left), modifiers);
1664 cx.simulate_mouse_up(point(px(300.), px(70.)), MouseButton::Left, modifiers);
1665 cx.update(|window, cx| {
1666 let _ = window.draw(cx);
1667 });
1668
1669 assert_eq!(
1670 window_selected_text(cx).trim(),
1671 "Hello world\n\nSecond message"
1672 );
1673 }
1674
1675 #[gpui::test]
1676 fn shift_click_uses_anchor_established_by_latest_plain_click(cx: &mut TestAppContext) {
1677 let (_, cx) = setup(true, cx);
1678 let start = point(px(0.), px(15.));
1679 let end = point(px(300.), px(15.));
1680 let new_anchor = point(px(20.), px(15.));
1681
1682 click(cx, start, Modifiers::default());
1683 click(cx, end, shift_modifiers());
1684 assert_eq!(window_selected_text(cx).trim(), "Hello world");
1685
1686 click(cx, new_anchor, Modifiers::default());
1687 click(cx, start, shift_modifiers());
1688 assert_eq!(window_selected_text(cx).trim(), "He");
1689 }
1690
1691 #[gpui::test]
1692 fn shift_click_without_anchor_falls_back_to_plain_click(cx: &mut TestAppContext) {
1693 let (_, cx) = setup(true, cx);
1694
1695 click(cx, point(px(20.), px(15.)), shift_modifiers());
1696
1697 assert_eq!(window_selected_text(cx), "");
1698 }
1699
1700 #[gpui::test]
1701 fn shift_click_extends_across_text_views(cx: &mut TestAppContext) {
1702 let (chat, cx) = setup(true, cx);
1703
1704 click(cx, point(px(0.), px(15.)), Modifiers::default());
1705 click(cx, point(px(300.), px(70.)), shift_modifiers());
1706
1707 let text = window_selected_text(cx);
1708 assert!(text.contains("Hello world"), "got: {text:?}");
1709 assert!(text.contains("Second message"), "got: {text:?}");
1710 let (first_selecting, second_selecting) = cx.update(|_, cx| {
1711 let chat = chat.read(cx);
1712 (
1713 chat.first.read(cx).is_selecting(),
1714 chat.second.read(cx).is_selecting(),
1715 )
1716 });
1717 assert!(!first_selecting);
1718 assert!(!second_selecting);
1719 }
1720
1721 #[gpui::test]
1722 fn shift_click_focuses_the_new_endpoint_view(cx: &mut TestAppContext) {
1723 let (chat, cx) = setup(true, cx);
1724
1725 click(cx, point(px(0.), px(15.)), Modifiers::default());
1726 click(cx, point(px(300.), px(70.)), shift_modifiers());
1727
1728 let second_is_focused = cx.update(|window, cx| {
1729 chat.read(cx)
1730 .second
1731 .read(cx)
1732 .focus_handle()
1733 .is_focused(window)
1734 });
1735 assert!(
1736 second_is_focused,
1737 "Shift-click left focus on the anchor view"
1738 );
1739 }
1740
1741 #[gpui::test]
1742 fn same_size_content_replacement_invalidates_finished_selection(cx: &mut TestAppContext) {
1743 let (chat, cx) = setup(true, cx);
1744
1745 drag(cx, point(px(0.), px(15.)), point(px(300.), px(15.)));
1746 assert_eq!(window_selected_text(cx).trim(), "Hello world");
1747
1748 let first = chat.read_with(cx, |chat, _| chat.first.clone());
1749 cx.update(|_, cx| {
1750 first.update(cx, |state, cx| state.set_text("Other words", cx));
1751 });
1752 cx.run_until_parked();
1753 cx.update(|window, cx| {
1754 let _ = window.draw(cx);
1755 });
1756
1757 assert_eq!(window_selected_text(cx), "");
1758 }
1759
1760 #[gpui::test]
1761 fn active_drag_replacement_invalidates_after_mouse_up(cx: &mut TestAppContext) {
1762 let (chat, cx) = setup(true, cx);
1763 let first = chat.read_with(cx, |chat, _| chat.first.clone());
1764
1765 cx.simulate_mouse_down(
1766 point(px(0.), px(15.)),
1767 MouseButton::Left,
1768 Modifiers::default(),
1769 );
1770 cx.simulate_mouse_move(
1771 point(px(300.), px(15.)),
1772 Some(MouseButton::Left),
1773 Modifiers::default(),
1774 );
1775 cx.update(|_, cx| {
1776 first.update(cx, |state, cx| state.set_text("Other words", cx));
1777 });
1778 cx.run_until_parked();
1779 cx.update(|window, cx| {
1780 let _ = window.draw(cx);
1781 });
1782 cx.simulate_mouse_up(
1783 point(px(300.), px(15.)),
1784 MouseButton::Left,
1785 Modifiers::default(),
1786 );
1787 cx.update(|window, cx| {
1788 let _ = window.draw(cx);
1789 });
1790
1791 assert_eq!(window_selected_text(cx), "");
1792 }
1793
1794 #[gpui::test]
1795 fn active_drag_append_keeps_compatible_selection(cx: &mut TestAppContext) {
1796 let (chat, cx) = setup(true, cx);
1797 let first = chat.read_with(cx, |chat, _| chat.first.clone());
1798
1799 cx.simulate_mouse_down(
1800 point(px(0.), px(15.)),
1801 MouseButton::Left,
1802 Modifiers::default(),
1803 );
1804 cx.simulate_mouse_move(
1805 point(px(300.), px(15.)),
1806 Some(MouseButton::Left),
1807 Modifiers::default(),
1808 );
1809 cx.update(|_, cx| {
1810 first.update(cx, |state, cx| state.push_str(" again", cx));
1811 });
1812 cx.run_until_parked();
1813 cx.simulate_mouse_up(
1814 point(px(300.), px(15.)),
1815 MouseButton::Left,
1816 Modifiers::default(),
1817 );
1818 cx.update(|window, cx| {
1819 let _ = window.draw(cx);
1820 });
1821
1822 let selected = window_selected_text(cx);
1823 assert!(selected.contains("Hello world"), "selected={selected:?}");
1824 }
1825
1826 #[gpui::test]
1827 fn same_size_style_reflow_invalidates_finished_selection(cx: &mut TestAppContext) {
1828 let (chat, cx) = setup(true, cx);
1829 drag(cx, point(px(0.), px(15.)), point(px(300.), px(15.)));
1830 assert_eq!(window_selected_text(cx).trim(), "Hello world");
1831
1832 chat.update(cx, |chat, cx| {
1833 chat.first_style.heading_base_font_size = px(28.);
1834 cx.notify();
1835 });
1836 cx.update(|window, cx| {
1837 let _ = window.draw(cx);
1838 });
1839
1840 assert_eq!(window_selected_text(cx), "");
1841 }
1842
1843 #[gpui::test]
1844 fn shift_click_on_suppressing_control_clears_text_view_selection(cx: &mut TestAppContext) {
1845 let (_, cx) = setup(true, cx);
1846
1847 drag(cx, point(px(0.), px(15.)), point(px(300.), px(70.)));
1848 assert!(!window_selected_text(cx).is_empty());
1849
1850 click(cx, point(px(20.), px(100.)), shift_modifiers());
1851
1852 assert_eq!(window_selected_text(cx), "");
1853 }
1854
1855 #[gpui::test]
1856 fn cross_view_drag_merges_text_top_to_bottom(cx: &mut TestAppContext) {
1857 let (_, cx) = setup(true, cx);
1858
1859 // From the very start of the first view down into the second view.
1860 drag(cx, point(px(0.), px(15.)), point(px(300.), px(70.)));
1861
1862 let text = window_selected_text(cx);
1863 let first = text.find("Hello world").expect("first view text missing");
1864 let second = text
1865 .find("Second message")
1866 .expect("second view text missing");
1867 assert!(first < second, "wrong order: {text:?}");
1868 assert!(text.contains('\n'), "expected newline separator: {text:?}");
1869 }
1870
1871 #[gpui::test]
1872 fn drag_from_blank_space_selects_views_below(cx: &mut TestAppContext) {
1873 let (_, cx) = setup(true, cx);
1874
1875 // Start in the blank padding above the first view, enter the second
1876 // view's rendered text, then drag past its end.
1877 drag_through(
1878 cx,
1879 &[
1880 point(px(5.), px(2.)),
1881 point(px(20.), px(70.)),
1882 point(px(300.), px(70.)),
1883 ],
1884 );
1885
1886 let text = window_selected_text(cx);
1887 assert!(text.contains("Hello world"), "got: {text:?}");
1888 assert!(text.contains("Second message"), "got: {text:?}");
1889 }
1890
1891 #[gpui::test]
1892 fn drag_entirely_in_blank_gap_selects_nothing(cx: &mut TestAppContext) {
1893 let (chat, cx) = setup(true, cx);
1894
1895 // Layout: first [10,50], gap [50,110], second [110,150].
1896 chat.update(cx, |chat, cx| {
1897 chat.mid_gap = px(60.);
1898 cx.notify();
1899 });
1900 cx.update(|window, cx| {
1901 let _ = window.draw(cx);
1902 });
1903
1904 // Drag only inside the gap. The selection never enters either TextView.
1905 drag(cx, point(px(5.), px(70.)), point(px(300.), px(90.)));
1906
1907 let text = window_selected_text(cx);
1908 assert_eq!(text, "", "blank-only drag selected text: {text:?}");
1909 }
1910
1911 #[gpui::test]
1912 fn drag_entirely_in_right_gutter_selects_nothing(cx: &mut TestAppContext) {
1913 let (_, cx) = setup(true, cx);
1914
1915 // x=300 is far to the right of the rendered text. Dragging vertically
1916 // through only that blank gutter must not select nearby TextViews.
1917 drag(cx, point(px(300.), px(2.)), point(px(300.), px(70.)));
1918
1919 let text = window_selected_text(cx);
1920 assert_eq!(text, "", "right-gutter drag selected text: {text:?}");
1921 }
1922
1923 #[gpui::test]
1924 fn selection_follows_content_when_layout_shifts(cx: &mut TestAppContext) {
1925 let (chat, cx) = setup(true, cx);
1926
1927 // Open a blank gap between the two views so we can anchor a selection
1928 // in blank space that sits *below* the first view's text and *above*
1929 // the second. Layout: first [10,50], gap [50,110], second [110,150].
1930 chat.update(cx, |chat, cx| {
1931 chat.mid_gap = px(60.);
1932 cx.notify();
1933 });
1934 cx.update(|window, cx| {
1935 let _ = window.draw(cx);
1936 });
1937
1938 // Anchor in the gap (blank space) and drag down-right into the second
1939 // view, ending past the end of its text so the whole line is selected.
1940 // The anchor sits below "Hello world", so only the second view is
1941 // selected.
1942 drag_through(
1943 cx,
1944 &[
1945 point(px(0.), px(80.)),
1946 point(px(20.), px(120.)),
1947 point(px(300.), px(120.)),
1948 ],
1949 );
1950 let before = window_selected_text(cx);
1951 assert!(
1952 before.contains("Second message") && !before.contains("Hello world"),
1953 "expected only the second view selected, got: {before:?}"
1954 );
1955
1956 // Shift the whole content down by 80px — the equivalent of an outer
1957 // container scrolling. A window-anchored blank endpoint stays at window
1958 // y=80, which the first view now covers (first moves to ~[90,130]), so
1959 // the selection drifts to also grab "Hello world". A proxy-anchored
1960 // endpoint moves with the content and the selection stays stable.
1961 chat.update(cx, |chat, cx| {
1962 chat.top_offset = px(90.);
1963 cx.notify();
1964 });
1965 cx.update(|window, cx| {
1966 let _ = window.draw(cx);
1967 });
1968
1969 let after = window_selected_text(cx);
1970 assert_eq!(before, after, "selection drifted after layout shift");
1971 }
1972
1973 #[gpui::test]
1974 fn suppressed_mouse_down_does_not_start_selection(cx: &mut TestAppContext) {
1975 let (_, cx) = setup(true, cx);
1976
1977 // The suppress selection sits below the two views (root pt=10, two 40px
1978 // view rows -> y in [90, 110)). Pressing inside it makes its bubble
1979 // handler set the suppress flag, so dragging up across both views must
1980 // not produce any window selection.
1981 drag(cx, point(px(20.), px(100.)), point(px(20.), px(15.)));
1982
1983 let text = window_selected_text(cx);
1984 assert!(text.is_empty(), "expected no selection, got: {text:?}");
1985 }
1986
1987 #[gpui::test]
1988 fn non_selectable_view_is_excluded(cx: &mut TestAppContext) {
1989 let (_, cx) = setup(false, cx);
1990
1991 drag_through(
1992 cx,
1993 &[
1994 point(px(5.), px(2.)),
1995 point(px(20.), px(15.)),
1996 point(px(300.), px(15.)),
1997 ],
1998 );
1999
2000 let text = window_selected_text(cx);
2001 assert!(text.contains("Hello world"), "got: {text:?}");
2002 assert!(!text.contains("Second message"), "got: {text:?}");
2003 }
2004
2005 #[gpui::test]
2006 fn drag_within_single_view_excludes_others(cx: &mut TestAppContext) {
2007 let (_, cx) = setup(true, cx);
2008
2009 // Entirely inside the first view.
2010 drag(cx, point(px(5.), px(15.)), point(px(60.), px(15.)));
2011
2012 let text = window_selected_text(cx);
2013 assert!(!text.contains("Second message"), "got: {text:?}");
2014 assert!(!text.trim().is_empty(), "expected some selection");
2015 }
2016
2017 #[gpui::test]
2018 fn mouse_down_clears_previous_selection(cx: &mut TestAppContext) {
2019 let (_, cx) = setup(true, cx);
2020
2021 drag(cx, point(px(5.), px(15.)), point(px(300.), px(70.)));
2022 assert!(!window_selected_text(cx).is_empty());
2023
2024 // A plain click clears the selection.
2025 cx.simulate_click(point(px(300.), px(100.)), Modifiers::default());
2026 cx.update(|window, cx| {
2027 let _ = window.draw(cx);
2028 });
2029
2030 assert_eq!(window_selected_text(cx), "");
2031 }
2032
2033 #[gpui::test]
2034 fn double_click_selects_word_under_root(cx: &mut TestAppContext) {
2035 let (_, cx) = setup(true, cx);
2036
2037 // Double-click inside the first view: must trigger the per-view word
2038 // selection (Inline), not a window-level drag selection.
2039 let position = point(px(10.), px(15.));
2040 cx.simulate_event(MouseDownEvent {
2041 position,
2042 modifiers: Modifiers::default(),
2043 button: MouseButton::Left,
2044 click_count: 2,
2045 first_mouse: false,
2046 });
2047 cx.simulate_event(MouseUpEvent {
2048 position,
2049 modifiers: Modifiers::default(),
2050 button: MouseButton::Left,
2051 click_count: 2,
2052 });
2053 cx.update(|window, cx| {
2054 let _ = window.draw(cx);
2055 });
2056
2057 let text = window_selected_text(cx);
2058 assert_eq!(text.trim(), "Hello", "expected word selection: {text:?}");
2059 assert!(!text.contains("Second message"), "got: {text:?}");
2060 }
2061
2062 #[gpui::test]
2063 fn drag_back_into_anchor_view_clears_other_views(cx: &mut TestAppContext) {
2064 let (chat, cx) = setup(true, cx);
2065 let second = chat.read_with(cx, |chat, _| chat.second.clone());
2066
2067 // Drag from view A down into view B: this is a cross-view selection, so
2068 // B paints a highlight and `selected_text` reports it.
2069 cx.simulate_mouse_down(
2070 point(px(0.), px(15.)),
2071 MouseButton::Left,
2072 Modifiers::default(),
2073 );
2074 cx.update(|window, cx| {
2075 let _ = window.draw(cx);
2076 });
2077 cx.simulate_mouse_move(
2078 point(px(300.), px(70.)),
2079 Some(MouseButton::Left),
2080 Modifiers::default(),
2081 );
2082 cx.update(|window, cx| {
2083 let _ = window.draw(cx);
2084 });
2085
2086 let text = second.read_with(cx, |state, _| state.selected_text());
2087 assert!(
2088 text.contains("Second message"),
2089 "precondition: B should be selected, got {text:?}"
2090 );
2091
2092 // Observe B's re-render requests. A view only drops a stale highlight
2093 // when it is notified and repaints; this asserts the controller does
2094 // notify B, independently of whether the test harness happens to
2095 // repaint B for unrelated reasons.
2096 let b_notified = Rc::new(Cell::new(false));
2097 let _subscription = cx.update({
2098 let b_notified = b_notified.clone();
2099 let second = second.clone();
2100 move |_, cx| cx.observe(&second, move |_, _| b_notified.set(true))
2101 });
2102 b_notified.set(false);
2103
2104 // Drag back up inside view A. The drag now lives entirely in A, so
2105 // `single_view` is Some(A) and the fast path runs. It must still notify
2106 // B (whose old band crossed B) so B can clear its now-stale highlight.
2107 //
2108 // We check this on the in-drag frame, not after mouse-up:
2109 // `TextSelection::end` notifies every selectable view, which would
2110 // notify B for an unrelated reason and mask the bug.
2111 cx.simulate_mouse_move(
2112 point(px(60.), px(15.)),
2113 Some(MouseButton::Left),
2114 Modifiers::default(),
2115 );
2116 cx.run_until_parked();
2117
2118 assert!(
2119 b_notified.get(),
2120 "view B was not notified when the drag returned to the anchor view, \
2121 so its stale highlight would never be repainted away",
2122 );
2123 }
2124
2125 /// A view with a selectable TextView used as Root content. Root mounts the
2126 /// Dialog/Sheet layers automatically, so a real modal can be opened above it.
2127 struct ModalScopeTestView {
2128 focus_handle: FocusHandle,
2129 base: Entity<TextViewState>,
2130 }
2131
2132 impl ModalScopeTestView {
2133 fn new(cx: &mut Context<Self>) -> Self {
2134 Self {
2135 focus_handle: cx.focus_handle(),
2136 base: cx.new(|cx| TextViewState::markdown("Hello world", cx)),
2137 }
2138 }
2139 }
2140
2141 impl Render for ModalScopeTestView {
2142 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2143 div().track_focus(&self.focus_handle).size_full().child(
2144 div()
2145 .h(px(40.))
2146 .child(TextView::new(&self.base).selectable(true)),
2147 )
2148 }
2149 }
2150
2151 fn setup_modal(
2152 cx: &mut TestAppContext,
2153 ) -> (Entity<ModalScopeTestView>, &mut VisualTestContext) {
2154 cx.update(crate::init);
2155 let (root, cx) = cx.add_window_view(|window, cx| {
2156 let view = cx.new(ModalScopeTestView::new);
2157 Root::new(view, window, cx)
2158 });
2159 let view = root.read_with(cx, |root, _| {
2160 root.view()
2161 .clone()
2162 .downcast::<ModalScopeTestView>()
2163 .unwrap()
2164 });
2165 cx.run_until_parked();
2166 cx.update(|window, cx| {
2167 let _ = window.draw(cx);
2168 });
2169 (view, cx)
2170 }
2171
2172 /// Advance past the modal open animation so it reaches its resting position,
2173 /// then redraw so its TextViews register and their bounds are stable for the
2174 /// subsequent drag.
2175 fn settle(cx: &mut VisualTestContext) {
2176 cx.executor().advance_clock(Duration::from_millis(500));
2177 cx.update(|window, cx| {
2178 let _ = window.draw(cx);
2179 });
2180 cx.update(|window, cx| {
2181 let _ = window.draw(cx);
2182 });
2183 }
2184
2185 fn open_dialog_with_text(
2186 cx: &mut VisualTestContext,
2187 text: &'static str,
2188 ) -> Entity<TextViewState> {
2189 let state = cx.update(|_, cx| cx.new(|cx| TextViewState::markdown(text, cx)));
2190 let state_for_builder = state.clone();
2191 cx.update(|window, cx| {
2192 crate::root::WindowState::update(window, cx, |root, window, cx| {
2193 root.open_dialog(
2194 move |dialog, _, _| {
2195 dialog.child(TextView::new(&state_for_builder).selectable(true))
2196 },
2197 window,
2198 cx,
2199 );
2200 });
2201 });
2202 settle(cx);
2203 state
2204 }
2205
2206 fn open_sheet_with_text(
2207 cx: &mut VisualTestContext,
2208 text: &'static str,
2209 ) -> Entity<TextViewState> {
2210 let state = cx.update(|_, cx| cx.new(|cx| TextViewState::markdown(text, cx)));
2211 let state_for_builder = state.clone();
2212 cx.update(|window, cx| {
2213 crate::root::WindowState::update(window, cx, |root, window, cx| {
2214 root.open_sheet_at(
2215 Placement::Right,
2216 move |sheet, _, _| {
2217 sheet.child(TextView::new(&state_for_builder).selectable(true))
2218 },
2219 window,
2220 cx,
2221 );
2222 });
2223 });
2224 settle(cx);
2225 state
2226 }
2227
2228 #[gpui::test]
2229 fn drag_inside_dialog_still_selects_its_text(cx: &mut TestAppContext) {
2230 let (_, cx) = setup_modal(cx);
2231 let dialog_state = open_dialog_with_text(cx, "Dialog text");
2232
2233 // A drag entirely within the dialog's TextView must still select (the
2234 // scope filter must not break in-dialog selection — see #2501).
2235 let b = dialog_state.read_with(cx, |s, _| s.bounds());
2236 drag(
2237 cx,
2238 point(b.origin.x + px(1.), b.center().y),
2239 point(b.origin.x + b.size.width + px(80.), b.center().y),
2240 );
2241
2242 let text = window_selected_text(cx);
2243 assert!(
2244 text.contains("Dialog text"),
2245 "dialog text was not selectable: {text:?}"
2246 );
2247 }
2248
2249 #[gpui::test]
2250 fn drag_inside_sheet_still_selects_its_text(cx: &mut TestAppContext) {
2251 let (_, cx) = setup_modal(cx);
2252 let sheet_state = open_sheet_with_text(cx, "Sheet text");
2253
2254 let bounds = sheet_state.read_with(cx, |state, _| state.bounds());
2255 drag(
2256 cx,
2257 point(bounds.origin.x + px(1.), bounds.center().y),
2258 point(bounds.right() + px(80.), bounds.center().y),
2259 );
2260
2261 let text = window_selected_text(cx);
2262 assert!(
2263 text.contains("Sheet text"),
2264 "sheet text was not selectable: {text:?}"
2265 );
2266 }
2267
2268 #[gpui::test]
2269 fn opening_dialog_clears_base_selection(cx: &mut TestAppContext) {
2270 let (view, cx) = setup_modal(cx);
2271
2272 let b = view.read_with(cx, |v, cx| v.base.read(cx).bounds());
2273 drag(
2274 cx,
2275 point(b.origin.x + px(1.), b.center().y),
2276 point(b.origin.x + b.size.width + px(80.), b.center().y),
2277 );
2278 assert!(window_selected_text(cx).contains("Hello world"));
2279
2280 let _dialog = open_dialog_with_text(cx, "Dialog text");
2281
2282 let text = window_selected_text(cx);
2283 assert!(
2284 !text.contains("Hello world"),
2285 "base selection was not cleared when the dialog opened: {text:?}"
2286 );
2287 }
2288
2289 /// Regression guard: with a dialog open, a drag that starts in the
2290 /// dialog's text and leaves it over the overlay must not select the
2291 /// TextView behind the overlay (#2501 de-guarded both Dialog and Sheet).
2292 #[gpui::test]
2293 fn selection_behind_active_dialog_is_excluded(cx: &mut TestAppContext) {
2294 let (view, cx) = setup_modal(cx);
2295 let dialog_state = open_dialog_with_text(cx, "Dialog text");
2296
2297 // Anchor inside the dialog's text, then drag up onto the base view's
2298 // glyphs (left side; the base view spans the full window width, so its
2299 // center is far from its text).
2300 let from = dialog_state.read_with(cx, |s, _| s.bounds().center());
2301 let to = view.read_with(cx, |v, cx| {
2302 let b = v.base.read(cx).bounds();
2303 point(b.origin.x + px(4.), b.center().y)
2304 });
2305 drag(cx, from, to);
2306
2307 let behind = view.read_with(cx, |v, cx| v.base.read(cx).selected_text());
2308 assert!(
2309 behind.trim().is_empty(),
2310 "view behind the dialog overlay was selected: {behind:?}"
2311 );
2312 }
2313
2314 /// The same guard for a Sheet.
2315 #[gpui::test]
2316 fn selection_behind_active_sheet_is_excluded(cx: &mut TestAppContext) {
2317 let (view, cx) = setup_modal(cx);
2318 let sheet_state = open_sheet_with_text(cx, "Sheet text");
2319
2320 let from = sheet_state.read_with(cx, |s, _| s.bounds().center());
2321 let to = view.read_with(cx, |v, cx| {
2322 let b = v.base.read(cx).bounds();
2323 point(b.origin.x + px(4.), b.center().y)
2324 });
2325 drag(cx, from, to);
2326
2327 let behind = view.read_with(cx, |v, cx| v.base.read(cx).selected_text());
2328 assert!(
2329 behind.trim().is_empty(),
2330 "view behind the sheet overlay was selected: {behind:?}"
2331 );
2332 }
2333}