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