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