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, 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}
67
68impl SelectionLayout {
69 fn new<T: ToPoint + ToDisplayPoint + Clone>(
70 selection: Selection<T>,
71 line_mode: bool,
72 cursor_shape: CursorShape,
73 map: &DisplaySnapshot,
74 is_newest: bool,
75 ) -> Self {
76 if line_mode {
77 let selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
78 let point_range = map.expand_to_line(selection.range());
79 Self {
80 head: selection.head().to_display_point(map),
81 cursor_shape,
82 is_newest,
83 range: point_range.start.to_display_point(map)
84 ..point_range.end.to_display_point(map),
85 }
86 } else {
87 let selection = selection.map(|p| p.to_display_point(map));
88 Self {
89 head: selection.head(),
90 cursor_shape,
91 is_newest,
92 range: selection.range(),
93 }
94 }
95 }
96}
97
98pub struct EditorElement {
99 style: Arc<EditorStyle>,
100}
101
102impl EditorElement {
103 pub fn new(style: EditorStyle) -> Self {
104 Self {
105 style: Arc::new(style),
106 }
107 }
108
109 fn attach_mouse_handlers(
110 scene: &mut SceneBuilder,
111 position_map: &Arc<PositionMap>,
112 has_popovers: bool,
113 visible_bounds: RectF,
114 text_bounds: RectF,
115 gutter_bounds: RectF,
116 bounds: RectF,
117 cx: &mut ViewContext<Editor>,
118 ) {
119 enum EditorElementMouseHandlers {}
120 scene.push_mouse_region(
121 MouseRegion::new::<EditorElementMouseHandlers>(
122 cx.view_id(),
123 cx.view_id(),
124 visible_bounds,
125 )
126 .on_down(MouseButton::Left, {
127 let position_map = position_map.clone();
128 move |event, editor, cx| {
129 if !Self::mouse_down(
130 editor,
131 event.platform_event,
132 position_map.as_ref(),
133 text_bounds,
134 gutter_bounds,
135 cx,
136 ) {
137 cx.propagate_event();
138 }
139 }
140 })
141 .on_down(MouseButton::Right, {
142 let position_map = position_map.clone();
143 move |event, editor, cx| {
144 if !Self::mouse_right_down(
145 editor,
146 event.position,
147 position_map.as_ref(),
148 text_bounds,
149 cx,
150 ) {
151 cx.propagate_event();
152 }
153 }
154 })
155 .on_up(MouseButton::Left, {
156 let position_map = position_map.clone();
157 move |event, editor, cx| {
158 if !Self::mouse_up(
159 editor,
160 event.position,
161 event.cmd,
162 event.shift,
163 event.alt,
164 position_map.as_ref(),
165 text_bounds,
166 cx,
167 ) {
168 cx.propagate_event()
169 }
170 }
171 })
172 .on_drag(MouseButton::Left, {
173 let position_map = position_map.clone();
174 move |event, editor, cx| {
175 if event.end {
176 return;
177 }
178
179 if !Self::mouse_dragged(
180 editor,
181 event.platform_event,
182 position_map.as_ref(),
183 text_bounds,
184 cx,
185 ) {
186 cx.propagate_event()
187 }
188 }
189 })
190 .on_move({
191 let position_map = position_map.clone();
192 move |event, editor, cx| {
193 if !Self::mouse_moved(
194 editor,
195 event.platform_event,
196 &position_map,
197 text_bounds,
198 cx,
199 ) {
200 cx.propagate_event()
201 }
202 }
203 })
204 .on_move_out(move |_, editor: &mut Editor, cx| {
205 if has_popovers {
206 hide_hover(editor, cx);
207 }
208 })
209 .on_scroll({
210 let position_map = position_map.clone();
211 move |event, editor, cx| {
212 if !Self::scroll(
213 editor,
214 event.position,
215 *event.delta.raw(),
216 event.delta.precise(),
217 &position_map,
218 bounds,
219 cx,
220 ) {
221 cx.propagate_event()
222 }
223 }
224 }),
225 );
226
227 enum GutterHandlers {}
228 scene.push_mouse_region(
229 MouseRegion::new::<GutterHandlers>(cx.view_id(), cx.view_id() + 1, gutter_bounds)
230 .on_hover(|hover, editor: &mut Editor, cx| {
231 editor.gutter_hover(
232 &GutterHover {
233 hovered: hover.started,
234 },
235 cx,
236 );
237 }),
238 )
239 }
240
241 fn mouse_down(
242 editor: &mut Editor,
243 MouseButtonEvent {
244 position,
245 modifiers:
246 Modifiers {
247 shift,
248 ctrl,
249 alt,
250 cmd,
251 ..
252 },
253 mut click_count,
254 ..
255 }: MouseButtonEvent,
256 position_map: &PositionMap,
257 text_bounds: RectF,
258 gutter_bounds: RectF,
259 cx: &mut EventContext<Editor>,
260 ) -> bool {
261 if gutter_bounds.contains_point(position) {
262 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
263 } else if !text_bounds.contains_point(position) {
264 return false;
265 }
266
267 let (position, target_position) = position_map.point_for_position(text_bounds, position);
268
269 if shift && alt {
270 editor.select(
271 SelectPhase::BeginColumnar {
272 position,
273 goal_column: target_position.column(),
274 },
275 cx,
276 );
277 } else if shift && !ctrl && !alt && !cmd {
278 editor.select(
279 SelectPhase::Extend {
280 position,
281 click_count,
282 },
283 cx,
284 );
285 } else {
286 editor.select(
287 SelectPhase::Begin {
288 position,
289 add: alt,
290 click_count,
291 },
292 cx,
293 );
294 }
295
296 true
297 }
298
299 fn mouse_right_down(
300 editor: &mut Editor,
301 position: Vector2F,
302 position_map: &PositionMap,
303 text_bounds: RectF,
304 cx: &mut EventContext<Editor>,
305 ) -> bool {
306 if !text_bounds.contains_point(position) {
307 return false;
308 }
309
310 let (point, _) = position_map.point_for_position(text_bounds, position);
311 mouse_context_menu::deploy_context_menu(editor, position, point, cx);
312 true
313 }
314
315 fn mouse_up(
316 editor: &mut Editor,
317 position: Vector2F,
318 cmd: bool,
319 shift: bool,
320 alt: bool,
321 position_map: &PositionMap,
322 text_bounds: RectF,
323 cx: &mut EventContext<Editor>,
324 ) -> bool {
325 let end_selection = editor.has_pending_selection();
326 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
327
328 if end_selection {
329 editor.select(SelectPhase::End, cx);
330 }
331
332 if !pending_nonempty_selections && cmd && text_bounds.contains_point(position) {
333 let (point, target_point) = position_map.point_for_position(text_bounds, position);
334
335 if point == target_point {
336 if shift {
337 go_to_fetched_type_definition(editor, point, alt, cx);
338 } else {
339 go_to_fetched_definition(editor, point, alt, cx);
340 }
341
342 return true;
343 }
344 }
345
346 end_selection
347 }
348
349 fn mouse_dragged(
350 editor: &mut Editor,
351 MouseMovedEvent {
352 modifiers: Modifiers { cmd, shift, .. },
353 position,
354 ..
355 }: MouseMovedEvent,
356 position_map: &PositionMap,
357 text_bounds: RectF,
358 cx: &mut EventContext<Editor>,
359 ) -> bool {
360 // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
361 // Don't trigger hover popover if mouse is hovering over context menu
362 let point = if text_bounds.contains_point(position) {
363 let (point, target_point) = position_map.point_for_position(text_bounds, position);
364 if point == target_point {
365 Some(point)
366 } else {
367 None
368 }
369 } else {
370 None
371 };
372
373 update_go_to_definition_link(editor, point, cmd, shift, cx);
374
375 if editor.has_pending_selection() {
376 let mut scroll_delta = Vector2F::zero();
377
378 let vertical_margin = position_map.line_height.min(text_bounds.height() / 3.0);
379 let top = text_bounds.origin_y() + vertical_margin;
380 let bottom = text_bounds.lower_left().y() - vertical_margin;
381 if position.y() < top {
382 scroll_delta.set_y(-scale_vertical_mouse_autoscroll_delta(top - position.y()))
383 }
384 if position.y() > bottom {
385 scroll_delta.set_y(scale_vertical_mouse_autoscroll_delta(position.y() - bottom))
386 }
387
388 let horizontal_margin = position_map.line_height.min(text_bounds.width() / 3.0);
389 let left = text_bounds.origin_x() + horizontal_margin;
390 let right = text_bounds.upper_right().x() - horizontal_margin;
391 if position.x() < left {
392 scroll_delta.set_x(-scale_horizontal_mouse_autoscroll_delta(
393 left - position.x(),
394 ))
395 }
396 if position.x() > right {
397 scroll_delta.set_x(scale_horizontal_mouse_autoscroll_delta(
398 position.x() - right,
399 ))
400 }
401
402 let (position, target_position) =
403 position_map.point_for_position(text_bounds, position);
404
405 editor.select(
406 SelectPhase::Update {
407 position,
408 goal_column: target_position.column(),
409 scroll_position: (position_map.snapshot.scroll_position() + scroll_delta)
410 .clamp(Vector2F::zero(), position_map.scroll_max),
411 },
412 cx,
413 );
414 hover_at(editor, point, cx);
415 true
416 } else {
417 hover_at(editor, point, cx);
418 false
419 }
420 }
421
422 fn mouse_moved(
423 editor: &mut Editor,
424 MouseMovedEvent {
425 modifiers: Modifiers { shift, cmd, .. },
426 position,
427 ..
428 }: MouseMovedEvent,
429 position_map: &PositionMap,
430 text_bounds: RectF,
431 cx: &mut ViewContext<Editor>,
432 ) -> bool {
433 // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
434 // Don't trigger hover popover if mouse is hovering over context menu
435 let point = position_to_display_point(position, text_bounds, position_map);
436
437 update_go_to_definition_link(editor, point, cmd, shift, cx);
438 hover_at(editor, point, cx);
439
440 true
441 }
442
443 fn scroll(
444 editor: &mut Editor,
445 position: Vector2F,
446 mut delta: Vector2F,
447 precise: bool,
448 position_map: &PositionMap,
449 bounds: RectF,
450 cx: &mut ViewContext<Editor>,
451 ) -> bool {
452 if !bounds.contains_point(position) {
453 return false;
454 }
455
456 let line_height = position_map.line_height;
457 let max_glyph_width = position_map.em_width;
458
459 let axis = if precise {
460 //Trackpad
461 position_map.snapshot.ongoing_scroll.filter(&mut delta)
462 } else {
463 //Not trackpad
464 delta *= vec2f(max_glyph_width, line_height);
465 None //Resets ongoing scroll
466 };
467
468 let scroll_position = position_map.snapshot.scroll_position();
469 let x = (scroll_position.x() * max_glyph_width - delta.x()) / max_glyph_width;
470 let y = (scroll_position.y() * line_height - delta.y()) / line_height;
471 let scroll_position = vec2f(x, y).clamp(Vector2F::zero(), position_map.scroll_max);
472 editor.scroll(scroll_position, axis, cx);
473
474 true
475 }
476
477 fn paint_background(
478 &self,
479 scene: &mut SceneBuilder,
480 gutter_bounds: RectF,
481 text_bounds: RectF,
482 layout: &LayoutState,
483 ) {
484 let bounds = gutter_bounds.union_rect(text_bounds);
485 let scroll_top =
486 layout.position_map.snapshot.scroll_position().y() * layout.position_map.line_height;
487 scene.push_quad(Quad {
488 bounds: gutter_bounds,
489 background: Some(self.style.gutter_background),
490 border: Border::new(0., Color::transparent_black()),
491 corner_radius: 0.,
492 });
493 scene.push_quad(Quad {
494 bounds: text_bounds,
495 background: Some(self.style.background),
496 border: Border::new(0., Color::transparent_black()),
497 corner_radius: 0.,
498 });
499
500 if let EditorMode::Full = layout.mode {
501 let mut active_rows = layout.active_rows.iter().peekable();
502 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
503 let mut end_row = *start_row;
504 while active_rows.peek().map_or(false, |r| {
505 *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
506 }) {
507 active_rows.next().unwrap();
508 end_row += 1;
509 }
510
511 if !contains_non_empty_selection {
512 let origin = vec2f(
513 bounds.origin_x(),
514 bounds.origin_y() + (layout.position_map.line_height * *start_row as f32)
515 - scroll_top,
516 );
517 let size = vec2f(
518 bounds.width(),
519 layout.position_map.line_height * (end_row - start_row + 1) as f32,
520 );
521 scene.push_quad(Quad {
522 bounds: RectF::new(origin, size),
523 background: Some(self.style.active_line_background),
524 border: Border::default(),
525 corner_radius: 0.,
526 });
527 }
528 }
529
530 if let Some(highlighted_rows) = &layout.highlighted_rows {
531 let origin = vec2f(
532 bounds.origin_x(),
533 bounds.origin_y()
534 + (layout.position_map.line_height * highlighted_rows.start as f32)
535 - scroll_top,
536 );
537 let size = vec2f(
538 bounds.width(),
539 layout.position_map.line_height * highlighted_rows.len() as f32,
540 );
541 scene.push_quad(Quad {
542 bounds: RectF::new(origin, size),
543 background: Some(self.style.highlighted_line_background),
544 border: Border::default(),
545 corner_radius: 0.,
546 });
547 }
548
549 let scroll_left =
550 layout.position_map.snapshot.scroll_position().x() * layout.position_map.em_width;
551
552 for (wrap_position, active) in layout.wrap_guides.iter() {
553 let x =
554 (text_bounds.origin_x() + wrap_position + layout.position_map.em_width / 2.)
555 - scroll_left;
556
557 if x < text_bounds.origin_x() {
558 continue;
559 }
560
561 let color = if *active {
562 self.style.active_wrap_guide
563 } else {
564 self.style.wrap_guide
565 };
566 scene.push_quad(Quad {
567 bounds: RectF::new(
568 vec2f(x, text_bounds.origin_y()),
569 vec2f(1., text_bounds.height()),
570 ),
571 background: Some(color),
572 border: Border::new(0., Color::transparent_black()),
573 corner_radius: 0.,
574 });
575 }
576 }
577 }
578
579 fn paint_gutter(
580 &mut self,
581 scene: &mut SceneBuilder,
582 bounds: RectF,
583 visible_bounds: RectF,
584 layout: &mut LayoutState,
585 editor: &mut Editor,
586 cx: &mut ViewContext<Editor>,
587 ) {
588 let line_height = layout.position_map.line_height;
589
590 let scroll_position = layout.position_map.snapshot.scroll_position();
591 let scroll_top = scroll_position.y() * line_height;
592
593 let show_gutter = matches!(
594 settings::get::<ProjectSettings>(cx).git.git_gutter,
595 Some(GitGutterSetting::TrackedFiles)
596 );
597
598 if show_gutter {
599 Self::paint_diff_hunks(scene, bounds, layout, cx);
600 }
601
602 for (ix, line) in layout.line_number_layouts.iter().enumerate() {
603 if let Some(line) = line {
604 let line_origin = bounds.origin()
605 + vec2f(
606 bounds.width() - line.width() - layout.gutter_padding,
607 ix as f32 * line_height - (scroll_top % line_height),
608 );
609
610 line.paint(scene, line_origin, visible_bounds, line_height, cx);
611 }
612 }
613
614 for (ix, fold_indicator) in layout.fold_indicators.iter_mut().enumerate() {
615 if let Some(indicator) = fold_indicator.as_mut() {
616 let position = vec2f(
617 bounds.width() - layout.gutter_padding,
618 ix as f32 * line_height - (scroll_top % line_height),
619 );
620 let centering_offset = vec2f(
621 (layout.gutter_padding + layout.gutter_margin - indicator.size().x()) / 2.,
622 (line_height - indicator.size().y()) / 2.,
623 );
624
625 let indicator_origin = bounds.origin() + position + centering_offset;
626
627 indicator.paint(scene, indicator_origin, visible_bounds, editor, cx);
628 }
629 }
630
631 if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
632 let mut x = 0.;
633 let mut y = *row as f32 * line_height - scroll_top;
634 x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
635 y += (line_height - indicator.size().y()) / 2.;
636 indicator.paint(
637 scene,
638 bounds.origin() + vec2f(x, y),
639 visible_bounds,
640 editor,
641 cx,
642 );
643 }
644 }
645
646 fn paint_diff_hunks(
647 scene: &mut SceneBuilder,
648 bounds: RectF,
649 layout: &mut LayoutState,
650 cx: &mut ViewContext<Editor>,
651 ) {
652 let diff_style = &theme::current(cx).editor.diff.clone();
653 let line_height = layout.position_map.line_height;
654
655 let scroll_position = layout.position_map.snapshot.scroll_position();
656 let scroll_top = scroll_position.y() * line_height;
657
658 for hunk in &layout.display_hunks {
659 let (display_row_range, status) = match hunk {
660 //TODO: This rendering is entirely a horrible hack
661 &DisplayDiffHunk::Folded { display_row: row } => {
662 let start_y = row as f32 * line_height - scroll_top;
663 let end_y = start_y + line_height;
664
665 let width = diff_style.removed_width_em * line_height;
666 let highlight_origin = bounds.origin() + vec2f(-width, start_y);
667 let highlight_size = vec2f(width * 2., end_y - start_y);
668 let highlight_bounds = RectF::new(highlight_origin, highlight_size);
669
670 scene.push_quad(Quad {
671 bounds: highlight_bounds,
672 background: Some(diff_style.modified),
673 border: Border::new(0., Color::transparent_black()),
674 corner_radius: 1. * line_height,
675 });
676
677 continue;
678 }
679
680 DisplayDiffHunk::Unfolded {
681 display_row_range,
682 status,
683 } => (display_row_range, status),
684 };
685
686 let color = match status {
687 DiffHunkStatus::Added => diff_style.inserted,
688 DiffHunkStatus::Modified => diff_style.modified,
689
690 //TODO: This rendering is entirely a horrible hack
691 DiffHunkStatus::Removed => {
692 let row = display_row_range.start;
693
694 let offset = line_height / 2.;
695 let start_y = row as f32 * line_height - offset - scroll_top;
696 let end_y = start_y + line_height;
697
698 let width = diff_style.removed_width_em * line_height;
699 let highlight_origin = bounds.origin() + vec2f(-width, start_y);
700 let highlight_size = vec2f(width * 2., end_y - start_y);
701 let highlight_bounds = RectF::new(highlight_origin, highlight_size);
702
703 scene.push_quad(Quad {
704 bounds: highlight_bounds,
705 background: Some(diff_style.deleted),
706 border: Border::new(0., Color::transparent_black()),
707 corner_radius: 1. * line_height,
708 });
709
710 continue;
711 }
712 };
713
714 let start_row = display_row_range.start;
715 let end_row = display_row_range.end;
716
717 let start_y = start_row as f32 * line_height - scroll_top;
718 let end_y = end_row as f32 * line_height - scroll_top;
719
720 let width = diff_style.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(color),
728 border: Border::new(0., Color::transparent_black()),
729 corner_radius: diff_style.corner_radius * line_height,
730 });
731 }
732 }
733
734 fn paint_text(
735 &mut self,
736 scene: &mut SceneBuilder,
737 bounds: RectF,
738 visible_bounds: RectF,
739 layout: &mut LayoutState,
740 editor: &mut Editor,
741 cx: &mut ViewContext<Editor>,
742 ) {
743 let style = &self.style;
744 let local_replica_id = editor.replica_id(cx);
745 let scroll_position = layout.position_map.snapshot.scroll_position();
746 let start_row = layout.visible_display_row_range.start;
747 let scroll_top = scroll_position.y() * layout.position_map.line_height;
748 let max_glyph_width = layout.position_map.em_width;
749 let scroll_left = scroll_position.x() * max_glyph_width;
750 let content_origin = bounds.origin() + vec2f(layout.gutter_margin, 0.);
751 let line_end_overshoot = 0.15 * layout.position_map.line_height;
752 let whitespace_setting = editor.buffer.read(cx).settings_at(0, cx).show_whitespaces;
753
754 scene.push_layer(Some(bounds));
755
756 scene.push_cursor_region(CursorRegion {
757 bounds,
758 style: if !editor.link_go_to_definition_state.definitions.is_empty() {
759 CursorStyle::PointingHand
760 } else {
761 CursorStyle::IBeam
762 },
763 });
764
765 let fold_corner_radius =
766 self.style.folds.ellipses.corner_radius_factor * layout.position_map.line_height;
767 for (id, range, color) in layout.fold_ranges.iter() {
768 self.paint_highlighted_range(
769 scene,
770 range.clone(),
771 *color,
772 fold_corner_radius,
773 fold_corner_radius * 2.,
774 layout,
775 content_origin,
776 scroll_top,
777 scroll_left,
778 bounds,
779 );
780
781 for bound in range_to_bounds(
782 &range,
783 content_origin,
784 scroll_left,
785 scroll_top,
786 &layout.visible_display_row_range,
787 line_end_overshoot,
788 &layout.position_map,
789 ) {
790 scene.push_cursor_region(CursorRegion {
791 bounds: bound,
792 style: CursorStyle::PointingHand,
793 });
794
795 let display_row = range.start.row();
796
797 let buffer_row = DisplayPoint::new(display_row, 0)
798 .to_point(&layout.position_map.snapshot.display_snapshot)
799 .row;
800
801 scene.push_mouse_region(
802 MouseRegion::new::<FoldMarkers>(cx.view_id(), *id as usize, bound)
803 .on_click(MouseButton::Left, move |_, editor: &mut Editor, cx| {
804 editor.unfold_at(&UnfoldAt { buffer_row }, cx)
805 })
806 .with_notify_on_hover(true)
807 .with_notify_on_click(true),
808 )
809 }
810 }
811
812 for (range, color) in &layout.highlighted_ranges {
813 self.paint_highlighted_range(
814 scene,
815 range.clone(),
816 *color,
817 0.,
818 line_end_overshoot,
819 layout,
820 content_origin,
821 scroll_top,
822 scroll_left,
823 bounds,
824 );
825 }
826
827 let mut cursors = SmallVec::<[Cursor; 32]>::new();
828 let corner_radius = 0.15 * layout.position_map.line_height;
829 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
830
831 for (replica_id, selections) in &layout.selections {
832 let replica_id = *replica_id;
833 let selection_style = style.replica_selection_style(replica_id);
834
835 for selection in selections {
836 if !selection.range.is_empty()
837 && (replica_id == local_replica_id
838 || Some(replica_id) == editor.leader_replica_id)
839 {
840 invisible_display_ranges.push(selection.range.clone());
841 }
842 self.paint_highlighted_range(
843 scene,
844 selection.range.clone(),
845 selection_style.selection,
846 corner_radius,
847 corner_radius * 2.,
848 layout,
849 content_origin,
850 scroll_top,
851 scroll_left,
852 bounds,
853 );
854
855 if editor.show_local_cursors(cx) || replica_id != local_replica_id {
856 let cursor_position = selection.head;
857 if layout
858 .visible_display_row_range
859 .contains(&cursor_position.row())
860 {
861 let cursor_row_layout = &layout.position_map.line_layouts
862 [(cursor_position.row() - start_row) as usize]
863 .line;
864 let cursor_column = cursor_position.column() as usize;
865
866 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
867 let mut block_width =
868 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
869 if block_width == 0.0 {
870 block_width = layout.position_map.em_width;
871 }
872 let block_text = if let CursorShape::Block = selection.cursor_shape {
873 layout
874 .position_map
875 .snapshot
876 .chars_at(cursor_position)
877 .next()
878 .and_then(|(character, _)| {
879 let font_id =
880 cursor_row_layout.font_for_index(cursor_column)?;
881 let text = character.to_string();
882
883 Some(cx.text_layout_cache().layout_str(
884 &text,
885 cursor_row_layout.font_size(),
886 &[(
887 text.len(),
888 RunStyle {
889 font_id,
890 color: style.background,
891 underline: Default::default(),
892 },
893 )],
894 ))
895 })
896 } else {
897 None
898 };
899
900 let x = cursor_character_x - scroll_left;
901 let y = cursor_position.row() as f32 * layout.position_map.line_height
902 - scroll_top;
903 if selection.is_newest {
904 editor.pixel_position_of_newest_cursor = Some(vec2f(
905 bounds.origin_x() + x + block_width / 2.,
906 bounds.origin_y() + y + layout.position_map.line_height / 2.,
907 ));
908 }
909 cursors.push(Cursor {
910 color: selection_style.cursor,
911 block_width,
912 origin: vec2f(x, y),
913 line_height: layout.position_map.line_height,
914 shape: selection.cursor_shape,
915 block_text,
916 });
917 }
918 }
919 }
920 }
921
922 if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
923 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
924 let row = start_row + ix as u32;
925 line_with_invisibles.draw(
926 layout,
927 row,
928 scroll_top,
929 scene,
930 content_origin,
931 scroll_left,
932 visible_text_bounds,
933 whitespace_setting,
934 &invisible_display_ranges,
935 visible_bounds,
936 cx,
937 )
938 }
939 }
940
941 scene.paint_layer(Some(bounds), |scene| {
942 for cursor in cursors {
943 cursor.paint(scene, content_origin, cx);
944 }
945 });
946
947 if let Some((position, context_menu)) = layout.context_menu.as_mut() {
948 scene.push_stacking_context(None, None);
949 let cursor_row_layout =
950 &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
951 let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
952 let y = (position.row() + 1) as f32 * layout.position_map.line_height - scroll_top;
953 let mut list_origin = content_origin + vec2f(x, y);
954 let list_width = context_menu.size().x();
955 let list_height = context_menu.size().y();
956
957 // Snap the right edge of the list to the right edge of the window if
958 // its horizontal bounds overflow.
959 if list_origin.x() + list_width > cx.window_size().x() {
960 list_origin.set_x((cx.window_size().x() - list_width).max(0.));
961 }
962
963 if list_origin.y() + list_height > bounds.max_y() {
964 list_origin.set_y(list_origin.y() - layout.position_map.line_height - list_height);
965 }
966
967 context_menu.paint(
968 scene,
969 list_origin,
970 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
971 editor,
972 cx,
973 );
974
975 scene.pop_stacking_context();
976 }
977
978 if let Some((position, hover_popovers)) = layout.hover_popovers.as_mut() {
979 scene.push_stacking_context(None, None);
980
981 // This is safe because we check on layout whether the required row is available
982 let hovered_row_layout =
983 &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
984
985 // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
986 // height. This is the size we will use to decide whether to render popovers above or below
987 // the hovered line.
988 let first_size = hover_popovers[0].size();
989 let height_to_reserve = first_size.y()
990 + 1.5 * MIN_POPOVER_LINE_HEIGHT as f32 * layout.position_map.line_height;
991
992 // Compute Hovered Point
993 let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
994 let y = position.row() as f32 * layout.position_map.line_height - scroll_top;
995 let hovered_point = content_origin + vec2f(x, y);
996
997 if hovered_point.y() - height_to_reserve > 0.0 {
998 // There is enough space above. Render popovers above the hovered point
999 let mut current_y = hovered_point.y();
1000 for hover_popover in hover_popovers {
1001 let size = hover_popover.size();
1002 let mut popover_origin = vec2f(hovered_point.x(), current_y - size.y());
1003
1004 let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
1005 if x_out_of_bounds < 0.0 {
1006 popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
1007 }
1008
1009 hover_popover.paint(
1010 scene,
1011 popover_origin,
1012 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
1013 editor,
1014 cx,
1015 );
1016
1017 current_y = popover_origin.y() - HOVER_POPOVER_GAP;
1018 }
1019 } else {
1020 // There is not enough space above. Render popovers below the hovered point
1021 let mut current_y = hovered_point.y() + layout.position_map.line_height;
1022 for hover_popover in hover_popovers {
1023 let size = hover_popover.size();
1024 let mut popover_origin = vec2f(hovered_point.x(), current_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() + size.y() + HOVER_POPOVER_GAP;
1040 }
1041 }
1042
1043 scene.pop_stacking_context();
1044 }
1045
1046 scene.pop_layer();
1047 }
1048
1049 fn paint_scrollbar(
1050 &mut self,
1051 scene: &mut SceneBuilder,
1052 bounds: RectF,
1053 layout: &mut LayoutState,
1054 cx: &mut ViewContext<Editor>,
1055 editor: &Editor,
1056 ) {
1057 enum ScrollbarMouseHandlers {}
1058 if layout.mode != EditorMode::Full {
1059 return;
1060 }
1061
1062 let style = &self.style.theme.scrollbar;
1063
1064 let top = bounds.min_y();
1065 let bottom = bounds.max_y();
1066 let right = bounds.max_x();
1067 let left = right - style.width;
1068 let row_range = &layout.scrollbar_row_range;
1069 let max_row = layout.max_row as f32 + (row_range.end - row_range.start);
1070
1071 let mut height = bounds.height();
1072 let mut first_row_y_offset = 0.0;
1073
1074 // Impose a minimum height on the scrollbar thumb
1075 let row_height = height / max_row;
1076 let min_thumb_height =
1077 style.min_height_factor * cx.font_cache.line_height(self.style.text.font_size);
1078 let thumb_height = (row_range.end - row_range.start) * row_height;
1079 if thumb_height < min_thumb_height {
1080 first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
1081 height -= min_thumb_height - thumb_height;
1082 }
1083
1084 let y_for_row = |row: f32| -> f32 { top + first_row_y_offset + row * row_height };
1085
1086 let thumb_top = y_for_row(row_range.start) - first_row_y_offset;
1087 let thumb_bottom = y_for_row(row_range.end) + first_row_y_offset;
1088 let track_bounds = RectF::from_points(vec2f(left, top), vec2f(right, bottom));
1089 let thumb_bounds = RectF::from_points(vec2f(left, thumb_top), vec2f(right, thumb_bottom));
1090
1091 if layout.show_scrollbars {
1092 scene.push_quad(Quad {
1093 bounds: track_bounds,
1094 border: style.track.border,
1095 background: style.track.background_color,
1096 ..Default::default()
1097 });
1098 let scrollbar_settings = settings::get::<EditorSettings>(cx).scrollbar;
1099 let theme = theme::current(cx);
1100 let scrollbar_theme = &theme.editor.scrollbar;
1101 if layout.is_singleton && scrollbar_settings.selections {
1102 let start_anchor = Anchor::min();
1103 let end_anchor = Anchor::max();
1104 let mut start_row = None;
1105 let mut end_row = None;
1106 let color = scrollbar_theme.selections;
1107 let border = Border {
1108 width: 1.,
1109 color: style.thumb.border.color,
1110 overlay: false,
1111 top: false,
1112 right: true,
1113 bottom: false,
1114 left: true,
1115 };
1116 let mut push_region = |start, end| {
1117 if let (Some(start_display), Some(end_display)) = (start, end) {
1118 let start_y = y_for_row(start_display as f32);
1119 let mut end_y = y_for_row(end_display as f32);
1120 if end_y - start_y < 1. {
1121 end_y = start_y + 1.;
1122 }
1123 let bounds = RectF::from_points(vec2f(left, start_y), vec2f(right, end_y));
1124
1125 scene.push_quad(Quad {
1126 bounds,
1127 background: Some(color),
1128 border,
1129 corner_radius: style.thumb.corner_radius,
1130 })
1131 }
1132 };
1133 for (row, _) in &editor
1134 .background_highlights_in_range_for::<crate::items::BufferSearchHighlights>(
1135 start_anchor..end_anchor,
1136 &layout.position_map.snapshot,
1137 &theme,
1138 )
1139 {
1140 let start_display = row.start;
1141 let end_display = row.end;
1142
1143 if start_row.is_none() {
1144 assert_eq!(end_row, None);
1145 start_row = Some(start_display.row());
1146 end_row = Some(end_display.row());
1147 continue;
1148 }
1149 if let Some(current_end) = end_row.as_mut() {
1150 if start_display.row() > *current_end + 1 {
1151 push_region(start_row, end_row);
1152 start_row = Some(start_display.row());
1153 end_row = Some(end_display.row());
1154 } else {
1155 // Merge two hunks.
1156 *current_end = end_display.row();
1157 }
1158 } else {
1159 unreachable!();
1160 }
1161 }
1162 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
1163 push_region(start_row, end_row);
1164 }
1165
1166 if layout.is_singleton && scrollbar_settings.git_diff {
1167 let diff_style = scrollbar_theme.git.clone();
1168 for hunk in layout
1169 .position_map
1170 .snapshot
1171 .buffer_snapshot
1172 .git_diff_hunks_in_range(0..(max_row.floor() as u32))
1173 {
1174 let start_display = Point::new(hunk.buffer_range.start, 0)
1175 .to_display_point(&layout.position_map.snapshot.display_snapshot);
1176 let end_display = Point::new(hunk.buffer_range.end, 0)
1177 .to_display_point(&layout.position_map.snapshot.display_snapshot);
1178 let start_y = y_for_row(start_display.row() as f32);
1179 let mut end_y = if hunk.buffer_range.start == hunk.buffer_range.end {
1180 y_for_row((end_display.row() + 1) as f32)
1181 } else {
1182 y_for_row((end_display.row()) as f32)
1183 };
1184
1185 if end_y - start_y < 1. {
1186 end_y = start_y + 1.;
1187 }
1188 let bounds = RectF::from_points(vec2f(left, start_y), vec2f(right, end_y));
1189
1190 let color = match hunk.status() {
1191 DiffHunkStatus::Added => diff_style.inserted,
1192 DiffHunkStatus::Modified => diff_style.modified,
1193 DiffHunkStatus::Removed => diff_style.deleted,
1194 };
1195
1196 let border = Border {
1197 width: 1.,
1198 color: style.thumb.border.color,
1199 overlay: false,
1200 top: false,
1201 right: true,
1202 bottom: false,
1203 left: true,
1204 };
1205
1206 scene.push_quad(Quad {
1207 bounds,
1208 background: Some(color),
1209 border,
1210 corner_radius: style.thumb.corner_radius,
1211 })
1212 }
1213 }
1214
1215 scene.push_quad(Quad {
1216 bounds: thumb_bounds,
1217 border: style.thumb.border,
1218 background: style.thumb.background_color,
1219 corner_radius: style.thumb.corner_radius,
1220 });
1221 }
1222
1223 scene.push_cursor_region(CursorRegion {
1224 bounds: track_bounds,
1225 style: CursorStyle::Arrow,
1226 });
1227 scene.push_mouse_region(
1228 MouseRegion::new::<ScrollbarMouseHandlers>(cx.view_id(), cx.view_id(), track_bounds)
1229 .on_move(move |event, editor: &mut Editor, cx| {
1230 if event.pressed_button.is_none() {
1231 editor.scroll_manager.show_scrollbar(cx);
1232 }
1233 })
1234 .on_down(MouseButton::Left, {
1235 let row_range = row_range.clone();
1236 move |event, editor: &mut Editor, cx| {
1237 let y = event.position.y();
1238 if y < thumb_top || thumb_bottom < y {
1239 let center_row = ((y - top) * max_row as f32 / height).round() as u32;
1240 let top_row = center_row
1241 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
1242 let mut position = editor.scroll_position(cx);
1243 position.set_y(top_row as f32);
1244 editor.set_scroll_position(position, cx);
1245 } else {
1246 editor.scroll_manager.show_scrollbar(cx);
1247 }
1248 }
1249 })
1250 .on_drag(MouseButton::Left, {
1251 move |event, editor: &mut Editor, cx| {
1252 if event.end {
1253 return;
1254 }
1255
1256 let y = event.prev_mouse_position.y();
1257 let new_y = event.position.y();
1258 if thumb_top < y && y < thumb_bottom {
1259 let mut position = editor.scroll_position(cx);
1260 position.set_y(position.y() + (new_y - y) * (max_row as f32) / height);
1261 if position.y() < 0.0 {
1262 position.set_y(0.);
1263 }
1264 editor.set_scroll_position(position, cx);
1265 }
1266 }
1267 }),
1268 );
1269 }
1270
1271 #[allow(clippy::too_many_arguments)]
1272 fn paint_highlighted_range(
1273 &self,
1274 scene: &mut SceneBuilder,
1275 range: Range<DisplayPoint>,
1276 color: Color,
1277 corner_radius: f32,
1278 line_end_overshoot: f32,
1279 layout: &LayoutState,
1280 content_origin: Vector2F,
1281 scroll_top: f32,
1282 scroll_left: f32,
1283 bounds: RectF,
1284 ) {
1285 let start_row = layout.visible_display_row_range.start;
1286 let end_row = layout.visible_display_row_range.end;
1287 if range.start != range.end {
1288 let row_range = if range.end.column() == 0 {
1289 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
1290 } else {
1291 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
1292 };
1293
1294 let highlighted_range = HighlightedRange {
1295 color,
1296 line_height: layout.position_map.line_height,
1297 corner_radius,
1298 start_y: content_origin.y()
1299 + row_range.start as f32 * layout.position_map.line_height
1300 - scroll_top,
1301 lines: row_range
1302 .into_iter()
1303 .map(|row| {
1304 let line_layout =
1305 &layout.position_map.line_layouts[(row - start_row) as usize].line;
1306 HighlightedRangeLine {
1307 start_x: if row == range.start.row() {
1308 content_origin.x()
1309 + line_layout.x_for_index(range.start.column() as usize)
1310 - scroll_left
1311 } else {
1312 content_origin.x() - scroll_left
1313 },
1314 end_x: if row == range.end.row() {
1315 content_origin.x()
1316 + line_layout.x_for_index(range.end.column() as usize)
1317 - scroll_left
1318 } else {
1319 content_origin.x() + line_layout.width() + line_end_overshoot
1320 - scroll_left
1321 },
1322 }
1323 })
1324 .collect(),
1325 };
1326
1327 highlighted_range.paint(bounds, scene);
1328 }
1329 }
1330
1331 fn paint_blocks(
1332 &mut self,
1333 scene: &mut SceneBuilder,
1334 bounds: RectF,
1335 visible_bounds: RectF,
1336 layout: &mut LayoutState,
1337 editor: &mut Editor,
1338 cx: &mut ViewContext<Editor>,
1339 ) {
1340 let scroll_position = layout.position_map.snapshot.scroll_position();
1341 let scroll_left = scroll_position.x() * layout.position_map.em_width;
1342 let scroll_top = scroll_position.y() * layout.position_map.line_height;
1343
1344 for block in &mut layout.blocks {
1345 let mut origin = bounds.origin()
1346 + vec2f(
1347 0.,
1348 block.row as f32 * layout.position_map.line_height - scroll_top,
1349 );
1350 if !matches!(block.style, BlockStyle::Sticky) {
1351 origin += vec2f(-scroll_left, 0.);
1352 }
1353 block
1354 .element
1355 .paint(scene, origin, visible_bounds, editor, cx);
1356 }
1357 }
1358
1359 fn column_pixels(&self, column: usize, cx: &ViewContext<Editor>) -> f32 {
1360 let style = &self.style;
1361
1362 cx.text_layout_cache()
1363 .layout_str(
1364 " ".repeat(column).as_str(),
1365 style.text.font_size,
1366 &[(
1367 column,
1368 RunStyle {
1369 font_id: style.text.font_id,
1370 color: Color::black(),
1371 underline: Default::default(),
1372 },
1373 )],
1374 )
1375 .width()
1376 }
1377
1378 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &ViewContext<Editor>) -> f32 {
1379 let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
1380 self.column_pixels(digit_count, cx)
1381 }
1382
1383 //Folds contained in a hunk are ignored apart from shrinking visual size
1384 //If a fold contains any hunks then that fold line is marked as modified
1385 fn layout_git_gutters(
1386 &self,
1387 display_rows: Range<u32>,
1388 snapshot: &EditorSnapshot,
1389 ) -> Vec<DisplayDiffHunk> {
1390 let buffer_snapshot = &snapshot.buffer_snapshot;
1391
1392 let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1393 .to_point(snapshot)
1394 .row;
1395 let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1396 .to_point(snapshot)
1397 .row;
1398
1399 buffer_snapshot
1400 .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1401 .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1402 .dedup()
1403 .collect()
1404 }
1405
1406 fn layout_line_numbers(
1407 &self,
1408 rows: Range<u32>,
1409 active_rows: &BTreeMap<u32, bool>,
1410 is_singleton: bool,
1411 snapshot: &EditorSnapshot,
1412 cx: &ViewContext<Editor>,
1413 ) -> (
1414 Vec<Option<text_layout::Line>>,
1415 Vec<Option<(FoldStatus, BufferRow, bool)>>,
1416 ) {
1417 let style = &self.style;
1418 let include_line_numbers = snapshot.mode == EditorMode::Full;
1419 let mut line_number_layouts = Vec::with_capacity(rows.len());
1420 let mut fold_statuses = Vec::with_capacity(rows.len());
1421 let mut line_number = String::new();
1422 for (ix, row) in snapshot
1423 .buffer_rows(rows.start)
1424 .take((rows.end - rows.start) as usize)
1425 .enumerate()
1426 {
1427 let display_row = rows.start + ix as u32;
1428 let (active, color) = if active_rows.contains_key(&display_row) {
1429 (true, style.line_number_active)
1430 } else {
1431 (false, style.line_number)
1432 };
1433 if let Some(buffer_row) = row {
1434 if include_line_numbers {
1435 line_number.clear();
1436 write!(&mut line_number, "{}", buffer_row + 1).unwrap();
1437 line_number_layouts.push(Some(cx.text_layout_cache().layout_str(
1438 &line_number,
1439 style.text.font_size,
1440 &[(
1441 line_number.len(),
1442 RunStyle {
1443 font_id: style.text.font_id,
1444 color,
1445 underline: Default::default(),
1446 },
1447 )],
1448 )));
1449 fold_statuses.push(
1450 is_singleton
1451 .then(|| {
1452 snapshot
1453 .fold_for_line(buffer_row)
1454 .map(|fold_status| (fold_status, buffer_row, active))
1455 })
1456 .flatten(),
1457 )
1458 }
1459 } else {
1460 fold_statuses.push(None);
1461 line_number_layouts.push(None);
1462 }
1463 }
1464
1465 (line_number_layouts, fold_statuses)
1466 }
1467
1468 fn layout_lines(
1469 &mut self,
1470 rows: Range<u32>,
1471 line_number_layouts: &[Option<Line>],
1472 snapshot: &EditorSnapshot,
1473 cx: &ViewContext<Editor>,
1474 ) -> Vec<LineWithInvisibles> {
1475 if rows.start >= rows.end {
1476 return Vec::new();
1477 }
1478
1479 // When the editor is empty and unfocused, then show the placeholder.
1480 if snapshot.is_empty() {
1481 let placeholder_style = self
1482 .style
1483 .placeholder_text
1484 .as_ref()
1485 .unwrap_or(&self.style.text);
1486 let placeholder_text = snapshot.placeholder_text();
1487 let placeholder_lines = placeholder_text
1488 .as_ref()
1489 .map_or("", AsRef::as_ref)
1490 .split('\n')
1491 .skip(rows.start as usize)
1492 .chain(iter::repeat(""))
1493 .take(rows.len());
1494 placeholder_lines
1495 .map(|line| {
1496 cx.text_layout_cache().layout_str(
1497 line,
1498 placeholder_style.font_size,
1499 &[(
1500 line.len(),
1501 RunStyle {
1502 font_id: placeholder_style.font_id,
1503 color: placeholder_style.color,
1504 underline: Default::default(),
1505 },
1506 )],
1507 )
1508 })
1509 .map(|line| LineWithInvisibles {
1510 line,
1511 invisibles: Vec::new(),
1512 })
1513 .collect()
1514 } else {
1515 let style = &self.style;
1516 let chunks = snapshot
1517 .chunks(
1518 rows.clone(),
1519 true,
1520 Some(style.theme.hint),
1521 Some(style.theme.suggestion),
1522 )
1523 .map(|chunk| {
1524 let mut highlight_style = chunk
1525 .syntax_highlight_id
1526 .and_then(|id| id.style(&style.syntax));
1527
1528 if let Some(chunk_highlight) = chunk.highlight_style {
1529 if let Some(highlight_style) = highlight_style.as_mut() {
1530 highlight_style.highlight(chunk_highlight);
1531 } else {
1532 highlight_style = Some(chunk_highlight);
1533 }
1534 }
1535
1536 let mut diagnostic_highlight = HighlightStyle::default();
1537
1538 if chunk.is_unnecessary {
1539 diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
1540 }
1541
1542 if let Some(severity) = chunk.diagnostic_severity {
1543 // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
1544 if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
1545 let diagnostic_style = super::diagnostic_style(severity, true, style);
1546 diagnostic_highlight.underline = Some(Underline {
1547 color: Some(diagnostic_style.message.text.color),
1548 thickness: 1.0.into(),
1549 squiggly: true,
1550 });
1551 }
1552 }
1553
1554 if let Some(highlight_style) = highlight_style.as_mut() {
1555 highlight_style.highlight(diagnostic_highlight);
1556 } else {
1557 highlight_style = Some(diagnostic_highlight);
1558 }
1559
1560 HighlightedChunk {
1561 chunk: chunk.text,
1562 style: highlight_style,
1563 is_tab: chunk.is_tab,
1564 }
1565 });
1566
1567 LineWithInvisibles::from_chunks(
1568 chunks,
1569 &style.text,
1570 cx.text_layout_cache(),
1571 cx.font_cache(),
1572 MAX_LINE_LEN,
1573 rows.len() as usize,
1574 line_number_layouts,
1575 snapshot.mode,
1576 )
1577 }
1578 }
1579
1580 #[allow(clippy::too_many_arguments)]
1581 fn layout_blocks(
1582 &mut self,
1583 rows: Range<u32>,
1584 snapshot: &EditorSnapshot,
1585 editor_width: f32,
1586 scroll_width: f32,
1587 gutter_padding: f32,
1588 gutter_width: f32,
1589 em_width: f32,
1590 text_x: f32,
1591 line_height: f32,
1592 style: &EditorStyle,
1593 line_layouts: &[LineWithInvisibles],
1594 editor: &mut Editor,
1595 cx: &mut LayoutContext<Editor>,
1596 ) -> (f32, Vec<BlockLayout>) {
1597 let mut block_id = 0;
1598 let scroll_x = snapshot.scroll_anchor.offset.x();
1599 let (fixed_blocks, non_fixed_blocks) = snapshot
1600 .blocks_in_range(rows.clone())
1601 .partition::<Vec<_>, _>(|(_, block)| match block {
1602 TransformBlock::ExcerptHeader { .. } => false,
1603 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1604 });
1605 let mut render_block = |block: &TransformBlock, width: f32, block_id: usize| {
1606 let mut element = match block {
1607 TransformBlock::Custom(block) => {
1608 let align_to = block
1609 .position()
1610 .to_point(&snapshot.buffer_snapshot)
1611 .to_display_point(snapshot);
1612 let anchor_x = text_x
1613 + if rows.contains(&align_to.row()) {
1614 line_layouts[(align_to.row() - rows.start) as usize]
1615 .line
1616 .x_for_index(align_to.column() as usize)
1617 } else {
1618 layout_line(align_to.row(), snapshot, style, cx.text_layout_cache())
1619 .x_for_index(align_to.column() as usize)
1620 };
1621
1622 block.render(&mut BlockContext {
1623 view_context: cx,
1624 anchor_x,
1625 gutter_padding,
1626 line_height,
1627 scroll_x,
1628 gutter_width,
1629 em_width,
1630 block_id,
1631 })
1632 }
1633 TransformBlock::ExcerptHeader {
1634 id,
1635 buffer,
1636 range,
1637 starts_new_buffer,
1638 ..
1639 } => {
1640 let tooltip_style = theme::current(cx).tooltip.clone();
1641 let include_root = editor
1642 .project
1643 .as_ref()
1644 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1645 .unwrap_or_default();
1646 let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1647 let jump_path = ProjectPath {
1648 worktree_id: file.worktree_id(cx),
1649 path: file.path.clone(),
1650 };
1651 let jump_anchor = range
1652 .primary
1653 .as_ref()
1654 .map_or(range.context.start, |primary| primary.start);
1655 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1656
1657 enum JumpIcon {}
1658 MouseEventHandler::<JumpIcon, _>::new((*id).into(), cx, |state, _| {
1659 let style = style.jump_icon.style_for(state);
1660 Svg::new("icons/arrow_up_right_8.svg")
1661 .with_color(style.color)
1662 .constrained()
1663 .with_width(style.icon_width)
1664 .aligned()
1665 .contained()
1666 .with_style(style.container)
1667 .constrained()
1668 .with_width(style.button_width)
1669 .with_height(style.button_width)
1670 })
1671 .with_cursor_style(CursorStyle::PointingHand)
1672 .on_click(MouseButton::Left, move |_, editor, cx| {
1673 if let Some(workspace) = editor
1674 .workspace
1675 .as_ref()
1676 .and_then(|(workspace, _)| workspace.upgrade(cx))
1677 {
1678 workspace.update(cx, |workspace, cx| {
1679 Editor::jump(
1680 workspace,
1681 jump_path.clone(),
1682 jump_position,
1683 jump_anchor,
1684 cx,
1685 );
1686 });
1687 }
1688 })
1689 .with_tooltip::<JumpIcon>(
1690 (*id).into(),
1691 "Jump to Buffer".to_string(),
1692 Some(Box::new(crate::OpenExcerpts)),
1693 tooltip_style.clone(),
1694 cx,
1695 )
1696 .aligned()
1697 .flex_float()
1698 });
1699
1700 if *starts_new_buffer {
1701 let editor_font_size = style.text.font_size;
1702 let style = &style.diagnostic_path_header;
1703 let font_size = (style.text_scale_factor * editor_font_size).round();
1704
1705 let path = buffer.resolve_file_path(cx, include_root);
1706 let mut filename = None;
1707 let mut parent_path = None;
1708 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1709 if let Some(path) = path {
1710 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1711 parent_path =
1712 path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1713 }
1714
1715 Flex::row()
1716 .with_child(
1717 Label::new(
1718 filename.unwrap_or_else(|| "untitled".to_string()),
1719 style.filename.text.clone().with_font_size(font_size),
1720 )
1721 .contained()
1722 .with_style(style.filename.container)
1723 .aligned(),
1724 )
1725 .with_children(parent_path.map(|path| {
1726 Label::new(path, style.path.text.clone().with_font_size(font_size))
1727 .contained()
1728 .with_style(style.path.container)
1729 .aligned()
1730 }))
1731 .with_children(jump_icon)
1732 .contained()
1733 .with_style(style.container)
1734 .with_padding_left(gutter_padding)
1735 .with_padding_right(gutter_padding)
1736 .expanded()
1737 .into_any_named("path header block")
1738 } else {
1739 let text_style = style.text.clone();
1740 Flex::row()
1741 .with_child(Label::new("⋯", text_style))
1742 .with_children(jump_icon)
1743 .contained()
1744 .with_padding_left(gutter_padding)
1745 .with_padding_right(gutter_padding)
1746 .expanded()
1747 .into_any_named("collapsed context")
1748 }
1749 }
1750 };
1751
1752 element.layout(
1753 SizeConstraint {
1754 min: Vector2F::zero(),
1755 max: vec2f(width, block.height() as f32 * line_height),
1756 },
1757 editor,
1758 cx,
1759 );
1760 element
1761 };
1762
1763 let mut fixed_block_max_width = 0f32;
1764 let mut blocks = Vec::new();
1765 for (row, block) in fixed_blocks {
1766 let element = render_block(block, f32::INFINITY, block_id);
1767 block_id += 1;
1768 fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1769 blocks.push(BlockLayout {
1770 row,
1771 element,
1772 style: BlockStyle::Fixed,
1773 });
1774 }
1775 for (row, block) in non_fixed_blocks {
1776 let style = match block {
1777 TransformBlock::Custom(block) => block.style(),
1778 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1779 };
1780 let width = match style {
1781 BlockStyle::Sticky => editor_width,
1782 BlockStyle::Flex => editor_width
1783 .max(fixed_block_max_width)
1784 .max(gutter_width + scroll_width),
1785 BlockStyle::Fixed => unreachable!(),
1786 };
1787 let element = render_block(block, width, block_id);
1788 block_id += 1;
1789 blocks.push(BlockLayout {
1790 row,
1791 element,
1792 style,
1793 });
1794 }
1795 (
1796 scroll_width.max(fixed_block_max_width - gutter_width),
1797 blocks,
1798 )
1799 }
1800}
1801
1802struct HighlightedChunk<'a> {
1803 chunk: &'a str,
1804 style: Option<HighlightStyle>,
1805 is_tab: bool,
1806}
1807
1808#[derive(Debug)]
1809pub struct LineWithInvisibles {
1810 pub line: Line,
1811 invisibles: Vec<Invisible>,
1812}
1813
1814impl LineWithInvisibles {
1815 fn from_chunks<'a>(
1816 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
1817 text_style: &TextStyle,
1818 text_layout_cache: &TextLayoutCache,
1819 font_cache: &Arc<FontCache>,
1820 max_line_len: usize,
1821 max_line_count: usize,
1822 line_number_layouts: &[Option<Line>],
1823 editor_mode: EditorMode,
1824 ) -> Vec<Self> {
1825 let mut layouts = Vec::with_capacity(max_line_count);
1826 let mut line = String::new();
1827 let mut invisibles = Vec::new();
1828 let mut styles = Vec::new();
1829 let mut non_whitespace_added = false;
1830 let mut row = 0;
1831 let mut line_exceeded_max_len = false;
1832 for highlighted_chunk in chunks.chain([HighlightedChunk {
1833 chunk: "\n",
1834 style: None,
1835 is_tab: false,
1836 }]) {
1837 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
1838 if ix > 0 {
1839 layouts.push(Self {
1840 line: text_layout_cache.layout_str(&line, text_style.font_size, &styles),
1841 invisibles: invisibles.drain(..).collect(),
1842 });
1843
1844 line.clear();
1845 styles.clear();
1846 row += 1;
1847 line_exceeded_max_len = false;
1848 non_whitespace_added = false;
1849 if row == max_line_count {
1850 return layouts;
1851 }
1852 }
1853
1854 if !line_chunk.is_empty() && !line_exceeded_max_len {
1855 let text_style = if let Some(style) = highlighted_chunk.style {
1856 text_style
1857 .clone()
1858 .highlight(style, font_cache)
1859 .map(Cow::Owned)
1860 .unwrap_or_else(|_| Cow::Borrowed(text_style))
1861 } else {
1862 Cow::Borrowed(text_style)
1863 };
1864
1865 if line.len() + line_chunk.len() > max_line_len {
1866 let mut chunk_len = max_line_len - line.len();
1867 while !line_chunk.is_char_boundary(chunk_len) {
1868 chunk_len -= 1;
1869 }
1870 line_chunk = &line_chunk[..chunk_len];
1871 line_exceeded_max_len = true;
1872 }
1873
1874 styles.push((
1875 line_chunk.len(),
1876 RunStyle {
1877 font_id: text_style.font_id,
1878 color: text_style.color,
1879 underline: text_style.underline,
1880 },
1881 ));
1882
1883 if editor_mode == EditorMode::Full {
1884 // Line wrap pads its contents with fake whitespaces,
1885 // avoid printing them
1886 let inside_wrapped_string = line_number_layouts
1887 .get(row)
1888 .and_then(|layout| layout.as_ref())
1889 .is_none();
1890 if highlighted_chunk.is_tab {
1891 if non_whitespace_added || !inside_wrapped_string {
1892 invisibles.push(Invisible::Tab {
1893 line_start_offset: line.len(),
1894 });
1895 }
1896 } else {
1897 invisibles.extend(
1898 line_chunk
1899 .chars()
1900 .enumerate()
1901 .filter(|(_, line_char)| {
1902 let is_whitespace = line_char.is_whitespace();
1903 non_whitespace_added |= !is_whitespace;
1904 is_whitespace
1905 && (non_whitespace_added || !inside_wrapped_string)
1906 })
1907 .map(|(whitespace_index, _)| Invisible::Whitespace {
1908 line_offset: line.len() + whitespace_index,
1909 }),
1910 )
1911 }
1912 }
1913
1914 line.push_str(line_chunk);
1915 }
1916 }
1917 }
1918
1919 layouts
1920 }
1921
1922 fn draw(
1923 &self,
1924 layout: &LayoutState,
1925 row: u32,
1926 scroll_top: f32,
1927 scene: &mut SceneBuilder,
1928 content_origin: Vector2F,
1929 scroll_left: f32,
1930 visible_text_bounds: RectF,
1931 whitespace_setting: ShowWhitespaceSetting,
1932 selection_ranges: &[Range<DisplayPoint>],
1933 visible_bounds: RectF,
1934 cx: &mut ViewContext<Editor>,
1935 ) {
1936 let line_height = layout.position_map.line_height;
1937 let line_y = row as f32 * line_height - scroll_top;
1938
1939 self.line.paint(
1940 scene,
1941 content_origin + vec2f(-scroll_left, line_y),
1942 visible_text_bounds,
1943 line_height,
1944 cx,
1945 );
1946
1947 self.draw_invisibles(
1948 &selection_ranges,
1949 layout,
1950 content_origin,
1951 scroll_left,
1952 line_y,
1953 row,
1954 scene,
1955 visible_bounds,
1956 line_height,
1957 whitespace_setting,
1958 cx,
1959 );
1960 }
1961
1962 fn draw_invisibles(
1963 &self,
1964 selection_ranges: &[Range<DisplayPoint>],
1965 layout: &LayoutState,
1966 content_origin: Vector2F,
1967 scroll_left: f32,
1968 line_y: f32,
1969 row: u32,
1970 scene: &mut SceneBuilder,
1971 visible_bounds: RectF,
1972 line_height: f32,
1973 whitespace_setting: ShowWhitespaceSetting,
1974 cx: &mut ViewContext<Editor>,
1975 ) {
1976 let allowed_invisibles_regions = match whitespace_setting {
1977 ShowWhitespaceSetting::None => return,
1978 ShowWhitespaceSetting::Selection => Some(selection_ranges),
1979 ShowWhitespaceSetting::All => None,
1980 };
1981
1982 for invisible in &self.invisibles {
1983 let (&token_offset, invisible_symbol) = match invisible {
1984 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
1985 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
1986 };
1987
1988 let x_offset = self.line.x_for_index(token_offset);
1989 let invisible_offset =
1990 (layout.position_map.em_width - invisible_symbol.width()).max(0.0) / 2.0;
1991 let origin = content_origin + vec2f(-scroll_left + x_offset + invisible_offset, line_y);
1992
1993 if let Some(allowed_regions) = allowed_invisibles_regions {
1994 let invisible_point = DisplayPoint::new(row, token_offset as u32);
1995 if !allowed_regions
1996 .iter()
1997 .any(|region| region.start <= invisible_point && invisible_point < region.end)
1998 {
1999 continue;
2000 }
2001 }
2002 invisible_symbol.paint(scene, origin, visible_bounds, line_height, cx);
2003 }
2004 }
2005}
2006
2007#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2008enum Invisible {
2009 Tab { line_start_offset: usize },
2010 Whitespace { line_offset: usize },
2011}
2012
2013impl Element<Editor> for EditorElement {
2014 type LayoutState = LayoutState;
2015 type PaintState = ();
2016
2017 fn layout(
2018 &mut self,
2019 constraint: SizeConstraint,
2020 editor: &mut Editor,
2021 cx: &mut LayoutContext<Editor>,
2022 ) -> (Vector2F, Self::LayoutState) {
2023 let mut size = constraint.max;
2024 if size.x().is_infinite() {
2025 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
2026 }
2027
2028 let snapshot = editor.snapshot(cx);
2029 let style = self.style.clone();
2030
2031 let line_height = (style.text.font_size * style.line_height_scalar).round();
2032
2033 let gutter_padding;
2034 let gutter_width;
2035 let gutter_margin;
2036 if snapshot.show_gutter {
2037 let em_width = style.text.em_width(cx.font_cache());
2038 gutter_padding = (em_width * style.gutter_padding_factor).round();
2039 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
2040 gutter_margin = -style.text.descent(cx.font_cache());
2041 } else {
2042 gutter_padding = 0.0;
2043 gutter_width = 0.0;
2044 gutter_margin = 0.0;
2045 };
2046
2047 let text_width = size.x() - gutter_width;
2048 let em_width = style.text.em_width(cx.font_cache());
2049 let em_advance = style.text.em_advance(cx.font_cache());
2050 let overscroll = vec2f(em_width, 0.);
2051 let snapshot = {
2052 editor.set_visible_line_count(size.y() / line_height, cx);
2053
2054 let editor_width = text_width - gutter_margin - overscroll.x() - em_width;
2055 let wrap_width = match editor.soft_wrap_mode(cx) {
2056 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
2057 SoftWrap::EditorWidth => editor_width,
2058 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
2059 };
2060
2061 if editor.set_wrap_width(Some(wrap_width), cx) {
2062 editor.snapshot(cx)
2063 } else {
2064 snapshot
2065 }
2066 };
2067
2068 let wrap_guides = editor
2069 .wrap_guides(cx)
2070 .iter()
2071 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
2072 .collect();
2073
2074 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
2075 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
2076 size.set_y(
2077 scroll_height
2078 .min(constraint.max_along(Axis::Vertical))
2079 .max(constraint.min_along(Axis::Vertical))
2080 .min(line_height * max_lines as f32),
2081 )
2082 } else if let EditorMode::SingleLine = snapshot.mode {
2083 size.set_y(
2084 line_height
2085 .min(constraint.max_along(Axis::Vertical))
2086 .max(constraint.min_along(Axis::Vertical)),
2087 )
2088 } else if size.y().is_infinite() {
2089 size.set_y(scroll_height);
2090 }
2091 let gutter_size = vec2f(gutter_width, size.y());
2092 let text_size = vec2f(text_width, size.y());
2093
2094 let autoscroll_horizontally = editor.autoscroll_vertically(size.y(), line_height, cx);
2095 let mut snapshot = editor.snapshot(cx);
2096
2097 let scroll_position = snapshot.scroll_position();
2098 // The scroll position is a fractional point, the whole number of which represents
2099 // the top of the window in terms of display rows.
2100 let start_row = scroll_position.y() as u32;
2101 let height_in_lines = size.y() / line_height;
2102 let max_row = snapshot.max_point().row();
2103
2104 // Add 1 to ensure selections bleed off screen
2105 let end_row = 1 + cmp::min(
2106 (scroll_position.y() + height_in_lines).ceil() as u32,
2107 max_row,
2108 );
2109
2110 let start_anchor = if start_row == 0 {
2111 Anchor::min()
2112 } else {
2113 snapshot
2114 .buffer_snapshot
2115 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
2116 };
2117 let end_anchor = if end_row > max_row {
2118 Anchor::max()
2119 } else {
2120 snapshot
2121 .buffer_snapshot
2122 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
2123 };
2124
2125 let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
2126 let mut active_rows = BTreeMap::new();
2127 let mut fold_ranges = Vec::new();
2128 let is_singleton = editor.is_singleton(cx);
2129
2130 let highlighted_rows = editor.highlighted_rows();
2131 let theme = theme::current(cx);
2132 let highlighted_ranges = editor.background_highlights_in_range(
2133 start_anchor..end_anchor,
2134 &snapshot.display_snapshot,
2135 theme.as_ref(),
2136 );
2137
2138 fold_ranges.extend(
2139 snapshot
2140 .folds_in_range(start_anchor..end_anchor)
2141 .map(|anchor| {
2142 let start = anchor.start.to_point(&snapshot.buffer_snapshot);
2143 (
2144 start.row,
2145 start.to_display_point(&snapshot.display_snapshot)
2146 ..anchor.end.to_display_point(&snapshot),
2147 )
2148 }),
2149 );
2150
2151 let mut remote_selections = HashMap::default();
2152 for (replica_id, line_mode, cursor_shape, selection) in snapshot
2153 .buffer_snapshot
2154 .remote_selections_in_range(&(start_anchor..end_anchor))
2155 {
2156 // The local selections match the leader's selections.
2157 if Some(replica_id) == editor.leader_replica_id {
2158 continue;
2159 }
2160 remote_selections
2161 .entry(replica_id)
2162 .or_insert(Vec::new())
2163 .push(SelectionLayout::new(
2164 selection,
2165 line_mode,
2166 cursor_shape,
2167 &snapshot.display_snapshot,
2168 false,
2169 ));
2170 }
2171 selections.extend(remote_selections);
2172
2173 if editor.show_local_selections {
2174 let mut local_selections = editor
2175 .selections
2176 .disjoint_in_range(start_anchor..end_anchor, cx);
2177 local_selections.extend(editor.selections.pending(cx));
2178 let newest = editor.selections.newest(cx);
2179 for selection in &local_selections {
2180 let is_empty = selection.start == selection.end;
2181 let selection_start = snapshot.prev_line_boundary(selection.start).1;
2182 let selection_end = snapshot.next_line_boundary(selection.end).1;
2183 for row in cmp::max(selection_start.row(), start_row)
2184 ..=cmp::min(selection_end.row(), end_row)
2185 {
2186 let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2187 *contains_non_empty_selection |= !is_empty;
2188 }
2189 }
2190
2191 // Render the local selections in the leader's color when following.
2192 let local_replica_id = editor
2193 .leader_replica_id
2194 .unwrap_or_else(|| editor.replica_id(cx));
2195
2196 selections.push((
2197 local_replica_id,
2198 local_selections
2199 .into_iter()
2200 .map(|selection| {
2201 let is_newest = selection == newest;
2202 SelectionLayout::new(
2203 selection,
2204 editor.selections.line_mode,
2205 editor.cursor_shape,
2206 &snapshot.display_snapshot,
2207 is_newest,
2208 )
2209 })
2210 .collect(),
2211 ));
2212 }
2213
2214 let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
2215 let show_scrollbars = match scrollbar_settings.show {
2216 ShowScrollbar::Auto => {
2217 // Git
2218 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2219 ||
2220 // Selections
2221 (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty())
2222 // Scrollmanager
2223 || editor.scroll_manager.scrollbars_visible()
2224 }
2225 ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2226 ShowScrollbar::Always => true,
2227 ShowScrollbar::Never => false,
2228 };
2229
2230 let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2231 .into_iter()
2232 .map(|(id, fold)| {
2233 let color = self
2234 .style
2235 .folds
2236 .ellipses
2237 .background
2238 .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
2239 .color;
2240
2241 (id, fold, color)
2242 })
2243 .collect();
2244
2245 let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2246 start_row..end_row,
2247 &active_rows,
2248 is_singleton,
2249 &snapshot,
2250 cx,
2251 );
2252
2253 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2254
2255 let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
2256
2257 let mut max_visible_line_width = 0.0;
2258 let line_layouts =
2259 self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2260 for line_with_invisibles in &line_layouts {
2261 if line_with_invisibles.line.width() > max_visible_line_width {
2262 max_visible_line_width = line_with_invisibles.line.width();
2263 }
2264 }
2265
2266 let style = self.style.clone();
2267 let longest_line_width = layout_line(
2268 snapshot.longest_row(),
2269 &snapshot,
2270 &style,
2271 cx.text_layout_cache(),
2272 )
2273 .width();
2274 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
2275 let em_width = style.text.em_width(cx.font_cache());
2276 let (scroll_width, blocks) = self.layout_blocks(
2277 start_row..end_row,
2278 &snapshot,
2279 size.x(),
2280 scroll_width,
2281 gutter_padding,
2282 gutter_width,
2283 em_width,
2284 gutter_width + gutter_margin,
2285 line_height,
2286 &style,
2287 &line_layouts,
2288 editor,
2289 cx,
2290 );
2291
2292 let scroll_max = vec2f(
2293 ((scroll_width - text_size.x()) / em_width).max(0.0),
2294 max_row as f32,
2295 );
2296
2297 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x());
2298
2299 let autoscrolled = if autoscroll_horizontally {
2300 editor.autoscroll_horizontally(
2301 start_row,
2302 text_size.x(),
2303 scroll_width,
2304 em_width,
2305 &line_layouts,
2306 cx,
2307 )
2308 } else {
2309 false
2310 };
2311
2312 if clamped || autoscrolled {
2313 snapshot = editor.snapshot(cx);
2314 }
2315
2316 let newest_selection_head = editor
2317 .selections
2318 .newest::<usize>(cx)
2319 .head()
2320 .to_display_point(&snapshot);
2321 let style = editor.style(cx);
2322
2323 let mut context_menu = None;
2324 let mut code_actions_indicator = None;
2325 if (start_row..end_row).contains(&newest_selection_head.row()) {
2326 if editor.context_menu_visible() {
2327 context_menu = editor.render_context_menu(newest_selection_head, style.clone(), cx);
2328 }
2329
2330 let active = matches!(
2331 editor.context_menu,
2332 Some(crate::ContextMenu::CodeActions(_))
2333 );
2334
2335 code_actions_indicator = editor
2336 .render_code_actions_indicator(&style, active, cx)
2337 .map(|indicator| (newest_selection_head.row(), indicator));
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 ViewContext<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_radius: 0.,
2747 });
2748 } else {
2749 scene.push_quad(Quad {
2750 bounds,
2751 background: Some(self.color),
2752 border: Default::default(),
2753 corner_radius: 0.,
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.add_window(|cx| {
3000 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3001 Editor::new(EditorMode::Full, buffer, None, None, cx)
3002 });
3003 let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3004
3005 let layouts = editor.update(cx, |editor, cx| {
3006 let snapshot = editor.snapshot(cx);
3007 element
3008 .layout_line_numbers(0..6, &Default::default(), false, &snapshot, cx)
3009 .0
3010 });
3011 assert_eq!(layouts.len(), 6);
3012 }
3013
3014 #[gpui::test]
3015 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
3016 init_test(cx, |_| {});
3017
3018 let (_, editor) = cx.add_window(|cx| {
3019 let buffer = MultiBuffer::build_simple("", cx);
3020 Editor::new(EditorMode::Full, buffer, None, None, cx)
3021 });
3022
3023 editor.update(cx, |editor, cx| {
3024 editor.set_placeholder_text("hello", cx);
3025 editor.insert_blocks(
3026 [BlockProperties {
3027 style: BlockStyle::Fixed,
3028 disposition: BlockDisposition::Above,
3029 height: 3,
3030 position: Anchor::min(),
3031 render: Arc::new(|_| Empty::new().into_any()),
3032 }],
3033 None,
3034 cx,
3035 );
3036
3037 // Blur the editor so that it displays placeholder text.
3038 cx.blur();
3039 });
3040
3041 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3042 let (size, mut state) = editor.update(cx, |editor, cx| {
3043 let mut new_parents = Default::default();
3044 let mut notify_views_if_parents_change = Default::default();
3045 let mut layout_cx = LayoutContext::new(
3046 cx,
3047 &mut new_parents,
3048 &mut notify_views_if_parents_change,
3049 false,
3050 );
3051 element.layout(
3052 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
3053 editor,
3054 &mut layout_cx,
3055 )
3056 });
3057
3058 assert_eq!(state.position_map.line_layouts.len(), 4);
3059 assert_eq!(
3060 state
3061 .line_number_layouts
3062 .iter()
3063 .map(Option::is_some)
3064 .collect::<Vec<_>>(),
3065 &[false, false, false, true]
3066 );
3067
3068 // Don't panic.
3069 let mut scene = SceneBuilder::new(1.0);
3070 let bounds = RectF::new(Default::default(), size);
3071 editor.update(cx, |editor, cx| {
3072 element.paint(&mut scene, bounds, bounds, &mut state, editor, cx);
3073 });
3074 }
3075
3076 #[gpui::test]
3077 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3078 const TAB_SIZE: u32 = 4;
3079
3080 let input_text = "\t \t|\t| a b";
3081 let expected_invisibles = vec![
3082 Invisible::Tab {
3083 line_start_offset: 0,
3084 },
3085 Invisible::Whitespace {
3086 line_offset: TAB_SIZE as usize,
3087 },
3088 Invisible::Tab {
3089 line_start_offset: TAB_SIZE as usize + 1,
3090 },
3091 Invisible::Tab {
3092 line_start_offset: TAB_SIZE as usize * 2 + 1,
3093 },
3094 Invisible::Whitespace {
3095 line_offset: TAB_SIZE as usize * 3 + 1,
3096 },
3097 Invisible::Whitespace {
3098 line_offset: TAB_SIZE as usize * 3 + 3,
3099 },
3100 ];
3101 assert_eq!(
3102 expected_invisibles.len(),
3103 input_text
3104 .chars()
3105 .filter(|initial_char| initial_char.is_whitespace())
3106 .count(),
3107 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3108 );
3109
3110 init_test(cx, |s| {
3111 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3112 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
3113 });
3114
3115 let actual_invisibles =
3116 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
3117
3118 assert_eq!(expected_invisibles, actual_invisibles);
3119 }
3120
3121 #[gpui::test]
3122 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
3123 init_test(cx, |s| {
3124 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3125 s.defaults.tab_size = NonZeroU32::new(4);
3126 });
3127
3128 for editor_mode_without_invisibles in [
3129 EditorMode::SingleLine,
3130 EditorMode::AutoHeight { max_lines: 100 },
3131 ] {
3132 let invisibles = collect_invisibles_from_new_editor(
3133 cx,
3134 editor_mode_without_invisibles,
3135 "\t\t\t| | a b",
3136 500.0,
3137 );
3138 assert!(invisibles.is_empty(),
3139 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
3140 }
3141 }
3142
3143 #[gpui::test]
3144 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
3145 let tab_size = 4;
3146 let input_text = "a\tbcd ".repeat(9);
3147 let repeated_invisibles = [
3148 Invisible::Tab {
3149 line_start_offset: 1,
3150 },
3151 Invisible::Whitespace {
3152 line_offset: tab_size as usize + 3,
3153 },
3154 Invisible::Whitespace {
3155 line_offset: tab_size as usize + 4,
3156 },
3157 Invisible::Whitespace {
3158 line_offset: tab_size as usize + 5,
3159 },
3160 ];
3161 let expected_invisibles = std::iter::once(repeated_invisibles)
3162 .cycle()
3163 .take(9)
3164 .flatten()
3165 .collect::<Vec<_>>();
3166 assert_eq!(
3167 expected_invisibles.len(),
3168 input_text
3169 .chars()
3170 .filter(|initial_char| initial_char.is_whitespace())
3171 .count(),
3172 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3173 );
3174 info!("Expected invisibles: {expected_invisibles:?}");
3175
3176 init_test(cx, |_| {});
3177
3178 // Put the same string with repeating whitespace pattern into editors of various size,
3179 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
3180 let resize_step = 10.0;
3181 let mut editor_width = 200.0;
3182 while editor_width <= 1000.0 {
3183 update_test_language_settings(cx, |s| {
3184 s.defaults.tab_size = NonZeroU32::new(tab_size);
3185 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3186 s.defaults.preferred_line_length = Some(editor_width as u32);
3187 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
3188 });
3189
3190 let actual_invisibles =
3191 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
3192
3193 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
3194 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
3195 let mut i = 0;
3196 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
3197 i = actual_index;
3198 match expected_invisibles.get(i) {
3199 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
3200 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
3201 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
3202 _ => {
3203 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
3204 }
3205 },
3206 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
3207 }
3208 }
3209 let missing_expected_invisibles = &expected_invisibles[i + 1..];
3210 assert!(
3211 missing_expected_invisibles.is_empty(),
3212 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
3213 );
3214
3215 editor_width += resize_step;
3216 }
3217 }
3218
3219 fn collect_invisibles_from_new_editor(
3220 cx: &mut TestAppContext,
3221 editor_mode: EditorMode,
3222 input_text: &str,
3223 editor_width: f32,
3224 ) -> Vec<Invisible> {
3225 info!(
3226 "Creating editor with mode {editor_mode:?}, width {editor_width} and text '{input_text}'"
3227 );
3228 let (_, editor) = cx.add_window(|cx| {
3229 let buffer = MultiBuffer::build_simple(&input_text, cx);
3230 Editor::new(editor_mode, buffer, None, None, cx)
3231 });
3232
3233 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3234 let (_, layout_state) = editor.update(cx, |editor, cx| {
3235 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
3236 editor.set_wrap_width(Some(editor_width), cx);
3237
3238 let mut new_parents = Default::default();
3239 let mut notify_views_if_parents_change = Default::default();
3240 let mut layout_cx = LayoutContext::new(
3241 cx,
3242 &mut new_parents,
3243 &mut notify_views_if_parents_change,
3244 false,
3245 );
3246 element.layout(
3247 SizeConstraint::new(vec2f(editor_width, 500.), vec2f(editor_width, 500.)),
3248 editor,
3249 &mut layout_cx,
3250 )
3251 });
3252
3253 layout_state
3254 .position_map
3255 .line_layouts
3256 .iter()
3257 .map(|line_with_invisibles| &line_with_invisibles.invisibles)
3258 .flatten()
3259 .cloned()
3260 .collect()
3261 }
3262}