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 .min(line_height * max_lines as f32),
2083 )
2084 } else if let EditorMode::SingleLine = snapshot.mode {
2085 size.set_y(
2086 line_height
2087 .min(constraint.max_along(Axis::Vertical))
2088 .max(constraint.min_along(Axis::Vertical)),
2089 )
2090 } else if size.y().is_infinite() {
2091 size.set_y(scroll_height);
2092 }
2093 let gutter_size = vec2f(gutter_width, size.y());
2094 let text_size = vec2f(text_width, size.y());
2095
2096 let autoscroll_horizontally = editor.autoscroll_vertically(size.y(), line_height, cx);
2097 let mut snapshot = editor.snapshot(cx);
2098
2099 let scroll_position = snapshot.scroll_position();
2100 // The scroll position is a fractional point, the whole number of which represents
2101 // the top of the window in terms of display rows.
2102 let start_row = scroll_position.y() as u32;
2103 let height_in_lines = size.y() / line_height;
2104 let max_row = snapshot.max_point().row();
2105
2106 // Add 1 to ensure selections bleed off screen
2107 let end_row = 1 + cmp::min(
2108 (scroll_position.y() + height_in_lines).ceil() as u32,
2109 max_row,
2110 );
2111
2112 let start_anchor = if start_row == 0 {
2113 Anchor::min()
2114 } else {
2115 snapshot
2116 .buffer_snapshot
2117 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
2118 };
2119 let end_anchor = if end_row > max_row {
2120 Anchor::max()
2121 } else {
2122 snapshot
2123 .buffer_snapshot
2124 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
2125 };
2126
2127 let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
2128 let mut active_rows = BTreeMap::new();
2129 let mut fold_ranges = Vec::new();
2130 let is_singleton = editor.is_singleton(cx);
2131
2132 let highlighted_rows = editor.highlighted_rows();
2133 let theme = theme::current(cx);
2134 let highlighted_ranges = editor.background_highlights_in_range(
2135 start_anchor..end_anchor,
2136 &snapshot.display_snapshot,
2137 theme.as_ref(),
2138 );
2139
2140 fold_ranges.extend(
2141 snapshot
2142 .folds_in_range(start_anchor..end_anchor)
2143 .map(|anchor| {
2144 let start = anchor.start.to_point(&snapshot.buffer_snapshot);
2145 (
2146 start.row,
2147 start.to_display_point(&snapshot.display_snapshot)
2148 ..anchor.end.to_display_point(&snapshot),
2149 )
2150 }),
2151 );
2152
2153 let mut remote_selections = HashMap::default();
2154 for (replica_id, line_mode, cursor_shape, selection) in snapshot
2155 .buffer_snapshot
2156 .remote_selections_in_range(&(start_anchor..end_anchor))
2157 {
2158 // The local selections match the leader's selections.
2159 if Some(replica_id) == editor.leader_replica_id {
2160 continue;
2161 }
2162 remote_selections
2163 .entry(replica_id)
2164 .or_insert(Vec::new())
2165 .push(SelectionLayout::new(
2166 selection,
2167 line_mode,
2168 cursor_shape,
2169 &snapshot.display_snapshot,
2170 false,
2171 ));
2172 }
2173 selections.extend(remote_selections);
2174
2175 let mut newest_selection_head = None;
2176
2177 if editor.show_local_selections {
2178 let mut local_selections: Vec<Selection<Point>> = editor
2179 .selections
2180 .disjoint_in_range(start_anchor..end_anchor, cx);
2181 local_selections.extend(editor.selections.pending(cx));
2182 let mut layouts = Vec::new();
2183 let newest = editor.selections.newest(cx);
2184 for selection in local_selections.drain(..) {
2185 let is_empty = selection.start == selection.end;
2186 let is_newest = selection == newest;
2187
2188 let layout = SelectionLayout::new(
2189 selection,
2190 editor.selections.line_mode,
2191 editor.cursor_shape,
2192 &snapshot.display_snapshot,
2193 is_newest,
2194 );
2195 if is_newest {
2196 newest_selection_head = Some(layout.head);
2197 }
2198
2199 for row in cmp::max(layout.active_rows.start, start_row)
2200 ..=cmp::min(layout.active_rows.end, end_row)
2201 {
2202 let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2203 *contains_non_empty_selection |= !is_empty;
2204 }
2205 layouts.push(layout);
2206 }
2207
2208 // Render the local selections in the leader's color when following.
2209 let local_replica_id = editor
2210 .leader_replica_id
2211 .unwrap_or_else(|| editor.replica_id(cx));
2212
2213 selections.push((local_replica_id, layouts));
2214 }
2215
2216 let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
2217 let show_scrollbars = match scrollbar_settings.show {
2218 ShowScrollbar::Auto => {
2219 // Git
2220 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2221 ||
2222 // Selections
2223 (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty())
2224 // Scrollmanager
2225 || editor.scroll_manager.scrollbars_visible()
2226 }
2227 ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2228 ShowScrollbar::Always => true,
2229 ShowScrollbar::Never => false,
2230 };
2231
2232 let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2233 .into_iter()
2234 .map(|(id, fold)| {
2235 let color = self
2236 .style
2237 .folds
2238 .ellipses
2239 .background
2240 .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
2241 .color;
2242
2243 (id, fold, color)
2244 })
2245 .collect();
2246
2247 let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2248 start_row..end_row,
2249 &active_rows,
2250 is_singleton,
2251 &snapshot,
2252 cx,
2253 );
2254
2255 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2256
2257 let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
2258
2259 let mut max_visible_line_width = 0.0;
2260 let line_layouts =
2261 self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2262 for line_with_invisibles in &line_layouts {
2263 if line_with_invisibles.line.width() > max_visible_line_width {
2264 max_visible_line_width = line_with_invisibles.line.width();
2265 }
2266 }
2267
2268 let style = self.style.clone();
2269 let longest_line_width = layout_line(
2270 snapshot.longest_row(),
2271 &snapshot,
2272 &style,
2273 cx.text_layout_cache(),
2274 )
2275 .width();
2276 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
2277 let em_width = style.text.em_width(cx.font_cache());
2278 let (scroll_width, blocks) = self.layout_blocks(
2279 start_row..end_row,
2280 &snapshot,
2281 size.x(),
2282 scroll_width,
2283 gutter_padding,
2284 gutter_width,
2285 em_width,
2286 gutter_width + gutter_margin,
2287 line_height,
2288 &style,
2289 &line_layouts,
2290 editor,
2291 cx,
2292 );
2293
2294 let scroll_max = vec2f(
2295 ((scroll_width - text_size.x()) / em_width).max(0.0),
2296 max_row as f32,
2297 );
2298
2299 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x());
2300
2301 let autoscrolled = if autoscroll_horizontally {
2302 editor.autoscroll_horizontally(
2303 start_row,
2304 text_size.x(),
2305 scroll_width,
2306 em_width,
2307 &line_layouts,
2308 cx,
2309 )
2310 } else {
2311 false
2312 };
2313
2314 if clamped || autoscrolled {
2315 snapshot = editor.snapshot(cx);
2316 }
2317
2318 let style = editor.style(cx);
2319
2320 let mut context_menu = None;
2321 let mut code_actions_indicator = None;
2322 if let Some(newest_selection_head) = newest_selection_head {
2323 if (start_row..end_row).contains(&newest_selection_head.row()) {
2324 if editor.context_menu_visible() {
2325 context_menu =
2326 editor.render_context_menu(newest_selection_head, style.clone(), cx);
2327 }
2328
2329 let active = matches!(
2330 editor.context_menu,
2331 Some(crate::ContextMenu::CodeActions(_))
2332 );
2333
2334 code_actions_indicator = editor
2335 .render_code_actions_indicator(&style, active, cx)
2336 .map(|indicator| (newest_selection_head.row(), indicator));
2337 }
2338 }
2339
2340 let visible_rows = start_row..start_row + line_layouts.len() as u32;
2341 let mut hover = editor
2342 .hover_state
2343 .render(&snapshot, &style, visible_rows, cx);
2344 let mode = editor.mode;
2345
2346 let mut fold_indicators = editor.render_fold_indicators(
2347 fold_statuses,
2348 &style,
2349 editor.gutter_hovered,
2350 line_height,
2351 gutter_margin,
2352 cx,
2353 );
2354
2355 if let Some((_, context_menu)) = context_menu.as_mut() {
2356 context_menu.layout(
2357 SizeConstraint {
2358 min: Vector2F::zero(),
2359 max: vec2f(
2360 cx.window_size().x() * 0.7,
2361 (12. * line_height).min((size.y() - line_height) / 2.),
2362 ),
2363 },
2364 editor,
2365 cx,
2366 );
2367 }
2368
2369 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
2370 indicator.layout(
2371 SizeConstraint::strict_along(
2372 Axis::Vertical,
2373 line_height * style.code_actions.vertical_scale,
2374 ),
2375 editor,
2376 cx,
2377 );
2378 }
2379
2380 for fold_indicator in fold_indicators.iter_mut() {
2381 if let Some(indicator) = fold_indicator.as_mut() {
2382 indicator.layout(
2383 SizeConstraint::strict_along(
2384 Axis::Vertical,
2385 line_height * style.code_actions.vertical_scale,
2386 ),
2387 editor,
2388 cx,
2389 );
2390 }
2391 }
2392
2393 if let Some((_, hover_popovers)) = hover.as_mut() {
2394 for hover_popover in hover_popovers.iter_mut() {
2395 hover_popover.layout(
2396 SizeConstraint {
2397 min: Vector2F::zero(),
2398 max: vec2f(
2399 (120. * em_width) // Default size
2400 .min(size.x() / 2.) // Shrink to half of the editor width
2401 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2402 (16. * line_height) // Default size
2403 .min(size.y() / 2.) // Shrink to half of the editor height
2404 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2405 ),
2406 },
2407 editor,
2408 cx,
2409 );
2410 }
2411 }
2412
2413 let invisible_symbol_font_size = self.style.text.font_size / 2.0;
2414 let invisible_symbol_style = RunStyle {
2415 color: self.style.whitespace,
2416 font_id: self.style.text.font_id,
2417 underline: Default::default(),
2418 };
2419
2420 (
2421 size,
2422 LayoutState {
2423 mode,
2424 position_map: Arc::new(PositionMap {
2425 size,
2426 scroll_max,
2427 line_layouts,
2428 line_height,
2429 em_width,
2430 em_advance,
2431 snapshot,
2432 }),
2433 visible_display_row_range: start_row..end_row,
2434 wrap_guides,
2435 gutter_size,
2436 gutter_padding,
2437 text_size,
2438 scrollbar_row_range,
2439 show_scrollbars,
2440 is_singleton,
2441 max_row,
2442 gutter_margin,
2443 active_rows,
2444 highlighted_rows,
2445 highlighted_ranges,
2446 fold_ranges,
2447 line_number_layouts,
2448 display_hunks,
2449 blocks,
2450 selections,
2451 context_menu,
2452 code_actions_indicator,
2453 fold_indicators,
2454 tab_invisible: cx.text_layout_cache().layout_str(
2455 "→",
2456 invisible_symbol_font_size,
2457 &[("→".len(), invisible_symbol_style)],
2458 ),
2459 space_invisible: cx.text_layout_cache().layout_str(
2460 "•",
2461 invisible_symbol_font_size,
2462 &[("•".len(), invisible_symbol_style)],
2463 ),
2464 hover_popovers: hover,
2465 },
2466 )
2467 }
2468
2469 fn paint(
2470 &mut self,
2471 scene: &mut SceneBuilder,
2472 bounds: RectF,
2473 visible_bounds: RectF,
2474 layout: &mut Self::LayoutState,
2475 editor: &mut Editor,
2476 cx: &mut PaintContext<Editor>,
2477 ) -> Self::PaintState {
2478 let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2479 scene.push_layer(Some(visible_bounds));
2480
2481 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
2482 let text_bounds = RectF::new(
2483 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2484 layout.text_size,
2485 );
2486
2487 Self::attach_mouse_handlers(
2488 scene,
2489 &layout.position_map,
2490 layout.hover_popovers.is_some(),
2491 visible_bounds,
2492 text_bounds,
2493 gutter_bounds,
2494 bounds,
2495 cx,
2496 );
2497
2498 self.paint_background(scene, gutter_bounds, text_bounds, layout);
2499 if layout.gutter_size.x() > 0. {
2500 self.paint_gutter(scene, gutter_bounds, visible_bounds, layout, editor, cx);
2501 }
2502 self.paint_text(scene, text_bounds, visible_bounds, layout, editor, cx);
2503
2504 scene.push_layer(Some(bounds));
2505 if !layout.blocks.is_empty() {
2506 self.paint_blocks(scene, bounds, visible_bounds, layout, editor, cx);
2507 }
2508 self.paint_scrollbar(scene, bounds, layout, cx, &editor);
2509 scene.pop_layer();
2510
2511 scene.pop_layer();
2512 }
2513
2514 fn rect_for_text_range(
2515 &self,
2516 range_utf16: Range<usize>,
2517 bounds: RectF,
2518 _: RectF,
2519 layout: &Self::LayoutState,
2520 _: &Self::PaintState,
2521 _: &Editor,
2522 _: &ViewContext<Editor>,
2523 ) -> Option<RectF> {
2524 let text_bounds = RectF::new(
2525 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2526 layout.text_size,
2527 );
2528 let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
2529 let scroll_position = layout.position_map.snapshot.scroll_position();
2530 let start_row = scroll_position.y() as u32;
2531 let scroll_top = scroll_position.y() * layout.position_map.line_height;
2532 let scroll_left = scroll_position.x() * layout.position_map.em_width;
2533
2534 let range_start = OffsetUtf16(range_utf16.start)
2535 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2536 if range_start.row() < start_row {
2537 return None;
2538 }
2539
2540 let line = &layout
2541 .position_map
2542 .line_layouts
2543 .get((range_start.row() - start_row) as usize)?
2544 .line;
2545 let range_start_x = line.x_for_index(range_start.column() as usize);
2546 let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
2547 Some(RectF::new(
2548 content_origin
2549 + vec2f(
2550 range_start_x,
2551 range_start_y + layout.position_map.line_height,
2552 )
2553 - vec2f(scroll_left, scroll_top),
2554 vec2f(
2555 layout.position_map.em_width,
2556 layout.position_map.line_height,
2557 ),
2558 ))
2559 }
2560
2561 fn debug(
2562 &self,
2563 bounds: RectF,
2564 _: &Self::LayoutState,
2565 _: &Self::PaintState,
2566 _: &Editor,
2567 _: &ViewContext<Editor>,
2568 ) -> json::Value {
2569 json!({
2570 "type": "BufferElement",
2571 "bounds": bounds.to_json()
2572 })
2573 }
2574}
2575
2576type BufferRow = u32;
2577
2578pub struct LayoutState {
2579 position_map: Arc<PositionMap>,
2580 gutter_size: Vector2F,
2581 gutter_padding: f32,
2582 gutter_margin: f32,
2583 text_size: Vector2F,
2584 mode: EditorMode,
2585 wrap_guides: SmallVec<[(f32, bool); 2]>,
2586 visible_display_row_range: Range<u32>,
2587 active_rows: BTreeMap<u32, bool>,
2588 highlighted_rows: Option<Range<u32>>,
2589 line_number_layouts: Vec<Option<text_layout::Line>>,
2590 display_hunks: Vec<DisplayDiffHunk>,
2591 blocks: Vec<BlockLayout>,
2592 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2593 fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)>,
2594 selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
2595 scrollbar_row_range: Range<f32>,
2596 show_scrollbars: bool,
2597 is_singleton: bool,
2598 max_row: u32,
2599 context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
2600 code_actions_indicator: Option<(u32, AnyElement<Editor>)>,
2601 hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
2602 fold_indicators: Vec<Option<AnyElement<Editor>>>,
2603 tab_invisible: Line,
2604 space_invisible: Line,
2605}
2606
2607struct PositionMap {
2608 size: Vector2F,
2609 line_height: f32,
2610 scroll_max: Vector2F,
2611 em_width: f32,
2612 em_advance: f32,
2613 line_layouts: Vec<LineWithInvisibles>,
2614 snapshot: EditorSnapshot,
2615}
2616
2617impl PositionMap {
2618 /// Returns two display points:
2619 /// 1. The nearest *valid* position in the editor
2620 /// 2. An unclipped, potentially *invalid* position that maps directly to
2621 /// the given pixel position.
2622 fn point_for_position(
2623 &self,
2624 text_bounds: RectF,
2625 position: Vector2F,
2626 ) -> (DisplayPoint, DisplayPoint) {
2627 let scroll_position = self.snapshot.scroll_position();
2628 let position = position - text_bounds.origin();
2629 let y = position.y().max(0.0).min(self.size.y());
2630 let x = position.x() + (scroll_position.x() * self.em_width);
2631 let row = (y / self.line_height + scroll_position.y()) as u32;
2632 let (column, x_overshoot) = if let Some(line) = self
2633 .line_layouts
2634 .get(row as usize - scroll_position.y() as usize)
2635 .map(|line_with_spaces| &line_with_spaces.line)
2636 {
2637 if let Some(ix) = line.index_for_x(x) {
2638 (ix as u32, 0.0)
2639 } else {
2640 (line.len() as u32, 0f32.max(x - line.width()))
2641 }
2642 } else {
2643 (0, x)
2644 };
2645
2646 let mut target_point = DisplayPoint::new(row, column);
2647 let point = self.snapshot.clip_point(target_point, Bias::Left);
2648 *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
2649
2650 (point, target_point)
2651 }
2652}
2653
2654struct BlockLayout {
2655 row: u32,
2656 element: AnyElement<Editor>,
2657 style: BlockStyle,
2658}
2659
2660fn layout_line(
2661 row: u32,
2662 snapshot: &EditorSnapshot,
2663 style: &EditorStyle,
2664 layout_cache: &TextLayoutCache,
2665) -> text_layout::Line {
2666 let mut line = snapshot.line(row);
2667
2668 if line.len() > MAX_LINE_LEN {
2669 let mut len = MAX_LINE_LEN;
2670 while !line.is_char_boundary(len) {
2671 len -= 1;
2672 }
2673
2674 line.truncate(len);
2675 }
2676
2677 layout_cache.layout_str(
2678 &line,
2679 style.text.font_size,
2680 &[(
2681 snapshot.line_len(row) as usize,
2682 RunStyle {
2683 font_id: style.text.font_id,
2684 color: Color::black(),
2685 underline: Default::default(),
2686 },
2687 )],
2688 )
2689}
2690
2691#[derive(Debug)]
2692pub struct Cursor {
2693 origin: Vector2F,
2694 block_width: f32,
2695 line_height: f32,
2696 color: Color,
2697 shape: CursorShape,
2698 block_text: Option<Line>,
2699}
2700
2701impl Cursor {
2702 pub fn new(
2703 origin: Vector2F,
2704 block_width: f32,
2705 line_height: f32,
2706 color: Color,
2707 shape: CursorShape,
2708 block_text: Option<Line>,
2709 ) -> Cursor {
2710 Cursor {
2711 origin,
2712 block_width,
2713 line_height,
2714 color,
2715 shape,
2716 block_text,
2717 }
2718 }
2719
2720 pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2721 RectF::new(
2722 self.origin + origin,
2723 vec2f(self.block_width, self.line_height),
2724 )
2725 }
2726
2727 pub fn paint(&self, scene: &mut SceneBuilder, origin: Vector2F, cx: &mut WindowContext) {
2728 let bounds = match self.shape {
2729 CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2730 CursorShape::Block | CursorShape::Hollow => RectF::new(
2731 self.origin + origin,
2732 vec2f(self.block_width, self.line_height),
2733 ),
2734 CursorShape::Underscore => RectF::new(
2735 self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2736 vec2f(self.block_width, 2.0),
2737 ),
2738 };
2739
2740 //Draw background or border quad
2741 if matches!(self.shape, CursorShape::Hollow) {
2742 scene.push_quad(Quad {
2743 bounds,
2744 background: None,
2745 border: Border::all(1., self.color),
2746 corner_radii: Default::default(),
2747 });
2748 } else {
2749 scene.push_quad(Quad {
2750 bounds,
2751 background: Some(self.color),
2752 border: Default::default(),
2753 corner_radii: Default::default(),
2754 });
2755 }
2756
2757 if let Some(block_text) = &self.block_text {
2758 block_text.paint(scene, self.origin + origin, bounds, self.line_height, cx);
2759 }
2760 }
2761
2762 pub fn shape(&self) -> CursorShape {
2763 self.shape
2764 }
2765}
2766
2767#[derive(Debug)]
2768pub struct HighlightedRange {
2769 pub start_y: f32,
2770 pub line_height: f32,
2771 pub lines: Vec<HighlightedRangeLine>,
2772 pub color: Color,
2773 pub corner_radius: f32,
2774}
2775
2776#[derive(Debug)]
2777pub struct HighlightedRangeLine {
2778 pub start_x: f32,
2779 pub end_x: f32,
2780}
2781
2782impl HighlightedRange {
2783 pub fn paint(&self, bounds: RectF, scene: &mut SceneBuilder) {
2784 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2785 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2786 self.paint_lines(
2787 self.start_y + self.line_height,
2788 &self.lines[1..],
2789 bounds,
2790 scene,
2791 );
2792 } else {
2793 self.paint_lines(self.start_y, &self.lines, bounds, scene);
2794 }
2795 }
2796
2797 fn paint_lines(
2798 &self,
2799 start_y: f32,
2800 lines: &[HighlightedRangeLine],
2801 bounds: RectF,
2802 scene: &mut SceneBuilder,
2803 ) {
2804 if lines.is_empty() {
2805 return;
2806 }
2807
2808 let mut path = PathBuilder::new();
2809 let first_line = lines.first().unwrap();
2810 let last_line = lines.last().unwrap();
2811
2812 let first_top_left = vec2f(first_line.start_x, start_y);
2813 let first_top_right = vec2f(first_line.end_x, start_y);
2814
2815 let curve_height = vec2f(0., self.corner_radius);
2816 let curve_width = |start_x: f32, end_x: f32| {
2817 let max = (end_x - start_x) / 2.;
2818 let width = if max < self.corner_radius {
2819 max
2820 } else {
2821 self.corner_radius
2822 };
2823
2824 vec2f(width, 0.)
2825 };
2826
2827 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2828 path.reset(first_top_right - top_curve_width);
2829 path.curve_to(first_top_right + curve_height, first_top_right);
2830
2831 let mut iter = lines.iter().enumerate().peekable();
2832 while let Some((ix, line)) = iter.next() {
2833 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2834
2835 if let Some((_, next_line)) = iter.peek() {
2836 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2837
2838 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2839 Ordering::Equal => {
2840 path.line_to(bottom_right);
2841 }
2842 Ordering::Less => {
2843 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2844 path.line_to(bottom_right - curve_height);
2845 if self.corner_radius > 0. {
2846 path.curve_to(bottom_right - curve_width, bottom_right);
2847 }
2848 path.line_to(next_top_right + curve_width);
2849 if self.corner_radius > 0. {
2850 path.curve_to(next_top_right + curve_height, next_top_right);
2851 }
2852 }
2853 Ordering::Greater => {
2854 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2855 path.line_to(bottom_right - curve_height);
2856 if self.corner_radius > 0. {
2857 path.curve_to(bottom_right + curve_width, bottom_right);
2858 }
2859 path.line_to(next_top_right - curve_width);
2860 if self.corner_radius > 0. {
2861 path.curve_to(next_top_right + curve_height, next_top_right);
2862 }
2863 }
2864 }
2865 } else {
2866 let curve_width = curve_width(line.start_x, line.end_x);
2867 path.line_to(bottom_right - curve_height);
2868 if self.corner_radius > 0. {
2869 path.curve_to(bottom_right - curve_width, bottom_right);
2870 }
2871
2872 let bottom_left = vec2f(line.start_x, bottom_right.y());
2873 path.line_to(bottom_left + curve_width);
2874 if self.corner_radius > 0. {
2875 path.curve_to(bottom_left - curve_height, bottom_left);
2876 }
2877 }
2878 }
2879
2880 if first_line.start_x > last_line.start_x {
2881 let curve_width = curve_width(last_line.start_x, first_line.start_x);
2882 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2883 path.line_to(second_top_left + curve_height);
2884 if self.corner_radius > 0. {
2885 path.curve_to(second_top_left + curve_width, second_top_left);
2886 }
2887 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2888 path.line_to(first_bottom_left - curve_width);
2889 if self.corner_radius > 0. {
2890 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2891 }
2892 }
2893
2894 path.line_to(first_top_left + curve_height);
2895 if self.corner_radius > 0. {
2896 path.curve_to(first_top_left + top_curve_width, first_top_left);
2897 }
2898 path.line_to(first_top_right - top_curve_width);
2899
2900 scene.push_path(path.build(self.color, Some(bounds)));
2901 }
2902}
2903
2904fn position_to_display_point(
2905 position: Vector2F,
2906 text_bounds: RectF,
2907 position_map: &PositionMap,
2908) -> Option<DisplayPoint> {
2909 if text_bounds.contains_point(position) {
2910 let (point, target_point) = position_map.point_for_position(text_bounds, position);
2911 if point == target_point {
2912 Some(point)
2913 } else {
2914 None
2915 }
2916 } else {
2917 None
2918 }
2919}
2920
2921fn range_to_bounds(
2922 range: &Range<DisplayPoint>,
2923 content_origin: Vector2F,
2924 scroll_left: f32,
2925 scroll_top: f32,
2926 visible_row_range: &Range<u32>,
2927 line_end_overshoot: f32,
2928 position_map: &PositionMap,
2929) -> impl Iterator<Item = RectF> {
2930 let mut bounds: SmallVec<[RectF; 1]> = SmallVec::new();
2931
2932 if range.start == range.end {
2933 return bounds.into_iter();
2934 }
2935
2936 let start_row = visible_row_range.start;
2937 let end_row = visible_row_range.end;
2938
2939 let row_range = if range.end.column() == 0 {
2940 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2941 } else {
2942 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2943 };
2944
2945 let first_y =
2946 content_origin.y() + row_range.start as f32 * position_map.line_height - scroll_top;
2947
2948 for (idx, row) in row_range.enumerate() {
2949 let line_layout = &position_map.line_layouts[(row - start_row) as usize].line;
2950
2951 let start_x = if row == range.start.row() {
2952 content_origin.x() + line_layout.x_for_index(range.start.column() as usize)
2953 - scroll_left
2954 } else {
2955 content_origin.x() - scroll_left
2956 };
2957
2958 let end_x = if row == range.end.row() {
2959 content_origin.x() + line_layout.x_for_index(range.end.column() as usize) - scroll_left
2960 } else {
2961 content_origin.x() + line_layout.width() + line_end_overshoot - scroll_left
2962 };
2963
2964 bounds.push(RectF::from_points(
2965 vec2f(start_x, first_y + position_map.line_height * idx as f32),
2966 vec2f(end_x, first_y + position_map.line_height * (idx + 1) as f32),
2967 ))
2968 }
2969
2970 bounds.into_iter()
2971}
2972
2973pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2974 delta.powf(1.5) / 100.0
2975}
2976
2977fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
2978 delta.powf(1.2) / 300.0
2979}
2980
2981#[cfg(test)]
2982mod tests {
2983 use super::*;
2984 use crate::{
2985 display_map::{BlockDisposition, BlockProperties},
2986 editor_tests::{init_test, update_test_language_settings},
2987 Editor, MultiBuffer,
2988 };
2989 use gpui::TestAppContext;
2990 use language::language_settings;
2991 use log::info;
2992 use std::{num::NonZeroU32, sync::Arc};
2993 use util::test::sample_text;
2994
2995 #[gpui::test]
2996 fn test_layout_line_numbers(cx: &mut TestAppContext) {
2997 init_test(cx, |_| {});
2998
2999 let editor = cx
3000 .add_window(|cx| {
3001 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3002 Editor::new(EditorMode::Full, buffer, None, None, cx)
3003 })
3004 .root(cx);
3005 let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3006
3007 let layouts = editor.update(cx, |editor, cx| {
3008 let snapshot = editor.snapshot(cx);
3009 element
3010 .layout_line_numbers(0..6, &Default::default(), false, &snapshot, cx)
3011 .0
3012 });
3013 assert_eq!(layouts.len(), 6);
3014 }
3015
3016 #[gpui::test]
3017 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
3018 init_test(cx, |_| {});
3019
3020 let editor = cx
3021 .add_window(|cx| {
3022 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
3023 Editor::new(EditorMode::Full, buffer, None, None, cx)
3024 })
3025 .root(cx);
3026 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3027 let (_, state) = editor.update(cx, |editor, cx| {
3028 editor.cursor_shape = CursorShape::Block;
3029 editor.change_selections(None, cx, |s| {
3030 s.select_ranges([
3031 Point::new(0, 0)..Point::new(1, 0),
3032 Point::new(3, 2)..Point::new(3, 3),
3033 Point::new(5, 6)..Point::new(6, 0),
3034 ]);
3035 });
3036 let mut new_parents = Default::default();
3037 let mut notify_views_if_parents_change = Default::default();
3038 let mut layout_cx = LayoutContext::new(
3039 cx,
3040 &mut new_parents,
3041 &mut notify_views_if_parents_change,
3042 false,
3043 );
3044 element.layout(
3045 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
3046 editor,
3047 &mut layout_cx,
3048 )
3049 });
3050 assert_eq!(state.selections.len(), 1);
3051 let local_selections = &state.selections[0].1;
3052 assert_eq!(local_selections.len(), 3);
3053 // moves cursor back one line
3054 assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
3055 assert_eq!(
3056 local_selections[0].range,
3057 DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
3058 );
3059
3060 // moves cursor back one column
3061 assert_eq!(
3062 local_selections[1].range,
3063 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
3064 );
3065 assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
3066
3067 // leaves cursor on the max point
3068 assert_eq!(
3069 local_selections[2].range,
3070 DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
3071 );
3072 assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
3073
3074 // active lines does not include 1 (even though the range of the selection does)
3075 assert_eq!(
3076 state.active_rows.keys().cloned().collect::<Vec<u32>>(),
3077 vec![0, 3, 5, 6]
3078 );
3079
3080 // multi-buffer support
3081 // in DisplayPoint co-ordinates, this is what we're dealing with:
3082 // 0: [[file
3083 // 1: header]]
3084 // 2: aaaaaa
3085 // 3: bbbbbb
3086 // 4: cccccc
3087 // 5:
3088 // 6: ...
3089 // 7: ffffff
3090 // 8: gggggg
3091 // 9: hhhhhh
3092 // 10:
3093 // 11: [[file
3094 // 12: header]]
3095 // 13: bbbbbb
3096 // 14: cccccc
3097 // 15: dddddd
3098 let editor = cx
3099 .add_window(|cx| {
3100 let buffer = MultiBuffer::build_multi(
3101 [
3102 (
3103 &(sample_text(8, 6, 'a') + "\n"),
3104 vec![
3105 Point::new(0, 0)..Point::new(3, 0),
3106 Point::new(4, 0)..Point::new(7, 0),
3107 ],
3108 ),
3109 (
3110 &(sample_text(8, 6, 'a') + "\n"),
3111 vec![Point::new(1, 0)..Point::new(3, 0)],
3112 ),
3113 ],
3114 cx,
3115 );
3116 Editor::new(EditorMode::Full, buffer, None, None, cx)
3117 })
3118 .root(cx);
3119 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3120 let (_, state) = editor.update(cx, |editor, cx| {
3121 editor.cursor_shape = CursorShape::Block;
3122 editor.change_selections(None, cx, |s| {
3123 s.select_display_ranges([
3124 DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
3125 DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
3126 ]);
3127 });
3128 let mut new_parents = Default::default();
3129 let mut notify_views_if_parents_change = Default::default();
3130 let mut layout_cx = LayoutContext::new(
3131 cx,
3132 &mut new_parents,
3133 &mut notify_views_if_parents_change,
3134 false,
3135 );
3136 element.layout(
3137 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
3138 editor,
3139 &mut layout_cx,
3140 )
3141 });
3142
3143 assert_eq!(state.selections.len(), 1);
3144 let local_selections = &state.selections[0].1;
3145 assert_eq!(local_selections.len(), 2);
3146
3147 // moves cursor on excerpt boundary back a line
3148 // and doesn't allow selection to bleed through
3149 assert_eq!(
3150 local_selections[0].range,
3151 DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
3152 );
3153 assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
3154
3155 // moves cursor on buffer boundary back two lines
3156 // and doesn't allow selection to bleed through
3157 assert_eq!(
3158 local_selections[1].range,
3159 DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
3160 );
3161 assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
3162 }
3163
3164 #[gpui::test]
3165 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
3166 init_test(cx, |_| {});
3167
3168 let editor = cx
3169 .add_window(|cx| {
3170 let buffer = MultiBuffer::build_simple("", cx);
3171 Editor::new(EditorMode::Full, buffer, None, None, cx)
3172 })
3173 .root(cx);
3174
3175 editor.update(cx, |editor, cx| {
3176 editor.set_placeholder_text("hello", cx);
3177 editor.insert_blocks(
3178 [BlockProperties {
3179 style: BlockStyle::Fixed,
3180 disposition: BlockDisposition::Above,
3181 height: 3,
3182 position: Anchor::min(),
3183 render: Arc::new(|_| Empty::new().into_any()),
3184 }],
3185 None,
3186 cx,
3187 );
3188
3189 // Blur the editor so that it displays placeholder text.
3190 cx.blur();
3191 });
3192
3193 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3194 let (size, mut state) = editor.update(cx, |editor, cx| {
3195 let mut new_parents = Default::default();
3196 let mut notify_views_if_parents_change = Default::default();
3197 let mut layout_cx = LayoutContext::new(
3198 cx,
3199 &mut new_parents,
3200 &mut notify_views_if_parents_change,
3201 false,
3202 );
3203 element.layout(
3204 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
3205 editor,
3206 &mut layout_cx,
3207 )
3208 });
3209
3210 assert_eq!(state.position_map.line_layouts.len(), 4);
3211 assert_eq!(
3212 state
3213 .line_number_layouts
3214 .iter()
3215 .map(Option::is_some)
3216 .collect::<Vec<_>>(),
3217 &[false, false, false, true]
3218 );
3219
3220 // Don't panic.
3221 let mut scene = SceneBuilder::new(1.0);
3222 let bounds = RectF::new(Default::default(), size);
3223 editor.update(cx, |editor, cx| {
3224 element.paint(
3225 &mut scene,
3226 bounds,
3227 bounds,
3228 &mut state,
3229 editor,
3230 &mut PaintContext::new(cx),
3231 );
3232 });
3233 }
3234
3235 #[gpui::test]
3236 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3237 const TAB_SIZE: u32 = 4;
3238
3239 let input_text = "\t \t|\t| a b";
3240 let expected_invisibles = vec![
3241 Invisible::Tab {
3242 line_start_offset: 0,
3243 },
3244 Invisible::Whitespace {
3245 line_offset: TAB_SIZE as usize,
3246 },
3247 Invisible::Tab {
3248 line_start_offset: TAB_SIZE as usize + 1,
3249 },
3250 Invisible::Tab {
3251 line_start_offset: TAB_SIZE as usize * 2 + 1,
3252 },
3253 Invisible::Whitespace {
3254 line_offset: TAB_SIZE as usize * 3 + 1,
3255 },
3256 Invisible::Whitespace {
3257 line_offset: TAB_SIZE as usize * 3 + 3,
3258 },
3259 ];
3260 assert_eq!(
3261 expected_invisibles.len(),
3262 input_text
3263 .chars()
3264 .filter(|initial_char| initial_char.is_whitespace())
3265 .count(),
3266 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3267 );
3268
3269 init_test(cx, |s| {
3270 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3271 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
3272 });
3273
3274 let actual_invisibles =
3275 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
3276
3277 assert_eq!(expected_invisibles, actual_invisibles);
3278 }
3279
3280 #[gpui::test]
3281 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
3282 init_test(cx, |s| {
3283 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3284 s.defaults.tab_size = NonZeroU32::new(4);
3285 });
3286
3287 for editor_mode_without_invisibles in [
3288 EditorMode::SingleLine,
3289 EditorMode::AutoHeight { max_lines: 100 },
3290 ] {
3291 let invisibles = collect_invisibles_from_new_editor(
3292 cx,
3293 editor_mode_without_invisibles,
3294 "\t\t\t| | a b",
3295 500.0,
3296 );
3297 assert!(invisibles.is_empty(),
3298 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
3299 }
3300 }
3301
3302 #[gpui::test]
3303 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
3304 let tab_size = 4;
3305 let input_text = "a\tbcd ".repeat(9);
3306 let repeated_invisibles = [
3307 Invisible::Tab {
3308 line_start_offset: 1,
3309 },
3310 Invisible::Whitespace {
3311 line_offset: tab_size as usize + 3,
3312 },
3313 Invisible::Whitespace {
3314 line_offset: tab_size as usize + 4,
3315 },
3316 Invisible::Whitespace {
3317 line_offset: tab_size as usize + 5,
3318 },
3319 ];
3320 let expected_invisibles = std::iter::once(repeated_invisibles)
3321 .cycle()
3322 .take(9)
3323 .flatten()
3324 .collect::<Vec<_>>();
3325 assert_eq!(
3326 expected_invisibles.len(),
3327 input_text
3328 .chars()
3329 .filter(|initial_char| initial_char.is_whitespace())
3330 .count(),
3331 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3332 );
3333 info!("Expected invisibles: {expected_invisibles:?}");
3334
3335 init_test(cx, |_| {});
3336
3337 // Put the same string with repeating whitespace pattern into editors of various size,
3338 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
3339 let resize_step = 10.0;
3340 let mut editor_width = 200.0;
3341 while editor_width <= 1000.0 {
3342 update_test_language_settings(cx, |s| {
3343 s.defaults.tab_size = NonZeroU32::new(tab_size);
3344 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3345 s.defaults.preferred_line_length = Some(editor_width as u32);
3346 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
3347 });
3348
3349 let actual_invisibles =
3350 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
3351
3352 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
3353 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
3354 let mut i = 0;
3355 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
3356 i = actual_index;
3357 match expected_invisibles.get(i) {
3358 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
3359 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
3360 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
3361 _ => {
3362 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
3363 }
3364 },
3365 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
3366 }
3367 }
3368 let missing_expected_invisibles = &expected_invisibles[i + 1..];
3369 assert!(
3370 missing_expected_invisibles.is_empty(),
3371 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
3372 );
3373
3374 editor_width += resize_step;
3375 }
3376 }
3377
3378 fn collect_invisibles_from_new_editor(
3379 cx: &mut TestAppContext,
3380 editor_mode: EditorMode,
3381 input_text: &str,
3382 editor_width: f32,
3383 ) -> Vec<Invisible> {
3384 info!(
3385 "Creating editor with mode {editor_mode:?}, width {editor_width} and text '{input_text}'"
3386 );
3387 let editor = cx
3388 .add_window(|cx| {
3389 let buffer = MultiBuffer::build_simple(&input_text, cx);
3390 Editor::new(editor_mode, buffer, None, None, cx)
3391 })
3392 .root(cx);
3393
3394 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3395 let (_, layout_state) = editor.update(cx, |editor, cx| {
3396 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
3397 editor.set_wrap_width(Some(editor_width), cx);
3398
3399 let mut new_parents = Default::default();
3400 let mut notify_views_if_parents_change = Default::default();
3401 let mut layout_cx = LayoutContext::new(
3402 cx,
3403 &mut new_parents,
3404 &mut notify_views_if_parents_change,
3405 false,
3406 );
3407 element.layout(
3408 SizeConstraint::new(vec2f(editor_width, 500.), vec2f(editor_width, 500.)),
3409 editor,
3410 &mut layout_cx,
3411 )
3412 });
3413
3414 layout_state
3415 .position_map
3416 .line_layouts
3417 .iter()
3418 .map(|line_with_invisibles| &line_with_invisibles.invisibles)
3419 .flatten()
3420 .cloned()
3421 .collect()
3422 }
3423}