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 clock::ReplicaId;
21use collections::{BTreeMap, HashMap};
22use git::diff::DiffHunkStatus;
23use gpui::{
24 color::Color,
25 elements::*,
26 fonts::{HighlightStyle, TextStyle, Underline},
27 geometry::{
28 rect::RectF,
29 vector::{vec2f, Vector2F},
30 PathBuilder,
31 },
32 json::{self, ToJson},
33 platform::{CursorStyle, Modifiers, MouseButton, MouseButtonEvent, MouseMovedEvent},
34 text_layout::{self, Line, RunStyle, TextLayoutCache},
35 AnyElement, Axis, CursorRegion, Element, EventContext, FontCache, MouseRegion, Quad,
36 SizeConstraint, ViewContext, WindowContext,
37};
38use itertools::Itertools;
39use json::json;
40use language::{
41 language_settings::ShowWhitespaceSetting, Bias, CursorShape, DiagnosticSeverity, OffsetUtf16,
42 Selection,
43};
44use project::{
45 project_settings::{GitGutterSetting, ProjectSettings},
46 ProjectPath,
47};
48use smallvec::SmallVec;
49use std::{
50 borrow::Cow,
51 cmp::{self, Ordering},
52 fmt::Write,
53 iter,
54 ops::Range,
55 sync::Arc,
56};
57use text::Point;
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 (replica_id, selections) in &layout.selections {
872 let replica_id = *replica_id;
873 let selection_style = if let Some(replica_id) = replica_id {
874 style.replica_selection_style(replica_id)
875 } else {
876 &style.absent_selection
877 };
878
879 for selection in selections {
880 self.paint_highlighted_range(
881 selection.range.clone(),
882 selection_style.selection,
883 corner_radius,
884 corner_radius * 2.,
885 layout,
886 content_origin,
887 scroll_top,
888 scroll_left,
889 bounds,
890 cx,
891 );
892
893 if selection.is_local && !selection.range.is_empty() {
894 invisible_display_ranges.push(selection.range.clone());
895 }
896 if !selection.is_local || editor.show_local_cursors(cx) {
897 let cursor_position = selection.head;
898 if layout
899 .visible_display_row_range
900 .contains(&cursor_position.row())
901 {
902 let cursor_row_layout = &layout.position_map.line_layouts
903 [(cursor_position.row() - start_row) as usize]
904 .line;
905 let cursor_column = cursor_position.column() as usize;
906
907 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
908 let mut block_width =
909 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
910 if block_width == 0.0 {
911 block_width = layout.position_map.em_width;
912 }
913 let block_text = if let CursorShape::Block = selection.cursor_shape {
914 layout
915 .position_map
916 .snapshot
917 .chars_at(cursor_position)
918 .next()
919 .and_then(|(character, _)| {
920 let font_id =
921 cursor_row_layout.font_for_index(cursor_column)?;
922 let text = character.to_string();
923
924 Some(cx.text_layout_cache().layout_str(
925 &text,
926 cursor_row_layout.font_size(),
927 &[(
928 text.chars().count(),
929 RunStyle {
930 font_id,
931 color: style.background,
932 underline: Default::default(),
933 },
934 )],
935 ))
936 })
937 } else {
938 None
939 };
940
941 let x = cursor_character_x - scroll_left;
942 let y = cursor_position.row() as f32 * layout.position_map.line_height
943 - scroll_top;
944 if selection.is_newest {
945 editor.pixel_position_of_newest_cursor = Some(vec2f(
946 bounds.origin_x() + x + block_width / 2.,
947 bounds.origin_y() + y + layout.position_map.line_height / 2.,
948 ));
949 }
950 cursors.push(Cursor {
951 color: selection_style.cursor,
952 block_width,
953 origin: vec2f(x, y),
954 line_height: layout.position_map.line_height,
955 shape: selection.cursor_shape,
956 block_text,
957 });
958 }
959 }
960 }
961 }
962
963 if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
964 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
965 let row = start_row + ix as u32;
966 line_with_invisibles.draw(
967 layout,
968 row,
969 scroll_top,
970 content_origin,
971 scroll_left,
972 visible_text_bounds,
973 whitespace_setting,
974 &invisible_display_ranges,
975 visible_bounds,
976 cx,
977 )
978 }
979 }
980
981 cx.scene().push_layer(Some(bounds));
982 for cursor in cursors {
983 cursor.paint(content_origin, cx);
984 }
985 cx.scene().pop_layer();
986
987 if let Some((position, context_menu)) = layout.context_menu.as_mut() {
988 cx.scene().push_stacking_context(None, None);
989 let cursor_row_layout =
990 &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
991 let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
992 let y = (position.row() + 1) as f32 * layout.position_map.line_height - scroll_top;
993 let mut list_origin = content_origin + vec2f(x, y);
994 let list_width = context_menu.size().x();
995 let list_height = context_menu.size().y();
996
997 // Snap the right edge of the list to the right edge of the window if
998 // its horizontal bounds overflow.
999 if list_origin.x() + list_width > cx.window_size().x() {
1000 list_origin.set_x((cx.window_size().x() - list_width).max(0.));
1001 }
1002
1003 if list_origin.y() + list_height > bounds.max_y() {
1004 list_origin.set_y(list_origin.y() - layout.position_map.line_height - list_height);
1005 }
1006
1007 context_menu.paint(
1008 list_origin,
1009 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
1010 editor,
1011 cx,
1012 );
1013
1014 cx.scene().pop_stacking_context();
1015 }
1016
1017 if let Some((position, hover_popovers)) = layout.hover_popovers.as_mut() {
1018 cx.scene().push_stacking_context(None, None);
1019
1020 // This is safe because we check on layout whether the required row is available
1021 let hovered_row_layout =
1022 &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
1023
1024 // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
1025 // height. This is the size we will use to decide whether to render popovers above or below
1026 // the hovered line.
1027 let first_size = hover_popovers[0].size();
1028 let height_to_reserve = first_size.y()
1029 + 1.5 * MIN_POPOVER_LINE_HEIGHT as f32 * layout.position_map.line_height;
1030
1031 // Compute Hovered Point
1032 let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
1033 let y = position.row() as f32 * layout.position_map.line_height - scroll_top;
1034 let hovered_point = content_origin + vec2f(x, y);
1035
1036 if hovered_point.y() - height_to_reserve > 0.0 {
1037 // There is enough space above. Render popovers above the hovered point
1038 let mut current_y = hovered_point.y();
1039 for hover_popover in hover_popovers {
1040 let size = hover_popover.size();
1041 let mut popover_origin = vec2f(hovered_point.x(), current_y - size.y());
1042
1043 let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
1044 if x_out_of_bounds < 0.0 {
1045 popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
1046 }
1047
1048 hover_popover.paint(
1049 popover_origin,
1050 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
1051 editor,
1052 cx,
1053 );
1054
1055 current_y = popover_origin.y() - HOVER_POPOVER_GAP;
1056 }
1057 } else {
1058 // There is not enough space above. Render popovers below the hovered point
1059 let mut current_y = hovered_point.y() + layout.position_map.line_height;
1060 for hover_popover in hover_popovers {
1061 let size = hover_popover.size();
1062 let mut popover_origin = vec2f(hovered_point.x(), current_y);
1063
1064 let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
1065 if x_out_of_bounds < 0.0 {
1066 popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
1067 }
1068
1069 hover_popover.paint(
1070 popover_origin,
1071 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
1072 editor,
1073 cx,
1074 );
1075
1076 current_y = popover_origin.y() + size.y() + HOVER_POPOVER_GAP;
1077 }
1078 }
1079
1080 cx.scene().pop_stacking_context();
1081 }
1082
1083 cx.scene().pop_layer();
1084 }
1085
1086 fn scrollbar_left(&self, bounds: &RectF) -> f32 {
1087 bounds.max_x() - self.style.theme.scrollbar.width
1088 }
1089
1090 fn paint_scrollbar(
1091 &mut self,
1092 bounds: RectF,
1093 layout: &mut LayoutState,
1094 editor: &Editor,
1095 cx: &mut ViewContext<Editor>,
1096 ) {
1097 enum ScrollbarMouseHandlers {}
1098 if layout.mode != EditorMode::Full {
1099 return;
1100 }
1101
1102 let style = &self.style.theme.scrollbar;
1103
1104 let top = bounds.min_y();
1105 let bottom = bounds.max_y();
1106 let right = bounds.max_x();
1107 let left = self.scrollbar_left(&bounds);
1108 let row_range = &layout.scrollbar_row_range;
1109 let max_row = layout.max_row as f32 + (row_range.end - row_range.start);
1110
1111 let mut height = bounds.height();
1112 let mut first_row_y_offset = 0.0;
1113
1114 // Impose a minimum height on the scrollbar thumb
1115 let row_height = height / max_row;
1116 let min_thumb_height =
1117 style.min_height_factor * cx.font_cache.line_height(self.style.text.font_size);
1118 let thumb_height = (row_range.end - row_range.start) * row_height;
1119 if thumb_height < min_thumb_height {
1120 first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
1121 height -= min_thumb_height - thumb_height;
1122 }
1123
1124 let y_for_row = |row: f32| -> f32 { top + first_row_y_offset + row * row_height };
1125
1126 let thumb_top = y_for_row(row_range.start) - first_row_y_offset;
1127 let thumb_bottom = y_for_row(row_range.end) + first_row_y_offset;
1128 let track_bounds = RectF::from_points(vec2f(left, top), vec2f(right, bottom));
1129 let thumb_bounds = RectF::from_points(vec2f(left, thumb_top), vec2f(right, thumb_bottom));
1130
1131 if layout.show_scrollbars {
1132 cx.scene().push_quad(Quad {
1133 bounds: track_bounds,
1134 border: style.track.border.into(),
1135 background: style.track.background_color,
1136 ..Default::default()
1137 });
1138 let scrollbar_settings = settings::get::<EditorSettings>(cx).scrollbar;
1139 let theme = theme::current(cx);
1140 let scrollbar_theme = &theme.editor.scrollbar;
1141 if layout.is_singleton && scrollbar_settings.selections {
1142 let start_anchor = Anchor::min();
1143 let end_anchor = Anchor::max();
1144 let color = scrollbar_theme.selections;
1145 let border = Border {
1146 width: 1.,
1147 color: style.thumb.border.color,
1148 overlay: false,
1149 top: false,
1150 right: true,
1151 bottom: false,
1152 left: true,
1153 };
1154 let mut push_region = |start: DisplayPoint, end: DisplayPoint| {
1155 let start_y = y_for_row(start.row() as f32);
1156 let mut end_y = y_for_row(end.row() as f32);
1157 if end_y - start_y < 1. {
1158 end_y = start_y + 1.;
1159 }
1160 let bounds = RectF::from_points(vec2f(left, start_y), vec2f(right, end_y));
1161
1162 cx.scene().push_quad(Quad {
1163 bounds,
1164 background: Some(color),
1165 border: border.into(),
1166 corner_radii: style.thumb.corner_radii.into(),
1167 })
1168 };
1169 let background_ranges = editor
1170 .background_highlight_row_ranges::<crate::items::BufferSearchHighlights>(
1171 start_anchor..end_anchor,
1172 &layout.position_map.snapshot,
1173 50000,
1174 );
1175 for row in background_ranges {
1176 let start = row.start();
1177 let end = row.end();
1178 push_region(*start, *end);
1179 }
1180 }
1181
1182 if layout.is_singleton && scrollbar_settings.git_diff {
1183 let diff_style = scrollbar_theme.git.clone();
1184 for hunk in layout
1185 .position_map
1186 .snapshot
1187 .buffer_snapshot
1188 .git_diff_hunks_in_range(0..(max_row.floor() as u32))
1189 {
1190 let start_display = Point::new(hunk.buffer_range.start, 0)
1191 .to_display_point(&layout.position_map.snapshot.display_snapshot);
1192 let end_display = Point::new(hunk.buffer_range.end, 0)
1193 .to_display_point(&layout.position_map.snapshot.display_snapshot);
1194 let start_y = y_for_row(start_display.row() as f32);
1195 let mut end_y = if hunk.buffer_range.start == hunk.buffer_range.end {
1196 y_for_row((end_display.row() + 1) as f32)
1197 } else {
1198 y_for_row((end_display.row()) as f32)
1199 };
1200
1201 if end_y - start_y < 1. {
1202 end_y = start_y + 1.;
1203 }
1204 let bounds = RectF::from_points(vec2f(left, start_y), vec2f(right, end_y));
1205
1206 let color = match hunk.status() {
1207 DiffHunkStatus::Added => diff_style.inserted,
1208 DiffHunkStatus::Modified => diff_style.modified,
1209 DiffHunkStatus::Removed => diff_style.deleted,
1210 };
1211
1212 let border = Border {
1213 width: 1.,
1214 color: style.thumb.border.color,
1215 overlay: false,
1216 top: false,
1217 right: true,
1218 bottom: false,
1219 left: true,
1220 };
1221
1222 cx.scene().push_quad(Quad {
1223 bounds,
1224 background: Some(color),
1225 border: border.into(),
1226 corner_radii: style.thumb.corner_radii.into(),
1227 })
1228 }
1229 }
1230
1231 cx.scene().push_quad(Quad {
1232 bounds: thumb_bounds,
1233 border: style.thumb.border.into(),
1234 background: style.thumb.background_color,
1235 corner_radii: style.thumb.corner_radii.into(),
1236 });
1237 }
1238
1239 cx.scene().push_cursor_region(CursorRegion {
1240 bounds: track_bounds,
1241 style: CursorStyle::Arrow,
1242 });
1243 let region_id = cx.view_id();
1244 cx.scene().push_mouse_region(
1245 MouseRegion::new::<ScrollbarMouseHandlers>(region_id, region_id, track_bounds)
1246 .on_move(move |event, editor: &mut Editor, cx| {
1247 if event.pressed_button.is_none() {
1248 editor.scroll_manager.show_scrollbar(cx);
1249 }
1250 })
1251 .on_down(MouseButton::Left, {
1252 let row_range = row_range.clone();
1253 move |event, editor: &mut Editor, cx| {
1254 let y = event.position.y();
1255 if y < thumb_top || thumb_bottom < y {
1256 let center_row = ((y - top) * max_row as f32 / height).round() as u32;
1257 let top_row = center_row
1258 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
1259 let mut position = editor.scroll_position(cx);
1260 position.set_y(top_row as f32);
1261 editor.set_scroll_position(position, cx);
1262 } else {
1263 editor.scroll_manager.show_scrollbar(cx);
1264 }
1265 }
1266 })
1267 .on_drag(MouseButton::Left, {
1268 move |event, editor: &mut Editor, cx| {
1269 if event.end {
1270 return;
1271 }
1272
1273 let y = event.prev_mouse_position.y();
1274 let new_y = event.position.y();
1275 if thumb_top < y && y < thumb_bottom {
1276 let mut position = editor.scroll_position(cx);
1277 position.set_y(position.y() + (new_y - y) * (max_row as f32) / height);
1278 if position.y() < 0.0 {
1279 position.set_y(0.);
1280 }
1281 editor.set_scroll_position(position, cx);
1282 }
1283 }
1284 }),
1285 );
1286 }
1287
1288 #[allow(clippy::too_many_arguments)]
1289 fn paint_highlighted_range(
1290 &self,
1291 range: Range<DisplayPoint>,
1292 color: Color,
1293 corner_radius: f32,
1294 line_end_overshoot: f32,
1295 layout: &LayoutState,
1296 content_origin: Vector2F,
1297 scroll_top: f32,
1298 scroll_left: f32,
1299 bounds: RectF,
1300 cx: &mut ViewContext<Editor>,
1301 ) {
1302 let start_row = layout.visible_display_row_range.start;
1303 let end_row = layout.visible_display_row_range.end;
1304 if range.start != range.end {
1305 let row_range = if range.end.column() == 0 {
1306 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
1307 } else {
1308 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
1309 };
1310
1311 let highlighted_range = HighlightedRange {
1312 color,
1313 line_height: layout.position_map.line_height,
1314 corner_radius,
1315 start_y: content_origin.y()
1316 + row_range.start as f32 * layout.position_map.line_height
1317 - scroll_top,
1318 lines: row_range
1319 .into_iter()
1320 .map(|row| {
1321 let line_layout =
1322 &layout.position_map.line_layouts[(row - start_row) as usize].line;
1323 HighlightedRangeLine {
1324 start_x: if row == range.start.row() {
1325 content_origin.x()
1326 + line_layout.x_for_index(range.start.column() as usize)
1327 - scroll_left
1328 } else {
1329 content_origin.x() - scroll_left
1330 },
1331 end_x: if row == range.end.row() {
1332 content_origin.x()
1333 + line_layout.x_for_index(range.end.column() as usize)
1334 - scroll_left
1335 } else {
1336 content_origin.x() + line_layout.width() + line_end_overshoot
1337 - scroll_left
1338 },
1339 }
1340 })
1341 .collect(),
1342 };
1343
1344 highlighted_range.paint(bounds, cx);
1345 }
1346 }
1347
1348 fn paint_blocks(
1349 &mut self,
1350 bounds: RectF,
1351 visible_bounds: RectF,
1352 layout: &mut LayoutState,
1353 editor: &mut Editor,
1354 cx: &mut ViewContext<Editor>,
1355 ) {
1356 let scroll_position = layout.position_map.snapshot.scroll_position();
1357 let scroll_left = scroll_position.x() * layout.position_map.em_width;
1358 let scroll_top = scroll_position.y() * layout.position_map.line_height;
1359
1360 for block in &mut layout.blocks {
1361 let mut origin = bounds.origin()
1362 + vec2f(
1363 0.,
1364 block.row as f32 * layout.position_map.line_height - scroll_top,
1365 );
1366 if !matches!(block.style, BlockStyle::Sticky) {
1367 origin += vec2f(-scroll_left, 0.);
1368 }
1369 block.element.paint(origin, visible_bounds, editor, cx);
1370 }
1371 }
1372
1373 fn column_pixels(&self, column: usize, cx: &ViewContext<Editor>) -> f32 {
1374 let style = &self.style;
1375
1376 cx.text_layout_cache()
1377 .layout_str(
1378 " ".repeat(column).as_str(),
1379 style.text.font_size,
1380 &[(
1381 column,
1382 RunStyle {
1383 font_id: style.text.font_id,
1384 color: Color::black(),
1385 underline: Default::default(),
1386 },
1387 )],
1388 )
1389 .width()
1390 }
1391
1392 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &ViewContext<Editor>) -> f32 {
1393 let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
1394 self.column_pixels(digit_count, cx)
1395 }
1396
1397 //Folds contained in a hunk are ignored apart from shrinking visual size
1398 //If a fold contains any hunks then that fold line is marked as modified
1399 fn layout_git_gutters(
1400 &self,
1401 display_rows: Range<u32>,
1402 snapshot: &EditorSnapshot,
1403 ) -> Vec<DisplayDiffHunk> {
1404 let buffer_snapshot = &snapshot.buffer_snapshot;
1405
1406 let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1407 .to_point(snapshot)
1408 .row;
1409 let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1410 .to_point(snapshot)
1411 .row;
1412
1413 buffer_snapshot
1414 .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1415 .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1416 .dedup()
1417 .collect()
1418 }
1419
1420 fn calculate_relative_line_numbers(
1421 &self,
1422 snapshot: &EditorSnapshot,
1423 rows: &Range<u32>,
1424 relative_to: Option<u32>,
1425 ) -> HashMap<u32, u32> {
1426 let mut relative_rows: HashMap<u32, u32> = Default::default();
1427 let Some(relative_to) = relative_to else {
1428 return relative_rows;
1429 };
1430
1431 let start = rows.start.min(relative_to);
1432 let end = rows.end.max(relative_to);
1433
1434 let buffer_rows = snapshot
1435 .buffer_rows(start)
1436 .take(1 + (end - start) as usize)
1437 .collect::<Vec<_>>();
1438
1439 let head_idx = relative_to - start;
1440 let mut delta = 1;
1441 let mut i = head_idx + 1;
1442 while i < buffer_rows.len() as u32 {
1443 if buffer_rows[i as usize].is_some() {
1444 if rows.contains(&(i + start)) {
1445 relative_rows.insert(i + start, delta);
1446 }
1447 delta += 1;
1448 }
1449 i += 1;
1450 }
1451 delta = 1;
1452 i = head_idx.min(buffer_rows.len() as u32 - 1);
1453 while i > 0 && buffer_rows[i as usize].is_none() {
1454 i -= 1;
1455 }
1456
1457 while i > 0 {
1458 i -= 1;
1459 if buffer_rows[i as usize].is_some() {
1460 if rows.contains(&(i + start)) {
1461 relative_rows.insert(i + start, delta);
1462 }
1463 delta += 1;
1464 }
1465 }
1466
1467 relative_rows
1468 }
1469
1470 fn layout_line_numbers(
1471 &self,
1472 rows: Range<u32>,
1473 active_rows: &BTreeMap<u32, bool>,
1474 newest_selection_head: DisplayPoint,
1475 is_singleton: bool,
1476 snapshot: &EditorSnapshot,
1477 cx: &ViewContext<Editor>,
1478 ) -> (
1479 Vec<Option<text_layout::Line>>,
1480 Vec<Option<(FoldStatus, BufferRow, bool)>>,
1481 ) {
1482 let style = &self.style;
1483 let include_line_numbers = snapshot.mode == EditorMode::Full;
1484 let mut line_number_layouts = Vec::with_capacity(rows.len());
1485 let mut fold_statuses = Vec::with_capacity(rows.len());
1486 let mut line_number = String::new();
1487 let is_relative = settings::get::<EditorSettings>(cx).relative_line_numbers;
1488 let relative_to = if is_relative {
1489 Some(newest_selection_head.row())
1490 } else {
1491 None
1492 };
1493
1494 let relative_rows = self.calculate_relative_line_numbers(&snapshot, &rows, relative_to);
1495
1496 for (ix, row) in snapshot
1497 .buffer_rows(rows.start)
1498 .take((rows.end - rows.start) as usize)
1499 .enumerate()
1500 {
1501 let display_row = rows.start + ix as u32;
1502 let (active, color) = if active_rows.contains_key(&display_row) {
1503 (true, style.line_number_active)
1504 } else {
1505 (false, style.line_number)
1506 };
1507 if let Some(buffer_row) = row {
1508 if include_line_numbers {
1509 line_number.clear();
1510 let default_number = buffer_row + 1;
1511 let number = relative_rows
1512 .get(&(ix as u32 + rows.start))
1513 .unwrap_or(&default_number);
1514 write!(&mut line_number, "{}", number).unwrap();
1515 line_number_layouts.push(Some(cx.text_layout_cache().layout_str(
1516 &line_number,
1517 style.text.font_size,
1518 &[(
1519 line_number.len(),
1520 RunStyle {
1521 font_id: style.text.font_id,
1522 color,
1523 underline: Default::default(),
1524 },
1525 )],
1526 )));
1527 fold_statuses.push(
1528 is_singleton
1529 .then(|| {
1530 snapshot
1531 .fold_for_line(buffer_row)
1532 .map(|fold_status| (fold_status, buffer_row, active))
1533 })
1534 .flatten(),
1535 )
1536 }
1537 } else {
1538 fold_statuses.push(None);
1539 line_number_layouts.push(None);
1540 }
1541 }
1542
1543 (line_number_layouts, fold_statuses)
1544 }
1545
1546 fn layout_lines(
1547 &mut self,
1548 rows: Range<u32>,
1549 line_number_layouts: &[Option<Line>],
1550 snapshot: &EditorSnapshot,
1551 cx: &ViewContext<Editor>,
1552 ) -> Vec<LineWithInvisibles> {
1553 if rows.start >= rows.end {
1554 return Vec::new();
1555 }
1556
1557 // When the editor is empty and unfocused, then show the placeholder.
1558 if snapshot.is_empty() {
1559 let placeholder_style = self
1560 .style
1561 .placeholder_text
1562 .as_ref()
1563 .unwrap_or(&self.style.text);
1564 let placeholder_text = snapshot.placeholder_text();
1565 let placeholder_lines = placeholder_text
1566 .as_ref()
1567 .map_or("", AsRef::as_ref)
1568 .split('\n')
1569 .skip(rows.start as usize)
1570 .chain(iter::repeat(""))
1571 .take(rows.len());
1572 placeholder_lines
1573 .map(|line| {
1574 cx.text_layout_cache().layout_str(
1575 line,
1576 placeholder_style.font_size,
1577 &[(
1578 line.len(),
1579 RunStyle {
1580 font_id: placeholder_style.font_id,
1581 color: placeholder_style.color,
1582 underline: Default::default(),
1583 },
1584 )],
1585 )
1586 })
1587 .map(|line| LineWithInvisibles {
1588 line,
1589 invisibles: Vec::new(),
1590 })
1591 .collect()
1592 } else {
1593 let style = &self.style;
1594 let chunks = snapshot
1595 .chunks(
1596 rows.clone(),
1597 true,
1598 Some(style.theme.hint),
1599 Some(style.theme.suggestion),
1600 )
1601 .map(|chunk| {
1602 let mut highlight_style = chunk
1603 .syntax_highlight_id
1604 .and_then(|id| id.style(&style.syntax));
1605
1606 if let Some(chunk_highlight) = chunk.highlight_style {
1607 if let Some(highlight_style) = highlight_style.as_mut() {
1608 highlight_style.highlight(chunk_highlight);
1609 } else {
1610 highlight_style = Some(chunk_highlight);
1611 }
1612 }
1613
1614 let mut diagnostic_highlight = HighlightStyle::default();
1615
1616 if chunk.is_unnecessary {
1617 diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
1618 }
1619
1620 if let Some(severity) = chunk.diagnostic_severity {
1621 // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
1622 if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
1623 let diagnostic_style = super::diagnostic_style(severity, true, style);
1624 diagnostic_highlight.underline = Some(Underline {
1625 color: Some(diagnostic_style.message.text.color),
1626 thickness: 1.0.into(),
1627 squiggly: true,
1628 });
1629 }
1630 }
1631
1632 if let Some(highlight_style) = highlight_style.as_mut() {
1633 highlight_style.highlight(diagnostic_highlight);
1634 } else {
1635 highlight_style = Some(diagnostic_highlight);
1636 }
1637
1638 HighlightedChunk {
1639 chunk: chunk.text,
1640 style: highlight_style,
1641 is_tab: chunk.is_tab,
1642 }
1643 });
1644
1645 LineWithInvisibles::from_chunks(
1646 chunks,
1647 &style.text,
1648 cx.text_layout_cache(),
1649 cx.font_cache(),
1650 MAX_LINE_LEN,
1651 rows.len() as usize,
1652 line_number_layouts,
1653 snapshot.mode,
1654 )
1655 }
1656 }
1657
1658 #[allow(clippy::too_many_arguments)]
1659 fn layout_blocks(
1660 &mut self,
1661 rows: Range<u32>,
1662 snapshot: &EditorSnapshot,
1663 editor_width: f32,
1664 scroll_width: f32,
1665 gutter_padding: f32,
1666 gutter_width: f32,
1667 em_width: f32,
1668 text_x: f32,
1669 line_height: f32,
1670 style: &EditorStyle,
1671 line_layouts: &[LineWithInvisibles],
1672 editor: &mut Editor,
1673 cx: &mut ViewContext<Editor>,
1674 ) -> (f32, Vec<BlockLayout>) {
1675 let mut block_id = 0;
1676 let scroll_x = snapshot.scroll_anchor.offset.x();
1677 let (fixed_blocks, non_fixed_blocks) = snapshot
1678 .blocks_in_range(rows.clone())
1679 .partition::<Vec<_>, _>(|(_, block)| match block {
1680 TransformBlock::ExcerptHeader { .. } => false,
1681 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1682 });
1683 let mut render_block = |block: &TransformBlock, width: f32, block_id: usize| {
1684 let mut element = match block {
1685 TransformBlock::Custom(block) => {
1686 let align_to = block
1687 .position()
1688 .to_point(&snapshot.buffer_snapshot)
1689 .to_display_point(snapshot);
1690 let anchor_x = text_x
1691 + if rows.contains(&align_to.row()) {
1692 line_layouts[(align_to.row() - rows.start) as usize]
1693 .line
1694 .x_for_index(align_to.column() as usize)
1695 } else {
1696 layout_line(align_to.row(), snapshot, style, cx.text_layout_cache())
1697 .x_for_index(align_to.column() as usize)
1698 };
1699
1700 block.render(&mut BlockContext {
1701 view_context: cx,
1702 anchor_x,
1703 gutter_padding,
1704 line_height,
1705 scroll_x,
1706 gutter_width,
1707 em_width,
1708 block_id,
1709 })
1710 }
1711 TransformBlock::ExcerptHeader {
1712 id,
1713 buffer,
1714 range,
1715 starts_new_buffer,
1716 ..
1717 } => {
1718 let tooltip_style = theme::current(cx).tooltip.clone();
1719 let include_root = editor
1720 .project
1721 .as_ref()
1722 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1723 .unwrap_or_default();
1724 let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1725 let jump_path = ProjectPath {
1726 worktree_id: file.worktree_id(cx),
1727 path: file.path.clone(),
1728 };
1729 let jump_anchor = range
1730 .primary
1731 .as_ref()
1732 .map_or(range.context.start, |primary| primary.start);
1733 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1734
1735 enum JumpIcon {}
1736 MouseEventHandler::new::<JumpIcon, _>((*id).into(), cx, |state, _| {
1737 let style = style.jump_icon.style_for(state);
1738 Svg::new("icons/arrow_up_right.svg")
1739 .with_color(style.color)
1740 .constrained()
1741 .with_width(style.icon_width)
1742 .aligned()
1743 .contained()
1744 .with_style(style.container)
1745 .constrained()
1746 .with_width(style.button_width)
1747 .with_height(style.button_width)
1748 })
1749 .with_cursor_style(CursorStyle::PointingHand)
1750 .on_click(MouseButton::Left, move |_, editor, cx| {
1751 if let Some(workspace) = editor
1752 .workspace
1753 .as_ref()
1754 .and_then(|(workspace, _)| workspace.upgrade(cx))
1755 {
1756 workspace.update(cx, |workspace, cx| {
1757 Editor::jump(
1758 workspace,
1759 jump_path.clone(),
1760 jump_position,
1761 jump_anchor,
1762 cx,
1763 );
1764 });
1765 }
1766 })
1767 .with_tooltip::<JumpIcon>(
1768 (*id).into(),
1769 "Jump to Buffer".to_string(),
1770 Some(Box::new(crate::OpenExcerpts)),
1771 tooltip_style.clone(),
1772 cx,
1773 )
1774 .aligned()
1775 .flex_float()
1776 });
1777
1778 if *starts_new_buffer {
1779 let editor_font_size = style.text.font_size;
1780 let style = &style.diagnostic_path_header;
1781 let font_size = (style.text_scale_factor * editor_font_size).round();
1782
1783 let path = buffer.resolve_file_path(cx, include_root);
1784 let mut filename = None;
1785 let mut parent_path = None;
1786 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1787 if let Some(path) = path {
1788 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1789 parent_path =
1790 path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1791 }
1792
1793 Flex::row()
1794 .with_child(
1795 Label::new(
1796 filename.unwrap_or_else(|| "untitled".to_string()),
1797 style.filename.text.clone().with_font_size(font_size),
1798 )
1799 .contained()
1800 .with_style(style.filename.container)
1801 .aligned(),
1802 )
1803 .with_children(parent_path.map(|path| {
1804 Label::new(path, style.path.text.clone().with_font_size(font_size))
1805 .contained()
1806 .with_style(style.path.container)
1807 .aligned()
1808 }))
1809 .with_children(jump_icon)
1810 .contained()
1811 .with_style(style.container)
1812 .with_padding_left(gutter_padding)
1813 .with_padding_right(gutter_padding)
1814 .expanded()
1815 .into_any_named("path header block")
1816 } else {
1817 let text_style = style.text.clone();
1818 Flex::row()
1819 .with_child(Label::new("⋯", text_style))
1820 .with_children(jump_icon)
1821 .contained()
1822 .with_padding_left(gutter_padding)
1823 .with_padding_right(gutter_padding)
1824 .expanded()
1825 .into_any_named("collapsed context")
1826 }
1827 }
1828 };
1829
1830 element.layout(
1831 SizeConstraint {
1832 min: Vector2F::zero(),
1833 max: vec2f(width, block.height() as f32 * line_height),
1834 },
1835 editor,
1836 cx,
1837 );
1838 element
1839 };
1840
1841 let mut fixed_block_max_width = 0f32;
1842 let mut blocks = Vec::new();
1843 for (row, block) in fixed_blocks {
1844 let element = render_block(block, f32::INFINITY, block_id);
1845 block_id += 1;
1846 fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1847 blocks.push(BlockLayout {
1848 row,
1849 element,
1850 style: BlockStyle::Fixed,
1851 });
1852 }
1853 for (row, block) in non_fixed_blocks {
1854 let style = match block {
1855 TransformBlock::Custom(block) => block.style(),
1856 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1857 };
1858 let width = match style {
1859 BlockStyle::Sticky => editor_width,
1860 BlockStyle::Flex => editor_width
1861 .max(fixed_block_max_width)
1862 .max(gutter_width + scroll_width),
1863 BlockStyle::Fixed => unreachable!(),
1864 };
1865 let element = render_block(block, width, block_id);
1866 block_id += 1;
1867 blocks.push(BlockLayout {
1868 row,
1869 element,
1870 style,
1871 });
1872 }
1873 (
1874 scroll_width.max(fixed_block_max_width - gutter_width),
1875 blocks,
1876 )
1877 }
1878}
1879
1880struct HighlightedChunk<'a> {
1881 chunk: &'a str,
1882 style: Option<HighlightStyle>,
1883 is_tab: bool,
1884}
1885
1886#[derive(Debug)]
1887pub struct LineWithInvisibles {
1888 pub line: Line,
1889 invisibles: Vec<Invisible>,
1890}
1891
1892impl LineWithInvisibles {
1893 fn from_chunks<'a>(
1894 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
1895 text_style: &TextStyle,
1896 text_layout_cache: &TextLayoutCache,
1897 font_cache: &Arc<FontCache>,
1898 max_line_len: usize,
1899 max_line_count: usize,
1900 line_number_layouts: &[Option<Line>],
1901 editor_mode: EditorMode,
1902 ) -> Vec<Self> {
1903 let mut layouts = Vec::with_capacity(max_line_count);
1904 let mut line = String::new();
1905 let mut invisibles = Vec::new();
1906 let mut styles = Vec::new();
1907 let mut non_whitespace_added = false;
1908 let mut row = 0;
1909 let mut line_exceeded_max_len = false;
1910 for highlighted_chunk in chunks.chain([HighlightedChunk {
1911 chunk: "\n",
1912 style: None,
1913 is_tab: false,
1914 }]) {
1915 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
1916 if ix > 0 {
1917 layouts.push(Self {
1918 line: text_layout_cache.layout_str(&line, text_style.font_size, &styles),
1919 invisibles: invisibles.drain(..).collect(),
1920 });
1921
1922 line.clear();
1923 styles.clear();
1924 row += 1;
1925 line_exceeded_max_len = false;
1926 non_whitespace_added = false;
1927 if row == max_line_count {
1928 return layouts;
1929 }
1930 }
1931
1932 if !line_chunk.is_empty() && !line_exceeded_max_len {
1933 let text_style = if let Some(style) = highlighted_chunk.style {
1934 text_style
1935 .clone()
1936 .highlight(style, font_cache)
1937 .map(Cow::Owned)
1938 .unwrap_or_else(|_| Cow::Borrowed(text_style))
1939 } else {
1940 Cow::Borrowed(text_style)
1941 };
1942
1943 if line.len() + line_chunk.len() > max_line_len {
1944 let mut chunk_len = max_line_len - line.len();
1945 while !line_chunk.is_char_boundary(chunk_len) {
1946 chunk_len -= 1;
1947 }
1948 line_chunk = &line_chunk[..chunk_len];
1949 line_exceeded_max_len = true;
1950 }
1951
1952 styles.push((
1953 line_chunk.len(),
1954 RunStyle {
1955 font_id: text_style.font_id,
1956 color: text_style.color,
1957 underline: text_style.underline,
1958 },
1959 ));
1960
1961 if editor_mode == EditorMode::Full {
1962 // Line wrap pads its contents with fake whitespaces,
1963 // avoid printing them
1964 let inside_wrapped_string = line_number_layouts
1965 .get(row)
1966 .and_then(|layout| layout.as_ref())
1967 .is_none();
1968 if highlighted_chunk.is_tab {
1969 if non_whitespace_added || !inside_wrapped_string {
1970 invisibles.push(Invisible::Tab {
1971 line_start_offset: line.len(),
1972 });
1973 }
1974 } else {
1975 invisibles.extend(
1976 line_chunk
1977 .chars()
1978 .enumerate()
1979 .filter(|(_, line_char)| {
1980 let is_whitespace = line_char.is_whitespace();
1981 non_whitespace_added |= !is_whitespace;
1982 is_whitespace
1983 && (non_whitespace_added || !inside_wrapped_string)
1984 })
1985 .map(|(whitespace_index, _)| Invisible::Whitespace {
1986 line_offset: line.len() + whitespace_index,
1987 }),
1988 )
1989 }
1990 }
1991
1992 line.push_str(line_chunk);
1993 }
1994 }
1995 }
1996
1997 layouts
1998 }
1999
2000 fn draw(
2001 &self,
2002 layout: &LayoutState,
2003 row: u32,
2004 scroll_top: f32,
2005 content_origin: Vector2F,
2006 scroll_left: f32,
2007 visible_text_bounds: RectF,
2008 whitespace_setting: ShowWhitespaceSetting,
2009 selection_ranges: &[Range<DisplayPoint>],
2010 visible_bounds: RectF,
2011 cx: &mut ViewContext<Editor>,
2012 ) {
2013 let line_height = layout.position_map.line_height;
2014 let line_y = row as f32 * line_height - scroll_top;
2015
2016 self.line.paint(
2017 content_origin + vec2f(-scroll_left, line_y),
2018 visible_text_bounds,
2019 line_height,
2020 cx,
2021 );
2022
2023 self.draw_invisibles(
2024 &selection_ranges,
2025 layout,
2026 content_origin,
2027 scroll_left,
2028 line_y,
2029 row,
2030 visible_bounds,
2031 line_height,
2032 whitespace_setting,
2033 cx,
2034 );
2035 }
2036
2037 fn draw_invisibles(
2038 &self,
2039 selection_ranges: &[Range<DisplayPoint>],
2040 layout: &LayoutState,
2041 content_origin: Vector2F,
2042 scroll_left: f32,
2043 line_y: f32,
2044 row: u32,
2045 visible_bounds: RectF,
2046 line_height: f32,
2047 whitespace_setting: ShowWhitespaceSetting,
2048 cx: &mut ViewContext<Editor>,
2049 ) {
2050 let allowed_invisibles_regions = match whitespace_setting {
2051 ShowWhitespaceSetting::None => return,
2052 ShowWhitespaceSetting::Selection => Some(selection_ranges),
2053 ShowWhitespaceSetting::All => None,
2054 };
2055
2056 for invisible in &self.invisibles {
2057 let (&token_offset, invisible_symbol) = match invisible {
2058 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
2059 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
2060 };
2061
2062 let x_offset = self.line.x_for_index(token_offset);
2063 let invisible_offset =
2064 (layout.position_map.em_width - invisible_symbol.width()).max(0.0) / 2.0;
2065 let origin = content_origin + vec2f(-scroll_left + x_offset + invisible_offset, line_y);
2066
2067 if let Some(allowed_regions) = allowed_invisibles_regions {
2068 let invisible_point = DisplayPoint::new(row, token_offset as u32);
2069 if !allowed_regions
2070 .iter()
2071 .any(|region| region.start <= invisible_point && invisible_point < region.end)
2072 {
2073 continue;
2074 }
2075 }
2076 invisible_symbol.paint(origin, visible_bounds, line_height, cx);
2077 }
2078 }
2079}
2080
2081#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2082enum Invisible {
2083 Tab { line_start_offset: usize },
2084 Whitespace { line_offset: usize },
2085}
2086
2087impl Element<Editor> for EditorElement {
2088 type LayoutState = LayoutState;
2089 type PaintState = ();
2090
2091 fn layout(
2092 &mut self,
2093 constraint: SizeConstraint,
2094 editor: &mut Editor,
2095 cx: &mut ViewContext<Editor>,
2096 ) -> (Vector2F, Self::LayoutState) {
2097 let mut size = constraint.max;
2098 if size.x().is_infinite() {
2099 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
2100 }
2101
2102 let snapshot = editor.snapshot(cx);
2103 let style = self.style.clone();
2104
2105 let line_height = (style.text.font_size * style.line_height_scalar).round();
2106
2107 let gutter_padding;
2108 let gutter_width;
2109 let gutter_margin;
2110 if snapshot.show_gutter {
2111 let em_width = style.text.em_width(cx.font_cache());
2112 gutter_padding = (em_width * style.gutter_padding_factor).round();
2113 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
2114 gutter_margin = -style.text.descent(cx.font_cache());
2115 } else {
2116 gutter_padding = 0.0;
2117 gutter_width = 0.0;
2118 gutter_margin = 0.0;
2119 };
2120
2121 let text_width = size.x() - gutter_width;
2122 let em_width = style.text.em_width(cx.font_cache());
2123 let em_advance = style.text.em_advance(cx.font_cache());
2124 let overscroll = vec2f(em_width, 0.);
2125 let snapshot = {
2126 editor.set_visible_line_count(size.y() / line_height, cx);
2127
2128 let editor_width = text_width - gutter_margin - overscroll.x() - em_width;
2129 let wrap_width = match editor.soft_wrap_mode(cx) {
2130 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
2131 SoftWrap::EditorWidth => editor_width,
2132 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
2133 };
2134
2135 if editor.set_wrap_width(Some(wrap_width), cx) {
2136 editor.snapshot(cx)
2137 } else {
2138 snapshot
2139 }
2140 };
2141
2142 let wrap_guides = editor
2143 .wrap_guides(cx)
2144 .iter()
2145 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
2146 .collect();
2147
2148 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
2149 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
2150 size.set_y(
2151 scroll_height
2152 .min(constraint.max_along(Axis::Vertical))
2153 .max(constraint.min_along(Axis::Vertical))
2154 .max(line_height)
2155 .min(line_height * max_lines as f32),
2156 )
2157 } else if let EditorMode::SingleLine = snapshot.mode {
2158 size.set_y(line_height.max(constraint.min_along(Axis::Vertical)))
2159 } else if size.y().is_infinite() {
2160 size.set_y(scroll_height);
2161 }
2162 let gutter_size = vec2f(gutter_width, size.y());
2163 let text_size = vec2f(text_width, size.y());
2164
2165 let autoscroll_horizontally = editor.autoscroll_vertically(size.y(), line_height, cx);
2166 let mut snapshot = editor.snapshot(cx);
2167
2168 let scroll_position = snapshot.scroll_position();
2169 // The scroll position is a fractional point, the whole number of which represents
2170 // the top of the window in terms of display rows.
2171 let start_row = scroll_position.y() as u32;
2172 let height_in_lines = size.y() / line_height;
2173 let max_row = snapshot.max_point().row();
2174
2175 // Add 1 to ensure selections bleed off screen
2176 let end_row = 1 + cmp::min(
2177 (scroll_position.y() + height_in_lines).ceil() as u32,
2178 max_row,
2179 );
2180
2181 let start_anchor = if start_row == 0 {
2182 Anchor::min()
2183 } else {
2184 snapshot
2185 .buffer_snapshot
2186 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
2187 };
2188 let end_anchor = if end_row > max_row {
2189 Anchor::max()
2190 } else {
2191 snapshot
2192 .buffer_snapshot
2193 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
2194 };
2195
2196 let mut selections: Vec<(Option<ReplicaId>, Vec<SelectionLayout>)> = Vec::new();
2197 let mut active_rows = BTreeMap::new();
2198 let mut fold_ranges = Vec::new();
2199 let is_singleton = editor.is_singleton(cx);
2200
2201 let highlighted_rows = editor.highlighted_rows();
2202 let theme = theme::current(cx);
2203 let highlighted_ranges = editor.background_highlights_in_range(
2204 start_anchor..end_anchor,
2205 &snapshot.display_snapshot,
2206 theme.as_ref(),
2207 );
2208
2209 fold_ranges.extend(
2210 snapshot
2211 .folds_in_range(start_anchor..end_anchor)
2212 .map(|anchor| {
2213 let start = anchor.start.to_point(&snapshot.buffer_snapshot);
2214 (
2215 start.row,
2216 start.to_display_point(&snapshot.display_snapshot)
2217 ..anchor.end.to_display_point(&snapshot),
2218 )
2219 }),
2220 );
2221
2222 let mut remote_selections = HashMap::default();
2223 for (replica_id, line_mode, cursor_shape, selection) in snapshot
2224 .buffer_snapshot
2225 .remote_selections_in_range(&(start_anchor..end_anchor))
2226 {
2227 let replica_id = if let Some(mapping) = &editor.replica_id_mapping {
2228 mapping.get(&replica_id).copied()
2229 } else {
2230 Some(replica_id)
2231 };
2232
2233 // The local selections match the leader's selections.
2234 if replica_id.is_some() && replica_id == editor.leader_replica_id {
2235 continue;
2236 }
2237 remote_selections
2238 .entry(replica_id)
2239 .or_insert(Vec::new())
2240 .push(SelectionLayout::new(
2241 selection,
2242 line_mode,
2243 cursor_shape,
2244 &snapshot.display_snapshot,
2245 false,
2246 false,
2247 ));
2248 }
2249 selections.extend(remote_selections);
2250
2251 let mut newest_selection_head = None;
2252
2253 if editor.show_local_selections {
2254 let mut local_selections: Vec<Selection<Point>> = editor
2255 .selections
2256 .disjoint_in_range(start_anchor..end_anchor, cx);
2257 local_selections.extend(editor.selections.pending(cx));
2258 let mut layouts = Vec::new();
2259 let newest = editor.selections.newest(cx);
2260 for selection in local_selections.drain(..) {
2261 let is_empty = selection.start == selection.end;
2262 let is_newest = selection == newest;
2263
2264 let layout = SelectionLayout::new(
2265 selection,
2266 editor.selections.line_mode,
2267 editor.cursor_shape,
2268 &snapshot.display_snapshot,
2269 is_newest,
2270 true,
2271 );
2272 if is_newest {
2273 newest_selection_head = Some(layout.head);
2274 }
2275
2276 for row in cmp::max(layout.active_rows.start, start_row)
2277 ..=cmp::min(layout.active_rows.end, end_row)
2278 {
2279 let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2280 *contains_non_empty_selection |= !is_empty;
2281 }
2282 layouts.push(layout);
2283 }
2284
2285 // Render the local selections in the leader's color when following.
2286 let local_replica_id = if let Some(leader_replica_id) = editor.leader_replica_id {
2287 leader_replica_id
2288 } else {
2289 let replica_id = editor.replica_id(cx);
2290 if let Some(mapping) = &editor.replica_id_mapping {
2291 mapping.get(&replica_id).copied().unwrap_or(replica_id)
2292 } else {
2293 replica_id
2294 }
2295 };
2296
2297 selections.push((Some(local_replica_id), layouts));
2298 }
2299
2300 let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
2301 let show_scrollbars = match scrollbar_settings.show {
2302 ShowScrollbar::Auto => {
2303 // Git
2304 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2305 ||
2306 // Selections
2307 (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty())
2308 // Scrollmanager
2309 || editor.scroll_manager.scrollbars_visible()
2310 }
2311 ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2312 ShowScrollbar::Always => true,
2313 ShowScrollbar::Never => false,
2314 };
2315
2316 let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2317 .into_iter()
2318 .map(|(id, fold)| {
2319 let color = self
2320 .style
2321 .folds
2322 .ellipses
2323 .background
2324 .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
2325 .color;
2326
2327 (id, fold, color)
2328 })
2329 .collect();
2330
2331 let head_for_relative = newest_selection_head.unwrap_or_else(|| {
2332 let newest = editor.selections.newest::<Point>(cx);
2333 SelectionLayout::new(
2334 newest,
2335 editor.selections.line_mode,
2336 editor.cursor_shape,
2337 &snapshot.display_snapshot,
2338 true,
2339 true,
2340 )
2341 .head
2342 });
2343
2344 let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2345 start_row..end_row,
2346 &active_rows,
2347 head_for_relative,
2348 is_singleton,
2349 &snapshot,
2350 cx,
2351 );
2352
2353 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2354
2355 let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
2356
2357 let mut max_visible_line_width = 0.0;
2358 let line_layouts =
2359 self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2360 for line_with_invisibles in &line_layouts {
2361 if line_with_invisibles.line.width() > max_visible_line_width {
2362 max_visible_line_width = line_with_invisibles.line.width();
2363 }
2364 }
2365
2366 let style = self.style.clone();
2367 let longest_line_width = layout_line(
2368 snapshot.longest_row(),
2369 &snapshot,
2370 &style,
2371 cx.text_layout_cache(),
2372 )
2373 .width();
2374 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
2375 let em_width = style.text.em_width(cx.font_cache());
2376 let (scroll_width, blocks) = self.layout_blocks(
2377 start_row..end_row,
2378 &snapshot,
2379 size.x(),
2380 scroll_width,
2381 gutter_padding,
2382 gutter_width,
2383 em_width,
2384 gutter_width + gutter_margin,
2385 line_height,
2386 &style,
2387 &line_layouts,
2388 editor,
2389 cx,
2390 );
2391
2392 let scroll_max = vec2f(
2393 ((scroll_width - text_size.x()) / em_width).max(0.0),
2394 max_row as f32,
2395 );
2396
2397 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x());
2398
2399 let autoscrolled = if autoscroll_horizontally {
2400 editor.autoscroll_horizontally(
2401 start_row,
2402 text_size.x(),
2403 scroll_width,
2404 em_width,
2405 &line_layouts,
2406 cx,
2407 )
2408 } else {
2409 false
2410 };
2411
2412 if clamped || autoscrolled {
2413 snapshot = editor.snapshot(cx);
2414 }
2415
2416 let style = editor.style(cx);
2417
2418 let mut context_menu = None;
2419 let mut code_actions_indicator = None;
2420 if let Some(newest_selection_head) = newest_selection_head {
2421 if (start_row..end_row).contains(&newest_selection_head.row()) {
2422 if editor.context_menu_visible() {
2423 context_menu =
2424 editor.render_context_menu(newest_selection_head, style.clone(), cx);
2425 }
2426
2427 let active = matches!(
2428 editor.context_menu,
2429 Some(crate::ContextMenu::CodeActions(_))
2430 );
2431
2432 code_actions_indicator = editor
2433 .render_code_actions_indicator(&style, active, cx)
2434 .map(|indicator| (newest_selection_head.row(), indicator));
2435 }
2436 }
2437
2438 let visible_rows = start_row..start_row + line_layouts.len() as u32;
2439 let mut hover = editor
2440 .hover_state
2441 .render(&snapshot, &style, visible_rows, cx);
2442 let mode = editor.mode;
2443
2444 let mut fold_indicators = editor.render_fold_indicators(
2445 fold_statuses,
2446 &style,
2447 editor.gutter_hovered,
2448 line_height,
2449 gutter_margin,
2450 cx,
2451 );
2452
2453 if let Some((_, context_menu)) = context_menu.as_mut() {
2454 context_menu.layout(
2455 SizeConstraint {
2456 min: Vector2F::zero(),
2457 max: vec2f(
2458 cx.window_size().x() * 0.7,
2459 (12. * line_height).min((size.y() - line_height) / 2.),
2460 ),
2461 },
2462 editor,
2463 cx,
2464 );
2465 }
2466
2467 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
2468 indicator.layout(
2469 SizeConstraint::strict_along(
2470 Axis::Vertical,
2471 line_height * style.code_actions.vertical_scale,
2472 ),
2473 editor,
2474 cx,
2475 );
2476 }
2477
2478 for fold_indicator in fold_indicators.iter_mut() {
2479 if let Some(indicator) = fold_indicator.as_mut() {
2480 indicator.layout(
2481 SizeConstraint::strict_along(
2482 Axis::Vertical,
2483 line_height * style.code_actions.vertical_scale,
2484 ),
2485 editor,
2486 cx,
2487 );
2488 }
2489 }
2490
2491 if let Some((_, hover_popovers)) = hover.as_mut() {
2492 for hover_popover in hover_popovers.iter_mut() {
2493 hover_popover.layout(
2494 SizeConstraint {
2495 min: Vector2F::zero(),
2496 max: vec2f(
2497 (120. * em_width) // Default size
2498 .min(size.x() / 2.) // Shrink to half of the editor width
2499 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2500 (16. * line_height) // Default size
2501 .min(size.y() / 2.) // Shrink to half of the editor height
2502 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2503 ),
2504 },
2505 editor,
2506 cx,
2507 );
2508 }
2509 }
2510
2511 let invisible_symbol_font_size = self.style.text.font_size / 2.0;
2512 let invisible_symbol_style = RunStyle {
2513 color: self.style.whitespace,
2514 font_id: self.style.text.font_id,
2515 underline: Default::default(),
2516 };
2517
2518 (
2519 size,
2520 LayoutState {
2521 mode,
2522 position_map: Arc::new(PositionMap {
2523 size,
2524 scroll_max,
2525 line_layouts,
2526 line_height,
2527 em_width,
2528 em_advance,
2529 snapshot,
2530 }),
2531 visible_display_row_range: start_row..end_row,
2532 wrap_guides,
2533 gutter_size,
2534 gutter_padding,
2535 text_size,
2536 scrollbar_row_range,
2537 show_scrollbars,
2538 is_singleton,
2539 max_row,
2540 gutter_margin,
2541 active_rows,
2542 highlighted_rows,
2543 highlighted_ranges,
2544 fold_ranges,
2545 line_number_layouts,
2546 display_hunks,
2547 blocks,
2548 selections,
2549 context_menu,
2550 code_actions_indicator,
2551 fold_indicators,
2552 tab_invisible: cx.text_layout_cache().layout_str(
2553 "→",
2554 invisible_symbol_font_size,
2555 &[("→".len(), invisible_symbol_style)],
2556 ),
2557 space_invisible: cx.text_layout_cache().layout_str(
2558 "•",
2559 invisible_symbol_font_size,
2560 &[("•".len(), invisible_symbol_style)],
2561 ),
2562 hover_popovers: hover,
2563 },
2564 )
2565 }
2566
2567 fn paint(
2568 &mut self,
2569 bounds: RectF,
2570 visible_bounds: RectF,
2571 layout: &mut Self::LayoutState,
2572 editor: &mut Editor,
2573 cx: &mut ViewContext<Editor>,
2574 ) -> Self::PaintState {
2575 let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2576 cx.scene().push_layer(Some(visible_bounds));
2577
2578 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
2579 let text_bounds = RectF::new(
2580 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2581 layout.text_size,
2582 );
2583
2584 Self::attach_mouse_handlers(
2585 &layout.position_map,
2586 layout.hover_popovers.is_some(),
2587 visible_bounds,
2588 text_bounds,
2589 gutter_bounds,
2590 bounds,
2591 cx,
2592 );
2593
2594 self.paint_background(gutter_bounds, text_bounds, layout, cx);
2595 if layout.gutter_size.x() > 0. {
2596 self.paint_gutter(gutter_bounds, visible_bounds, layout, editor, cx);
2597 }
2598 self.paint_text(text_bounds, visible_bounds, layout, editor, cx);
2599
2600 cx.scene().push_layer(Some(bounds));
2601 if !layout.blocks.is_empty() {
2602 self.paint_blocks(bounds, visible_bounds, layout, editor, cx);
2603 }
2604 self.paint_scrollbar(bounds, layout, &editor, cx);
2605 cx.scene().pop_layer();
2606 cx.scene().pop_layer();
2607 }
2608
2609 fn rect_for_text_range(
2610 &self,
2611 range_utf16: Range<usize>,
2612 bounds: RectF,
2613 _: RectF,
2614 layout: &Self::LayoutState,
2615 _: &Self::PaintState,
2616 _: &Editor,
2617 _: &ViewContext<Editor>,
2618 ) -> Option<RectF> {
2619 let text_bounds = RectF::new(
2620 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2621 layout.text_size,
2622 );
2623 let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
2624 let scroll_position = layout.position_map.snapshot.scroll_position();
2625 let start_row = scroll_position.y() as u32;
2626 let scroll_top = scroll_position.y() * layout.position_map.line_height;
2627 let scroll_left = scroll_position.x() * layout.position_map.em_width;
2628
2629 let range_start = OffsetUtf16(range_utf16.start)
2630 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2631 if range_start.row() < start_row {
2632 return None;
2633 }
2634
2635 let line = &layout
2636 .position_map
2637 .line_layouts
2638 .get((range_start.row() - start_row) as usize)?
2639 .line;
2640 let range_start_x = line.x_for_index(range_start.column() as usize);
2641 let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
2642 Some(RectF::new(
2643 content_origin
2644 + vec2f(
2645 range_start_x,
2646 range_start_y + layout.position_map.line_height,
2647 )
2648 - vec2f(scroll_left, scroll_top),
2649 vec2f(
2650 layout.position_map.em_width,
2651 layout.position_map.line_height,
2652 ),
2653 ))
2654 }
2655
2656 fn debug(
2657 &self,
2658 bounds: RectF,
2659 _: &Self::LayoutState,
2660 _: &Self::PaintState,
2661 _: &Editor,
2662 _: &ViewContext<Editor>,
2663 ) -> json::Value {
2664 json!({
2665 "type": "BufferElement",
2666 "bounds": bounds.to_json()
2667 })
2668 }
2669}
2670
2671type BufferRow = u32;
2672
2673pub struct LayoutState {
2674 position_map: Arc<PositionMap>,
2675 gutter_size: Vector2F,
2676 gutter_padding: f32,
2677 gutter_margin: f32,
2678 text_size: Vector2F,
2679 mode: EditorMode,
2680 wrap_guides: SmallVec<[(f32, bool); 2]>,
2681 visible_display_row_range: Range<u32>,
2682 active_rows: BTreeMap<u32, bool>,
2683 highlighted_rows: Option<Range<u32>>,
2684 line_number_layouts: Vec<Option<text_layout::Line>>,
2685 display_hunks: Vec<DisplayDiffHunk>,
2686 blocks: Vec<BlockLayout>,
2687 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2688 fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)>,
2689 selections: Vec<(Option<ReplicaId>, Vec<SelectionLayout>)>,
2690 scrollbar_row_range: Range<f32>,
2691 show_scrollbars: bool,
2692 is_singleton: bool,
2693 max_row: u32,
2694 context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
2695 code_actions_indicator: Option<(u32, AnyElement<Editor>)>,
2696 hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
2697 fold_indicators: Vec<Option<AnyElement<Editor>>>,
2698 tab_invisible: Line,
2699 space_invisible: Line,
2700}
2701
2702struct PositionMap {
2703 size: Vector2F,
2704 line_height: f32,
2705 scroll_max: Vector2F,
2706 em_width: f32,
2707 em_advance: f32,
2708 line_layouts: Vec<LineWithInvisibles>,
2709 snapshot: EditorSnapshot,
2710}
2711
2712#[derive(Debug, Copy, Clone)]
2713pub struct PointForPosition {
2714 pub previous_valid: DisplayPoint,
2715 pub next_valid: DisplayPoint,
2716 pub exact_unclipped: DisplayPoint,
2717 pub column_overshoot_after_line_end: u32,
2718}
2719
2720impl PointForPosition {
2721 #[cfg(test)]
2722 pub fn valid(valid: DisplayPoint) -> Self {
2723 Self {
2724 previous_valid: valid,
2725 next_valid: valid,
2726 exact_unclipped: valid,
2727 column_overshoot_after_line_end: 0,
2728 }
2729 }
2730
2731 pub fn as_valid(&self) -> Option<DisplayPoint> {
2732 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
2733 Some(self.previous_valid)
2734 } else {
2735 None
2736 }
2737 }
2738}
2739
2740impl PositionMap {
2741 fn point_for_position(&self, text_bounds: RectF, position: Vector2F) -> PointForPosition {
2742 let scroll_position = self.snapshot.scroll_position();
2743 let position = position - text_bounds.origin();
2744 let y = position.y().max(0.0).min(self.size.y());
2745 let x = position.x() + (scroll_position.x() * self.em_width);
2746 let row = (y / self.line_height + scroll_position.y()) as u32;
2747 let (column, x_overshoot_after_line_end) = if let Some(line) = self
2748 .line_layouts
2749 .get(row as usize - scroll_position.y() as usize)
2750 .map(|line_with_spaces| &line_with_spaces.line)
2751 {
2752 if let Some(ix) = line.index_for_x(x) {
2753 (ix as u32, 0.0)
2754 } else {
2755 (line.len() as u32, 0f32.max(x - line.width()))
2756 }
2757 } else {
2758 (0, x)
2759 };
2760
2761 let mut exact_unclipped = DisplayPoint::new(row, column);
2762 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
2763 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
2764
2765 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
2766 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
2767 PointForPosition {
2768 previous_valid,
2769 next_valid,
2770 exact_unclipped,
2771 column_overshoot_after_line_end,
2772 }
2773 }
2774}
2775
2776struct BlockLayout {
2777 row: u32,
2778 element: AnyElement<Editor>,
2779 style: BlockStyle,
2780}
2781
2782fn layout_line(
2783 row: u32,
2784 snapshot: &EditorSnapshot,
2785 style: &EditorStyle,
2786 layout_cache: &TextLayoutCache,
2787) -> text_layout::Line {
2788 let mut line = snapshot.line(row);
2789
2790 if line.len() > MAX_LINE_LEN {
2791 let mut len = MAX_LINE_LEN;
2792 while !line.is_char_boundary(len) {
2793 len -= 1;
2794 }
2795
2796 line.truncate(len);
2797 }
2798
2799 layout_cache.layout_str(
2800 &line,
2801 style.text.font_size,
2802 &[(
2803 snapshot.line_len(row) as usize,
2804 RunStyle {
2805 font_id: style.text.font_id,
2806 color: Color::black(),
2807 underline: Default::default(),
2808 },
2809 )],
2810 )
2811}
2812
2813#[derive(Debug)]
2814pub struct Cursor {
2815 origin: Vector2F,
2816 block_width: f32,
2817 line_height: f32,
2818 color: Color,
2819 shape: CursorShape,
2820 block_text: Option<Line>,
2821}
2822
2823impl Cursor {
2824 pub fn new(
2825 origin: Vector2F,
2826 block_width: f32,
2827 line_height: f32,
2828 color: Color,
2829 shape: CursorShape,
2830 block_text: Option<Line>,
2831 ) -> Cursor {
2832 Cursor {
2833 origin,
2834 block_width,
2835 line_height,
2836 color,
2837 shape,
2838 block_text,
2839 }
2840 }
2841
2842 pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2843 RectF::new(
2844 self.origin + origin,
2845 vec2f(self.block_width, self.line_height),
2846 )
2847 }
2848
2849 pub fn paint(&self, origin: Vector2F, cx: &mut WindowContext) {
2850 let bounds = match self.shape {
2851 CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2852 CursorShape::Block | CursorShape::Hollow => RectF::new(
2853 self.origin + origin,
2854 vec2f(self.block_width, self.line_height),
2855 ),
2856 CursorShape::Underscore => RectF::new(
2857 self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2858 vec2f(self.block_width, 2.0),
2859 ),
2860 };
2861
2862 //Draw background or border quad
2863 if matches!(self.shape, CursorShape::Hollow) {
2864 cx.scene().push_quad(Quad {
2865 bounds,
2866 background: None,
2867 border: Border::all(1., self.color).into(),
2868 corner_radii: Default::default(),
2869 });
2870 } else {
2871 cx.scene().push_quad(Quad {
2872 bounds,
2873 background: Some(self.color),
2874 border: Default::default(),
2875 corner_radii: Default::default(),
2876 });
2877 }
2878
2879 if let Some(block_text) = &self.block_text {
2880 block_text.paint(self.origin + origin, bounds, self.line_height, cx);
2881 }
2882 }
2883
2884 pub fn shape(&self) -> CursorShape {
2885 self.shape
2886 }
2887}
2888
2889#[derive(Debug)]
2890pub struct HighlightedRange {
2891 pub start_y: f32,
2892 pub line_height: f32,
2893 pub lines: Vec<HighlightedRangeLine>,
2894 pub color: Color,
2895 pub corner_radius: f32,
2896}
2897
2898#[derive(Debug)]
2899pub struct HighlightedRangeLine {
2900 pub start_x: f32,
2901 pub end_x: f32,
2902}
2903
2904impl HighlightedRange {
2905 pub fn paint(&self, bounds: RectF, cx: &mut WindowContext) {
2906 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2907 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
2908 self.paint_lines(
2909 self.start_y + self.line_height,
2910 &self.lines[1..],
2911 bounds,
2912 cx,
2913 );
2914 } else {
2915 self.paint_lines(self.start_y, &self.lines, bounds, cx);
2916 }
2917 }
2918
2919 fn paint_lines(
2920 &self,
2921 start_y: f32,
2922 lines: &[HighlightedRangeLine],
2923 bounds: RectF,
2924 cx: &mut WindowContext,
2925 ) {
2926 if lines.is_empty() {
2927 return;
2928 }
2929
2930 let mut path = PathBuilder::new();
2931 let first_line = lines.first().unwrap();
2932 let last_line = lines.last().unwrap();
2933
2934 let first_top_left = vec2f(first_line.start_x, start_y);
2935 let first_top_right = vec2f(first_line.end_x, start_y);
2936
2937 let curve_height = vec2f(0., self.corner_radius);
2938 let curve_width = |start_x: f32, end_x: f32| {
2939 let max = (end_x - start_x) / 2.;
2940 let width = if max < self.corner_radius {
2941 max
2942 } else {
2943 self.corner_radius
2944 };
2945
2946 vec2f(width, 0.)
2947 };
2948
2949 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2950 path.reset(first_top_right - top_curve_width);
2951 path.curve_to(first_top_right + curve_height, first_top_right);
2952
2953 let mut iter = lines.iter().enumerate().peekable();
2954 while let Some((ix, line)) = iter.next() {
2955 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2956
2957 if let Some((_, next_line)) = iter.peek() {
2958 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2959
2960 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2961 Ordering::Equal => {
2962 path.line_to(bottom_right);
2963 }
2964 Ordering::Less => {
2965 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2966 path.line_to(bottom_right - curve_height);
2967 if self.corner_radius > 0. {
2968 path.curve_to(bottom_right - curve_width, bottom_right);
2969 }
2970 path.line_to(next_top_right + curve_width);
2971 if self.corner_radius > 0. {
2972 path.curve_to(next_top_right + curve_height, next_top_right);
2973 }
2974 }
2975 Ordering::Greater => {
2976 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2977 path.line_to(bottom_right - curve_height);
2978 if self.corner_radius > 0. {
2979 path.curve_to(bottom_right + curve_width, bottom_right);
2980 }
2981 path.line_to(next_top_right - curve_width);
2982 if self.corner_radius > 0. {
2983 path.curve_to(next_top_right + curve_height, next_top_right);
2984 }
2985 }
2986 }
2987 } else {
2988 let curve_width = curve_width(line.start_x, line.end_x);
2989 path.line_to(bottom_right - curve_height);
2990 if self.corner_radius > 0. {
2991 path.curve_to(bottom_right - curve_width, bottom_right);
2992 }
2993
2994 let bottom_left = vec2f(line.start_x, bottom_right.y());
2995 path.line_to(bottom_left + curve_width);
2996 if self.corner_radius > 0. {
2997 path.curve_to(bottom_left - curve_height, bottom_left);
2998 }
2999 }
3000 }
3001
3002 if first_line.start_x > last_line.start_x {
3003 let curve_width = curve_width(last_line.start_x, first_line.start_x);
3004 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
3005 path.line_to(second_top_left + curve_height);
3006 if self.corner_radius > 0. {
3007 path.curve_to(second_top_left + curve_width, second_top_left);
3008 }
3009 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
3010 path.line_to(first_bottom_left - curve_width);
3011 if self.corner_radius > 0. {
3012 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
3013 }
3014 }
3015
3016 path.line_to(first_top_left + curve_height);
3017 if self.corner_radius > 0. {
3018 path.curve_to(first_top_left + top_curve_width, first_top_left);
3019 }
3020 path.line_to(first_top_right - top_curve_width);
3021
3022 cx.scene().push_path(path.build(self.color, Some(bounds)));
3023 }
3024}
3025
3026fn range_to_bounds(
3027 range: &Range<DisplayPoint>,
3028 content_origin: Vector2F,
3029 scroll_left: f32,
3030 scroll_top: f32,
3031 visible_row_range: &Range<u32>,
3032 line_end_overshoot: f32,
3033 position_map: &PositionMap,
3034) -> impl Iterator<Item = RectF> {
3035 let mut bounds: SmallVec<[RectF; 1]> = SmallVec::new();
3036
3037 if range.start == range.end {
3038 return bounds.into_iter();
3039 }
3040
3041 let start_row = visible_row_range.start;
3042 let end_row = visible_row_range.end;
3043
3044 let row_range = if range.end.column() == 0 {
3045 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3046 } else {
3047 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
3048 };
3049
3050 let first_y =
3051 content_origin.y() + row_range.start as f32 * position_map.line_height - scroll_top;
3052
3053 for (idx, row) in row_range.enumerate() {
3054 let line_layout = &position_map.line_layouts[(row - start_row) as usize].line;
3055
3056 let start_x = if row == range.start.row() {
3057 content_origin.x() + line_layout.x_for_index(range.start.column() as usize)
3058 - scroll_left
3059 } else {
3060 content_origin.x() - scroll_left
3061 };
3062
3063 let end_x = if row == range.end.row() {
3064 content_origin.x() + line_layout.x_for_index(range.end.column() as usize) - scroll_left
3065 } else {
3066 content_origin.x() + line_layout.width() + line_end_overshoot - scroll_left
3067 };
3068
3069 bounds.push(RectF::from_points(
3070 vec2f(start_x, first_y + position_map.line_height * idx as f32),
3071 vec2f(end_x, first_y + position_map.line_height * (idx + 1) as f32),
3072 ))
3073 }
3074
3075 bounds.into_iter()
3076}
3077
3078pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
3079 delta.powf(1.5) / 100.0
3080}
3081
3082fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
3083 delta.powf(1.2) / 300.0
3084}
3085
3086#[cfg(test)]
3087mod tests {
3088 use super::*;
3089 use crate::{
3090 display_map::{BlockDisposition, BlockProperties},
3091 editor_tests::{init_test, update_test_language_settings},
3092 Editor, MultiBuffer,
3093 };
3094 use gpui::TestAppContext;
3095 use language::language_settings;
3096 use log::info;
3097 use std::{num::NonZeroU32, sync::Arc};
3098 use util::test::sample_text;
3099
3100 #[gpui::test]
3101 fn test_layout_line_numbers(cx: &mut TestAppContext) {
3102 init_test(cx, |_| {});
3103 let editor = cx
3104 .add_window(|cx| {
3105 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3106 Editor::new(EditorMode::Full, buffer, None, None, cx)
3107 })
3108 .root(cx);
3109 let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3110
3111 let layouts = editor.update(cx, |editor, cx| {
3112 let snapshot = editor.snapshot(cx);
3113 element
3114 .layout_line_numbers(
3115 0..6,
3116 &Default::default(),
3117 DisplayPoint::new(0, 0),
3118 false,
3119 &snapshot,
3120 cx,
3121 )
3122 .0
3123 });
3124 assert_eq!(layouts.len(), 6);
3125
3126 let relative_rows = editor.update(cx, |editor, cx| {
3127 let snapshot = editor.snapshot(cx);
3128 element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
3129 });
3130 assert_eq!(relative_rows[&0], 3);
3131 assert_eq!(relative_rows[&1], 2);
3132 assert_eq!(relative_rows[&2], 1);
3133 // current line has no relative number
3134 assert_eq!(relative_rows[&4], 1);
3135 assert_eq!(relative_rows[&5], 2);
3136
3137 // works if cursor is before screen
3138 let relative_rows = editor.update(cx, |editor, cx| {
3139 let snapshot = editor.snapshot(cx);
3140
3141 element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
3142 });
3143 assert_eq!(relative_rows.len(), 3);
3144 assert_eq!(relative_rows[&3], 2);
3145 assert_eq!(relative_rows[&4], 3);
3146 assert_eq!(relative_rows[&5], 4);
3147
3148 // works if cursor is after screen
3149 let relative_rows = editor.update(cx, |editor, cx| {
3150 let snapshot = editor.snapshot(cx);
3151
3152 element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
3153 });
3154 assert_eq!(relative_rows.len(), 3);
3155 assert_eq!(relative_rows[&0], 5);
3156 assert_eq!(relative_rows[&1], 4);
3157 assert_eq!(relative_rows[&2], 3);
3158 }
3159
3160 #[gpui::test]
3161 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
3162 init_test(cx, |_| {});
3163
3164 let editor = cx
3165 .add_window(|cx| {
3166 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
3167 Editor::new(EditorMode::Full, buffer, None, None, cx)
3168 })
3169 .root(cx);
3170 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3171 let (_, state) = editor.update(cx, |editor, cx| {
3172 editor.cursor_shape = CursorShape::Block;
3173 editor.change_selections(None, cx, |s| {
3174 s.select_ranges([
3175 Point::new(0, 0)..Point::new(1, 0),
3176 Point::new(3, 2)..Point::new(3, 3),
3177 Point::new(5, 6)..Point::new(6, 0),
3178 ]);
3179 });
3180 element.layout(
3181 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
3182 editor,
3183 cx,
3184 )
3185 });
3186 assert_eq!(state.selections.len(), 1);
3187 let local_selections = &state.selections[0].1;
3188 assert_eq!(local_selections.len(), 3);
3189 // moves cursor back one line
3190 assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
3191 assert_eq!(
3192 local_selections[0].range,
3193 DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
3194 );
3195
3196 // moves cursor back one column
3197 assert_eq!(
3198 local_selections[1].range,
3199 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
3200 );
3201 assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
3202
3203 // leaves cursor on the max point
3204 assert_eq!(
3205 local_selections[2].range,
3206 DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
3207 );
3208 assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
3209
3210 // active lines does not include 1 (even though the range of the selection does)
3211 assert_eq!(
3212 state.active_rows.keys().cloned().collect::<Vec<u32>>(),
3213 vec![0, 3, 5, 6]
3214 );
3215
3216 // multi-buffer support
3217 // in DisplayPoint co-ordinates, this is what we're dealing with:
3218 // 0: [[file
3219 // 1: header]]
3220 // 2: aaaaaa
3221 // 3: bbbbbb
3222 // 4: cccccc
3223 // 5:
3224 // 6: ...
3225 // 7: ffffff
3226 // 8: gggggg
3227 // 9: hhhhhh
3228 // 10:
3229 // 11: [[file
3230 // 12: header]]
3231 // 13: bbbbbb
3232 // 14: cccccc
3233 // 15: dddddd
3234 let editor = cx
3235 .add_window(|cx| {
3236 let buffer = MultiBuffer::build_multi(
3237 [
3238 (
3239 &(sample_text(8, 6, 'a') + "\n"),
3240 vec![
3241 Point::new(0, 0)..Point::new(3, 0),
3242 Point::new(4, 0)..Point::new(7, 0),
3243 ],
3244 ),
3245 (
3246 &(sample_text(8, 6, 'a') + "\n"),
3247 vec![Point::new(1, 0)..Point::new(3, 0)],
3248 ),
3249 ],
3250 cx,
3251 );
3252 Editor::new(EditorMode::Full, buffer, None, None, cx)
3253 })
3254 .root(cx);
3255 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3256 let (_, state) = editor.update(cx, |editor, cx| {
3257 editor.cursor_shape = CursorShape::Block;
3258 editor.change_selections(None, cx, |s| {
3259 s.select_display_ranges([
3260 DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
3261 DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
3262 ]);
3263 });
3264 element.layout(
3265 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
3266 editor,
3267 cx,
3268 )
3269 });
3270
3271 assert_eq!(state.selections.len(), 1);
3272 let local_selections = &state.selections[0].1;
3273 assert_eq!(local_selections.len(), 2);
3274
3275 // moves cursor on excerpt boundary back a line
3276 // and doesn't allow selection to bleed through
3277 assert_eq!(
3278 local_selections[0].range,
3279 DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
3280 );
3281 assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
3282
3283 // moves cursor on buffer boundary back two lines
3284 // and doesn't allow selection to bleed through
3285 assert_eq!(
3286 local_selections[1].range,
3287 DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
3288 );
3289 assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
3290 }
3291
3292 #[gpui::test]
3293 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
3294 init_test(cx, |_| {});
3295
3296 let editor = cx
3297 .add_window(|cx| {
3298 let buffer = MultiBuffer::build_simple("", cx);
3299 Editor::new(EditorMode::Full, buffer, None, None, cx)
3300 })
3301 .root(cx);
3302
3303 editor.update(cx, |editor, cx| {
3304 editor.set_placeholder_text("hello", cx);
3305 editor.insert_blocks(
3306 [BlockProperties {
3307 style: BlockStyle::Fixed,
3308 disposition: BlockDisposition::Above,
3309 height: 3,
3310 position: Anchor::min(),
3311 render: Arc::new(|_| Empty::new().into_any()),
3312 }],
3313 None,
3314 cx,
3315 );
3316
3317 // Blur the editor so that it displays placeholder text.
3318 cx.blur();
3319 });
3320
3321 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3322 let (size, mut state) = editor.update(cx, |editor, cx| {
3323 element.layout(
3324 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
3325 editor,
3326 cx,
3327 )
3328 });
3329
3330 assert_eq!(state.position_map.line_layouts.len(), 4);
3331 assert_eq!(
3332 state
3333 .line_number_layouts
3334 .iter()
3335 .map(Option::is_some)
3336 .collect::<Vec<_>>(),
3337 &[false, false, false, true]
3338 );
3339
3340 // Don't panic.
3341 let bounds = RectF::new(Default::default(), size);
3342 editor.update(cx, |editor, cx| {
3343 element.paint(bounds, bounds, &mut state, editor, cx);
3344 });
3345 }
3346
3347 #[gpui::test]
3348 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3349 const TAB_SIZE: u32 = 4;
3350
3351 let input_text = "\t \t|\t| a b";
3352 let expected_invisibles = vec![
3353 Invisible::Tab {
3354 line_start_offset: 0,
3355 },
3356 Invisible::Whitespace {
3357 line_offset: TAB_SIZE as usize,
3358 },
3359 Invisible::Tab {
3360 line_start_offset: TAB_SIZE as usize + 1,
3361 },
3362 Invisible::Tab {
3363 line_start_offset: TAB_SIZE as usize * 2 + 1,
3364 },
3365 Invisible::Whitespace {
3366 line_offset: TAB_SIZE as usize * 3 + 1,
3367 },
3368 Invisible::Whitespace {
3369 line_offset: TAB_SIZE as usize * 3 + 3,
3370 },
3371 ];
3372 assert_eq!(
3373 expected_invisibles.len(),
3374 input_text
3375 .chars()
3376 .filter(|initial_char| initial_char.is_whitespace())
3377 .count(),
3378 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3379 );
3380
3381 init_test(cx, |s| {
3382 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3383 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
3384 });
3385
3386 let actual_invisibles =
3387 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
3388
3389 assert_eq!(expected_invisibles, actual_invisibles);
3390 }
3391
3392 #[gpui::test]
3393 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
3394 init_test(cx, |s| {
3395 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3396 s.defaults.tab_size = NonZeroU32::new(4);
3397 });
3398
3399 for editor_mode_without_invisibles in [
3400 EditorMode::SingleLine,
3401 EditorMode::AutoHeight { max_lines: 100 },
3402 ] {
3403 let invisibles = collect_invisibles_from_new_editor(
3404 cx,
3405 editor_mode_without_invisibles,
3406 "\t\t\t| | a b",
3407 500.0,
3408 );
3409 assert!(invisibles.is_empty(),
3410 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
3411 }
3412 }
3413
3414 #[gpui::test]
3415 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
3416 let tab_size = 4;
3417 let input_text = "a\tbcd ".repeat(9);
3418 let repeated_invisibles = [
3419 Invisible::Tab {
3420 line_start_offset: 1,
3421 },
3422 Invisible::Whitespace {
3423 line_offset: tab_size as usize + 3,
3424 },
3425 Invisible::Whitespace {
3426 line_offset: tab_size as usize + 4,
3427 },
3428 Invisible::Whitespace {
3429 line_offset: tab_size as usize + 5,
3430 },
3431 ];
3432 let expected_invisibles = std::iter::once(repeated_invisibles)
3433 .cycle()
3434 .take(9)
3435 .flatten()
3436 .collect::<Vec<_>>();
3437 assert_eq!(
3438 expected_invisibles.len(),
3439 input_text
3440 .chars()
3441 .filter(|initial_char| initial_char.is_whitespace())
3442 .count(),
3443 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3444 );
3445 info!("Expected invisibles: {expected_invisibles:?}");
3446
3447 init_test(cx, |_| {});
3448
3449 // Put the same string with repeating whitespace pattern into editors of various size,
3450 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
3451 let resize_step = 10.0;
3452 let mut editor_width = 200.0;
3453 while editor_width <= 1000.0 {
3454 update_test_language_settings(cx, |s| {
3455 s.defaults.tab_size = NonZeroU32::new(tab_size);
3456 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3457 s.defaults.preferred_line_length = Some(editor_width as u32);
3458 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
3459 });
3460
3461 let actual_invisibles =
3462 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
3463
3464 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
3465 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
3466 let mut i = 0;
3467 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
3468 i = actual_index;
3469 match expected_invisibles.get(i) {
3470 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
3471 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
3472 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
3473 _ => {
3474 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
3475 }
3476 },
3477 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
3478 }
3479 }
3480 let missing_expected_invisibles = &expected_invisibles[i + 1..];
3481 assert!(
3482 missing_expected_invisibles.is_empty(),
3483 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
3484 );
3485
3486 editor_width += resize_step;
3487 }
3488 }
3489
3490 fn collect_invisibles_from_new_editor(
3491 cx: &mut TestAppContext,
3492 editor_mode: EditorMode,
3493 input_text: &str,
3494 editor_width: f32,
3495 ) -> Vec<Invisible> {
3496 info!(
3497 "Creating editor with mode {editor_mode:?}, width {editor_width} and text '{input_text}'"
3498 );
3499 let editor = cx
3500 .add_window(|cx| {
3501 let buffer = MultiBuffer::build_simple(&input_text, cx);
3502 Editor::new(editor_mode, buffer, None, None, cx)
3503 })
3504 .root(cx);
3505
3506 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3507 let (_, layout_state) = editor.update(cx, |editor, cx| {
3508 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
3509 editor.set_wrap_width(Some(editor_width), cx);
3510
3511 element.layout(
3512 SizeConstraint::new(vec2f(editor_width, 500.), vec2f(editor_width, 500.)),
3513 editor,
3514 cx,
3515 )
3516 });
3517
3518 layout_state
3519 .position_map
3520 .line_layouts
3521 .iter()
3522 .map(|line_with_invisibles| &line_with_invisibles.invisibles)
3523 .flatten()
3524 .cloned()
3525 .collect()
3526 }
3527}