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