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