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 git::{diff_hunk_to_display, DisplayDiffHunk},
9 hover_popover::{
10 hide_hover, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH,
11 MIN_POPOVER_LINE_HEIGHT,
12 },
13 link_go_to_definition::{
14 go_to_fetched_definition, go_to_fetched_type_definition, update_go_to_definition_link,
15 },
16 mouse_context_menu, EditorStyle, GutterHover, UnfoldAt,
17};
18use clock::ReplicaId;
19use collections::{BTreeMap, HashMap};
20use git::diff::DiffHunkStatus;
21use gpui::{
22 color::Color,
23 elements::*,
24 fonts::{HighlightStyle, TextStyle, Underline},
25 geometry::{
26 rect::RectF,
27 vector::{vec2f, Vector2F},
28 PathBuilder,
29 },
30 json::{self, ToJson},
31 platform::{CursorStyle, Modifiers, MouseButton, MouseButtonEvent, MouseMovedEvent},
32 text_layout::{self, Line, RunStyle, TextLayoutCache},
33 AnyElement, Axis, Border, CursorRegion, Element, EventContext, FontCache, LayoutContext,
34 MouseRegion, Quad, SceneBuilder, SizeConstraint, ViewContext, WindowContext,
35};
36use itertools::Itertools;
37use json::json;
38use language::{
39 language_settings::ShowWhitespaceSetting, Bias, CursorShape, DiagnosticSeverity, OffsetUtf16,
40 Selection,
41};
42use project::ProjectPath;
43use settings::Settings;
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 = &cx.global::<Settings>().theme.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 min_thumb_height =
1031 style.min_height_factor * cx.font_cache.line_height(self.style.text.font_size);
1032 let thumb_height = (row_range.end - row_range.start) * height / max_row;
1033 if thumb_height < min_thumb_height {
1034 first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
1035 height -= min_thumb_height - thumb_height;
1036 }
1037
1038 let y_for_row = |row: f32| -> f32 { top + first_row_y_offset + row * height / max_row };
1039
1040 let thumb_top = y_for_row(row_range.start) - first_row_y_offset;
1041 let thumb_bottom = y_for_row(row_range.end) + first_row_y_offset;
1042 let track_bounds = RectF::from_points(vec2f(left, top), vec2f(right, bottom));
1043 let thumb_bounds = RectF::from_points(vec2f(left, thumb_top), vec2f(right, thumb_bottom));
1044
1045 if layout.show_scrollbars {
1046 scene.push_quad(Quad {
1047 bounds: track_bounds,
1048 border: style.track.border,
1049 background: style.track.background_color,
1050 ..Default::default()
1051 });
1052 scene.push_quad(Quad {
1053 bounds: thumb_bounds,
1054 border: style.thumb.border,
1055 background: style.thumb.background_color,
1056 corner_radius: style.thumb.corner_radius,
1057 });
1058 }
1059
1060 scene.push_cursor_region(CursorRegion {
1061 bounds: track_bounds,
1062 style: CursorStyle::Arrow,
1063 });
1064 scene.push_mouse_region(
1065 MouseRegion::new::<ScrollbarMouseHandlers>(cx.view_id(), cx.view_id(), track_bounds)
1066 .on_move(move |_, editor: &mut Editor, cx| {
1067 editor.scroll_manager.show_scrollbar(cx);
1068 })
1069 .on_down(MouseButton::Left, {
1070 let row_range = row_range.clone();
1071 move |event, editor: &mut Editor, cx| {
1072 let y = event.position.y();
1073 if y < thumb_top || thumb_bottom < y {
1074 let center_row = ((y - top) * max_row as f32 / height).round() as u32;
1075 let top_row = center_row
1076 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
1077 let mut position = editor.scroll_position(cx);
1078 position.set_y(top_row as f32);
1079 editor.set_scroll_position(position, cx);
1080 } else {
1081 editor.scroll_manager.show_scrollbar(cx);
1082 }
1083 }
1084 })
1085 .on_drag(MouseButton::Left, {
1086 move |event, editor: &mut Editor, cx| {
1087 let y = event.prev_mouse_position.y();
1088 let new_y = event.position.y();
1089 if thumb_top < y && y < thumb_bottom {
1090 let mut position = editor.scroll_position(cx);
1091 position.set_y(position.y() + (new_y - y) * (max_row as f32) / height);
1092 if position.y() < 0.0 {
1093 position.set_y(0.);
1094 }
1095 editor.set_scroll_position(position, cx);
1096 }
1097 }
1098 }),
1099 );
1100 }
1101
1102 #[allow(clippy::too_many_arguments)]
1103 fn paint_highlighted_range(
1104 &self,
1105 scene: &mut SceneBuilder,
1106 range: Range<DisplayPoint>,
1107 color: Color,
1108 corner_radius: f32,
1109 line_end_overshoot: f32,
1110 layout: &LayoutState,
1111 content_origin: Vector2F,
1112 scroll_top: f32,
1113 scroll_left: f32,
1114 bounds: RectF,
1115 ) {
1116 let start_row = layout.visible_display_row_range.start;
1117 let end_row = layout.visible_display_row_range.end;
1118 if range.start != range.end {
1119 let row_range = if range.end.column() == 0 {
1120 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
1121 } else {
1122 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
1123 };
1124
1125 let highlighted_range = HighlightedRange {
1126 color,
1127 line_height: layout.position_map.line_height,
1128 corner_radius,
1129 start_y: content_origin.y()
1130 + row_range.start as f32 * layout.position_map.line_height
1131 - scroll_top,
1132 lines: row_range
1133 .into_iter()
1134 .map(|row| {
1135 let line_layout =
1136 &layout.position_map.line_layouts[(row - start_row) as usize].line;
1137 HighlightedRangeLine {
1138 start_x: if row == range.start.row() {
1139 content_origin.x()
1140 + line_layout.x_for_index(range.start.column() as usize)
1141 - scroll_left
1142 } else {
1143 content_origin.x() - scroll_left
1144 },
1145 end_x: if row == range.end.row() {
1146 content_origin.x()
1147 + line_layout.x_for_index(range.end.column() as usize)
1148 - scroll_left
1149 } else {
1150 content_origin.x() + line_layout.width() + line_end_overshoot
1151 - scroll_left
1152 },
1153 }
1154 })
1155 .collect(),
1156 };
1157
1158 highlighted_range.paint(bounds, scene);
1159 }
1160 }
1161
1162 fn paint_blocks(
1163 &mut self,
1164 scene: &mut SceneBuilder,
1165 bounds: RectF,
1166 visible_bounds: RectF,
1167 layout: &mut LayoutState,
1168 editor: &mut Editor,
1169 cx: &mut ViewContext<Editor>,
1170 ) {
1171 let scroll_position = layout.position_map.snapshot.scroll_position();
1172 let scroll_left = scroll_position.x() * layout.position_map.em_width;
1173 let scroll_top = scroll_position.y() * layout.position_map.line_height;
1174
1175 for block in &mut layout.blocks {
1176 let mut origin = bounds.origin()
1177 + vec2f(
1178 0.,
1179 block.row as f32 * layout.position_map.line_height - scroll_top,
1180 );
1181 if !matches!(block.style, BlockStyle::Sticky) {
1182 origin += vec2f(-scroll_left, 0.);
1183 }
1184 block
1185 .element
1186 .paint(scene, origin, visible_bounds, editor, cx);
1187 }
1188 }
1189
1190 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &ViewContext<Editor>) -> f32 {
1191 let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
1192 let style = &self.style;
1193
1194 cx.text_layout_cache()
1195 .layout_str(
1196 "1".repeat(digit_count).as_str(),
1197 style.text.font_size,
1198 &[(
1199 digit_count,
1200 RunStyle {
1201 font_id: style.text.font_id,
1202 color: Color::black(),
1203 underline: Default::default(),
1204 },
1205 )],
1206 )
1207 .width()
1208 }
1209
1210 //Folds contained in a hunk are ignored apart from shrinking visual size
1211 //If a fold contains any hunks then that fold line is marked as modified
1212 fn layout_git_gutters(
1213 &self,
1214 display_rows: Range<u32>,
1215 snapshot: &EditorSnapshot,
1216 ) -> Vec<DisplayDiffHunk> {
1217 let buffer_snapshot = &snapshot.buffer_snapshot;
1218
1219 let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1220 .to_point(snapshot)
1221 .row;
1222 let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1223 .to_point(snapshot)
1224 .row;
1225
1226 buffer_snapshot
1227 .git_diff_hunks_in_range(buffer_start_row..buffer_end_row, false)
1228 .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1229 .dedup()
1230 .collect()
1231 }
1232
1233 fn layout_line_numbers(
1234 &self,
1235 rows: Range<u32>,
1236 active_rows: &BTreeMap<u32, bool>,
1237 is_singleton: bool,
1238 snapshot: &EditorSnapshot,
1239 cx: &ViewContext<Editor>,
1240 ) -> (
1241 Vec<Option<text_layout::Line>>,
1242 Vec<Option<(FoldStatus, BufferRow, bool)>>,
1243 ) {
1244 let style = &self.style;
1245 let include_line_numbers = snapshot.mode == EditorMode::Full;
1246 let mut line_number_layouts = Vec::with_capacity(rows.len());
1247 let mut fold_statuses = Vec::with_capacity(rows.len());
1248 let mut line_number = String::new();
1249 for (ix, row) in snapshot
1250 .buffer_rows(rows.start)
1251 .take((rows.end - rows.start) as usize)
1252 .enumerate()
1253 {
1254 let display_row = rows.start + ix as u32;
1255 let (active, color) = if active_rows.contains_key(&display_row) {
1256 (true, style.line_number_active)
1257 } else {
1258 (false, style.line_number)
1259 };
1260 if let Some(buffer_row) = row {
1261 if include_line_numbers {
1262 line_number.clear();
1263 write!(&mut line_number, "{}", buffer_row + 1).unwrap();
1264 line_number_layouts.push(Some(cx.text_layout_cache().layout_str(
1265 &line_number,
1266 style.text.font_size,
1267 &[(
1268 line_number.len(),
1269 RunStyle {
1270 font_id: style.text.font_id,
1271 color,
1272 underline: Default::default(),
1273 },
1274 )],
1275 )));
1276 fold_statuses.push(
1277 is_singleton
1278 .then(|| {
1279 snapshot
1280 .fold_for_line(buffer_row)
1281 .map(|fold_status| (fold_status, buffer_row, active))
1282 })
1283 .flatten(),
1284 )
1285 }
1286 } else {
1287 fold_statuses.push(None);
1288 line_number_layouts.push(None);
1289 }
1290 }
1291
1292 (line_number_layouts, fold_statuses)
1293 }
1294
1295 fn layout_lines(
1296 &mut self,
1297 rows: Range<u32>,
1298 line_number_layouts: &[Option<Line>],
1299 snapshot: &EditorSnapshot,
1300 cx: &ViewContext<Editor>,
1301 ) -> Vec<LineWithInvisibles> {
1302 if rows.start >= rows.end {
1303 return Vec::new();
1304 }
1305
1306 // When the editor is empty and unfocused, then show the placeholder.
1307 if snapshot.is_empty() {
1308 let placeholder_style = self
1309 .style
1310 .placeholder_text
1311 .as_ref()
1312 .unwrap_or(&self.style.text);
1313 let placeholder_text = snapshot.placeholder_text();
1314 let placeholder_lines = placeholder_text
1315 .as_ref()
1316 .map_or("", AsRef::as_ref)
1317 .split('\n')
1318 .skip(rows.start as usize)
1319 .chain(iter::repeat(""))
1320 .take(rows.len());
1321 placeholder_lines
1322 .map(|line| {
1323 cx.text_layout_cache().layout_str(
1324 line,
1325 placeholder_style.font_size,
1326 &[(
1327 line.len(),
1328 RunStyle {
1329 font_id: placeholder_style.font_id,
1330 color: placeholder_style.color,
1331 underline: Default::default(),
1332 },
1333 )],
1334 )
1335 })
1336 .map(|line| LineWithInvisibles {
1337 line,
1338 invisibles: Vec::new(),
1339 })
1340 .collect()
1341 } else {
1342 let style = &self.style;
1343 let chunks = snapshot
1344 .chunks(rows.clone(), true, Some(style.theme.suggestion))
1345 .map(|chunk| {
1346 let mut highlight_style = chunk
1347 .syntax_highlight_id
1348 .and_then(|id| id.style(&style.syntax));
1349
1350 if let Some(chunk_highlight) = chunk.highlight_style {
1351 if let Some(highlight_style) = highlight_style.as_mut() {
1352 highlight_style.highlight(chunk_highlight);
1353 } else {
1354 highlight_style = Some(chunk_highlight);
1355 }
1356 }
1357
1358 let mut diagnostic_highlight = HighlightStyle::default();
1359
1360 if chunk.is_unnecessary {
1361 diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
1362 }
1363
1364 if let Some(severity) = chunk.diagnostic_severity {
1365 // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
1366 if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
1367 let diagnostic_style = super::diagnostic_style(severity, true, style);
1368 diagnostic_highlight.underline = Some(Underline {
1369 color: Some(diagnostic_style.message.text.color),
1370 thickness: 1.0.into(),
1371 squiggly: true,
1372 });
1373 }
1374 }
1375
1376 if let Some(highlight_style) = highlight_style.as_mut() {
1377 highlight_style.highlight(diagnostic_highlight);
1378 } else {
1379 highlight_style = Some(diagnostic_highlight);
1380 }
1381
1382 HighlightedChunk {
1383 chunk: chunk.text,
1384 style: highlight_style,
1385 is_tab: chunk.is_tab,
1386 }
1387 });
1388
1389 LineWithInvisibles::from_chunks(
1390 chunks,
1391 &style.text,
1392 cx.text_layout_cache(),
1393 cx.font_cache(),
1394 MAX_LINE_LEN,
1395 rows.len() as usize,
1396 line_number_layouts,
1397 snapshot.mode,
1398 )
1399 }
1400 }
1401
1402 #[allow(clippy::too_many_arguments)]
1403 fn layout_blocks(
1404 &mut self,
1405 rows: Range<u32>,
1406 snapshot: &EditorSnapshot,
1407 editor_width: f32,
1408 scroll_width: f32,
1409 gutter_padding: f32,
1410 gutter_width: f32,
1411 em_width: f32,
1412 text_x: f32,
1413 line_height: f32,
1414 style: &EditorStyle,
1415 line_layouts: &[LineWithInvisibles],
1416 include_root: bool,
1417 editor: &mut Editor,
1418 cx: &mut LayoutContext<Editor>,
1419 ) -> (f32, Vec<BlockLayout>) {
1420 let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
1421 let scroll_x = snapshot.scroll_anchor.offset.x();
1422 let (fixed_blocks, non_fixed_blocks) = snapshot
1423 .blocks_in_range(rows.clone())
1424 .partition::<Vec<_>, _>(|(_, block)| match block {
1425 TransformBlock::ExcerptHeader { .. } => false,
1426 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1427 });
1428 let mut render_block = |block: &TransformBlock, width: f32| {
1429 let mut element = match block {
1430 TransformBlock::Custom(block) => {
1431 let align_to = block
1432 .position()
1433 .to_point(&snapshot.buffer_snapshot)
1434 .to_display_point(snapshot);
1435 let anchor_x = text_x
1436 + if rows.contains(&align_to.row()) {
1437 line_layouts[(align_to.row() - rows.start) as usize]
1438 .line
1439 .x_for_index(align_to.column() as usize)
1440 } else {
1441 layout_line(align_to.row(), snapshot, style, cx.text_layout_cache())
1442 .x_for_index(align_to.column() as usize)
1443 };
1444
1445 block.render(&mut BlockContext {
1446 view_context: cx,
1447 anchor_x,
1448 gutter_padding,
1449 line_height,
1450 scroll_x,
1451 gutter_width,
1452 em_width,
1453 })
1454 }
1455 TransformBlock::ExcerptHeader {
1456 id,
1457 buffer,
1458 range,
1459 starts_new_buffer,
1460 ..
1461 } => {
1462 let id = *id;
1463 let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1464 let jump_path = ProjectPath {
1465 worktree_id: file.worktree_id(cx),
1466 path: file.path.clone(),
1467 };
1468 let jump_anchor = range
1469 .primary
1470 .as_ref()
1471 .map_or(range.context.start, |primary| primary.start);
1472 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1473
1474 enum JumpIcon {}
1475 MouseEventHandler::<JumpIcon, _>::new(id.into(), cx, |state, _| {
1476 let style = style.jump_icon.style_for(state, false);
1477 Svg::new("icons/arrow_up_right_8.svg")
1478 .with_color(style.color)
1479 .constrained()
1480 .with_width(style.icon_width)
1481 .aligned()
1482 .contained()
1483 .with_style(style.container)
1484 .constrained()
1485 .with_width(style.button_width)
1486 .with_height(style.button_width)
1487 })
1488 .with_cursor_style(CursorStyle::PointingHand)
1489 .on_click(MouseButton::Left, move |_, editor, cx| {
1490 if let Some(workspace) = editor
1491 .workspace
1492 .as_ref()
1493 .and_then(|(workspace, _)| workspace.upgrade(cx))
1494 {
1495 workspace.update(cx, |workspace, cx| {
1496 Editor::jump(
1497 workspace,
1498 jump_path.clone(),
1499 jump_position,
1500 jump_anchor,
1501 cx,
1502 );
1503 });
1504 }
1505 })
1506 .with_tooltip::<JumpIcon>(
1507 id.into(),
1508 "Jump to Buffer".to_string(),
1509 Some(Box::new(crate::OpenExcerpts)),
1510 tooltip_style.clone(),
1511 cx,
1512 )
1513 .aligned()
1514 .flex_float()
1515 });
1516
1517 if *starts_new_buffer {
1518 let style = &self.style.diagnostic_path_header;
1519 let font_size =
1520 (style.text_scale_factor * self.style.text.font_size).round();
1521
1522 let path = buffer.resolve_file_path(cx, include_root);
1523 let mut filename = None;
1524 let mut parent_path = None;
1525 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1526 if let Some(path) = path {
1527 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1528 parent_path =
1529 path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1530 }
1531
1532 Flex::row()
1533 .with_child(
1534 Label::new(
1535 filename.unwrap_or_else(|| "untitled".to_string()),
1536 style.filename.text.clone().with_font_size(font_size),
1537 )
1538 .contained()
1539 .with_style(style.filename.container)
1540 .aligned(),
1541 )
1542 .with_children(parent_path.map(|path| {
1543 Label::new(path, style.path.text.clone().with_font_size(font_size))
1544 .contained()
1545 .with_style(style.path.container)
1546 .aligned()
1547 }))
1548 .with_children(jump_icon)
1549 .contained()
1550 .with_style(style.container)
1551 .with_padding_left(gutter_padding)
1552 .with_padding_right(gutter_padding)
1553 .expanded()
1554 .into_any_named("path header block")
1555 } else {
1556 let text_style = self.style.text.clone();
1557 Flex::row()
1558 .with_child(Label::new("⋯", text_style))
1559 .with_children(jump_icon)
1560 .contained()
1561 .with_padding_left(gutter_padding)
1562 .with_padding_right(gutter_padding)
1563 .expanded()
1564 .into_any_named("collapsed context")
1565 }
1566 }
1567 };
1568
1569 element.layout(
1570 SizeConstraint {
1571 min: Vector2F::zero(),
1572 max: vec2f(width, block.height() as f32 * line_height),
1573 },
1574 editor,
1575 cx,
1576 );
1577 element
1578 };
1579
1580 let mut fixed_block_max_width = 0f32;
1581 let mut blocks = Vec::new();
1582 for (row, block) in fixed_blocks {
1583 let element = render_block(block, f32::INFINITY);
1584 fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1585 blocks.push(BlockLayout {
1586 row,
1587 element,
1588 style: BlockStyle::Fixed,
1589 });
1590 }
1591 for (row, block) in non_fixed_blocks {
1592 let style = match block {
1593 TransformBlock::Custom(block) => block.style(),
1594 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1595 };
1596 let width = match style {
1597 BlockStyle::Sticky => editor_width,
1598 BlockStyle::Flex => editor_width
1599 .max(fixed_block_max_width)
1600 .max(gutter_width + scroll_width),
1601 BlockStyle::Fixed => unreachable!(),
1602 };
1603 let element = render_block(block, width);
1604 blocks.push(BlockLayout {
1605 row,
1606 element,
1607 style,
1608 });
1609 }
1610 (
1611 scroll_width.max(fixed_block_max_width - gutter_width),
1612 blocks,
1613 )
1614 }
1615}
1616
1617struct HighlightedChunk<'a> {
1618 chunk: &'a str,
1619 style: Option<HighlightStyle>,
1620 is_tab: bool,
1621}
1622
1623#[derive(Debug)]
1624pub struct LineWithInvisibles {
1625 pub line: Line,
1626 invisibles: Vec<Invisible>,
1627}
1628
1629impl LineWithInvisibles {
1630 fn from_chunks<'a>(
1631 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
1632 text_style: &TextStyle,
1633 text_layout_cache: &TextLayoutCache,
1634 font_cache: &Arc<FontCache>,
1635 max_line_len: usize,
1636 max_line_count: usize,
1637 line_number_layouts: &[Option<Line>],
1638 editor_mode: EditorMode,
1639 ) -> Vec<Self> {
1640 let mut layouts = Vec::with_capacity(max_line_count);
1641 let mut line = String::new();
1642 let mut invisibles = Vec::new();
1643 let mut styles = Vec::new();
1644 let mut non_whitespace_added = false;
1645 let mut row = 0;
1646 let mut line_exceeded_max_len = false;
1647 for highlighted_chunk in chunks.chain([HighlightedChunk {
1648 chunk: "\n",
1649 style: None,
1650 is_tab: false,
1651 }]) {
1652 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
1653 if ix > 0 {
1654 layouts.push(Self {
1655 line: text_layout_cache.layout_str(&line, text_style.font_size, &styles),
1656 invisibles: invisibles.drain(..).collect(),
1657 });
1658
1659 line.clear();
1660 styles.clear();
1661 row += 1;
1662 line_exceeded_max_len = false;
1663 non_whitespace_added = false;
1664 if row == max_line_count {
1665 return layouts;
1666 }
1667 }
1668
1669 if !line_chunk.is_empty() && !line_exceeded_max_len {
1670 let text_style = if let Some(style) = highlighted_chunk.style {
1671 text_style
1672 .clone()
1673 .highlight(style, font_cache)
1674 .map(Cow::Owned)
1675 .unwrap_or_else(|_| Cow::Borrowed(text_style))
1676 } else {
1677 Cow::Borrowed(text_style)
1678 };
1679
1680 if line.len() + line_chunk.len() > max_line_len {
1681 let mut chunk_len = max_line_len - line.len();
1682 while !line_chunk.is_char_boundary(chunk_len) {
1683 chunk_len -= 1;
1684 }
1685 line_chunk = &line_chunk[..chunk_len];
1686 line_exceeded_max_len = true;
1687 }
1688
1689 styles.push((
1690 line_chunk.len(),
1691 RunStyle {
1692 font_id: text_style.font_id,
1693 color: text_style.color,
1694 underline: text_style.underline,
1695 },
1696 ));
1697
1698 if editor_mode == EditorMode::Full {
1699 // Line wrap pads its contents with fake whitespaces,
1700 // avoid printing them
1701 let inside_wrapped_string = line_number_layouts
1702 .get(row)
1703 .and_then(|layout| layout.as_ref())
1704 .is_none();
1705 if highlighted_chunk.is_tab {
1706 if non_whitespace_added || !inside_wrapped_string {
1707 invisibles.push(Invisible::Tab {
1708 line_start_offset: line.len(),
1709 });
1710 }
1711 } else {
1712 invisibles.extend(
1713 line_chunk
1714 .chars()
1715 .enumerate()
1716 .filter(|(_, line_char)| {
1717 let is_whitespace = line_char.is_whitespace();
1718 non_whitespace_added |= !is_whitespace;
1719 is_whitespace
1720 && (non_whitespace_added || !inside_wrapped_string)
1721 })
1722 .map(|(whitespace_index, _)| Invisible::Whitespace {
1723 line_offset: line.len() + whitespace_index,
1724 }),
1725 )
1726 }
1727 }
1728
1729 line.push_str(line_chunk);
1730 }
1731 }
1732 }
1733
1734 layouts
1735 }
1736
1737 fn draw(
1738 &self,
1739 layout: &LayoutState,
1740 row: u32,
1741 scroll_top: f32,
1742 scene: &mut SceneBuilder,
1743 content_origin: Vector2F,
1744 scroll_left: f32,
1745 visible_text_bounds: RectF,
1746 whitespace_setting: ShowWhitespaceSetting,
1747 selection_ranges: &[Range<DisplayPoint>],
1748 visible_bounds: RectF,
1749 cx: &mut ViewContext<Editor>,
1750 ) {
1751 let line_height = layout.position_map.line_height;
1752 let line_y = row as f32 * line_height - scroll_top;
1753
1754 self.line.paint(
1755 scene,
1756 content_origin + vec2f(-scroll_left, line_y),
1757 visible_text_bounds,
1758 line_height,
1759 cx,
1760 );
1761
1762 self.draw_invisibles(
1763 &selection_ranges,
1764 layout,
1765 content_origin,
1766 scroll_left,
1767 line_y,
1768 row,
1769 scene,
1770 visible_bounds,
1771 line_height,
1772 whitespace_setting,
1773 cx,
1774 );
1775 }
1776
1777 fn draw_invisibles(
1778 &self,
1779 selection_ranges: &[Range<DisplayPoint>],
1780 layout: &LayoutState,
1781 content_origin: Vector2F,
1782 scroll_left: f32,
1783 line_y: f32,
1784 row: u32,
1785 scene: &mut SceneBuilder,
1786 visible_bounds: RectF,
1787 line_height: f32,
1788 whitespace_setting: ShowWhitespaceSetting,
1789 cx: &mut ViewContext<Editor>,
1790 ) {
1791 let allowed_invisibles_regions = match whitespace_setting {
1792 ShowWhitespaceSetting::None => return,
1793 ShowWhitespaceSetting::Selection => Some(selection_ranges),
1794 ShowWhitespaceSetting::All => None,
1795 };
1796
1797 for invisible in &self.invisibles {
1798 let (&token_offset, invisible_symbol) = match invisible {
1799 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
1800 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
1801 };
1802
1803 let x_offset = self.line.x_for_index(token_offset);
1804 let invisible_offset =
1805 (layout.position_map.em_width - invisible_symbol.width()).max(0.0) / 2.0;
1806 let origin = content_origin + vec2f(-scroll_left + x_offset + invisible_offset, line_y);
1807
1808 if let Some(allowed_regions) = allowed_invisibles_regions {
1809 let invisible_point = DisplayPoint::new(row, token_offset as u32);
1810 if !allowed_regions
1811 .iter()
1812 .any(|region| region.start <= invisible_point && invisible_point < region.end)
1813 {
1814 continue;
1815 }
1816 }
1817 invisible_symbol.paint(scene, origin, visible_bounds, line_height, cx);
1818 }
1819 }
1820}
1821
1822#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1823enum Invisible {
1824 Tab { line_start_offset: usize },
1825 Whitespace { line_offset: usize },
1826}
1827
1828impl Element<Editor> for EditorElement {
1829 type LayoutState = LayoutState;
1830 type PaintState = ();
1831
1832 fn layout(
1833 &mut self,
1834 constraint: SizeConstraint,
1835 editor: &mut Editor,
1836 cx: &mut LayoutContext<Editor>,
1837 ) -> (Vector2F, Self::LayoutState) {
1838 let mut size = constraint.max;
1839 if size.x().is_infinite() {
1840 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1841 }
1842
1843 let snapshot = editor.snapshot(cx);
1844 let style = self.style.clone();
1845 let line_height = style.text.line_height(cx.font_cache());
1846
1847 let gutter_padding;
1848 let gutter_width;
1849 let gutter_margin;
1850 if snapshot.mode == EditorMode::Full {
1851 let em_width = style.text.em_width(cx.font_cache());
1852 gutter_padding = (em_width * style.gutter_padding_factor).round();
1853 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1854 gutter_margin = -style.text.descent(cx.font_cache());
1855 } else {
1856 gutter_padding = 0.0;
1857 gutter_width = 0.0;
1858 gutter_margin = 0.0;
1859 };
1860
1861 let text_width = size.x() - gutter_width;
1862 let em_width = style.text.em_width(cx.font_cache());
1863 let em_advance = style.text.em_advance(cx.font_cache());
1864 let overscroll = vec2f(em_width, 0.);
1865 let snapshot = {
1866 editor.set_visible_line_count(size.y() / line_height);
1867
1868 let editor_width = text_width - gutter_margin - overscroll.x() - em_width;
1869 let wrap_width = match editor.soft_wrap_mode(cx) {
1870 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
1871 SoftWrap::EditorWidth => editor_width,
1872 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
1873 };
1874
1875 if editor.set_wrap_width(Some(wrap_width), cx) {
1876 editor.snapshot(cx)
1877 } else {
1878 snapshot
1879 }
1880 };
1881
1882 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1883 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1884 size.set_y(
1885 scroll_height
1886 .min(constraint.max_along(Axis::Vertical))
1887 .max(constraint.min_along(Axis::Vertical))
1888 .min(line_height * max_lines as f32),
1889 )
1890 } else if let EditorMode::SingleLine = snapshot.mode {
1891 size.set_y(
1892 line_height
1893 .min(constraint.max_along(Axis::Vertical))
1894 .max(constraint.min_along(Axis::Vertical)),
1895 )
1896 } else if size.y().is_infinite() {
1897 size.set_y(scroll_height);
1898 }
1899 let gutter_size = vec2f(gutter_width, size.y());
1900 let text_size = vec2f(text_width, size.y());
1901
1902 let autoscroll_horizontally = editor.autoscroll_vertically(size.y(), line_height, cx);
1903 let mut snapshot = editor.snapshot(cx);
1904
1905 let scroll_position = snapshot.scroll_position();
1906 // The scroll position is a fractional point, the whole number of which represents
1907 // the top of the window in terms of display rows.
1908 let start_row = scroll_position.y() as u32;
1909 let height_in_lines = size.y() / line_height;
1910 let max_row = snapshot.max_point().row();
1911
1912 // Add 1 to ensure selections bleed off screen
1913 let end_row = 1 + cmp::min(
1914 (scroll_position.y() + height_in_lines).ceil() as u32,
1915 max_row,
1916 );
1917
1918 let start_anchor = if start_row == 0 {
1919 Anchor::min()
1920 } else {
1921 snapshot
1922 .buffer_snapshot
1923 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1924 };
1925 let end_anchor = if end_row > max_row {
1926 Anchor::max()
1927 } else {
1928 snapshot
1929 .buffer_snapshot
1930 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1931 };
1932
1933 let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1934 let mut active_rows = BTreeMap::new();
1935 let mut fold_ranges = Vec::new();
1936 let is_singleton = editor.is_singleton(cx);
1937
1938 let highlighted_rows = editor.highlighted_rows();
1939 let theme = cx.global::<Settings>().theme.as_ref();
1940 let highlighted_ranges = editor.background_highlights_in_range(
1941 start_anchor..end_anchor,
1942 &snapshot.display_snapshot,
1943 theme,
1944 );
1945
1946 fold_ranges.extend(
1947 snapshot
1948 .folds_in_range(start_anchor..end_anchor)
1949 .map(|anchor| {
1950 let start = anchor.start.to_point(&snapshot.buffer_snapshot);
1951 (
1952 start.row,
1953 start.to_display_point(&snapshot.display_snapshot)
1954 ..anchor.end.to_display_point(&snapshot),
1955 )
1956 }),
1957 );
1958
1959 let mut remote_selections = HashMap::default();
1960 for (replica_id, line_mode, cursor_shape, selection) in snapshot
1961 .buffer_snapshot
1962 .remote_selections_in_range(&(start_anchor..end_anchor))
1963 {
1964 // The local selections match the leader's selections.
1965 if Some(replica_id) == editor.leader_replica_id {
1966 continue;
1967 }
1968 remote_selections
1969 .entry(replica_id)
1970 .or_insert(Vec::new())
1971 .push(SelectionLayout::new(
1972 selection,
1973 line_mode,
1974 cursor_shape,
1975 &snapshot.display_snapshot,
1976 ));
1977 }
1978 selections.extend(remote_selections);
1979
1980 if editor.show_local_selections {
1981 let mut local_selections = editor
1982 .selections
1983 .disjoint_in_range(start_anchor..end_anchor, cx);
1984 local_selections.extend(editor.selections.pending(cx));
1985 for selection in &local_selections {
1986 let is_empty = selection.start == selection.end;
1987 let selection_start = snapshot.prev_line_boundary(selection.start).1;
1988 let selection_end = snapshot.next_line_boundary(selection.end).1;
1989 for row in cmp::max(selection_start.row(), start_row)
1990 ..=cmp::min(selection_end.row(), end_row)
1991 {
1992 let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
1993 *contains_non_empty_selection |= !is_empty;
1994 }
1995 }
1996
1997 // Render the local selections in the leader's color when following.
1998 let local_replica_id = editor
1999 .leader_replica_id
2000 .unwrap_or_else(|| editor.replica_id(cx));
2001
2002 selections.push((
2003 local_replica_id,
2004 local_selections
2005 .into_iter()
2006 .map(|selection| {
2007 SelectionLayout::new(
2008 selection,
2009 editor.selections.line_mode,
2010 editor.cursor_shape,
2011 &snapshot.display_snapshot,
2012 )
2013 })
2014 .collect(),
2015 ));
2016 }
2017
2018 let show_scrollbars = editor.scroll_manager.scrollbars_visible();
2019 let include_root = editor
2020 .project
2021 .as_ref()
2022 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2023 .unwrap_or_default();
2024
2025 let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2026 .into_iter()
2027 .map(|(id, fold)| {
2028 let color = self
2029 .style
2030 .folds
2031 .ellipses
2032 .background
2033 .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize), false)
2034 .color;
2035
2036 (id, fold, color)
2037 })
2038 .collect();
2039
2040 let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2041 start_row..end_row,
2042 &active_rows,
2043 is_singleton,
2044 &snapshot,
2045 cx,
2046 );
2047
2048 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2049
2050 let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
2051
2052 let mut max_visible_line_width = 0.0;
2053 let line_layouts =
2054 self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2055 for line_with_invisibles in &line_layouts {
2056 if line_with_invisibles.line.width() > max_visible_line_width {
2057 max_visible_line_width = line_with_invisibles.line.width();
2058 }
2059 }
2060
2061 let style = self.style.clone();
2062 let longest_line_width = layout_line(
2063 snapshot.longest_row(),
2064 &snapshot,
2065 &style,
2066 cx.text_layout_cache(),
2067 )
2068 .width();
2069 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
2070 let em_width = style.text.em_width(cx.font_cache());
2071 let (scroll_width, blocks) = self.layout_blocks(
2072 start_row..end_row,
2073 &snapshot,
2074 size.x(),
2075 scroll_width,
2076 gutter_padding,
2077 gutter_width,
2078 em_width,
2079 gutter_width + gutter_margin,
2080 line_height,
2081 &style,
2082 &line_layouts,
2083 include_root,
2084 editor,
2085 cx,
2086 );
2087
2088 let scroll_max = vec2f(
2089 ((scroll_width - text_size.x()) / em_width).max(0.0),
2090 max_row as f32,
2091 );
2092
2093 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x());
2094
2095 let autoscrolled = if autoscroll_horizontally {
2096 editor.autoscroll_horizontally(
2097 start_row,
2098 text_size.x(),
2099 scroll_width,
2100 em_width,
2101 &line_layouts,
2102 cx,
2103 )
2104 } else {
2105 false
2106 };
2107
2108 if clamped || autoscrolled {
2109 snapshot = editor.snapshot(cx);
2110 }
2111
2112 let newest_selection_head = editor
2113 .selections
2114 .newest::<usize>(cx)
2115 .head()
2116 .to_display_point(&snapshot);
2117 let style = editor.style(cx);
2118
2119 let mut context_menu = None;
2120 let mut code_actions_indicator = None;
2121 if (start_row..end_row).contains(&newest_selection_head.row()) {
2122 if editor.context_menu_visible() {
2123 context_menu = editor.render_context_menu(newest_selection_head, style.clone(), cx);
2124 }
2125
2126 let active = matches!(
2127 editor.context_menu,
2128 Some(crate::ContextMenu::CodeActions(_))
2129 );
2130
2131 code_actions_indicator = editor
2132 .render_code_actions_indicator(&style, active, cx)
2133 .map(|indicator| (newest_selection_head.row(), indicator));
2134 }
2135
2136 let visible_rows = start_row..start_row + line_layouts.len() as u32;
2137 let mut hover = editor
2138 .hover_state
2139 .render(&snapshot, &style, visible_rows, cx);
2140 let mode = editor.mode;
2141
2142 let mut fold_indicators = editor.render_fold_indicators(
2143 fold_statuses,
2144 &style,
2145 editor.gutter_hovered,
2146 line_height,
2147 gutter_margin,
2148 cx,
2149 );
2150
2151 if let Some((_, context_menu)) = context_menu.as_mut() {
2152 context_menu.layout(
2153 SizeConstraint {
2154 min: Vector2F::zero(),
2155 max: vec2f(
2156 cx.window_size().x() * 0.7,
2157 (12. * line_height).min((size.y() - line_height) / 2.),
2158 ),
2159 },
2160 editor,
2161 cx,
2162 );
2163 }
2164
2165 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
2166 indicator.layout(
2167 SizeConstraint::strict_along(
2168 Axis::Vertical,
2169 line_height * style.code_actions.vertical_scale,
2170 ),
2171 editor,
2172 cx,
2173 );
2174 }
2175
2176 for fold_indicator in fold_indicators.iter_mut() {
2177 if let Some(indicator) = fold_indicator.as_mut() {
2178 indicator.layout(
2179 SizeConstraint::strict_along(
2180 Axis::Vertical,
2181 line_height * style.code_actions.vertical_scale,
2182 ),
2183 editor,
2184 cx,
2185 );
2186 }
2187 }
2188
2189 if let Some((_, hover_popovers)) = hover.as_mut() {
2190 for hover_popover in hover_popovers.iter_mut() {
2191 hover_popover.layout(
2192 SizeConstraint {
2193 min: Vector2F::zero(),
2194 max: vec2f(
2195 (120. * em_width) // Default size
2196 .min(size.x() / 2.) // Shrink to half of the editor width
2197 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2198 (16. * line_height) // Default size
2199 .min(size.y() / 2.) // Shrink to half of the editor height
2200 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2201 ),
2202 },
2203 editor,
2204 cx,
2205 );
2206 }
2207 }
2208
2209 let invisible_symbol_font_size = self.style.text.font_size / 2.0;
2210 let invisible_symbol_style = RunStyle {
2211 color: self.style.whitespace,
2212 font_id: self.style.text.font_id,
2213 underline: Default::default(),
2214 };
2215
2216 (
2217 size,
2218 LayoutState {
2219 mode,
2220 position_map: Arc::new(PositionMap {
2221 size,
2222 scroll_max,
2223 line_layouts,
2224 line_height,
2225 em_width,
2226 em_advance,
2227 snapshot,
2228 }),
2229 visible_display_row_range: start_row..end_row,
2230 gutter_size,
2231 gutter_padding,
2232 text_size,
2233 scrollbar_row_range,
2234 show_scrollbars,
2235 max_row,
2236 gutter_margin,
2237 active_rows,
2238 highlighted_rows,
2239 highlighted_ranges,
2240 fold_ranges,
2241 line_number_layouts,
2242 display_hunks,
2243 blocks,
2244 selections,
2245 context_menu,
2246 code_actions_indicator,
2247 fold_indicators,
2248 tab_invisible: cx.text_layout_cache().layout_str(
2249 "→",
2250 invisible_symbol_font_size,
2251 &[("→".len(), invisible_symbol_style)],
2252 ),
2253 space_invisible: cx.text_layout_cache().layout_str(
2254 "•",
2255 invisible_symbol_font_size,
2256 &[("•".len(), invisible_symbol_style)],
2257 ),
2258 hover_popovers: hover,
2259 },
2260 )
2261 }
2262
2263 fn paint(
2264 &mut self,
2265 scene: &mut SceneBuilder,
2266 bounds: RectF,
2267 visible_bounds: RectF,
2268 layout: &mut Self::LayoutState,
2269 editor: &mut Editor,
2270 cx: &mut ViewContext<Editor>,
2271 ) -> Self::PaintState {
2272 let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2273 scene.push_layer(Some(visible_bounds));
2274
2275 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
2276 let text_bounds = RectF::new(
2277 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2278 layout.text_size,
2279 );
2280
2281 Self::attach_mouse_handlers(
2282 scene,
2283 &layout.position_map,
2284 layout.hover_popovers.is_some(),
2285 visible_bounds,
2286 text_bounds,
2287 gutter_bounds,
2288 bounds,
2289 cx,
2290 );
2291
2292 self.paint_background(scene, gutter_bounds, text_bounds, layout);
2293 if layout.gutter_size.x() > 0. {
2294 self.paint_gutter(scene, gutter_bounds, visible_bounds, layout, editor, cx);
2295 }
2296 self.paint_text(scene, text_bounds, visible_bounds, layout, editor, cx);
2297
2298 scene.push_layer(Some(bounds));
2299 if !layout.blocks.is_empty() {
2300 self.paint_blocks(scene, bounds, visible_bounds, layout, editor, cx);
2301 }
2302 self.paint_scrollbar(scene, bounds, layout, cx);
2303 scene.pop_layer();
2304
2305 scene.pop_layer();
2306 }
2307
2308 fn rect_for_text_range(
2309 &self,
2310 range_utf16: Range<usize>,
2311 bounds: RectF,
2312 _: RectF,
2313 layout: &Self::LayoutState,
2314 _: &Self::PaintState,
2315 _: &Editor,
2316 _: &ViewContext<Editor>,
2317 ) -> Option<RectF> {
2318 let text_bounds = RectF::new(
2319 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2320 layout.text_size,
2321 );
2322 let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
2323 let scroll_position = layout.position_map.snapshot.scroll_position();
2324 let start_row = scroll_position.y() as u32;
2325 let scroll_top = scroll_position.y() * layout.position_map.line_height;
2326 let scroll_left = scroll_position.x() * layout.position_map.em_width;
2327
2328 let range_start = OffsetUtf16(range_utf16.start)
2329 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2330 if range_start.row() < start_row {
2331 return None;
2332 }
2333
2334 let line = &layout
2335 .position_map
2336 .line_layouts
2337 .get((range_start.row() - start_row) as usize)?
2338 .line;
2339 let range_start_x = line.x_for_index(range_start.column() as usize);
2340 let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
2341 Some(RectF::new(
2342 content_origin
2343 + vec2f(
2344 range_start_x,
2345 range_start_y + layout.position_map.line_height,
2346 )
2347 - vec2f(scroll_left, scroll_top),
2348 vec2f(
2349 layout.position_map.em_width,
2350 layout.position_map.line_height,
2351 ),
2352 ))
2353 }
2354
2355 fn debug(
2356 &self,
2357 bounds: RectF,
2358 _: &Self::LayoutState,
2359 _: &Self::PaintState,
2360 _: &Editor,
2361 _: &ViewContext<Editor>,
2362 ) -> json::Value {
2363 json!({
2364 "type": "BufferElement",
2365 "bounds": bounds.to_json()
2366 })
2367 }
2368}
2369
2370type BufferRow = u32;
2371
2372pub struct LayoutState {
2373 position_map: Arc<PositionMap>,
2374 gutter_size: Vector2F,
2375 gutter_padding: f32,
2376 gutter_margin: f32,
2377 text_size: Vector2F,
2378 mode: EditorMode,
2379 visible_display_row_range: Range<u32>,
2380 active_rows: BTreeMap<u32, bool>,
2381 highlighted_rows: Option<Range<u32>>,
2382 line_number_layouts: Vec<Option<text_layout::Line>>,
2383 display_hunks: Vec<DisplayDiffHunk>,
2384 blocks: Vec<BlockLayout>,
2385 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2386 fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)>,
2387 selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
2388 scrollbar_row_range: Range<f32>,
2389 show_scrollbars: bool,
2390 max_row: u32,
2391 context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
2392 code_actions_indicator: Option<(u32, AnyElement<Editor>)>,
2393 hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
2394 fold_indicators: Vec<Option<AnyElement<Editor>>>,
2395 tab_invisible: Line,
2396 space_invisible: Line,
2397}
2398
2399struct PositionMap {
2400 size: Vector2F,
2401 line_height: f32,
2402 scroll_max: Vector2F,
2403 em_width: f32,
2404 em_advance: f32,
2405 line_layouts: Vec<LineWithInvisibles>,
2406 snapshot: EditorSnapshot,
2407}
2408
2409impl PositionMap {
2410 /// Returns two display points:
2411 /// 1. The nearest *valid* position in the editor
2412 /// 2. An unclipped, potentially *invalid* position that maps directly to
2413 /// the given pixel position.
2414 fn point_for_position(
2415 &self,
2416 text_bounds: RectF,
2417 position: Vector2F,
2418 ) -> (DisplayPoint, DisplayPoint) {
2419 let scroll_position = self.snapshot.scroll_position();
2420 let position = position - text_bounds.origin();
2421 let y = position.y().max(0.0).min(self.size.y());
2422 let x = position.x() + (scroll_position.x() * self.em_width);
2423 let row = (y / self.line_height + scroll_position.y()) as u32;
2424 let (column, x_overshoot) = if let Some(line) = self
2425 .line_layouts
2426 .get(row as usize - scroll_position.y() as usize)
2427 .map(|line_with_spaces| &line_with_spaces.line)
2428 {
2429 if let Some(ix) = line.index_for_x(x) {
2430 (ix as u32, 0.0)
2431 } else {
2432 (line.len() as u32, 0f32.max(x - line.width()))
2433 }
2434 } else {
2435 (0, x)
2436 };
2437
2438 let mut target_point = DisplayPoint::new(row, column);
2439 let point = self.snapshot.clip_point(target_point, Bias::Left);
2440 *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
2441
2442 (point, target_point)
2443 }
2444}
2445
2446struct BlockLayout {
2447 row: u32,
2448 element: AnyElement<Editor>,
2449 style: BlockStyle,
2450}
2451
2452fn layout_line(
2453 row: u32,
2454 snapshot: &EditorSnapshot,
2455 style: &EditorStyle,
2456 layout_cache: &TextLayoutCache,
2457) -> text_layout::Line {
2458 let mut line = snapshot.line(row);
2459
2460 if line.len() > MAX_LINE_LEN {
2461 let mut len = MAX_LINE_LEN;
2462 while !line.is_char_boundary(len) {
2463 len -= 1;
2464 }
2465
2466 line.truncate(len);
2467 }
2468
2469 layout_cache.layout_str(
2470 &line,
2471 style.text.font_size,
2472 &[(
2473 snapshot.line_len(row) as usize,
2474 RunStyle {
2475 font_id: style.text.font_id,
2476 color: Color::black(),
2477 underline: Default::default(),
2478 },
2479 )],
2480 )
2481}
2482
2483#[derive(Debug)]
2484pub struct Cursor {
2485 origin: Vector2F,
2486 block_width: f32,
2487 line_height: f32,
2488 color: Color,
2489 shape: CursorShape,
2490 block_text: Option<Line>,
2491}
2492
2493impl Cursor {
2494 pub fn new(
2495 origin: Vector2F,
2496 block_width: f32,
2497 line_height: f32,
2498 color: Color,
2499 shape: CursorShape,
2500 block_text: Option<Line>,
2501 ) -> Cursor {
2502 Cursor {
2503 origin,
2504 block_width,
2505 line_height,
2506 color,
2507 shape,
2508 block_text,
2509 }
2510 }
2511
2512 pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2513 RectF::new(
2514 self.origin + origin,
2515 vec2f(self.block_width, self.line_height),
2516 )
2517 }
2518
2519 pub fn paint(&self, scene: &mut SceneBuilder, origin: Vector2F, cx: &mut WindowContext) {
2520 let bounds = match self.shape {
2521 CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2522 CursorShape::Block | CursorShape::Hollow => RectF::new(
2523 self.origin + origin,
2524 vec2f(self.block_width, self.line_height),
2525 ),
2526 CursorShape::Underscore => RectF::new(
2527 self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2528 vec2f(self.block_width, 2.0),
2529 ),
2530 };
2531
2532 //Draw background or border quad
2533 if matches!(self.shape, CursorShape::Hollow) {
2534 scene.push_quad(Quad {
2535 bounds,
2536 background: None,
2537 border: Border::all(1., self.color),
2538 corner_radius: 0.,
2539 });
2540 } else {
2541 scene.push_quad(Quad {
2542 bounds,
2543 background: Some(self.color),
2544 border: Default::default(),
2545 corner_radius: 0.,
2546 });
2547 }
2548
2549 if let Some(block_text) = &self.block_text {
2550 block_text.paint(scene, self.origin + origin, bounds, self.line_height, cx);
2551 }
2552 }
2553
2554 pub fn shape(&self) -> CursorShape {
2555 self.shape
2556 }
2557}
2558
2559#[derive(Debug)]
2560pub struct HighlightedRange {
2561 pub start_y: f32,
2562 pub line_height: f32,
2563 pub lines: Vec<HighlightedRangeLine>,
2564 pub color: Color,
2565 pub corner_radius: f32,
2566}
2567
2568#[derive(Debug)]
2569pub struct HighlightedRangeLine {
2570 pub start_x: f32,
2571 pub end_x: f32,
2572}
2573
2574impl HighlightedRange {
2575 pub fn paint(&self, bounds: RectF, scene: &mut SceneBuilder) {
2576 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2577 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2578 self.paint_lines(
2579 self.start_y + self.line_height,
2580 &self.lines[1..],
2581 bounds,
2582 scene,
2583 );
2584 } else {
2585 self.paint_lines(self.start_y, &self.lines, bounds, scene);
2586 }
2587 }
2588
2589 fn paint_lines(
2590 &self,
2591 start_y: f32,
2592 lines: &[HighlightedRangeLine],
2593 bounds: RectF,
2594 scene: &mut SceneBuilder,
2595 ) {
2596 if lines.is_empty() {
2597 return;
2598 }
2599
2600 let mut path = PathBuilder::new();
2601 let first_line = lines.first().unwrap();
2602 let last_line = lines.last().unwrap();
2603
2604 let first_top_left = vec2f(first_line.start_x, start_y);
2605 let first_top_right = vec2f(first_line.end_x, start_y);
2606
2607 let curve_height = vec2f(0., self.corner_radius);
2608 let curve_width = |start_x: f32, end_x: f32| {
2609 let max = (end_x - start_x) / 2.;
2610 let width = if max < self.corner_radius {
2611 max
2612 } else {
2613 self.corner_radius
2614 };
2615
2616 vec2f(width, 0.)
2617 };
2618
2619 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2620 path.reset(first_top_right - top_curve_width);
2621 path.curve_to(first_top_right + curve_height, first_top_right);
2622
2623 let mut iter = lines.iter().enumerate().peekable();
2624 while let Some((ix, line)) = iter.next() {
2625 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2626
2627 if let Some((_, next_line)) = iter.peek() {
2628 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2629
2630 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2631 Ordering::Equal => {
2632 path.line_to(bottom_right);
2633 }
2634 Ordering::Less => {
2635 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2636 path.line_to(bottom_right - curve_height);
2637 if self.corner_radius > 0. {
2638 path.curve_to(bottom_right - curve_width, bottom_right);
2639 }
2640 path.line_to(next_top_right + curve_width);
2641 if self.corner_radius > 0. {
2642 path.curve_to(next_top_right + curve_height, next_top_right);
2643 }
2644 }
2645 Ordering::Greater => {
2646 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2647 path.line_to(bottom_right - curve_height);
2648 if self.corner_radius > 0. {
2649 path.curve_to(bottom_right + curve_width, bottom_right);
2650 }
2651 path.line_to(next_top_right - curve_width);
2652 if self.corner_radius > 0. {
2653 path.curve_to(next_top_right + curve_height, next_top_right);
2654 }
2655 }
2656 }
2657 } else {
2658 let curve_width = curve_width(line.start_x, line.end_x);
2659 path.line_to(bottom_right - curve_height);
2660 if self.corner_radius > 0. {
2661 path.curve_to(bottom_right - curve_width, bottom_right);
2662 }
2663
2664 let bottom_left = vec2f(line.start_x, bottom_right.y());
2665 path.line_to(bottom_left + curve_width);
2666 if self.corner_radius > 0. {
2667 path.curve_to(bottom_left - curve_height, bottom_left);
2668 }
2669 }
2670 }
2671
2672 if first_line.start_x > last_line.start_x {
2673 let curve_width = curve_width(last_line.start_x, first_line.start_x);
2674 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2675 path.line_to(second_top_left + curve_height);
2676 if self.corner_radius > 0. {
2677 path.curve_to(second_top_left + curve_width, second_top_left);
2678 }
2679 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2680 path.line_to(first_bottom_left - curve_width);
2681 if self.corner_radius > 0. {
2682 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2683 }
2684 }
2685
2686 path.line_to(first_top_left + curve_height);
2687 if self.corner_radius > 0. {
2688 path.curve_to(first_top_left + top_curve_width, first_top_left);
2689 }
2690 path.line_to(first_top_right - top_curve_width);
2691
2692 scene.push_path(path.build(self.color, Some(bounds)));
2693 }
2694}
2695
2696fn position_to_display_point(
2697 position: Vector2F,
2698 text_bounds: RectF,
2699 position_map: &PositionMap,
2700) -> Option<DisplayPoint> {
2701 if text_bounds.contains_point(position) {
2702 let (point, target_point) = position_map.point_for_position(text_bounds, position);
2703 if point == target_point {
2704 Some(point)
2705 } else {
2706 None
2707 }
2708 } else {
2709 None
2710 }
2711}
2712
2713fn range_to_bounds(
2714 range: &Range<DisplayPoint>,
2715 content_origin: Vector2F,
2716 scroll_left: f32,
2717 scroll_top: f32,
2718 visible_row_range: &Range<u32>,
2719 line_end_overshoot: f32,
2720 position_map: &PositionMap,
2721) -> impl Iterator<Item = RectF> {
2722 let mut bounds: SmallVec<[RectF; 1]> = SmallVec::new();
2723
2724 if range.start == range.end {
2725 return bounds.into_iter();
2726 }
2727
2728 let start_row = visible_row_range.start;
2729 let end_row = visible_row_range.end;
2730
2731 let row_range = if range.end.column() == 0 {
2732 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2733 } else {
2734 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2735 };
2736
2737 let first_y =
2738 content_origin.y() + row_range.start as f32 * position_map.line_height - scroll_top;
2739
2740 for (idx, row) in row_range.enumerate() {
2741 let line_layout = &position_map.line_layouts[(row - start_row) as usize].line;
2742
2743 let start_x = if row == range.start.row() {
2744 content_origin.x() + line_layout.x_for_index(range.start.column() as usize)
2745 - scroll_left
2746 } else {
2747 content_origin.x() - scroll_left
2748 };
2749
2750 let end_x = if row == range.end.row() {
2751 content_origin.x() + line_layout.x_for_index(range.end.column() as usize) - scroll_left
2752 } else {
2753 content_origin.x() + line_layout.width() + line_end_overshoot - scroll_left
2754 };
2755
2756 bounds.push(RectF::from_points(
2757 vec2f(start_x, first_y + position_map.line_height * idx as f32),
2758 vec2f(end_x, first_y + position_map.line_height * (idx + 1) as f32),
2759 ))
2760 }
2761
2762 bounds.into_iter()
2763}
2764
2765pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2766 delta.powf(1.5) / 100.0
2767}
2768
2769fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
2770 delta.powf(1.2) / 300.0
2771}
2772
2773#[cfg(test)]
2774mod tests {
2775 use super::*;
2776 use crate::{
2777 display_map::{BlockDisposition, BlockProperties},
2778 editor_tests::{init_test, update_test_settings},
2779 Editor, MultiBuffer,
2780 };
2781 use gpui::TestAppContext;
2782 use language::language_settings;
2783 use log::info;
2784 use std::{num::NonZeroU32, sync::Arc};
2785 use util::test::sample_text;
2786
2787 #[gpui::test]
2788 fn test_layout_line_numbers(cx: &mut TestAppContext) {
2789 init_test(cx, |_| {});
2790
2791 let (_, editor) = cx.add_window(|cx| {
2792 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
2793 Editor::new(EditorMode::Full, buffer, None, None, cx)
2794 });
2795 let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
2796
2797 let layouts = editor.update(cx, |editor, cx| {
2798 let snapshot = editor.snapshot(cx);
2799 element
2800 .layout_line_numbers(0..6, &Default::default(), false, &snapshot, cx)
2801 .0
2802 });
2803 assert_eq!(layouts.len(), 6);
2804 }
2805
2806 #[gpui::test]
2807 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
2808 init_test(cx, |_| {});
2809
2810 let (_, editor) = cx.add_window(|cx| {
2811 let buffer = MultiBuffer::build_simple("", cx);
2812 Editor::new(EditorMode::Full, buffer, None, None, cx)
2813 });
2814
2815 editor.update(cx, |editor, cx| {
2816 editor.set_placeholder_text("hello", cx);
2817 editor.insert_blocks(
2818 [BlockProperties {
2819 style: BlockStyle::Fixed,
2820 disposition: BlockDisposition::Above,
2821 height: 3,
2822 position: Anchor::min(),
2823 render: Arc::new(|_| Empty::new().into_any()),
2824 }],
2825 cx,
2826 );
2827
2828 // Blur the editor so that it displays placeholder text.
2829 cx.blur();
2830 });
2831
2832 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
2833 let (size, mut state) = editor.update(cx, |editor, cx| {
2834 let mut new_parents = Default::default();
2835 let mut notify_views_if_parents_change = Default::default();
2836 let mut layout_cx = LayoutContext::new(
2837 cx,
2838 &mut new_parents,
2839 &mut notify_views_if_parents_change,
2840 false,
2841 );
2842 element.layout(
2843 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
2844 editor,
2845 &mut layout_cx,
2846 )
2847 });
2848
2849 assert_eq!(state.position_map.line_layouts.len(), 4);
2850 assert_eq!(
2851 state
2852 .line_number_layouts
2853 .iter()
2854 .map(Option::is_some)
2855 .collect::<Vec<_>>(),
2856 &[false, false, false, true]
2857 );
2858
2859 // Don't panic.
2860 let mut scene = SceneBuilder::new(1.0);
2861 let bounds = RectF::new(Default::default(), size);
2862 editor.update(cx, |editor, cx| {
2863 element.paint(&mut scene, bounds, bounds, &mut state, editor, cx);
2864 });
2865 }
2866
2867 #[gpui::test]
2868 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
2869 const TAB_SIZE: u32 = 4;
2870
2871 let input_text = "\t \t|\t| a b";
2872 let expected_invisibles = vec![
2873 Invisible::Tab {
2874 line_start_offset: 0,
2875 },
2876 Invisible::Whitespace {
2877 line_offset: TAB_SIZE as usize,
2878 },
2879 Invisible::Tab {
2880 line_start_offset: TAB_SIZE as usize + 1,
2881 },
2882 Invisible::Tab {
2883 line_start_offset: TAB_SIZE as usize * 2 + 1,
2884 },
2885 Invisible::Whitespace {
2886 line_offset: TAB_SIZE as usize * 3 + 1,
2887 },
2888 Invisible::Whitespace {
2889 line_offset: TAB_SIZE as usize * 3 + 3,
2890 },
2891 ];
2892 assert_eq!(
2893 expected_invisibles.len(),
2894 input_text
2895 .chars()
2896 .filter(|initial_char| initial_char.is_whitespace())
2897 .count(),
2898 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
2899 );
2900
2901 init_test(cx, |s| {
2902 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
2903 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
2904 });
2905
2906 let actual_invisibles =
2907 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
2908
2909 assert_eq!(expected_invisibles, actual_invisibles);
2910 }
2911
2912 #[gpui::test]
2913 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
2914 init_test(cx, |s| {
2915 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
2916 s.defaults.tab_size = NonZeroU32::new(4);
2917 });
2918
2919 for editor_mode_without_invisibles in [
2920 EditorMode::SingleLine,
2921 EditorMode::AutoHeight { max_lines: 100 },
2922 ] {
2923 let invisibles = collect_invisibles_from_new_editor(
2924 cx,
2925 editor_mode_without_invisibles,
2926 "\t\t\t| | a b",
2927 500.0,
2928 );
2929 assert!(invisibles.is_empty(),
2930 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
2931 }
2932 }
2933
2934 #[gpui::test]
2935 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
2936 let tab_size = 4;
2937 let input_text = "a\tbcd ".repeat(9);
2938 let repeated_invisibles = [
2939 Invisible::Tab {
2940 line_start_offset: 1,
2941 },
2942 Invisible::Whitespace {
2943 line_offset: tab_size as usize + 3,
2944 },
2945 Invisible::Whitespace {
2946 line_offset: tab_size as usize + 4,
2947 },
2948 Invisible::Whitespace {
2949 line_offset: tab_size as usize + 5,
2950 },
2951 ];
2952 let expected_invisibles = std::iter::once(repeated_invisibles)
2953 .cycle()
2954 .take(9)
2955 .flatten()
2956 .collect::<Vec<_>>();
2957 assert_eq!(
2958 expected_invisibles.len(),
2959 input_text
2960 .chars()
2961 .filter(|initial_char| initial_char.is_whitespace())
2962 .count(),
2963 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
2964 );
2965 info!("Expected invisibles: {expected_invisibles:?}");
2966
2967 init_test(cx, |_| {});
2968
2969 // Put the same string with repeating whitespace pattern into editors of various size,
2970 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
2971 let resize_step = 10.0;
2972 let mut editor_width = 200.0;
2973 while editor_width <= 1000.0 {
2974 update_test_settings(cx, |s| {
2975 s.defaults.tab_size = NonZeroU32::new(tab_size);
2976 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
2977 s.defaults.preferred_line_length = Some(editor_width as u32);
2978 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
2979 });
2980
2981 let actual_invisibles =
2982 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
2983
2984 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
2985 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
2986 let mut i = 0;
2987 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
2988 i = actual_index;
2989 match expected_invisibles.get(i) {
2990 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
2991 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
2992 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
2993 _ => {
2994 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
2995 }
2996 },
2997 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
2998 }
2999 }
3000 let missing_expected_invisibles = &expected_invisibles[i + 1..];
3001 assert!(
3002 missing_expected_invisibles.is_empty(),
3003 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
3004 );
3005
3006 editor_width += resize_step;
3007 }
3008 }
3009
3010 fn collect_invisibles_from_new_editor(
3011 cx: &mut TestAppContext,
3012 editor_mode: EditorMode,
3013 input_text: &str,
3014 editor_width: f32,
3015 ) -> Vec<Invisible> {
3016 info!(
3017 "Creating editor with mode {editor_mode:?}, witdh {editor_width} and text '{input_text}'"
3018 );
3019 let (_, editor) = cx.add_window(|cx| {
3020 let buffer = MultiBuffer::build_simple(&input_text, cx);
3021 Editor::new(editor_mode, buffer, None, None, cx)
3022 });
3023
3024 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3025 let (_, layout_state) = editor.update(cx, |editor, cx| {
3026 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
3027 editor.set_wrap_width(Some(editor_width), cx);
3028
3029 let mut new_parents = Default::default();
3030 let mut notify_views_if_parents_change = Default::default();
3031 let mut layout_cx = LayoutContext::new(
3032 cx,
3033 &mut new_parents,
3034 &mut notify_views_if_parents_change,
3035 false,
3036 );
3037 element.layout(
3038 SizeConstraint::new(vec2f(editor_width, 500.), vec2f(editor_width, 500.)),
3039 editor,
3040 &mut layout_cx,
3041 )
3042 });
3043
3044 layout_state
3045 .position_map
3046 .line_layouts
3047 .iter()
3048 .map(|line_with_invisibles| &line_with_invisibles.invisibles)
3049 .flatten()
3050 .cloned()
3051 .collect()
3052 }
3053}