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