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