1use super::{
2 display_map::{BlockContext, ToDisplayPoint},
3 Anchor, DisplayPoint, Editor, EditorMode, EditorSnapshot, SelectPhase, SoftWrap, ToPoint,
4 MAX_LINE_LEN,
5};
6use crate::{
7 display_map::{BlockStyle, DisplaySnapshot, FoldStatus, TransformBlock},
8 editor_settings::ShowScrollbars,
9 git::{diff_hunk_to_display, DisplayDiffHunk},
10 hover_popover::{
11 hide_hover, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH,
12 MIN_POPOVER_LINE_HEIGHT,
13 },
14 link_go_to_definition::{
15 go_to_fetched_definition, go_to_fetched_type_definition, update_go_to_definition_link,
16 },
17 mouse_context_menu, EditorSettings, EditorStyle, GutterHover, UnfoldAt,
18};
19use clock::ReplicaId;
20use collections::{BTreeMap, HashMap};
21use git::diff::DiffHunkStatus;
22use gpui::{
23 color::Color,
24 elements::*,
25 fonts::{HighlightStyle, TextStyle, Underline},
26 geometry::{
27 rect::RectF,
28 vector::{vec2f, Vector2F},
29 PathBuilder,
30 },
31 json::{self, ToJson},
32 platform::{CursorStyle, Modifiers, MouseButton, MouseButtonEvent, MouseMovedEvent},
33 text_layout::{self, Line, RunStyle, TextLayoutCache},
34 AnyElement, Axis, Border, CursorRegion, Element, EventContext, FontCache, LayoutContext,
35 MouseRegion, Quad, SceneBuilder, SizeConstraint, ViewContext, WindowContext,
36};
37use itertools::Itertools;
38use json::json;
39use language::{
40 language_settings::ShowWhitespaceSetting, Bias, CursorShape, DiagnosticSeverity, OffsetUtf16,
41 Selection,
42};
43use project::ProjectPath;
44use smallvec::SmallVec;
45use std::{
46 borrow::Cow,
47 cmp::{self, Ordering},
48 fmt::Write,
49 iter,
50 ops::Range,
51 sync::Arc,
52};
53use workspace::{item::Item, GitGutterSetting, WorkspaceSettings};
54
55enum FoldMarkers {}
56
57struct SelectionLayout {
58 head: DisplayPoint,
59 cursor_shape: CursorShape,
60 range: Range<DisplayPoint>,
61}
62
63impl SelectionLayout {
64 fn new<T: ToPoint + ToDisplayPoint + Clone>(
65 selection: Selection<T>,
66 line_mode: bool,
67 cursor_shape: CursorShape,
68 map: &DisplaySnapshot,
69 ) -> Self {
70 if line_mode {
71 let selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
72 let point_range = map.expand_to_line(selection.range());
73 Self {
74 head: selection.head().to_display_point(map),
75 cursor_shape,
76 range: point_range.start.to_display_point(map)
77 ..point_range.end.to_display_point(map),
78 }
79 } else {
80 let selection = selection.map(|p| p.to_display_point(map));
81 Self {
82 head: selection.head(),
83 cursor_shape,
84 range: selection.range(),
85 }
86 }
87 }
88}
89
90#[derive(Clone)]
91pub struct EditorElement {
92 style: Arc<EditorStyle>,
93}
94
95impl EditorElement {
96 pub fn new(style: EditorStyle) -> Self {
97 Self {
98 style: Arc::new(style),
99 }
100 }
101
102 fn attach_mouse_handlers(
103 scene: &mut SceneBuilder,
104 position_map: &Arc<PositionMap>,
105 has_popovers: bool,
106 visible_bounds: RectF,
107 text_bounds: RectF,
108 gutter_bounds: RectF,
109 bounds: RectF,
110 cx: &mut ViewContext<Editor>,
111 ) {
112 enum EditorElementMouseHandlers {}
113 scene.push_mouse_region(
114 MouseRegion::new::<EditorElementMouseHandlers>(
115 cx.view_id(),
116 cx.view_id(),
117 visible_bounds,
118 )
119 .on_down(MouseButton::Left, {
120 let position_map = position_map.clone();
121 move |event, editor, cx| {
122 if !Self::mouse_down(
123 editor,
124 event.platform_event,
125 position_map.as_ref(),
126 text_bounds,
127 gutter_bounds,
128 cx,
129 ) {
130 cx.propagate_event();
131 }
132 }
133 })
134 .on_down(MouseButton::Right, {
135 let position_map = position_map.clone();
136 move |event, editor, cx| {
137 if !Self::mouse_right_down(
138 editor,
139 event.position,
140 position_map.as_ref(),
141 text_bounds,
142 cx,
143 ) {
144 cx.propagate_event();
145 }
146 }
147 })
148 .on_up(MouseButton::Left, {
149 let position_map = position_map.clone();
150 move |event, editor, cx| {
151 if !Self::mouse_up(
152 editor,
153 event.position,
154 event.cmd,
155 event.shift,
156 position_map.as_ref(),
157 text_bounds,
158 cx,
159 ) {
160 cx.propagate_event()
161 }
162 }
163 })
164 .on_drag(MouseButton::Left, {
165 let position_map = position_map.clone();
166 move |event, editor, cx| {
167 if !Self::mouse_dragged(
168 editor,
169 event.platform_event,
170 position_map.as_ref(),
171 text_bounds,
172 cx,
173 ) {
174 cx.propagate_event()
175 }
176 }
177 })
178 .on_move({
179 let position_map = position_map.clone();
180 move |event, editor, cx| {
181 if !Self::mouse_moved(
182 editor,
183 event.platform_event,
184 &position_map,
185 text_bounds,
186 cx,
187 ) {
188 cx.propagate_event()
189 }
190 }
191 })
192 .on_move_out(move |_, editor: &mut Editor, cx| {
193 if has_popovers {
194 hide_hover(editor, cx);
195 }
196 })
197 .on_scroll({
198 let position_map = position_map.clone();
199 move |event, editor, cx| {
200 if !Self::scroll(
201 editor,
202 event.position,
203 *event.delta.raw(),
204 event.delta.precise(),
205 &position_map,
206 bounds,
207 cx,
208 ) {
209 cx.propagate_event()
210 }
211 }
212 }),
213 );
214
215 enum GutterHandlers {}
216 scene.push_mouse_region(
217 MouseRegion::new::<GutterHandlers>(cx.view_id(), cx.view_id() + 1, gutter_bounds)
218 .on_hover(|hover, editor: &mut Editor, cx| {
219 editor.gutter_hover(
220 &GutterHover {
221 hovered: hover.started,
222 },
223 cx,
224 );
225 }),
226 )
227 }
228
229 fn mouse_down(
230 editor: &mut Editor,
231 MouseButtonEvent {
232 position,
233 modifiers:
234 Modifiers {
235 shift,
236 ctrl,
237 alt,
238 cmd,
239 ..
240 },
241 mut click_count,
242 ..
243 }: MouseButtonEvent,
244 position_map: &PositionMap,
245 text_bounds: RectF,
246 gutter_bounds: RectF,
247 cx: &mut EventContext<Editor>,
248 ) -> bool {
249 if gutter_bounds.contains_point(position) {
250 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
251 } else if !text_bounds.contains_point(position) {
252 return false;
253 }
254
255 let (position, target_position) = position_map.point_for_position(text_bounds, position);
256
257 if shift && alt {
258 editor.select(
259 SelectPhase::BeginColumnar {
260 position,
261 goal_column: target_position.column(),
262 },
263 cx,
264 );
265 } else if shift && !ctrl && !alt && !cmd {
266 editor.select(
267 SelectPhase::Extend {
268 position,
269 click_count,
270 },
271 cx,
272 );
273 } else {
274 editor.select(
275 SelectPhase::Begin {
276 position,
277 add: alt,
278 click_count,
279 },
280 cx,
281 );
282 }
283
284 true
285 }
286
287 fn mouse_right_down(
288 editor: &mut Editor,
289 position: Vector2F,
290 position_map: &PositionMap,
291 text_bounds: RectF,
292 cx: &mut EventContext<Editor>,
293 ) -> bool {
294 if !text_bounds.contains_point(position) {
295 return false;
296 }
297
298 let (point, _) = position_map.point_for_position(text_bounds, position);
299 mouse_context_menu::deploy_context_menu(editor, position, point, cx);
300 true
301 }
302
303 fn mouse_up(
304 editor: &mut Editor,
305 position: Vector2F,
306 cmd: bool,
307 shift: bool,
308 position_map: &PositionMap,
309 text_bounds: RectF,
310 cx: &mut EventContext<Editor>,
311 ) -> bool {
312 let end_selection = editor.has_pending_selection();
313 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
314
315 if end_selection {
316 editor.select(SelectPhase::End, cx);
317 }
318
319 if !pending_nonempty_selections && cmd && text_bounds.contains_point(position) {
320 let (point, target_point) = position_map.point_for_position(text_bounds, position);
321
322 if point == target_point {
323 if shift {
324 go_to_fetched_type_definition(editor, point, cx);
325 } else {
326 go_to_fetched_definition(editor, point, cx);
327 }
328
329 return true;
330 }
331 }
332
333 end_selection
334 }
335
336 fn mouse_dragged(
337 editor: &mut Editor,
338 MouseMovedEvent {
339 modifiers: Modifiers { cmd, shift, .. },
340 position,
341 ..
342 }: MouseMovedEvent,
343 position_map: &PositionMap,
344 text_bounds: RectF,
345 cx: &mut EventContext<Editor>,
346 ) -> bool {
347 // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
348 // Don't trigger hover popover if mouse is hovering over context menu
349 let point = if text_bounds.contains_point(position) {
350 let (point, target_point) = position_map.point_for_position(text_bounds, position);
351 if point == target_point {
352 Some(point)
353 } else {
354 None
355 }
356 } else {
357 None
358 };
359
360 update_go_to_definition_link(editor, point, cmd, shift, cx);
361
362 if editor.has_pending_selection() {
363 let mut scroll_delta = Vector2F::zero();
364
365 let vertical_margin = position_map.line_height.min(text_bounds.height() / 3.0);
366 let top = text_bounds.origin_y() + vertical_margin;
367 let bottom = text_bounds.lower_left().y() - vertical_margin;
368 if position.y() < top {
369 scroll_delta.set_y(-scale_vertical_mouse_autoscroll_delta(top - position.y()))
370 }
371 if position.y() > bottom {
372 scroll_delta.set_y(scale_vertical_mouse_autoscroll_delta(position.y() - bottom))
373 }
374
375 let horizontal_margin = position_map.line_height.min(text_bounds.width() / 3.0);
376 let left = text_bounds.origin_x() + horizontal_margin;
377 let right = text_bounds.upper_right().x() - horizontal_margin;
378 if position.x() < left {
379 scroll_delta.set_x(-scale_horizontal_mouse_autoscroll_delta(
380 left - position.x(),
381 ))
382 }
383 if position.x() > right {
384 scroll_delta.set_x(scale_horizontal_mouse_autoscroll_delta(
385 position.x() - right,
386 ))
387 }
388
389 let (position, target_position) =
390 position_map.point_for_position(text_bounds, position);
391
392 editor.select(
393 SelectPhase::Update {
394 position,
395 goal_column: target_position.column(),
396 scroll_position: (position_map.snapshot.scroll_position() + scroll_delta)
397 .clamp(Vector2F::zero(), position_map.scroll_max),
398 },
399 cx,
400 );
401 hover_at(editor, point, cx);
402 true
403 } else {
404 hover_at(editor, point, cx);
405 false
406 }
407 }
408
409 fn mouse_moved(
410 editor: &mut Editor,
411 MouseMovedEvent {
412 modifiers: Modifiers { shift, cmd, .. },
413 position,
414 ..
415 }: MouseMovedEvent,
416 position_map: &PositionMap,
417 text_bounds: RectF,
418 cx: &mut ViewContext<Editor>,
419 ) -> bool {
420 // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
421 // Don't trigger hover popover if mouse is hovering over context menu
422 let point = position_to_display_point(position, text_bounds, position_map);
423
424 update_go_to_definition_link(editor, point, cmd, shift, cx);
425 hover_at(editor, point, cx);
426
427 true
428 }
429
430 fn scroll(
431 editor: &mut Editor,
432 position: Vector2F,
433 mut delta: Vector2F,
434 precise: bool,
435 position_map: &PositionMap,
436 bounds: RectF,
437 cx: &mut ViewContext<Editor>,
438 ) -> bool {
439 if !bounds.contains_point(position) {
440 return false;
441 }
442
443 let line_height = position_map.line_height;
444 let max_glyph_width = position_map.em_width;
445
446 let axis = if precise {
447 //Trackpad
448 position_map.snapshot.ongoing_scroll.filter(&mut delta)
449 } else {
450 //Not trackpad
451 delta *= vec2f(max_glyph_width, line_height);
452 None //Resets ongoing scroll
453 };
454
455 let scroll_position = position_map.snapshot.scroll_position();
456 let x = (scroll_position.x() * max_glyph_width - delta.x()) / max_glyph_width;
457 let y = (scroll_position.y() * line_height - delta.y()) / line_height;
458 let scroll_position = vec2f(x, y).clamp(Vector2F::zero(), position_map.scroll_max);
459 editor.scroll(scroll_position, axis, cx);
460
461 true
462 }
463
464 fn paint_background(
465 &self,
466 scene: &mut SceneBuilder,
467 gutter_bounds: RectF,
468 text_bounds: RectF,
469 layout: &LayoutState,
470 ) {
471 let bounds = gutter_bounds.union_rect(text_bounds);
472 let scroll_top =
473 layout.position_map.snapshot.scroll_position().y() * layout.position_map.line_height;
474 scene.push_quad(Quad {
475 bounds: gutter_bounds,
476 background: Some(self.style.gutter_background),
477 border: Border::new(0., Color::transparent_black()),
478 corner_radius: 0.,
479 });
480 scene.push_quad(Quad {
481 bounds: text_bounds,
482 background: Some(self.style.background),
483 border: Border::new(0., Color::transparent_black()),
484 corner_radius: 0.,
485 });
486
487 if let EditorMode::Full = layout.mode {
488 let mut active_rows = layout.active_rows.iter().peekable();
489 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
490 let mut end_row = *start_row;
491 while active_rows.peek().map_or(false, |r| {
492 *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
493 }) {
494 active_rows.next().unwrap();
495 end_row += 1;
496 }
497
498 if !contains_non_empty_selection {
499 let origin = vec2f(
500 bounds.origin_x(),
501 bounds.origin_y() + (layout.position_map.line_height * *start_row as f32)
502 - scroll_top,
503 );
504 let size = vec2f(
505 bounds.width(),
506 layout.position_map.line_height * (end_row - start_row + 1) as f32,
507 );
508 scene.push_quad(Quad {
509 bounds: RectF::new(origin, size),
510 background: Some(self.style.active_line_background),
511 border: Border::default(),
512 corner_radius: 0.,
513 });
514 }
515 }
516
517 if let Some(highlighted_rows) = &layout.highlighted_rows {
518 let origin = vec2f(
519 bounds.origin_x(),
520 bounds.origin_y()
521 + (layout.position_map.line_height * highlighted_rows.start as f32)
522 - scroll_top,
523 );
524 let size = vec2f(
525 bounds.width(),
526 layout.position_map.line_height * highlighted_rows.len() as f32,
527 );
528 scene.push_quad(Quad {
529 bounds: RectF::new(origin, size),
530 background: Some(self.style.highlighted_line_background),
531 border: Border::default(),
532 corner_radius: 0.,
533 });
534 }
535 }
536 }
537
538 fn paint_gutter(
539 &mut self,
540 scene: &mut SceneBuilder,
541 bounds: RectF,
542 visible_bounds: RectF,
543 layout: &mut LayoutState,
544 editor: &mut Editor,
545 cx: &mut ViewContext<Editor>,
546 ) {
547 let line_height = layout.position_map.line_height;
548
549 let scroll_position = layout.position_map.snapshot.scroll_position();
550 let scroll_top = scroll_position.y() * line_height;
551
552 let show_gutter = matches!(
553 settings::get_setting::<WorkspaceSettings>(None, cx)
554 .git
555 .git_gutter
556 .unwrap_or_default(),
557 GitGutterSetting::TrackedFiles
558 );
559
560 if show_gutter {
561 Self::paint_diff_hunks(scene, bounds, layout, cx);
562 }
563
564 for (ix, line) in layout.line_number_layouts.iter().enumerate() {
565 if let Some(line) = line {
566 let line_origin = bounds.origin()
567 + vec2f(
568 bounds.width() - line.width() - layout.gutter_padding,
569 ix as f32 * line_height - (scroll_top % line_height),
570 );
571
572 line.paint(scene, line_origin, visible_bounds, line_height, cx);
573 }
574 }
575
576 for (ix, fold_indicator) in layout.fold_indicators.iter_mut().enumerate() {
577 if let Some(indicator) = fold_indicator.as_mut() {
578 let position = vec2f(
579 bounds.width() - layout.gutter_padding,
580 ix as f32 * line_height - (scroll_top % line_height),
581 );
582 let centering_offset = vec2f(
583 (layout.gutter_padding + layout.gutter_margin - indicator.size().x()) / 2.,
584 (line_height - indicator.size().y()) / 2.,
585 );
586
587 let indicator_origin = bounds.origin() + position + centering_offset;
588
589 indicator.paint(scene, indicator_origin, visible_bounds, editor, cx);
590 }
591 }
592
593 if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
594 let mut x = 0.;
595 let mut y = *row as f32 * line_height - scroll_top;
596 x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
597 y += (line_height - indicator.size().y()) / 2.;
598 indicator.paint(
599 scene,
600 bounds.origin() + vec2f(x, y),
601 visible_bounds,
602 editor,
603 cx,
604 );
605 }
606 }
607
608 fn paint_diff_hunks(
609 scene: &mut SceneBuilder,
610 bounds: RectF,
611 layout: &mut LayoutState,
612 cx: &mut ViewContext<Editor>,
613 ) {
614 let diff_style = &theme::current(cx).editor.diff.clone();
615 let line_height = layout.position_map.line_height;
616
617 let scroll_position = layout.position_map.snapshot.scroll_position();
618 let scroll_top = scroll_position.y() * line_height;
619
620 for hunk in &layout.display_hunks {
621 let (display_row_range, status) = match hunk {
622 //TODO: This rendering is entirely a horrible hack
623 &DisplayDiffHunk::Folded { display_row: row } => {
624 let start_y = row as f32 * line_height - scroll_top;
625 let end_y = start_y + line_height;
626
627 let width = diff_style.removed_width_em * line_height;
628 let highlight_origin = bounds.origin() + vec2f(-width, start_y);
629 let highlight_size = vec2f(width * 2., end_y - start_y);
630 let highlight_bounds = RectF::new(highlight_origin, highlight_size);
631
632 scene.push_quad(Quad {
633 bounds: highlight_bounds,
634 background: Some(diff_style.modified),
635 border: Border::new(0., Color::transparent_black()),
636 corner_radius: 1. * line_height,
637 });
638
639 continue;
640 }
641
642 DisplayDiffHunk::Unfolded {
643 display_row_range,
644 status,
645 } => (display_row_range, status),
646 };
647
648 let color = match status {
649 DiffHunkStatus::Added => diff_style.inserted,
650 DiffHunkStatus::Modified => diff_style.modified,
651
652 //TODO: This rendering is entirely a horrible hack
653 DiffHunkStatus::Removed => {
654 let row = *display_row_range.start();
655
656 let offset = line_height / 2.;
657 let start_y = row as f32 * line_height - offset - scroll_top;
658 let end_y = start_y + line_height;
659
660 let width = diff_style.removed_width_em * line_height;
661 let highlight_origin = bounds.origin() + vec2f(-width, start_y);
662 let highlight_size = vec2f(width * 2., end_y - start_y);
663 let highlight_bounds = RectF::new(highlight_origin, highlight_size);
664
665 scene.push_quad(Quad {
666 bounds: highlight_bounds,
667 background: Some(diff_style.deleted),
668 border: Border::new(0., Color::transparent_black()),
669 corner_radius: 1. * line_height,
670 });
671
672 continue;
673 }
674 };
675
676 let start_row = *display_row_range.start();
677 let end_row = *display_row_range.end();
678
679 let start_y = start_row as f32 * line_height - scroll_top;
680 let end_y = end_row as f32 * line_height - scroll_top + line_height;
681
682 let width = diff_style.width_em * line_height;
683 let highlight_origin = bounds.origin() + vec2f(-width, start_y);
684 let highlight_size = vec2f(width * 2., end_y - start_y);
685 let highlight_bounds = RectF::new(highlight_origin, highlight_size);
686
687 scene.push_quad(Quad {
688 bounds: highlight_bounds,
689 background: Some(color),
690 border: Border::new(0., Color::transparent_black()),
691 corner_radius: diff_style.corner_radius * line_height,
692 });
693 }
694 }
695
696 fn paint_text(
697 &mut self,
698 scene: &mut SceneBuilder,
699 bounds: RectF,
700 visible_bounds: RectF,
701 layout: &mut LayoutState,
702 editor: &mut Editor,
703 cx: &mut ViewContext<Editor>,
704 ) {
705 let style = &self.style;
706 let local_replica_id = editor.replica_id(cx);
707 let scroll_position = layout.position_map.snapshot.scroll_position();
708 let start_row = layout.visible_display_row_range.start;
709 let scroll_top = scroll_position.y() * layout.position_map.line_height;
710 let max_glyph_width = layout.position_map.em_width;
711 let scroll_left = scroll_position.x() * max_glyph_width;
712 let content_origin = bounds.origin() + vec2f(layout.gutter_margin, 0.);
713 let line_end_overshoot = 0.15 * layout.position_map.line_height;
714 let whitespace_setting = editor.buffer.read(cx).settings_at(0, cx).show_whitespaces;
715
716 scene.push_layer(Some(bounds));
717
718 scene.push_cursor_region(CursorRegion {
719 bounds,
720 style: if !editor.link_go_to_definition_state.definitions.is_empty() {
721 CursorStyle::PointingHand
722 } else {
723 CursorStyle::IBeam
724 },
725 });
726
727 let fold_corner_radius =
728 self.style.folds.ellipses.corner_radius_factor * layout.position_map.line_height;
729 for (id, range, color) in layout.fold_ranges.iter() {
730 self.paint_highlighted_range(
731 scene,
732 range.clone(),
733 *color,
734 fold_corner_radius,
735 fold_corner_radius * 2.,
736 layout,
737 content_origin,
738 scroll_top,
739 scroll_left,
740 bounds,
741 );
742
743 for bound in range_to_bounds(
744 &range,
745 content_origin,
746 scroll_left,
747 scroll_top,
748 &layout.visible_display_row_range,
749 line_end_overshoot,
750 &layout.position_map,
751 ) {
752 scene.push_cursor_region(CursorRegion {
753 bounds: bound,
754 style: CursorStyle::PointingHand,
755 });
756
757 let display_row = range.start.row();
758
759 let buffer_row = DisplayPoint::new(display_row, 0)
760 .to_point(&layout.position_map.snapshot.display_snapshot)
761 .row;
762
763 scene.push_mouse_region(
764 MouseRegion::new::<FoldMarkers>(cx.view_id(), *id as usize, bound)
765 .on_click(MouseButton::Left, move |_, editor: &mut Editor, cx| {
766 editor.unfold_at(&UnfoldAt { buffer_row }, cx)
767 })
768 .with_notify_on_hover(true)
769 .with_notify_on_click(true),
770 )
771 }
772 }
773
774 for (range, color) in &layout.highlighted_ranges {
775 self.paint_highlighted_range(
776 scene,
777 range.clone(),
778 *color,
779 0.,
780 line_end_overshoot,
781 layout,
782 content_origin,
783 scroll_top,
784 scroll_left,
785 bounds,
786 );
787 }
788
789 let mut cursors = SmallVec::<[Cursor; 32]>::new();
790 let corner_radius = 0.15 * layout.position_map.line_height;
791 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
792
793 for (replica_id, selections) in &layout.selections {
794 let replica_id = *replica_id;
795 let selection_style = style.replica_selection_style(replica_id);
796
797 for selection in selections {
798 if !selection.range.is_empty()
799 && (replica_id == local_replica_id
800 || Some(replica_id) == editor.leader_replica_id)
801 {
802 invisible_display_ranges.push(selection.range.clone());
803 }
804 self.paint_highlighted_range(
805 scene,
806 selection.range.clone(),
807 selection_style.selection,
808 corner_radius,
809 corner_radius * 2.,
810 layout,
811 content_origin,
812 scroll_top,
813 scroll_left,
814 bounds,
815 );
816
817 if editor.show_local_cursors(cx) || replica_id != local_replica_id {
818 let cursor_position = selection.head;
819 if layout
820 .visible_display_row_range
821 .contains(&cursor_position.row())
822 {
823 let cursor_row_layout = &layout.position_map.line_layouts
824 [(cursor_position.row() - start_row) as usize]
825 .line;
826 let cursor_column = cursor_position.column() as usize;
827
828 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
829 let mut block_width =
830 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
831 if block_width == 0.0 {
832 block_width = layout.position_map.em_width;
833 }
834 let block_text = if let CursorShape::Block = selection.cursor_shape {
835 layout
836 .position_map
837 .snapshot
838 .chars_at(cursor_position)
839 .next()
840 .and_then(|(character, _)| {
841 let font_id =
842 cursor_row_layout.font_for_index(cursor_column)?;
843 let text = character.to_string();
844
845 Some(cx.text_layout_cache().layout_str(
846 &text,
847 cursor_row_layout.font_size(),
848 &[(
849 text.len(),
850 RunStyle {
851 font_id,
852 color: style.background,
853 underline: Default::default(),
854 },
855 )],
856 ))
857 })
858 } else {
859 None
860 };
861
862 let x = cursor_character_x - scroll_left;
863 let y = cursor_position.row() as f32 * layout.position_map.line_height
864 - scroll_top;
865 cursors.push(Cursor {
866 color: selection_style.cursor,
867 block_width,
868 origin: vec2f(x, y),
869 line_height: layout.position_map.line_height,
870 shape: selection.cursor_shape,
871 block_text,
872 });
873 }
874 }
875 }
876 }
877
878 if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
879 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
880 let row = start_row + ix as u32;
881 line_with_invisibles.draw(
882 layout,
883 row,
884 scroll_top,
885 scene,
886 content_origin,
887 scroll_left,
888 visible_text_bounds,
889 whitespace_setting,
890 &invisible_display_ranges,
891 visible_bounds,
892 cx,
893 )
894 }
895 }
896
897 scene.paint_layer(Some(bounds), |scene| {
898 for cursor in cursors {
899 cursor.paint(scene, content_origin, cx);
900 }
901 });
902
903 if let Some((position, context_menu)) = layout.context_menu.as_mut() {
904 scene.push_stacking_context(None, None);
905 let cursor_row_layout =
906 &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
907 let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
908 let y = (position.row() + 1) as f32 * layout.position_map.line_height - scroll_top;
909 let mut list_origin = content_origin + vec2f(x, y);
910 let list_width = context_menu.size().x();
911 let list_height = context_menu.size().y();
912
913 // Snap the right edge of the list to the right edge of the window if
914 // its horizontal bounds overflow.
915 if list_origin.x() + list_width > cx.window_size().x() {
916 list_origin.set_x((cx.window_size().x() - list_width).max(0.));
917 }
918
919 if list_origin.y() + list_height > bounds.max_y() {
920 list_origin.set_y(list_origin.y() - layout.position_map.line_height - list_height);
921 }
922
923 context_menu.paint(
924 scene,
925 list_origin,
926 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
927 editor,
928 cx,
929 );
930
931 scene.pop_stacking_context();
932 }
933
934 if let Some((position, hover_popovers)) = layout.hover_popovers.as_mut() {
935 scene.push_stacking_context(None, None);
936
937 // This is safe because we check on layout whether the required row is available
938 let hovered_row_layout =
939 &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
940
941 // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
942 // height. This is the size we will use to decide whether to render popovers above or below
943 // the hovered line.
944 let first_size = hover_popovers[0].size();
945 let height_to_reserve = first_size.y()
946 + 1.5 * MIN_POPOVER_LINE_HEIGHT as f32 * layout.position_map.line_height;
947
948 // Compute Hovered Point
949 let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
950 let y = position.row() as f32 * layout.position_map.line_height - scroll_top;
951 let hovered_point = content_origin + vec2f(x, y);
952
953 if hovered_point.y() - height_to_reserve > 0.0 {
954 // There is enough space above. Render popovers above the hovered point
955 let mut current_y = hovered_point.y();
956 for hover_popover in hover_popovers {
957 let size = hover_popover.size();
958 let mut popover_origin = vec2f(hovered_point.x(), current_y - size.y());
959
960 let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
961 if x_out_of_bounds < 0.0 {
962 popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
963 }
964
965 hover_popover.paint(
966 scene,
967 popover_origin,
968 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
969 editor,
970 cx,
971 );
972
973 current_y = popover_origin.y() - HOVER_POPOVER_GAP;
974 }
975 } else {
976 // There is not enough space above. Render popovers below the hovered point
977 let mut current_y = hovered_point.y() + layout.position_map.line_height;
978 for hover_popover in hover_popovers {
979 let size = hover_popover.size();
980 let mut popover_origin = vec2f(hovered_point.x(), current_y);
981
982 let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
983 if x_out_of_bounds < 0.0 {
984 popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
985 }
986
987 hover_popover.paint(
988 scene,
989 popover_origin,
990 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
991 editor,
992 cx,
993 );
994
995 current_y = popover_origin.y() + size.y() + HOVER_POPOVER_GAP;
996 }
997 }
998
999 scene.pop_stacking_context();
1000 }
1001
1002 scene.pop_layer();
1003 }
1004
1005 fn paint_scrollbar(
1006 &mut self,
1007 scene: &mut SceneBuilder,
1008 bounds: RectF,
1009 layout: &mut LayoutState,
1010 cx: &mut ViewContext<Editor>,
1011 ) {
1012 enum ScrollbarMouseHandlers {}
1013 if layout.mode != EditorMode::Full {
1014 return;
1015 }
1016
1017 let style = &self.style.theme.scrollbar;
1018
1019 let top = bounds.min_y();
1020 let bottom = bounds.max_y();
1021 let right = bounds.max_x();
1022 let left = right - style.width;
1023 let row_range = &layout.scrollbar_row_range;
1024 let max_row = layout.max_row as f32 + (row_range.end - row_range.start);
1025
1026 let mut height = bounds.height();
1027 let mut first_row_y_offset = 0.0;
1028
1029 // Impose a minimum height on the scrollbar thumb
1030 let row_height = height / max_row;
1031 let min_thumb_height =
1032 style.min_height_factor * cx.font_cache.line_height(self.style.text.font_size);
1033 let thumb_height = (row_range.end - row_range.start) * row_height;
1034 if thumb_height < min_thumb_height {
1035 first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
1036 height -= min_thumb_height - thumb_height;
1037 }
1038
1039 let y_for_row = |row: f32| -> f32 { top + first_row_y_offset + row * row_height };
1040
1041 let thumb_top = y_for_row(row_range.start) - first_row_y_offset;
1042 let thumb_bottom = y_for_row(row_range.end) + first_row_y_offset;
1043 let track_bounds = RectF::from_points(vec2f(left, top), vec2f(right, bottom));
1044 let thumb_bounds = RectF::from_points(vec2f(left, thumb_top), vec2f(right, thumb_bottom));
1045
1046 if layout.show_scrollbars {
1047 scene.push_quad(Quad {
1048 bounds: track_bounds,
1049 border: style.track.border,
1050 background: style.track.background_color,
1051 ..Default::default()
1052 });
1053
1054 let diff_style = theme::current(cx).editor.diff.clone();
1055 for hunk in layout
1056 .position_map
1057 .snapshot
1058 .buffer_snapshot
1059 .git_diff_hunks_in_range(0..(max_row.floor() as u32), false)
1060 {
1061 let start_y = y_for_row(hunk.buffer_range.start as f32);
1062 let mut end_y = if hunk.buffer_range.start == hunk.buffer_range.end {
1063 y_for_row((hunk.buffer_range.end + 1) as f32)
1064 } else {
1065 y_for_row((hunk.buffer_range.end) as f32)
1066 };
1067
1068 if end_y - start_y < 1. {
1069 end_y = start_y + 1.;
1070 }
1071 let bounds = RectF::from_points(vec2f(left, start_y), vec2f(right, end_y));
1072
1073 let color = match hunk.status() {
1074 DiffHunkStatus::Added => diff_style.inserted,
1075 DiffHunkStatus::Modified => diff_style.modified,
1076 DiffHunkStatus::Removed => diff_style.deleted,
1077 };
1078
1079 let border = Border {
1080 width: 1.,
1081 color: style.thumb.border.color,
1082 overlay: false,
1083 top: false,
1084 right: true,
1085 bottom: false,
1086 left: true,
1087 };
1088
1089 scene.push_quad(Quad {
1090 bounds,
1091 background: Some(color),
1092 border,
1093 corner_radius: style.thumb.corner_radius,
1094 })
1095 }
1096
1097 scene.push_quad(Quad {
1098 bounds: thumb_bounds,
1099 border: style.thumb.border,
1100 background: style.thumb.background_color,
1101 corner_radius: style.thumb.corner_radius,
1102 });
1103 }
1104
1105 scene.push_cursor_region(CursorRegion {
1106 bounds: track_bounds,
1107 style: CursorStyle::Arrow,
1108 });
1109 scene.push_mouse_region(
1110 MouseRegion::new::<ScrollbarMouseHandlers>(cx.view_id(), cx.view_id(), track_bounds)
1111 .on_move(move |_, editor: &mut Editor, cx| {
1112 editor.scroll_manager.show_scrollbar(cx);
1113 })
1114 .on_down(MouseButton::Left, {
1115 let row_range = row_range.clone();
1116 move |event, editor: &mut Editor, cx| {
1117 let y = event.position.y();
1118 if y < thumb_top || thumb_bottom < y {
1119 let center_row = ((y - top) * max_row as f32 / height).round() as u32;
1120 let top_row = center_row
1121 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
1122 let mut position = editor.scroll_position(cx);
1123 position.set_y(top_row as f32);
1124 editor.set_scroll_position(position, cx);
1125 } else {
1126 editor.scroll_manager.show_scrollbar(cx);
1127 }
1128 }
1129 })
1130 .on_drag(MouseButton::Left, {
1131 move |event, editor: &mut Editor, cx| {
1132 let y = event.prev_mouse_position.y();
1133 let new_y = event.position.y();
1134 if thumb_top < y && y < thumb_bottom {
1135 let mut position = editor.scroll_position(cx);
1136 position.set_y(position.y() + (new_y - y) * (max_row as f32) / height);
1137 if position.y() < 0.0 {
1138 position.set_y(0.);
1139 }
1140 editor.set_scroll_position(position, cx);
1141 }
1142 }
1143 }),
1144 );
1145 }
1146
1147 #[allow(clippy::too_many_arguments)]
1148 fn paint_highlighted_range(
1149 &self,
1150 scene: &mut SceneBuilder,
1151 range: Range<DisplayPoint>,
1152 color: Color,
1153 corner_radius: f32,
1154 line_end_overshoot: f32,
1155 layout: &LayoutState,
1156 content_origin: Vector2F,
1157 scroll_top: f32,
1158 scroll_left: f32,
1159 bounds: RectF,
1160 ) {
1161 let start_row = layout.visible_display_row_range.start;
1162 let end_row = layout.visible_display_row_range.end;
1163 if range.start != range.end {
1164 let row_range = if range.end.column() == 0 {
1165 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
1166 } else {
1167 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
1168 };
1169
1170 let highlighted_range = HighlightedRange {
1171 color,
1172 line_height: layout.position_map.line_height,
1173 corner_radius,
1174 start_y: content_origin.y()
1175 + row_range.start as f32 * layout.position_map.line_height
1176 - scroll_top,
1177 lines: row_range
1178 .into_iter()
1179 .map(|row| {
1180 let line_layout =
1181 &layout.position_map.line_layouts[(row - start_row) as usize].line;
1182 HighlightedRangeLine {
1183 start_x: if row == range.start.row() {
1184 content_origin.x()
1185 + line_layout.x_for_index(range.start.column() as usize)
1186 - scroll_left
1187 } else {
1188 content_origin.x() - scroll_left
1189 },
1190 end_x: if row == range.end.row() {
1191 content_origin.x()
1192 + line_layout.x_for_index(range.end.column() as usize)
1193 - scroll_left
1194 } else {
1195 content_origin.x() + line_layout.width() + line_end_overshoot
1196 - scroll_left
1197 },
1198 }
1199 })
1200 .collect(),
1201 };
1202
1203 highlighted_range.paint(bounds, scene);
1204 }
1205 }
1206
1207 fn paint_blocks(
1208 &mut self,
1209 scene: &mut SceneBuilder,
1210 bounds: RectF,
1211 visible_bounds: RectF,
1212 layout: &mut LayoutState,
1213 editor: &mut Editor,
1214 cx: &mut ViewContext<Editor>,
1215 ) {
1216 let scroll_position = layout.position_map.snapshot.scroll_position();
1217 let scroll_left = scroll_position.x() * layout.position_map.em_width;
1218 let scroll_top = scroll_position.y() * layout.position_map.line_height;
1219
1220 for block in &mut layout.blocks {
1221 let mut origin = bounds.origin()
1222 + vec2f(
1223 0.,
1224 block.row as f32 * layout.position_map.line_height - scroll_top,
1225 );
1226 if !matches!(block.style, BlockStyle::Sticky) {
1227 origin += vec2f(-scroll_left, 0.);
1228 }
1229 block
1230 .element
1231 .paint(scene, origin, visible_bounds, editor, cx);
1232 }
1233 }
1234
1235 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &ViewContext<Editor>) -> f32 {
1236 let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
1237 let style = &self.style;
1238
1239 cx.text_layout_cache()
1240 .layout_str(
1241 "1".repeat(digit_count).as_str(),
1242 style.text.font_size,
1243 &[(
1244 digit_count,
1245 RunStyle {
1246 font_id: style.text.font_id,
1247 color: Color::black(),
1248 underline: Default::default(),
1249 },
1250 )],
1251 )
1252 .width()
1253 }
1254
1255 //Folds contained in a hunk are ignored apart from shrinking visual size
1256 //If a fold contains any hunks then that fold line is marked as modified
1257 fn layout_git_gutters(
1258 &self,
1259 display_rows: Range<u32>,
1260 snapshot: &EditorSnapshot,
1261 ) -> Vec<DisplayDiffHunk> {
1262 let buffer_snapshot = &snapshot.buffer_snapshot;
1263
1264 let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1265 .to_point(snapshot)
1266 .row;
1267 let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1268 .to_point(snapshot)
1269 .row;
1270
1271 buffer_snapshot
1272 .git_diff_hunks_in_range(buffer_start_row..buffer_end_row, false)
1273 .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1274 .dedup()
1275 .collect()
1276 }
1277
1278 fn layout_line_numbers(
1279 &self,
1280 rows: Range<u32>,
1281 active_rows: &BTreeMap<u32, bool>,
1282 is_singleton: bool,
1283 snapshot: &EditorSnapshot,
1284 cx: &ViewContext<Editor>,
1285 ) -> (
1286 Vec<Option<text_layout::Line>>,
1287 Vec<Option<(FoldStatus, BufferRow, bool)>>,
1288 ) {
1289 let style = &self.style;
1290 let include_line_numbers = snapshot.mode == EditorMode::Full;
1291 let mut line_number_layouts = Vec::with_capacity(rows.len());
1292 let mut fold_statuses = Vec::with_capacity(rows.len());
1293 let mut line_number = String::new();
1294 for (ix, row) in snapshot
1295 .buffer_rows(rows.start)
1296 .take((rows.end - rows.start) as usize)
1297 .enumerate()
1298 {
1299 let display_row = rows.start + ix as u32;
1300 let (active, color) = if active_rows.contains_key(&display_row) {
1301 (true, style.line_number_active)
1302 } else {
1303 (false, style.line_number)
1304 };
1305 if let Some(buffer_row) = row {
1306 if include_line_numbers {
1307 line_number.clear();
1308 write!(&mut line_number, "{}", buffer_row + 1).unwrap();
1309 line_number_layouts.push(Some(cx.text_layout_cache().layout_str(
1310 &line_number,
1311 style.text.font_size,
1312 &[(
1313 line_number.len(),
1314 RunStyle {
1315 font_id: style.text.font_id,
1316 color,
1317 underline: Default::default(),
1318 },
1319 )],
1320 )));
1321 fold_statuses.push(
1322 is_singleton
1323 .then(|| {
1324 snapshot
1325 .fold_for_line(buffer_row)
1326 .map(|fold_status| (fold_status, buffer_row, active))
1327 })
1328 .flatten(),
1329 )
1330 }
1331 } else {
1332 fold_statuses.push(None);
1333 line_number_layouts.push(None);
1334 }
1335 }
1336
1337 (line_number_layouts, fold_statuses)
1338 }
1339
1340 fn layout_lines(
1341 &mut self,
1342 rows: Range<u32>,
1343 line_number_layouts: &[Option<Line>],
1344 snapshot: &EditorSnapshot,
1345 cx: &ViewContext<Editor>,
1346 ) -> Vec<LineWithInvisibles> {
1347 if rows.start >= rows.end {
1348 return Vec::new();
1349 }
1350
1351 // When the editor is empty and unfocused, then show the placeholder.
1352 if snapshot.is_empty() {
1353 let placeholder_style = self
1354 .style
1355 .placeholder_text
1356 .as_ref()
1357 .unwrap_or(&self.style.text);
1358 let placeholder_text = snapshot.placeholder_text();
1359 let placeholder_lines = placeholder_text
1360 .as_ref()
1361 .map_or("", AsRef::as_ref)
1362 .split('\n')
1363 .skip(rows.start as usize)
1364 .chain(iter::repeat(""))
1365 .take(rows.len());
1366 placeholder_lines
1367 .map(|line| {
1368 cx.text_layout_cache().layout_str(
1369 line,
1370 placeholder_style.font_size,
1371 &[(
1372 line.len(),
1373 RunStyle {
1374 font_id: placeholder_style.font_id,
1375 color: placeholder_style.color,
1376 underline: Default::default(),
1377 },
1378 )],
1379 )
1380 })
1381 .map(|line| LineWithInvisibles {
1382 line,
1383 invisibles: Vec::new(),
1384 })
1385 .collect()
1386 } else {
1387 let style = &self.style;
1388 let chunks = snapshot
1389 .chunks(rows.clone(), true, Some(style.theme.suggestion))
1390 .map(|chunk| {
1391 let mut highlight_style = chunk
1392 .syntax_highlight_id
1393 .and_then(|id| id.style(&style.syntax));
1394
1395 if let Some(chunk_highlight) = chunk.highlight_style {
1396 if let Some(highlight_style) = highlight_style.as_mut() {
1397 highlight_style.highlight(chunk_highlight);
1398 } else {
1399 highlight_style = Some(chunk_highlight);
1400 }
1401 }
1402
1403 let mut diagnostic_highlight = HighlightStyle::default();
1404
1405 if chunk.is_unnecessary {
1406 diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
1407 }
1408
1409 if let Some(severity) = chunk.diagnostic_severity {
1410 // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
1411 if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
1412 let diagnostic_style = super::diagnostic_style(severity, true, style);
1413 diagnostic_highlight.underline = Some(Underline {
1414 color: Some(diagnostic_style.message.text.color),
1415 thickness: 1.0.into(),
1416 squiggly: true,
1417 });
1418 }
1419 }
1420
1421 if let Some(highlight_style) = highlight_style.as_mut() {
1422 highlight_style.highlight(diagnostic_highlight);
1423 } else {
1424 highlight_style = Some(diagnostic_highlight);
1425 }
1426
1427 HighlightedChunk {
1428 chunk: chunk.text,
1429 style: highlight_style,
1430 is_tab: chunk.is_tab,
1431 }
1432 });
1433
1434 LineWithInvisibles::from_chunks(
1435 chunks,
1436 &style.text,
1437 cx.text_layout_cache(),
1438 cx.font_cache(),
1439 MAX_LINE_LEN,
1440 rows.len() as usize,
1441 line_number_layouts,
1442 snapshot.mode,
1443 )
1444 }
1445 }
1446
1447 #[allow(clippy::too_many_arguments)]
1448 fn layout_blocks(
1449 &mut self,
1450 rows: Range<u32>,
1451 snapshot: &EditorSnapshot,
1452 editor_width: f32,
1453 scroll_width: f32,
1454 gutter_padding: f32,
1455 gutter_width: f32,
1456 em_width: f32,
1457 text_x: f32,
1458 line_height: f32,
1459 style: &EditorStyle,
1460 line_layouts: &[LineWithInvisibles],
1461 include_root: bool,
1462 editor: &mut Editor,
1463 cx: &mut LayoutContext<Editor>,
1464 ) -> (f32, Vec<BlockLayout>) {
1465 let tooltip_style = theme::current(cx).tooltip.clone();
1466 let scroll_x = snapshot.scroll_anchor.offset.x();
1467 let (fixed_blocks, non_fixed_blocks) = snapshot
1468 .blocks_in_range(rows.clone())
1469 .partition::<Vec<_>, _>(|(_, block)| match block {
1470 TransformBlock::ExcerptHeader { .. } => false,
1471 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1472 });
1473 let mut render_block = |block: &TransformBlock, width: f32| {
1474 let mut element = match block {
1475 TransformBlock::Custom(block) => {
1476 let align_to = block
1477 .position()
1478 .to_point(&snapshot.buffer_snapshot)
1479 .to_display_point(snapshot);
1480 let anchor_x = text_x
1481 + if rows.contains(&align_to.row()) {
1482 line_layouts[(align_to.row() - rows.start) as usize]
1483 .line
1484 .x_for_index(align_to.column() as usize)
1485 } else {
1486 layout_line(align_to.row(), snapshot, style, cx.text_layout_cache())
1487 .x_for_index(align_to.column() as usize)
1488 };
1489
1490 block.render(&mut BlockContext {
1491 view_context: cx,
1492 anchor_x,
1493 gutter_padding,
1494 line_height,
1495 scroll_x,
1496 gutter_width,
1497 em_width,
1498 })
1499 }
1500 TransformBlock::ExcerptHeader {
1501 id,
1502 buffer,
1503 range,
1504 starts_new_buffer,
1505 ..
1506 } => {
1507 let id = *id;
1508 let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1509 let jump_path = ProjectPath {
1510 worktree_id: file.worktree_id(cx),
1511 path: file.path.clone(),
1512 };
1513 let jump_anchor = range
1514 .primary
1515 .as_ref()
1516 .map_or(range.context.start, |primary| primary.start);
1517 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1518
1519 enum JumpIcon {}
1520 MouseEventHandler::<JumpIcon, _>::new(id.into(), cx, |state, _| {
1521 let style = style.jump_icon.style_for(state, false);
1522 Svg::new("icons/arrow_up_right_8.svg")
1523 .with_color(style.color)
1524 .constrained()
1525 .with_width(style.icon_width)
1526 .aligned()
1527 .contained()
1528 .with_style(style.container)
1529 .constrained()
1530 .with_width(style.button_width)
1531 .with_height(style.button_width)
1532 })
1533 .with_cursor_style(CursorStyle::PointingHand)
1534 .on_click(MouseButton::Left, move |_, editor, cx| {
1535 if let Some(workspace) = editor
1536 .workspace
1537 .as_ref()
1538 .and_then(|(workspace, _)| workspace.upgrade(cx))
1539 {
1540 workspace.update(cx, |workspace, cx| {
1541 Editor::jump(
1542 workspace,
1543 jump_path.clone(),
1544 jump_position,
1545 jump_anchor,
1546 cx,
1547 );
1548 });
1549 }
1550 })
1551 .with_tooltip::<JumpIcon>(
1552 id.into(),
1553 "Jump to Buffer".to_string(),
1554 Some(Box::new(crate::OpenExcerpts)),
1555 tooltip_style.clone(),
1556 cx,
1557 )
1558 .aligned()
1559 .flex_float()
1560 });
1561
1562 if *starts_new_buffer {
1563 let style = &self.style.diagnostic_path_header;
1564 let font_size =
1565 (style.text_scale_factor * self.style.text.font_size).round();
1566
1567 let path = buffer.resolve_file_path(cx, include_root);
1568 let mut filename = None;
1569 let mut parent_path = None;
1570 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1571 if let Some(path) = path {
1572 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1573 parent_path =
1574 path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1575 }
1576
1577 Flex::row()
1578 .with_child(
1579 Label::new(
1580 filename.unwrap_or_else(|| "untitled".to_string()),
1581 style.filename.text.clone().with_font_size(font_size),
1582 )
1583 .contained()
1584 .with_style(style.filename.container)
1585 .aligned(),
1586 )
1587 .with_children(parent_path.map(|path| {
1588 Label::new(path, style.path.text.clone().with_font_size(font_size))
1589 .contained()
1590 .with_style(style.path.container)
1591 .aligned()
1592 }))
1593 .with_children(jump_icon)
1594 .contained()
1595 .with_style(style.container)
1596 .with_padding_left(gutter_padding)
1597 .with_padding_right(gutter_padding)
1598 .expanded()
1599 .into_any_named("path header block")
1600 } else {
1601 let text_style = self.style.text.clone();
1602 Flex::row()
1603 .with_child(Label::new("⋯", text_style))
1604 .with_children(jump_icon)
1605 .contained()
1606 .with_padding_left(gutter_padding)
1607 .with_padding_right(gutter_padding)
1608 .expanded()
1609 .into_any_named("collapsed context")
1610 }
1611 }
1612 };
1613
1614 element.layout(
1615 SizeConstraint {
1616 min: Vector2F::zero(),
1617 max: vec2f(width, block.height() as f32 * line_height),
1618 },
1619 editor,
1620 cx,
1621 );
1622 element
1623 };
1624
1625 let mut fixed_block_max_width = 0f32;
1626 let mut blocks = Vec::new();
1627 for (row, block) in fixed_blocks {
1628 let element = render_block(block, f32::INFINITY);
1629 fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1630 blocks.push(BlockLayout {
1631 row,
1632 element,
1633 style: BlockStyle::Fixed,
1634 });
1635 }
1636 for (row, block) in non_fixed_blocks {
1637 let style = match block {
1638 TransformBlock::Custom(block) => block.style(),
1639 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1640 };
1641 let width = match style {
1642 BlockStyle::Sticky => editor_width,
1643 BlockStyle::Flex => editor_width
1644 .max(fixed_block_max_width)
1645 .max(gutter_width + scroll_width),
1646 BlockStyle::Fixed => unreachable!(),
1647 };
1648 let element = render_block(block, width);
1649 blocks.push(BlockLayout {
1650 row,
1651 element,
1652 style,
1653 });
1654 }
1655 (
1656 scroll_width.max(fixed_block_max_width - gutter_width),
1657 blocks,
1658 )
1659 }
1660}
1661
1662struct HighlightedChunk<'a> {
1663 chunk: &'a str,
1664 style: Option<HighlightStyle>,
1665 is_tab: bool,
1666}
1667
1668#[derive(Debug)]
1669pub struct LineWithInvisibles {
1670 pub line: Line,
1671 invisibles: Vec<Invisible>,
1672}
1673
1674impl LineWithInvisibles {
1675 fn from_chunks<'a>(
1676 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
1677 text_style: &TextStyle,
1678 text_layout_cache: &TextLayoutCache,
1679 font_cache: &Arc<FontCache>,
1680 max_line_len: usize,
1681 max_line_count: usize,
1682 line_number_layouts: &[Option<Line>],
1683 editor_mode: EditorMode,
1684 ) -> Vec<Self> {
1685 let mut layouts = Vec::with_capacity(max_line_count);
1686 let mut line = String::new();
1687 let mut invisibles = Vec::new();
1688 let mut styles = Vec::new();
1689 let mut non_whitespace_added = false;
1690 let mut row = 0;
1691 let mut line_exceeded_max_len = false;
1692 for highlighted_chunk in chunks.chain([HighlightedChunk {
1693 chunk: "\n",
1694 style: None,
1695 is_tab: false,
1696 }]) {
1697 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
1698 if ix > 0 {
1699 layouts.push(Self {
1700 line: text_layout_cache.layout_str(&line, text_style.font_size, &styles),
1701 invisibles: invisibles.drain(..).collect(),
1702 });
1703
1704 line.clear();
1705 styles.clear();
1706 row += 1;
1707 line_exceeded_max_len = false;
1708 non_whitespace_added = false;
1709 if row == max_line_count {
1710 return layouts;
1711 }
1712 }
1713
1714 if !line_chunk.is_empty() && !line_exceeded_max_len {
1715 let text_style = if let Some(style) = highlighted_chunk.style {
1716 text_style
1717 .clone()
1718 .highlight(style, font_cache)
1719 .map(Cow::Owned)
1720 .unwrap_or_else(|_| Cow::Borrowed(text_style))
1721 } else {
1722 Cow::Borrowed(text_style)
1723 };
1724
1725 if line.len() + line_chunk.len() > max_line_len {
1726 let mut chunk_len = max_line_len - line.len();
1727 while !line_chunk.is_char_boundary(chunk_len) {
1728 chunk_len -= 1;
1729 }
1730 line_chunk = &line_chunk[..chunk_len];
1731 line_exceeded_max_len = true;
1732 }
1733
1734 styles.push((
1735 line_chunk.len(),
1736 RunStyle {
1737 font_id: text_style.font_id,
1738 color: text_style.color,
1739 underline: text_style.underline,
1740 },
1741 ));
1742
1743 if editor_mode == EditorMode::Full {
1744 // Line wrap pads its contents with fake whitespaces,
1745 // avoid printing them
1746 let inside_wrapped_string = line_number_layouts
1747 .get(row)
1748 .and_then(|layout| layout.as_ref())
1749 .is_none();
1750 if highlighted_chunk.is_tab {
1751 if non_whitespace_added || !inside_wrapped_string {
1752 invisibles.push(Invisible::Tab {
1753 line_start_offset: line.len(),
1754 });
1755 }
1756 } else {
1757 invisibles.extend(
1758 line_chunk
1759 .chars()
1760 .enumerate()
1761 .filter(|(_, line_char)| {
1762 let is_whitespace = line_char.is_whitespace();
1763 non_whitespace_added |= !is_whitespace;
1764 is_whitespace
1765 && (non_whitespace_added || !inside_wrapped_string)
1766 })
1767 .map(|(whitespace_index, _)| Invisible::Whitespace {
1768 line_offset: line.len() + whitespace_index,
1769 }),
1770 )
1771 }
1772 }
1773
1774 line.push_str(line_chunk);
1775 }
1776 }
1777 }
1778
1779 layouts
1780 }
1781
1782 fn draw(
1783 &self,
1784 layout: &LayoutState,
1785 row: u32,
1786 scroll_top: f32,
1787 scene: &mut SceneBuilder,
1788 content_origin: Vector2F,
1789 scroll_left: f32,
1790 visible_text_bounds: RectF,
1791 whitespace_setting: ShowWhitespaceSetting,
1792 selection_ranges: &[Range<DisplayPoint>],
1793 visible_bounds: RectF,
1794 cx: &mut ViewContext<Editor>,
1795 ) {
1796 let line_height = layout.position_map.line_height;
1797 let line_y = row as f32 * line_height - scroll_top;
1798
1799 self.line.paint(
1800 scene,
1801 content_origin + vec2f(-scroll_left, line_y),
1802 visible_text_bounds,
1803 line_height,
1804 cx,
1805 );
1806
1807 self.draw_invisibles(
1808 &selection_ranges,
1809 layout,
1810 content_origin,
1811 scroll_left,
1812 line_y,
1813 row,
1814 scene,
1815 visible_bounds,
1816 line_height,
1817 whitespace_setting,
1818 cx,
1819 );
1820 }
1821
1822 fn draw_invisibles(
1823 &self,
1824 selection_ranges: &[Range<DisplayPoint>],
1825 layout: &LayoutState,
1826 content_origin: Vector2F,
1827 scroll_left: f32,
1828 line_y: f32,
1829 row: u32,
1830 scene: &mut SceneBuilder,
1831 visible_bounds: RectF,
1832 line_height: f32,
1833 whitespace_setting: ShowWhitespaceSetting,
1834 cx: &mut ViewContext<Editor>,
1835 ) {
1836 let allowed_invisibles_regions = match whitespace_setting {
1837 ShowWhitespaceSetting::None => return,
1838 ShowWhitespaceSetting::Selection => Some(selection_ranges),
1839 ShowWhitespaceSetting::All => None,
1840 };
1841
1842 for invisible in &self.invisibles {
1843 let (&token_offset, invisible_symbol) = match invisible {
1844 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
1845 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
1846 };
1847
1848 let x_offset = self.line.x_for_index(token_offset);
1849 let invisible_offset =
1850 (layout.position_map.em_width - invisible_symbol.width()).max(0.0) / 2.0;
1851 let origin = content_origin + vec2f(-scroll_left + x_offset + invisible_offset, line_y);
1852
1853 if let Some(allowed_regions) = allowed_invisibles_regions {
1854 let invisible_point = DisplayPoint::new(row, token_offset as u32);
1855 if !allowed_regions
1856 .iter()
1857 .any(|region| region.start <= invisible_point && invisible_point < region.end)
1858 {
1859 continue;
1860 }
1861 }
1862 invisible_symbol.paint(scene, origin, visible_bounds, line_height, cx);
1863 }
1864 }
1865}
1866
1867#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1868enum Invisible {
1869 Tab { line_start_offset: usize },
1870 Whitespace { line_offset: usize },
1871}
1872
1873impl Element<Editor> for EditorElement {
1874 type LayoutState = LayoutState;
1875 type PaintState = ();
1876
1877 fn layout(
1878 &mut self,
1879 constraint: SizeConstraint,
1880 editor: &mut Editor,
1881 cx: &mut LayoutContext<Editor>,
1882 ) -> (Vector2F, Self::LayoutState) {
1883 let mut size = constraint.max;
1884 if size.x().is_infinite() {
1885 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1886 }
1887
1888 let snapshot = editor.snapshot(cx);
1889 let style = self.style.clone();
1890 let line_height = style.text.line_height(cx.font_cache());
1891
1892 let gutter_padding;
1893 let gutter_width;
1894 let gutter_margin;
1895 if snapshot.mode == EditorMode::Full {
1896 let em_width = style.text.em_width(cx.font_cache());
1897 gutter_padding = (em_width * style.gutter_padding_factor).round();
1898 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1899 gutter_margin = -style.text.descent(cx.font_cache());
1900 } else {
1901 gutter_padding = 0.0;
1902 gutter_width = 0.0;
1903 gutter_margin = 0.0;
1904 };
1905
1906 let text_width = size.x() - gutter_width;
1907 let em_width = style.text.em_width(cx.font_cache());
1908 let em_advance = style.text.em_advance(cx.font_cache());
1909 let overscroll = vec2f(em_width, 0.);
1910 let snapshot = {
1911 editor.set_visible_line_count(size.y() / line_height);
1912
1913 let editor_width = text_width - gutter_margin - overscroll.x() - em_width;
1914 let wrap_width = match editor.soft_wrap_mode(cx) {
1915 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
1916 SoftWrap::EditorWidth => editor_width,
1917 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
1918 };
1919
1920 if editor.set_wrap_width(Some(wrap_width), cx) {
1921 editor.snapshot(cx)
1922 } else {
1923 snapshot
1924 }
1925 };
1926
1927 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1928 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1929 size.set_y(
1930 scroll_height
1931 .min(constraint.max_along(Axis::Vertical))
1932 .max(constraint.min_along(Axis::Vertical))
1933 .min(line_height * max_lines as f32),
1934 )
1935 } else if let EditorMode::SingleLine = snapshot.mode {
1936 size.set_y(
1937 line_height
1938 .min(constraint.max_along(Axis::Vertical))
1939 .max(constraint.min_along(Axis::Vertical)),
1940 )
1941 } else if size.y().is_infinite() {
1942 size.set_y(scroll_height);
1943 }
1944 let gutter_size = vec2f(gutter_width, size.y());
1945 let text_size = vec2f(text_width, size.y());
1946
1947 let autoscroll_horizontally = editor.autoscroll_vertically(size.y(), line_height, cx);
1948 let mut snapshot = editor.snapshot(cx);
1949
1950 let scroll_position = snapshot.scroll_position();
1951 // The scroll position is a fractional point, the whole number of which represents
1952 // the top of the window in terms of display rows.
1953 let start_row = scroll_position.y() as u32;
1954 let height_in_lines = size.y() / line_height;
1955 let max_row = snapshot.max_point().row();
1956
1957 // Add 1 to ensure selections bleed off screen
1958 let end_row = 1 + cmp::min(
1959 (scroll_position.y() + height_in_lines).ceil() as u32,
1960 max_row,
1961 );
1962
1963 let start_anchor = if start_row == 0 {
1964 Anchor::min()
1965 } else {
1966 snapshot
1967 .buffer_snapshot
1968 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1969 };
1970 let end_anchor = if end_row > max_row {
1971 Anchor::max()
1972 } else {
1973 snapshot
1974 .buffer_snapshot
1975 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1976 };
1977
1978 let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1979 let mut active_rows = BTreeMap::new();
1980 let mut fold_ranges = Vec::new();
1981 let is_singleton = editor.is_singleton(cx);
1982
1983 let highlighted_rows = editor.highlighted_rows();
1984 let theme = theme::current(cx);
1985 let highlighted_ranges = editor.background_highlights_in_range(
1986 start_anchor..end_anchor,
1987 &snapshot.display_snapshot,
1988 theme.as_ref(),
1989 );
1990
1991 fold_ranges.extend(
1992 snapshot
1993 .folds_in_range(start_anchor..end_anchor)
1994 .map(|anchor| {
1995 let start = anchor.start.to_point(&snapshot.buffer_snapshot);
1996 (
1997 start.row,
1998 start.to_display_point(&snapshot.display_snapshot)
1999 ..anchor.end.to_display_point(&snapshot),
2000 )
2001 }),
2002 );
2003
2004 let mut remote_selections = HashMap::default();
2005 for (replica_id, line_mode, cursor_shape, selection) in snapshot
2006 .buffer_snapshot
2007 .remote_selections_in_range(&(start_anchor..end_anchor))
2008 {
2009 // The local selections match the leader's selections.
2010 if Some(replica_id) == editor.leader_replica_id {
2011 continue;
2012 }
2013 remote_selections
2014 .entry(replica_id)
2015 .or_insert(Vec::new())
2016 .push(SelectionLayout::new(
2017 selection,
2018 line_mode,
2019 cursor_shape,
2020 &snapshot.display_snapshot,
2021 ));
2022 }
2023 selections.extend(remote_selections);
2024
2025 if editor.show_local_selections {
2026 let mut local_selections = editor
2027 .selections
2028 .disjoint_in_range(start_anchor..end_anchor, cx);
2029 local_selections.extend(editor.selections.pending(cx));
2030 for selection in &local_selections {
2031 let is_empty = selection.start == selection.end;
2032 let selection_start = snapshot.prev_line_boundary(selection.start).1;
2033 let selection_end = snapshot.next_line_boundary(selection.end).1;
2034 for row in cmp::max(selection_start.row(), start_row)
2035 ..=cmp::min(selection_end.row(), end_row)
2036 {
2037 let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2038 *contains_non_empty_selection |= !is_empty;
2039 }
2040 }
2041
2042 // Render the local selections in the leader's color when following.
2043 let local_replica_id = editor
2044 .leader_replica_id
2045 .unwrap_or_else(|| editor.replica_id(cx));
2046
2047 selections.push((
2048 local_replica_id,
2049 local_selections
2050 .into_iter()
2051 .map(|selection| {
2052 SelectionLayout::new(
2053 selection,
2054 editor.selections.line_mode,
2055 editor.cursor_shape,
2056 &snapshot.display_snapshot,
2057 )
2058 })
2059 .collect(),
2060 ));
2061 }
2062
2063 let show_scrollbars =
2064 match settings::get_setting::<EditorSettings>(None, cx).show_scrollbars {
2065 ShowScrollbars::Auto => {
2066 snapshot.has_scrollbar_info() || editor.scroll_manager.scrollbars_visible()
2067 }
2068 ShowScrollbars::System => editor.scroll_manager.scrollbars_visible(),
2069 ShowScrollbars::Always => true,
2070 ShowScrollbars::Never => false,
2071 };
2072
2073 let include_root = editor
2074 .project
2075 .as_ref()
2076 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2077 .unwrap_or_default();
2078
2079 let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2080 .into_iter()
2081 .map(|(id, fold)| {
2082 let color = self
2083 .style
2084 .folds
2085 .ellipses
2086 .background
2087 .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize), false)
2088 .color;
2089
2090 (id, fold, color)
2091 })
2092 .collect();
2093
2094 let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2095 start_row..end_row,
2096 &active_rows,
2097 is_singleton,
2098 &snapshot,
2099 cx,
2100 );
2101
2102 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2103
2104 let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
2105
2106 let mut max_visible_line_width = 0.0;
2107 let line_layouts =
2108 self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2109 for line_with_invisibles in &line_layouts {
2110 if line_with_invisibles.line.width() > max_visible_line_width {
2111 max_visible_line_width = line_with_invisibles.line.width();
2112 }
2113 }
2114
2115 let style = self.style.clone();
2116 let longest_line_width = layout_line(
2117 snapshot.longest_row(),
2118 &snapshot,
2119 &style,
2120 cx.text_layout_cache(),
2121 )
2122 .width();
2123 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
2124 let em_width = style.text.em_width(cx.font_cache());
2125 let (scroll_width, blocks) = self.layout_blocks(
2126 start_row..end_row,
2127 &snapshot,
2128 size.x(),
2129 scroll_width,
2130 gutter_padding,
2131 gutter_width,
2132 em_width,
2133 gutter_width + gutter_margin,
2134 line_height,
2135 &style,
2136 &line_layouts,
2137 include_root,
2138 editor,
2139 cx,
2140 );
2141
2142 let scroll_max = vec2f(
2143 ((scroll_width - text_size.x()) / em_width).max(0.0),
2144 max_row as f32,
2145 );
2146
2147 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x());
2148
2149 let autoscrolled = if autoscroll_horizontally {
2150 editor.autoscroll_horizontally(
2151 start_row,
2152 text_size.x(),
2153 scroll_width,
2154 em_width,
2155 &line_layouts,
2156 cx,
2157 )
2158 } else {
2159 false
2160 };
2161
2162 if clamped || autoscrolled {
2163 snapshot = editor.snapshot(cx);
2164 }
2165
2166 let newest_selection_head = editor
2167 .selections
2168 .newest::<usize>(cx)
2169 .head()
2170 .to_display_point(&snapshot);
2171 let style = editor.style(cx);
2172
2173 let mut context_menu = None;
2174 let mut code_actions_indicator = None;
2175 if (start_row..end_row).contains(&newest_selection_head.row()) {
2176 if editor.context_menu_visible() {
2177 context_menu = editor.render_context_menu(newest_selection_head, style.clone(), cx);
2178 }
2179
2180 let active = matches!(
2181 editor.context_menu,
2182 Some(crate::ContextMenu::CodeActions(_))
2183 );
2184
2185 code_actions_indicator = editor
2186 .render_code_actions_indicator(&style, active, cx)
2187 .map(|indicator| (newest_selection_head.row(), indicator));
2188 }
2189
2190 let visible_rows = start_row..start_row + line_layouts.len() as u32;
2191 let mut hover = editor
2192 .hover_state
2193 .render(&snapshot, &style, visible_rows, cx);
2194 let mode = editor.mode;
2195
2196 let mut fold_indicators = editor.render_fold_indicators(
2197 fold_statuses,
2198 &style,
2199 editor.gutter_hovered,
2200 line_height,
2201 gutter_margin,
2202 cx,
2203 );
2204
2205 if let Some((_, context_menu)) = context_menu.as_mut() {
2206 context_menu.layout(
2207 SizeConstraint {
2208 min: Vector2F::zero(),
2209 max: vec2f(
2210 cx.window_size().x() * 0.7,
2211 (12. * line_height).min((size.y() - line_height) / 2.),
2212 ),
2213 },
2214 editor,
2215 cx,
2216 );
2217 }
2218
2219 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
2220 indicator.layout(
2221 SizeConstraint::strict_along(
2222 Axis::Vertical,
2223 line_height * style.code_actions.vertical_scale,
2224 ),
2225 editor,
2226 cx,
2227 );
2228 }
2229
2230 for fold_indicator in fold_indicators.iter_mut() {
2231 if let Some(indicator) = fold_indicator.as_mut() {
2232 indicator.layout(
2233 SizeConstraint::strict_along(
2234 Axis::Vertical,
2235 line_height * style.code_actions.vertical_scale,
2236 ),
2237 editor,
2238 cx,
2239 );
2240 }
2241 }
2242
2243 if let Some((_, hover_popovers)) = hover.as_mut() {
2244 for hover_popover in hover_popovers.iter_mut() {
2245 hover_popover.layout(
2246 SizeConstraint {
2247 min: Vector2F::zero(),
2248 max: vec2f(
2249 (120. * em_width) // Default size
2250 .min(size.x() / 2.) // Shrink to half of the editor width
2251 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2252 (16. * line_height) // Default size
2253 .min(size.y() / 2.) // Shrink to half of the editor height
2254 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2255 ),
2256 },
2257 editor,
2258 cx,
2259 );
2260 }
2261 }
2262
2263 let invisible_symbol_font_size = self.style.text.font_size / 2.0;
2264 let invisible_symbol_style = RunStyle {
2265 color: self.style.whitespace,
2266 font_id: self.style.text.font_id,
2267 underline: Default::default(),
2268 };
2269
2270 (
2271 size,
2272 LayoutState {
2273 mode,
2274 position_map: Arc::new(PositionMap {
2275 size,
2276 scroll_max,
2277 line_layouts,
2278 line_height,
2279 em_width,
2280 em_advance,
2281 snapshot,
2282 }),
2283 visible_display_row_range: start_row..end_row,
2284 gutter_size,
2285 gutter_padding,
2286 text_size,
2287 scrollbar_row_range,
2288 show_scrollbars,
2289 max_row,
2290 gutter_margin,
2291 active_rows,
2292 highlighted_rows,
2293 highlighted_ranges,
2294 fold_ranges,
2295 line_number_layouts,
2296 display_hunks,
2297 blocks,
2298 selections,
2299 context_menu,
2300 code_actions_indicator,
2301 fold_indicators,
2302 tab_invisible: cx.text_layout_cache().layout_str(
2303 "→",
2304 invisible_symbol_font_size,
2305 &[("→".len(), invisible_symbol_style)],
2306 ),
2307 space_invisible: cx.text_layout_cache().layout_str(
2308 "•",
2309 invisible_symbol_font_size,
2310 &[("•".len(), invisible_symbol_style)],
2311 ),
2312 hover_popovers: hover,
2313 },
2314 )
2315 }
2316
2317 fn paint(
2318 &mut self,
2319 scene: &mut SceneBuilder,
2320 bounds: RectF,
2321 visible_bounds: RectF,
2322 layout: &mut Self::LayoutState,
2323 editor: &mut Editor,
2324 cx: &mut ViewContext<Editor>,
2325 ) -> Self::PaintState {
2326 let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2327 scene.push_layer(Some(visible_bounds));
2328
2329 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
2330 let text_bounds = RectF::new(
2331 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2332 layout.text_size,
2333 );
2334
2335 Self::attach_mouse_handlers(
2336 scene,
2337 &layout.position_map,
2338 layout.hover_popovers.is_some(),
2339 visible_bounds,
2340 text_bounds,
2341 gutter_bounds,
2342 bounds,
2343 cx,
2344 );
2345
2346 self.paint_background(scene, gutter_bounds, text_bounds, layout);
2347 if layout.gutter_size.x() > 0. {
2348 self.paint_gutter(scene, gutter_bounds, visible_bounds, layout, editor, cx);
2349 }
2350 self.paint_text(scene, text_bounds, visible_bounds, layout, editor, cx);
2351
2352 scene.push_layer(Some(bounds));
2353 if !layout.blocks.is_empty() {
2354 self.paint_blocks(scene, bounds, visible_bounds, layout, editor, cx);
2355 }
2356 self.paint_scrollbar(scene, bounds, layout, cx);
2357 scene.pop_layer();
2358
2359 scene.pop_layer();
2360 }
2361
2362 fn rect_for_text_range(
2363 &self,
2364 range_utf16: Range<usize>,
2365 bounds: RectF,
2366 _: RectF,
2367 layout: &Self::LayoutState,
2368 _: &Self::PaintState,
2369 _: &Editor,
2370 _: &ViewContext<Editor>,
2371 ) -> Option<RectF> {
2372 let text_bounds = RectF::new(
2373 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2374 layout.text_size,
2375 );
2376 let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
2377 let scroll_position = layout.position_map.snapshot.scroll_position();
2378 let start_row = scroll_position.y() as u32;
2379 let scroll_top = scroll_position.y() * layout.position_map.line_height;
2380 let scroll_left = scroll_position.x() * layout.position_map.em_width;
2381
2382 let range_start = OffsetUtf16(range_utf16.start)
2383 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2384 if range_start.row() < start_row {
2385 return None;
2386 }
2387
2388 let line = &layout
2389 .position_map
2390 .line_layouts
2391 .get((range_start.row() - start_row) as usize)?
2392 .line;
2393 let range_start_x = line.x_for_index(range_start.column() as usize);
2394 let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
2395 Some(RectF::new(
2396 content_origin
2397 + vec2f(
2398 range_start_x,
2399 range_start_y + layout.position_map.line_height,
2400 )
2401 - vec2f(scroll_left, scroll_top),
2402 vec2f(
2403 layout.position_map.em_width,
2404 layout.position_map.line_height,
2405 ),
2406 ))
2407 }
2408
2409 fn debug(
2410 &self,
2411 bounds: RectF,
2412 _: &Self::LayoutState,
2413 _: &Self::PaintState,
2414 _: &Editor,
2415 _: &ViewContext<Editor>,
2416 ) -> json::Value {
2417 json!({
2418 "type": "BufferElement",
2419 "bounds": bounds.to_json()
2420 })
2421 }
2422}
2423
2424type BufferRow = u32;
2425
2426pub struct LayoutState {
2427 position_map: Arc<PositionMap>,
2428 gutter_size: Vector2F,
2429 gutter_padding: f32,
2430 gutter_margin: f32,
2431 text_size: Vector2F,
2432 mode: EditorMode,
2433 visible_display_row_range: Range<u32>,
2434 active_rows: BTreeMap<u32, bool>,
2435 highlighted_rows: Option<Range<u32>>,
2436 line_number_layouts: Vec<Option<text_layout::Line>>,
2437 display_hunks: Vec<DisplayDiffHunk>,
2438 blocks: Vec<BlockLayout>,
2439 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2440 fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)>,
2441 selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
2442 scrollbar_row_range: Range<f32>,
2443 show_scrollbars: bool,
2444 max_row: u32,
2445 context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
2446 code_actions_indicator: Option<(u32, AnyElement<Editor>)>,
2447 hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
2448 fold_indicators: Vec<Option<AnyElement<Editor>>>,
2449 tab_invisible: Line,
2450 space_invisible: Line,
2451}
2452
2453struct PositionMap {
2454 size: Vector2F,
2455 line_height: f32,
2456 scroll_max: Vector2F,
2457 em_width: f32,
2458 em_advance: f32,
2459 line_layouts: Vec<LineWithInvisibles>,
2460 snapshot: EditorSnapshot,
2461}
2462
2463impl PositionMap {
2464 /// Returns two display points:
2465 /// 1. The nearest *valid* position in the editor
2466 /// 2. An unclipped, potentially *invalid* position that maps directly to
2467 /// the given pixel position.
2468 fn point_for_position(
2469 &self,
2470 text_bounds: RectF,
2471 position: Vector2F,
2472 ) -> (DisplayPoint, DisplayPoint) {
2473 let scroll_position = self.snapshot.scroll_position();
2474 let position = position - text_bounds.origin();
2475 let y = position.y().max(0.0).min(self.size.y());
2476 let x = position.x() + (scroll_position.x() * self.em_width);
2477 let row = (y / self.line_height + scroll_position.y()) as u32;
2478 let (column, x_overshoot) = if let Some(line) = self
2479 .line_layouts
2480 .get(row as usize - scroll_position.y() as usize)
2481 .map(|line_with_spaces| &line_with_spaces.line)
2482 {
2483 if let Some(ix) = line.index_for_x(x) {
2484 (ix as u32, 0.0)
2485 } else {
2486 (line.len() as u32, 0f32.max(x - line.width()))
2487 }
2488 } else {
2489 (0, x)
2490 };
2491
2492 let mut target_point = DisplayPoint::new(row, column);
2493 let point = self.snapshot.clip_point(target_point, Bias::Left);
2494 *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
2495
2496 (point, target_point)
2497 }
2498}
2499
2500struct BlockLayout {
2501 row: u32,
2502 element: AnyElement<Editor>,
2503 style: BlockStyle,
2504}
2505
2506fn layout_line(
2507 row: u32,
2508 snapshot: &EditorSnapshot,
2509 style: &EditorStyle,
2510 layout_cache: &TextLayoutCache,
2511) -> text_layout::Line {
2512 let mut line = snapshot.line(row);
2513
2514 if line.len() > MAX_LINE_LEN {
2515 let mut len = MAX_LINE_LEN;
2516 while !line.is_char_boundary(len) {
2517 len -= 1;
2518 }
2519
2520 line.truncate(len);
2521 }
2522
2523 layout_cache.layout_str(
2524 &line,
2525 style.text.font_size,
2526 &[(
2527 snapshot.line_len(row) as usize,
2528 RunStyle {
2529 font_id: style.text.font_id,
2530 color: Color::black(),
2531 underline: Default::default(),
2532 },
2533 )],
2534 )
2535}
2536
2537#[derive(Debug)]
2538pub struct Cursor {
2539 origin: Vector2F,
2540 block_width: f32,
2541 line_height: f32,
2542 color: Color,
2543 shape: CursorShape,
2544 block_text: Option<Line>,
2545}
2546
2547impl Cursor {
2548 pub fn new(
2549 origin: Vector2F,
2550 block_width: f32,
2551 line_height: f32,
2552 color: Color,
2553 shape: CursorShape,
2554 block_text: Option<Line>,
2555 ) -> Cursor {
2556 Cursor {
2557 origin,
2558 block_width,
2559 line_height,
2560 color,
2561 shape,
2562 block_text,
2563 }
2564 }
2565
2566 pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2567 RectF::new(
2568 self.origin + origin,
2569 vec2f(self.block_width, self.line_height),
2570 )
2571 }
2572
2573 pub fn paint(&self, scene: &mut SceneBuilder, origin: Vector2F, cx: &mut WindowContext) {
2574 let bounds = match self.shape {
2575 CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2576 CursorShape::Block | CursorShape::Hollow => RectF::new(
2577 self.origin + origin,
2578 vec2f(self.block_width, self.line_height),
2579 ),
2580 CursorShape::Underscore => RectF::new(
2581 self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2582 vec2f(self.block_width, 2.0),
2583 ),
2584 };
2585
2586 //Draw background or border quad
2587 if matches!(self.shape, CursorShape::Hollow) {
2588 scene.push_quad(Quad {
2589 bounds,
2590 background: None,
2591 border: Border::all(1., self.color),
2592 corner_radius: 0.,
2593 });
2594 } else {
2595 scene.push_quad(Quad {
2596 bounds,
2597 background: Some(self.color),
2598 border: Default::default(),
2599 corner_radius: 0.,
2600 });
2601 }
2602
2603 if let Some(block_text) = &self.block_text {
2604 block_text.paint(scene, self.origin + origin, bounds, self.line_height, cx);
2605 }
2606 }
2607
2608 pub fn shape(&self) -> CursorShape {
2609 self.shape
2610 }
2611}
2612
2613#[derive(Debug)]
2614pub struct HighlightedRange {
2615 pub start_y: f32,
2616 pub line_height: f32,
2617 pub lines: Vec<HighlightedRangeLine>,
2618 pub color: Color,
2619 pub corner_radius: f32,
2620}
2621
2622#[derive(Debug)]
2623pub struct HighlightedRangeLine {
2624 pub start_x: f32,
2625 pub end_x: f32,
2626}
2627
2628impl HighlightedRange {
2629 pub fn paint(&self, bounds: RectF, scene: &mut SceneBuilder) {
2630 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2631 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2632 self.paint_lines(
2633 self.start_y + self.line_height,
2634 &self.lines[1..],
2635 bounds,
2636 scene,
2637 );
2638 } else {
2639 self.paint_lines(self.start_y, &self.lines, bounds, scene);
2640 }
2641 }
2642
2643 fn paint_lines(
2644 &self,
2645 start_y: f32,
2646 lines: &[HighlightedRangeLine],
2647 bounds: RectF,
2648 scene: &mut SceneBuilder,
2649 ) {
2650 if lines.is_empty() {
2651 return;
2652 }
2653
2654 let mut path = PathBuilder::new();
2655 let first_line = lines.first().unwrap();
2656 let last_line = lines.last().unwrap();
2657
2658 let first_top_left = vec2f(first_line.start_x, start_y);
2659 let first_top_right = vec2f(first_line.end_x, start_y);
2660
2661 let curve_height = vec2f(0., self.corner_radius);
2662 let curve_width = |start_x: f32, end_x: f32| {
2663 let max = (end_x - start_x) / 2.;
2664 let width = if max < self.corner_radius {
2665 max
2666 } else {
2667 self.corner_radius
2668 };
2669
2670 vec2f(width, 0.)
2671 };
2672
2673 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2674 path.reset(first_top_right - top_curve_width);
2675 path.curve_to(first_top_right + curve_height, first_top_right);
2676
2677 let mut iter = lines.iter().enumerate().peekable();
2678 while let Some((ix, line)) = iter.next() {
2679 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2680
2681 if let Some((_, next_line)) = iter.peek() {
2682 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2683
2684 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2685 Ordering::Equal => {
2686 path.line_to(bottom_right);
2687 }
2688 Ordering::Less => {
2689 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2690 path.line_to(bottom_right - curve_height);
2691 if self.corner_radius > 0. {
2692 path.curve_to(bottom_right - curve_width, bottom_right);
2693 }
2694 path.line_to(next_top_right + curve_width);
2695 if self.corner_radius > 0. {
2696 path.curve_to(next_top_right + curve_height, next_top_right);
2697 }
2698 }
2699 Ordering::Greater => {
2700 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2701 path.line_to(bottom_right - curve_height);
2702 if self.corner_radius > 0. {
2703 path.curve_to(bottom_right + curve_width, bottom_right);
2704 }
2705 path.line_to(next_top_right - curve_width);
2706 if self.corner_radius > 0. {
2707 path.curve_to(next_top_right + curve_height, next_top_right);
2708 }
2709 }
2710 }
2711 } else {
2712 let curve_width = curve_width(line.start_x, line.end_x);
2713 path.line_to(bottom_right - curve_height);
2714 if self.corner_radius > 0. {
2715 path.curve_to(bottom_right - curve_width, bottom_right);
2716 }
2717
2718 let bottom_left = vec2f(line.start_x, bottom_right.y());
2719 path.line_to(bottom_left + curve_width);
2720 if self.corner_radius > 0. {
2721 path.curve_to(bottom_left - curve_height, bottom_left);
2722 }
2723 }
2724 }
2725
2726 if first_line.start_x > last_line.start_x {
2727 let curve_width = curve_width(last_line.start_x, first_line.start_x);
2728 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2729 path.line_to(second_top_left + curve_height);
2730 if self.corner_radius > 0. {
2731 path.curve_to(second_top_left + curve_width, second_top_left);
2732 }
2733 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2734 path.line_to(first_bottom_left - curve_width);
2735 if self.corner_radius > 0. {
2736 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2737 }
2738 }
2739
2740 path.line_to(first_top_left + curve_height);
2741 if self.corner_radius > 0. {
2742 path.curve_to(first_top_left + top_curve_width, first_top_left);
2743 }
2744 path.line_to(first_top_right - top_curve_width);
2745
2746 scene.push_path(path.build(self.color, Some(bounds)));
2747 }
2748}
2749
2750fn position_to_display_point(
2751 position: Vector2F,
2752 text_bounds: RectF,
2753 position_map: &PositionMap,
2754) -> Option<DisplayPoint> {
2755 if text_bounds.contains_point(position) {
2756 let (point, target_point) = position_map.point_for_position(text_bounds, position);
2757 if point == target_point {
2758 Some(point)
2759 } else {
2760 None
2761 }
2762 } else {
2763 None
2764 }
2765}
2766
2767fn range_to_bounds(
2768 range: &Range<DisplayPoint>,
2769 content_origin: Vector2F,
2770 scroll_left: f32,
2771 scroll_top: f32,
2772 visible_row_range: &Range<u32>,
2773 line_end_overshoot: f32,
2774 position_map: &PositionMap,
2775) -> impl Iterator<Item = RectF> {
2776 let mut bounds: SmallVec<[RectF; 1]> = SmallVec::new();
2777
2778 if range.start == range.end {
2779 return bounds.into_iter();
2780 }
2781
2782 let start_row = visible_row_range.start;
2783 let end_row = visible_row_range.end;
2784
2785 let row_range = if range.end.column() == 0 {
2786 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2787 } else {
2788 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2789 };
2790
2791 let first_y =
2792 content_origin.y() + row_range.start as f32 * position_map.line_height - scroll_top;
2793
2794 for (idx, row) in row_range.enumerate() {
2795 let line_layout = &position_map.line_layouts[(row - start_row) as usize].line;
2796
2797 let start_x = if row == range.start.row() {
2798 content_origin.x() + line_layout.x_for_index(range.start.column() as usize)
2799 - scroll_left
2800 } else {
2801 content_origin.x() - scroll_left
2802 };
2803
2804 let end_x = if row == range.end.row() {
2805 content_origin.x() + line_layout.x_for_index(range.end.column() as usize) - scroll_left
2806 } else {
2807 content_origin.x() + line_layout.width() + line_end_overshoot - scroll_left
2808 };
2809
2810 bounds.push(RectF::from_points(
2811 vec2f(start_x, first_y + position_map.line_height * idx as f32),
2812 vec2f(end_x, first_y + position_map.line_height * (idx + 1) as f32),
2813 ))
2814 }
2815
2816 bounds.into_iter()
2817}
2818
2819pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2820 delta.powf(1.5) / 100.0
2821}
2822
2823fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
2824 delta.powf(1.2) / 300.0
2825}
2826
2827#[cfg(test)]
2828mod tests {
2829 use super::*;
2830 use crate::{
2831 display_map::{BlockDisposition, BlockProperties},
2832 editor_tests::{init_test, update_test_settings},
2833 Editor, MultiBuffer,
2834 };
2835 use gpui::TestAppContext;
2836 use language::language_settings;
2837 use log::info;
2838 use std::{num::NonZeroU32, sync::Arc};
2839 use util::test::sample_text;
2840
2841 #[gpui::test]
2842 fn test_layout_line_numbers(cx: &mut TestAppContext) {
2843 init_test(cx, |_| {});
2844
2845 let (_, editor) = cx.add_window(|cx| {
2846 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
2847 Editor::new(EditorMode::Full, buffer, None, None, cx)
2848 });
2849 let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
2850
2851 let layouts = editor.update(cx, |editor, cx| {
2852 let snapshot = editor.snapshot(cx);
2853 element
2854 .layout_line_numbers(0..6, &Default::default(), false, &snapshot, cx)
2855 .0
2856 });
2857 assert_eq!(layouts.len(), 6);
2858 }
2859
2860 #[gpui::test]
2861 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
2862 init_test(cx, |_| {});
2863
2864 let (_, editor) = cx.add_window(|cx| {
2865 let buffer = MultiBuffer::build_simple("", cx);
2866 Editor::new(EditorMode::Full, buffer, None, None, cx)
2867 });
2868
2869 editor.update(cx, |editor, cx| {
2870 editor.set_placeholder_text("hello", cx);
2871 editor.insert_blocks(
2872 [BlockProperties {
2873 style: BlockStyle::Fixed,
2874 disposition: BlockDisposition::Above,
2875 height: 3,
2876 position: Anchor::min(),
2877 render: Arc::new(|_| Empty::new().into_any()),
2878 }],
2879 cx,
2880 );
2881
2882 // Blur the editor so that it displays placeholder text.
2883 cx.blur();
2884 });
2885
2886 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
2887 let (size, mut state) = editor.update(cx, |editor, cx| {
2888 let mut new_parents = Default::default();
2889 let mut notify_views_if_parents_change = Default::default();
2890 let mut layout_cx = LayoutContext::new(
2891 cx,
2892 &mut new_parents,
2893 &mut notify_views_if_parents_change,
2894 false,
2895 );
2896 element.layout(
2897 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
2898 editor,
2899 &mut layout_cx,
2900 )
2901 });
2902
2903 assert_eq!(state.position_map.line_layouts.len(), 4);
2904 assert_eq!(
2905 state
2906 .line_number_layouts
2907 .iter()
2908 .map(Option::is_some)
2909 .collect::<Vec<_>>(),
2910 &[false, false, false, true]
2911 );
2912
2913 // Don't panic.
2914 let mut scene = SceneBuilder::new(1.0);
2915 let bounds = RectF::new(Default::default(), size);
2916 editor.update(cx, |editor, cx| {
2917 element.paint(&mut scene, bounds, bounds, &mut state, editor, cx);
2918 });
2919 }
2920
2921 #[gpui::test]
2922 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
2923 const TAB_SIZE: u32 = 4;
2924
2925 let input_text = "\t \t|\t| a b";
2926 let expected_invisibles = vec![
2927 Invisible::Tab {
2928 line_start_offset: 0,
2929 },
2930 Invisible::Whitespace {
2931 line_offset: TAB_SIZE as usize,
2932 },
2933 Invisible::Tab {
2934 line_start_offset: TAB_SIZE as usize + 1,
2935 },
2936 Invisible::Tab {
2937 line_start_offset: TAB_SIZE as usize * 2 + 1,
2938 },
2939 Invisible::Whitespace {
2940 line_offset: TAB_SIZE as usize * 3 + 1,
2941 },
2942 Invisible::Whitespace {
2943 line_offset: TAB_SIZE as usize * 3 + 3,
2944 },
2945 ];
2946 assert_eq!(
2947 expected_invisibles.len(),
2948 input_text
2949 .chars()
2950 .filter(|initial_char| initial_char.is_whitespace())
2951 .count(),
2952 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
2953 );
2954
2955 init_test(cx, |s| {
2956 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
2957 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
2958 });
2959
2960 let actual_invisibles =
2961 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
2962
2963 assert_eq!(expected_invisibles, actual_invisibles);
2964 }
2965
2966 #[gpui::test]
2967 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
2968 init_test(cx, |s| {
2969 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
2970 s.defaults.tab_size = NonZeroU32::new(4);
2971 });
2972
2973 for editor_mode_without_invisibles in [
2974 EditorMode::SingleLine,
2975 EditorMode::AutoHeight { max_lines: 100 },
2976 ] {
2977 let invisibles = collect_invisibles_from_new_editor(
2978 cx,
2979 editor_mode_without_invisibles,
2980 "\t\t\t| | a b",
2981 500.0,
2982 );
2983 assert!(invisibles.is_empty(),
2984 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
2985 }
2986 }
2987
2988 #[gpui::test]
2989 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
2990 let tab_size = 4;
2991 let input_text = "a\tbcd ".repeat(9);
2992 let repeated_invisibles = [
2993 Invisible::Tab {
2994 line_start_offset: 1,
2995 },
2996 Invisible::Whitespace {
2997 line_offset: tab_size as usize + 3,
2998 },
2999 Invisible::Whitespace {
3000 line_offset: tab_size as usize + 4,
3001 },
3002 Invisible::Whitespace {
3003 line_offset: tab_size as usize + 5,
3004 },
3005 ];
3006 let expected_invisibles = std::iter::once(repeated_invisibles)
3007 .cycle()
3008 .take(9)
3009 .flatten()
3010 .collect::<Vec<_>>();
3011 assert_eq!(
3012 expected_invisibles.len(),
3013 input_text
3014 .chars()
3015 .filter(|initial_char| initial_char.is_whitespace())
3016 .count(),
3017 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3018 );
3019 info!("Expected invisibles: {expected_invisibles:?}");
3020
3021 init_test(cx, |_| {});
3022
3023 // Put the same string with repeating whitespace pattern into editors of various size,
3024 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
3025 let resize_step = 10.0;
3026 let mut editor_width = 200.0;
3027 while editor_width <= 1000.0 {
3028 update_test_settings(cx, |s| {
3029 s.defaults.tab_size = NonZeroU32::new(tab_size);
3030 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3031 s.defaults.preferred_line_length = Some(editor_width as u32);
3032 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
3033 });
3034
3035 let actual_invisibles =
3036 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
3037
3038 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
3039 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
3040 let mut i = 0;
3041 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
3042 i = actual_index;
3043 match expected_invisibles.get(i) {
3044 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
3045 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
3046 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
3047 _ => {
3048 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
3049 }
3050 },
3051 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
3052 }
3053 }
3054 let missing_expected_invisibles = &expected_invisibles[i + 1..];
3055 assert!(
3056 missing_expected_invisibles.is_empty(),
3057 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
3058 );
3059
3060 editor_width += resize_step;
3061 }
3062 }
3063
3064 fn collect_invisibles_from_new_editor(
3065 cx: &mut TestAppContext,
3066 editor_mode: EditorMode,
3067 input_text: &str,
3068 editor_width: f32,
3069 ) -> Vec<Invisible> {
3070 info!(
3071 "Creating editor with mode {editor_mode:?}, witdh {editor_width} and text '{input_text}'"
3072 );
3073 let (_, editor) = cx.add_window(|cx| {
3074 let buffer = MultiBuffer::build_simple(&input_text, cx);
3075 Editor::new(editor_mode, buffer, None, None, cx)
3076 });
3077
3078 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3079 let (_, layout_state) = editor.update(cx, |editor, cx| {
3080 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
3081 editor.set_wrap_width(Some(editor_width), cx);
3082
3083 let mut new_parents = Default::default();
3084 let mut notify_views_if_parents_change = Default::default();
3085 let mut layout_cx = LayoutContext::new(
3086 cx,
3087 &mut new_parents,
3088 &mut notify_views_if_parents_change,
3089 false,
3090 );
3091 element.layout(
3092 SizeConstraint::new(vec2f(editor_width, 500.), vec2f(editor_width, 500.)),
3093 editor,
3094 &mut layout_cx,
3095 )
3096 });
3097
3098 layout_state
3099 .position_map
3100 .line_layouts
3101 .iter()
3102 .map(|line_with_invisibles| &line_with_invisibles.invisibles)
3103 .flatten()
3104 .cloned()
3105 .collect()
3106 }
3107}