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 let mut cursor_column = cursor_position.column() as usize;
851 let mut cursor_row = cursor_position.row();
852
853 // highlight the last character in a selection
854 if CursorShape::Block == selection.cursor_shape
855 && !selection.range.is_empty()
856 && !selection.reversed
857 {
858 if cursor_column > 0 {
859 cursor_column -= 1;
860 } else if cursor_row > 0
861 && cursor_position != layout.position_map.snapshot.max_point()
862 {
863 cursor_row -= 1;
864 cursor_column =
865 layout.position_map.snapshot.line_len(cursor_row) as usize;
866 }
867 }
868 dbg!(selection.head, cursor_row, cursor_column);
869
870 if layout.visible_display_row_range.contains(&cursor_row) {
871 let cursor_row_layout = &layout.position_map.line_layouts
872 [(cursor_row - start_row) as usize]
873 .line;
874
875 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
876 let mut block_width =
877 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
878 if block_width == 0.0 {
879 block_width = layout.position_map.em_width;
880 }
881 let block_text = if let CursorShape::Block = selection.cursor_shape {
882 layout
883 .position_map
884 .snapshot
885 .chars_at(DisplayPoint::new(
886 cursor_row as u32,
887 cursor_column as u32,
888 ))
889 .next()
890 .and_then(|(character, _)| {
891 let font_id =
892 cursor_row_layout.font_for_index(cursor_column)?;
893 let text = character.to_string();
894
895 Some(cx.text_layout_cache().layout_str(
896 &text,
897 cursor_row_layout.font_size(),
898 &[(
899 text.len(),
900 RunStyle {
901 font_id,
902 color: style.background,
903 underline: Default::default(),
904 },
905 )],
906 ))
907 })
908 } else {
909 None
910 };
911
912 let x = cursor_character_x - scroll_left;
913 let y = cursor_row as f32 * layout.position_map.line_height - scroll_top;
914 if selection.is_newest {
915 editor.pixel_position_of_newest_cursor = Some(vec2f(
916 bounds.origin_x() + x + block_width / 2.,
917 bounds.origin_y() + y + layout.position_map.line_height / 2.,
918 ));
919 }
920 cursors.push(Cursor {
921 color: selection_style.cursor,
922 block_width,
923 origin: vec2f(x, y),
924 line_height: layout.position_map.line_height,
925 shape: selection.cursor_shape,
926 block_text,
927 });
928 }
929 }
930 }
931 }
932
933 if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
934 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
935 let row = start_row + ix as u32;
936 line_with_invisibles.draw(
937 layout,
938 row,
939 scroll_top,
940 scene,
941 content_origin,
942 scroll_left,
943 visible_text_bounds,
944 whitespace_setting,
945 &invisible_display_ranges,
946 visible_bounds,
947 cx,
948 )
949 }
950 }
951
952 scene.paint_layer(Some(bounds), |scene| {
953 for cursor in cursors {
954 cursor.paint(scene, content_origin, cx);
955 }
956 });
957
958 if let Some((position, context_menu)) = layout.context_menu.as_mut() {
959 scene.push_stacking_context(None, None);
960 let cursor_row_layout =
961 &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
962 let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
963 let y = (position.row() + 1) as f32 * layout.position_map.line_height - scroll_top;
964 let mut list_origin = content_origin + vec2f(x, y);
965 let list_width = context_menu.size().x();
966 let list_height = context_menu.size().y();
967
968 // Snap the right edge of the list to the right edge of the window if
969 // its horizontal bounds overflow.
970 if list_origin.x() + list_width > cx.window_size().x() {
971 list_origin.set_x((cx.window_size().x() - list_width).max(0.));
972 }
973
974 if list_origin.y() + list_height > bounds.max_y() {
975 list_origin.set_y(list_origin.y() - layout.position_map.line_height - list_height);
976 }
977
978 context_menu.paint(
979 scene,
980 list_origin,
981 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
982 editor,
983 cx,
984 );
985
986 scene.pop_stacking_context();
987 }
988
989 if let Some((position, hover_popovers)) = layout.hover_popovers.as_mut() {
990 scene.push_stacking_context(None, None);
991
992 // This is safe because we check on layout whether the required row is available
993 let hovered_row_layout =
994 &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
995
996 // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
997 // height. This is the size we will use to decide whether to render popovers above or below
998 // the hovered line.
999 let first_size = hover_popovers[0].size();
1000 let height_to_reserve = first_size.y()
1001 + 1.5 * MIN_POPOVER_LINE_HEIGHT as f32 * layout.position_map.line_height;
1002
1003 // Compute Hovered Point
1004 let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
1005 let y = position.row() as f32 * layout.position_map.line_height - scroll_top;
1006 let hovered_point = content_origin + vec2f(x, y);
1007
1008 if hovered_point.y() - height_to_reserve > 0.0 {
1009 // There is enough space above. Render popovers above the hovered point
1010 let mut current_y = hovered_point.y();
1011 for hover_popover in hover_popovers {
1012 let size = hover_popover.size();
1013 let mut popover_origin = vec2f(hovered_point.x(), current_y - size.y());
1014
1015 let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
1016 if x_out_of_bounds < 0.0 {
1017 popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
1018 }
1019
1020 hover_popover.paint(
1021 scene,
1022 popover_origin,
1023 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
1024 editor,
1025 cx,
1026 );
1027
1028 current_y = popover_origin.y() - HOVER_POPOVER_GAP;
1029 }
1030 } else {
1031 // There is not enough space above. Render popovers below the hovered point
1032 let mut current_y = hovered_point.y() + layout.position_map.line_height;
1033 for hover_popover in hover_popovers {
1034 let size = hover_popover.size();
1035 let mut popover_origin = vec2f(hovered_point.x(), current_y);
1036
1037 let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
1038 if x_out_of_bounds < 0.0 {
1039 popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
1040 }
1041
1042 hover_popover.paint(
1043 scene,
1044 popover_origin,
1045 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
1046 editor,
1047 cx,
1048 );
1049
1050 current_y = popover_origin.y() + size.y() + HOVER_POPOVER_GAP;
1051 }
1052 }
1053
1054 scene.pop_stacking_context();
1055 }
1056
1057 scene.pop_layer();
1058 }
1059
1060 fn paint_scrollbar(
1061 &mut self,
1062 scene: &mut SceneBuilder,
1063 bounds: RectF,
1064 layout: &mut LayoutState,
1065 cx: &mut ViewContext<Editor>,
1066 editor: &Editor,
1067 ) {
1068 enum ScrollbarMouseHandlers {}
1069 if layout.mode != EditorMode::Full {
1070 return;
1071 }
1072
1073 let style = &self.style.theme.scrollbar;
1074
1075 let top = bounds.min_y();
1076 let bottom = bounds.max_y();
1077 let right = bounds.max_x();
1078 let left = right - style.width;
1079 let row_range = &layout.scrollbar_row_range;
1080 let max_row = layout.max_row as f32 + (row_range.end - row_range.start);
1081
1082 let mut height = bounds.height();
1083 let mut first_row_y_offset = 0.0;
1084
1085 // Impose a minimum height on the scrollbar thumb
1086 let row_height = height / max_row;
1087 let min_thumb_height =
1088 style.min_height_factor * cx.font_cache.line_height(self.style.text.font_size);
1089 let thumb_height = (row_range.end - row_range.start) * row_height;
1090 if thumb_height < min_thumb_height {
1091 first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
1092 height -= min_thumb_height - thumb_height;
1093 }
1094
1095 let y_for_row = |row: f32| -> f32 { top + first_row_y_offset + row * row_height };
1096
1097 let thumb_top = y_for_row(row_range.start) - first_row_y_offset;
1098 let thumb_bottom = y_for_row(row_range.end) + first_row_y_offset;
1099 let track_bounds = RectF::from_points(vec2f(left, top), vec2f(right, bottom));
1100 let thumb_bounds = RectF::from_points(vec2f(left, thumb_top), vec2f(right, thumb_bottom));
1101
1102 if layout.show_scrollbars {
1103 scene.push_quad(Quad {
1104 bounds: track_bounds,
1105 border: style.track.border,
1106 background: style.track.background_color,
1107 ..Default::default()
1108 });
1109 let scrollbar_settings = settings::get::<EditorSettings>(cx).scrollbar;
1110 let theme = theme::current(cx);
1111 let scrollbar_theme = &theme.editor.scrollbar;
1112 if layout.is_singleton && scrollbar_settings.selections {
1113 let start_anchor = Anchor::min();
1114 let end_anchor = Anchor::max();
1115 let mut start_row = None;
1116 let mut end_row = None;
1117 let color = scrollbar_theme.selections;
1118 let border = Border {
1119 width: 1.,
1120 color: style.thumb.border.color,
1121 overlay: false,
1122 top: false,
1123 right: true,
1124 bottom: false,
1125 left: true,
1126 };
1127 let mut push_region = |start, end| {
1128 if let (Some(start_display), Some(end_display)) = (start, end) {
1129 let start_y = y_for_row(start_display as f32);
1130 let mut end_y = y_for_row(end_display as f32);
1131 if end_y - start_y < 1. {
1132 end_y = start_y + 1.;
1133 }
1134 let bounds = RectF::from_points(vec2f(left, start_y), vec2f(right, end_y));
1135
1136 scene.push_quad(Quad {
1137 bounds,
1138 background: Some(color),
1139 border,
1140 corner_radius: style.thumb.corner_radius,
1141 })
1142 }
1143 };
1144 for (row, _) in &editor
1145 .background_highlights_in_range_for::<crate::items::BufferSearchHighlights>(
1146 start_anchor..end_anchor,
1147 &layout.position_map.snapshot,
1148 &theme,
1149 )
1150 {
1151 let start_display = row.start;
1152 let end_display = row.end;
1153
1154 if start_row.is_none() {
1155 assert_eq!(end_row, None);
1156 start_row = Some(start_display.row());
1157 end_row = Some(end_display.row());
1158 continue;
1159 }
1160 if let Some(current_end) = end_row.as_mut() {
1161 if start_display.row() > *current_end + 1 {
1162 push_region(start_row, end_row);
1163 start_row = Some(start_display.row());
1164 end_row = Some(end_display.row());
1165 } else {
1166 // Merge two hunks.
1167 *current_end = end_display.row();
1168 }
1169 } else {
1170 unreachable!();
1171 }
1172 }
1173 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
1174 push_region(start_row, end_row);
1175 }
1176
1177 if layout.is_singleton && scrollbar_settings.git_diff {
1178 let diff_style = scrollbar_theme.git.clone();
1179 for hunk in layout
1180 .position_map
1181 .snapshot
1182 .buffer_snapshot
1183 .git_diff_hunks_in_range(0..(max_row.floor() as u32))
1184 {
1185 let start_display = Point::new(hunk.buffer_range.start, 0)
1186 .to_display_point(&layout.position_map.snapshot.display_snapshot);
1187 let end_display = Point::new(hunk.buffer_range.end, 0)
1188 .to_display_point(&layout.position_map.snapshot.display_snapshot);
1189 let start_y = y_for_row(start_display.row() as f32);
1190 let mut end_y = if hunk.buffer_range.start == hunk.buffer_range.end {
1191 y_for_row((end_display.row() + 1) as f32)
1192 } else {
1193 y_for_row((end_display.row()) as f32)
1194 };
1195
1196 if end_y - start_y < 1. {
1197 end_y = start_y + 1.;
1198 }
1199 let bounds = RectF::from_points(vec2f(left, start_y), vec2f(right, end_y));
1200
1201 let color = match hunk.status() {
1202 DiffHunkStatus::Added => diff_style.inserted,
1203 DiffHunkStatus::Modified => diff_style.modified,
1204 DiffHunkStatus::Removed => diff_style.deleted,
1205 };
1206
1207 let border = Border {
1208 width: 1.,
1209 color: style.thumb.border.color,
1210 overlay: false,
1211 top: false,
1212 right: true,
1213 bottom: false,
1214 left: true,
1215 };
1216
1217 scene.push_quad(Quad {
1218 bounds,
1219 background: Some(color),
1220 border,
1221 corner_radius: style.thumb.corner_radius,
1222 })
1223 }
1224 }
1225
1226 scene.push_quad(Quad {
1227 bounds: thumb_bounds,
1228 border: style.thumb.border,
1229 background: style.thumb.background_color,
1230 corner_radius: style.thumb.corner_radius,
1231 });
1232 }
1233
1234 scene.push_cursor_region(CursorRegion {
1235 bounds: track_bounds,
1236 style: CursorStyle::Arrow,
1237 });
1238 scene.push_mouse_region(
1239 MouseRegion::new::<ScrollbarMouseHandlers>(cx.view_id(), cx.view_id(), track_bounds)
1240 .on_move(move |event, editor: &mut Editor, cx| {
1241 if event.pressed_button.is_none() {
1242 editor.scroll_manager.show_scrollbar(cx);
1243 }
1244 })
1245 .on_down(MouseButton::Left, {
1246 let row_range = row_range.clone();
1247 move |event, editor: &mut Editor, cx| {
1248 let y = event.position.y();
1249 if y < thumb_top || thumb_bottom < y {
1250 let center_row = ((y - top) * max_row as f32 / height).round() as u32;
1251 let top_row = center_row
1252 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
1253 let mut position = editor.scroll_position(cx);
1254 position.set_y(top_row as f32);
1255 editor.set_scroll_position(position, cx);
1256 } else {
1257 editor.scroll_manager.show_scrollbar(cx);
1258 }
1259 }
1260 })
1261 .on_drag(MouseButton::Left, {
1262 move |event, editor: &mut Editor, cx| {
1263 if event.end {
1264 return;
1265 }
1266
1267 let y = event.prev_mouse_position.y();
1268 let new_y = event.position.y();
1269 if thumb_top < y && y < thumb_bottom {
1270 let mut position = editor.scroll_position(cx);
1271 position.set_y(position.y() + (new_y - y) * (max_row as f32) / height);
1272 if position.y() < 0.0 {
1273 position.set_y(0.);
1274 }
1275 editor.set_scroll_position(position, cx);
1276 }
1277 }
1278 }),
1279 );
1280 }
1281
1282 #[allow(clippy::too_many_arguments)]
1283 fn paint_highlighted_range(
1284 &self,
1285 scene: &mut SceneBuilder,
1286 range: Range<DisplayPoint>,
1287 color: Color,
1288 corner_radius: f32,
1289 line_end_overshoot: f32,
1290 layout: &LayoutState,
1291 content_origin: Vector2F,
1292 scroll_top: f32,
1293 scroll_left: f32,
1294 bounds: RectF,
1295 ) {
1296 let start_row = layout.visible_display_row_range.start;
1297 let end_row = layout.visible_display_row_range.end;
1298 if range.start != range.end {
1299 let row_range = if range.end.column() == 0 {
1300 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
1301 } else {
1302 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
1303 };
1304
1305 let highlighted_range = HighlightedRange {
1306 color,
1307 line_height: layout.position_map.line_height,
1308 corner_radius,
1309 start_y: content_origin.y()
1310 + row_range.start as f32 * layout.position_map.line_height
1311 - scroll_top,
1312 lines: row_range
1313 .into_iter()
1314 .map(|row| {
1315 let line_layout =
1316 &layout.position_map.line_layouts[(row - start_row) as usize].line;
1317 HighlightedRangeLine {
1318 start_x: if row == range.start.row() {
1319 content_origin.x()
1320 + line_layout.x_for_index(range.start.column() as usize)
1321 - scroll_left
1322 } else {
1323 content_origin.x() - scroll_left
1324 },
1325 end_x: if row == range.end.row() {
1326 content_origin.x()
1327 + line_layout.x_for_index(range.end.column() as usize)
1328 - scroll_left
1329 } else {
1330 content_origin.x() + line_layout.width() + line_end_overshoot
1331 - scroll_left
1332 },
1333 }
1334 })
1335 .collect(),
1336 };
1337
1338 highlighted_range.paint(bounds, scene);
1339 }
1340 }
1341
1342 fn paint_blocks(
1343 &mut self,
1344 scene: &mut SceneBuilder,
1345 bounds: RectF,
1346 visible_bounds: RectF,
1347 layout: &mut LayoutState,
1348 editor: &mut Editor,
1349 cx: &mut ViewContext<Editor>,
1350 ) {
1351 let scroll_position = layout.position_map.snapshot.scroll_position();
1352 let scroll_left = scroll_position.x() * layout.position_map.em_width;
1353 let scroll_top = scroll_position.y() * layout.position_map.line_height;
1354
1355 for block in &mut layout.blocks {
1356 let mut origin = bounds.origin()
1357 + vec2f(
1358 0.,
1359 block.row as f32 * layout.position_map.line_height - scroll_top,
1360 );
1361 if !matches!(block.style, BlockStyle::Sticky) {
1362 origin += vec2f(-scroll_left, 0.);
1363 }
1364 block
1365 .element
1366 .paint(scene, origin, visible_bounds, editor, cx);
1367 }
1368 }
1369
1370 fn column_pixels(&self, column: usize, cx: &ViewContext<Editor>) -> f32 {
1371 let style = &self.style;
1372
1373 cx.text_layout_cache()
1374 .layout_str(
1375 " ".repeat(column).as_str(),
1376 style.text.font_size,
1377 &[(
1378 column,
1379 RunStyle {
1380 font_id: style.text.font_id,
1381 color: Color::black(),
1382 underline: Default::default(),
1383 },
1384 )],
1385 )
1386 .width()
1387 }
1388
1389 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &ViewContext<Editor>) -> f32 {
1390 let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
1391 self.column_pixels(digit_count, cx)
1392 }
1393
1394 //Folds contained in a hunk are ignored apart from shrinking visual size
1395 //If a fold contains any hunks then that fold line is marked as modified
1396 fn layout_git_gutters(
1397 &self,
1398 display_rows: Range<u32>,
1399 snapshot: &EditorSnapshot,
1400 ) -> Vec<DisplayDiffHunk> {
1401 let buffer_snapshot = &snapshot.buffer_snapshot;
1402
1403 let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1404 .to_point(snapshot)
1405 .row;
1406 let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1407 .to_point(snapshot)
1408 .row;
1409
1410 buffer_snapshot
1411 .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1412 .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1413 .dedup()
1414 .collect()
1415 }
1416
1417 fn layout_line_numbers(
1418 &self,
1419 rows: Range<u32>,
1420 active_rows: &BTreeMap<u32, bool>,
1421 is_singleton: bool,
1422 snapshot: &EditorSnapshot,
1423 cx: &ViewContext<Editor>,
1424 ) -> (
1425 Vec<Option<text_layout::Line>>,
1426 Vec<Option<(FoldStatus, BufferRow, bool)>>,
1427 ) {
1428 let style = &self.style;
1429 let include_line_numbers = snapshot.mode == EditorMode::Full;
1430 let mut line_number_layouts = Vec::with_capacity(rows.len());
1431 let mut fold_statuses = Vec::with_capacity(rows.len());
1432 let mut line_number = String::new();
1433 for (ix, row) in snapshot
1434 .buffer_rows(rows.start)
1435 .take((rows.end - rows.start) as usize)
1436 .enumerate()
1437 {
1438 let display_row = rows.start + ix as u32;
1439 let (active, color) = if active_rows.contains_key(&display_row) {
1440 (true, style.line_number_active)
1441 } else {
1442 (false, style.line_number)
1443 };
1444 if let Some(buffer_row) = row {
1445 if include_line_numbers {
1446 line_number.clear();
1447 write!(&mut line_number, "{}", buffer_row + 1).unwrap();
1448 line_number_layouts.push(Some(cx.text_layout_cache().layout_str(
1449 &line_number,
1450 style.text.font_size,
1451 &[(
1452 line_number.len(),
1453 RunStyle {
1454 font_id: style.text.font_id,
1455 color,
1456 underline: Default::default(),
1457 },
1458 )],
1459 )));
1460 fold_statuses.push(
1461 is_singleton
1462 .then(|| {
1463 snapshot
1464 .fold_for_line(buffer_row)
1465 .map(|fold_status| (fold_status, buffer_row, active))
1466 })
1467 .flatten(),
1468 )
1469 }
1470 } else {
1471 fold_statuses.push(None);
1472 line_number_layouts.push(None);
1473 }
1474 }
1475
1476 (line_number_layouts, fold_statuses)
1477 }
1478
1479 fn layout_lines(
1480 &mut self,
1481 rows: Range<u32>,
1482 line_number_layouts: &[Option<Line>],
1483 snapshot: &EditorSnapshot,
1484 cx: &ViewContext<Editor>,
1485 ) -> Vec<LineWithInvisibles> {
1486 if rows.start >= rows.end {
1487 return Vec::new();
1488 }
1489
1490 // When the editor is empty and unfocused, then show the placeholder.
1491 if snapshot.is_empty() {
1492 let placeholder_style = self
1493 .style
1494 .placeholder_text
1495 .as_ref()
1496 .unwrap_or(&self.style.text);
1497 let placeholder_text = snapshot.placeholder_text();
1498 let placeholder_lines = placeholder_text
1499 .as_ref()
1500 .map_or("", AsRef::as_ref)
1501 .split('\n')
1502 .skip(rows.start as usize)
1503 .chain(iter::repeat(""))
1504 .take(rows.len());
1505 placeholder_lines
1506 .map(|line| {
1507 cx.text_layout_cache().layout_str(
1508 line,
1509 placeholder_style.font_size,
1510 &[(
1511 line.len(),
1512 RunStyle {
1513 font_id: placeholder_style.font_id,
1514 color: placeholder_style.color,
1515 underline: Default::default(),
1516 },
1517 )],
1518 )
1519 })
1520 .map(|line| LineWithInvisibles {
1521 line,
1522 invisibles: Vec::new(),
1523 })
1524 .collect()
1525 } else {
1526 let style = &self.style;
1527 let chunks = snapshot
1528 .chunks(
1529 rows.clone(),
1530 true,
1531 Some(style.theme.hint),
1532 Some(style.theme.suggestion),
1533 )
1534 .map(|chunk| {
1535 let mut highlight_style = chunk
1536 .syntax_highlight_id
1537 .and_then(|id| id.style(&style.syntax));
1538
1539 if let Some(chunk_highlight) = chunk.highlight_style {
1540 if let Some(highlight_style) = highlight_style.as_mut() {
1541 highlight_style.highlight(chunk_highlight);
1542 } else {
1543 highlight_style = Some(chunk_highlight);
1544 }
1545 }
1546
1547 let mut diagnostic_highlight = HighlightStyle::default();
1548
1549 if chunk.is_unnecessary {
1550 diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
1551 }
1552
1553 if let Some(severity) = chunk.diagnostic_severity {
1554 // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
1555 if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
1556 let diagnostic_style = super::diagnostic_style(severity, true, style);
1557 diagnostic_highlight.underline = Some(Underline {
1558 color: Some(diagnostic_style.message.text.color),
1559 thickness: 1.0.into(),
1560 squiggly: true,
1561 });
1562 }
1563 }
1564
1565 if let Some(highlight_style) = highlight_style.as_mut() {
1566 highlight_style.highlight(diagnostic_highlight);
1567 } else {
1568 highlight_style = Some(diagnostic_highlight);
1569 }
1570
1571 HighlightedChunk {
1572 chunk: chunk.text,
1573 style: highlight_style,
1574 is_tab: chunk.is_tab,
1575 }
1576 });
1577
1578 LineWithInvisibles::from_chunks(
1579 chunks,
1580 &style.text,
1581 cx.text_layout_cache(),
1582 cx.font_cache(),
1583 MAX_LINE_LEN,
1584 rows.len() as usize,
1585 line_number_layouts,
1586 snapshot.mode,
1587 )
1588 }
1589 }
1590
1591 #[allow(clippy::too_many_arguments)]
1592 fn layout_blocks(
1593 &mut self,
1594 rows: Range<u32>,
1595 snapshot: &EditorSnapshot,
1596 editor_width: f32,
1597 scroll_width: f32,
1598 gutter_padding: f32,
1599 gutter_width: f32,
1600 em_width: f32,
1601 text_x: f32,
1602 line_height: f32,
1603 style: &EditorStyle,
1604 line_layouts: &[LineWithInvisibles],
1605 editor: &mut Editor,
1606 cx: &mut LayoutContext<Editor>,
1607 ) -> (f32, Vec<BlockLayout>) {
1608 let mut block_id = 0;
1609 let scroll_x = snapshot.scroll_anchor.offset.x();
1610 let (fixed_blocks, non_fixed_blocks) = snapshot
1611 .blocks_in_range(rows.clone())
1612 .partition::<Vec<_>, _>(|(_, block)| match block {
1613 TransformBlock::ExcerptHeader { .. } => false,
1614 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1615 });
1616 let mut render_block = |block: &TransformBlock, width: f32, block_id: usize| {
1617 let mut element = match block {
1618 TransformBlock::Custom(block) => {
1619 let align_to = block
1620 .position()
1621 .to_point(&snapshot.buffer_snapshot)
1622 .to_display_point(snapshot);
1623 let anchor_x = text_x
1624 + if rows.contains(&align_to.row()) {
1625 line_layouts[(align_to.row() - rows.start) as usize]
1626 .line
1627 .x_for_index(align_to.column() as usize)
1628 } else {
1629 layout_line(align_to.row(), snapshot, style, cx.text_layout_cache())
1630 .x_for_index(align_to.column() as usize)
1631 };
1632
1633 block.render(&mut BlockContext {
1634 view_context: cx,
1635 anchor_x,
1636 gutter_padding,
1637 line_height,
1638 scroll_x,
1639 gutter_width,
1640 em_width,
1641 block_id,
1642 })
1643 }
1644 TransformBlock::ExcerptHeader {
1645 id,
1646 buffer,
1647 range,
1648 starts_new_buffer,
1649 ..
1650 } => {
1651 let tooltip_style = theme::current(cx).tooltip.clone();
1652 let include_root = editor
1653 .project
1654 .as_ref()
1655 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1656 .unwrap_or_default();
1657 let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1658 let jump_path = ProjectPath {
1659 worktree_id: file.worktree_id(cx),
1660 path: file.path.clone(),
1661 };
1662 let jump_anchor = range
1663 .primary
1664 .as_ref()
1665 .map_or(range.context.start, |primary| primary.start);
1666 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1667
1668 enum JumpIcon {}
1669 MouseEventHandler::<JumpIcon, _>::new((*id).into(), cx, |state, _| {
1670 let style = style.jump_icon.style_for(state);
1671 Svg::new("icons/arrow_up_right_8.svg")
1672 .with_color(style.color)
1673 .constrained()
1674 .with_width(style.icon_width)
1675 .aligned()
1676 .contained()
1677 .with_style(style.container)
1678 .constrained()
1679 .with_width(style.button_width)
1680 .with_height(style.button_width)
1681 })
1682 .with_cursor_style(CursorStyle::PointingHand)
1683 .on_click(MouseButton::Left, move |_, editor, cx| {
1684 if let Some(workspace) = editor
1685 .workspace
1686 .as_ref()
1687 .and_then(|(workspace, _)| workspace.upgrade(cx))
1688 {
1689 workspace.update(cx, |workspace, cx| {
1690 Editor::jump(
1691 workspace,
1692 jump_path.clone(),
1693 jump_position,
1694 jump_anchor,
1695 cx,
1696 );
1697 });
1698 }
1699 })
1700 .with_tooltip::<JumpIcon>(
1701 (*id).into(),
1702 "Jump to Buffer".to_string(),
1703 Some(Box::new(crate::OpenExcerpts)),
1704 tooltip_style.clone(),
1705 cx,
1706 )
1707 .aligned()
1708 .flex_float()
1709 });
1710
1711 if *starts_new_buffer {
1712 let editor_font_size = style.text.font_size;
1713 let style = &style.diagnostic_path_header;
1714 let font_size = (style.text_scale_factor * editor_font_size).round();
1715
1716 let path = buffer.resolve_file_path(cx, include_root);
1717 let mut filename = None;
1718 let mut parent_path = None;
1719 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1720 if let Some(path) = path {
1721 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1722 parent_path =
1723 path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1724 }
1725
1726 Flex::row()
1727 .with_child(
1728 Label::new(
1729 filename.unwrap_or_else(|| "untitled".to_string()),
1730 style.filename.text.clone().with_font_size(font_size),
1731 )
1732 .contained()
1733 .with_style(style.filename.container)
1734 .aligned(),
1735 )
1736 .with_children(parent_path.map(|path| {
1737 Label::new(path, style.path.text.clone().with_font_size(font_size))
1738 .contained()
1739 .with_style(style.path.container)
1740 .aligned()
1741 }))
1742 .with_children(jump_icon)
1743 .contained()
1744 .with_style(style.container)
1745 .with_padding_left(gutter_padding)
1746 .with_padding_right(gutter_padding)
1747 .expanded()
1748 .into_any_named("path header block")
1749 } else {
1750 let text_style = style.text.clone();
1751 Flex::row()
1752 .with_child(Label::new("⋯", text_style))
1753 .with_children(jump_icon)
1754 .contained()
1755 .with_padding_left(gutter_padding)
1756 .with_padding_right(gutter_padding)
1757 .expanded()
1758 .into_any_named("collapsed context")
1759 }
1760 }
1761 };
1762
1763 element.layout(
1764 SizeConstraint {
1765 min: Vector2F::zero(),
1766 max: vec2f(width, block.height() as f32 * line_height),
1767 },
1768 editor,
1769 cx,
1770 );
1771 element
1772 };
1773
1774 let mut fixed_block_max_width = 0f32;
1775 let mut blocks = Vec::new();
1776 for (row, block) in fixed_blocks {
1777 let element = render_block(block, f32::INFINITY, block_id);
1778 block_id += 1;
1779 fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1780 blocks.push(BlockLayout {
1781 row,
1782 element,
1783 style: BlockStyle::Fixed,
1784 });
1785 }
1786 for (row, block) in non_fixed_blocks {
1787 let style = match block {
1788 TransformBlock::Custom(block) => block.style(),
1789 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1790 };
1791 let width = match style {
1792 BlockStyle::Sticky => editor_width,
1793 BlockStyle::Flex => editor_width
1794 .max(fixed_block_max_width)
1795 .max(gutter_width + scroll_width),
1796 BlockStyle::Fixed => unreachable!(),
1797 };
1798 let element = render_block(block, width, block_id);
1799 block_id += 1;
1800 blocks.push(BlockLayout {
1801 row,
1802 element,
1803 style,
1804 });
1805 }
1806 (
1807 scroll_width.max(fixed_block_max_width - gutter_width),
1808 blocks,
1809 )
1810 }
1811}
1812
1813struct HighlightedChunk<'a> {
1814 chunk: &'a str,
1815 style: Option<HighlightStyle>,
1816 is_tab: bool,
1817}
1818
1819#[derive(Debug)]
1820pub struct LineWithInvisibles {
1821 pub line: Line,
1822 invisibles: Vec<Invisible>,
1823}
1824
1825impl LineWithInvisibles {
1826 fn from_chunks<'a>(
1827 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
1828 text_style: &TextStyle,
1829 text_layout_cache: &TextLayoutCache,
1830 font_cache: &Arc<FontCache>,
1831 max_line_len: usize,
1832 max_line_count: usize,
1833 line_number_layouts: &[Option<Line>],
1834 editor_mode: EditorMode,
1835 ) -> Vec<Self> {
1836 let mut layouts = Vec::with_capacity(max_line_count);
1837 let mut line = String::new();
1838 let mut invisibles = Vec::new();
1839 let mut styles = Vec::new();
1840 let mut non_whitespace_added = false;
1841 let mut row = 0;
1842 let mut line_exceeded_max_len = false;
1843 for highlighted_chunk in chunks.chain([HighlightedChunk {
1844 chunk: "\n",
1845 style: None,
1846 is_tab: false,
1847 }]) {
1848 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
1849 if ix > 0 {
1850 layouts.push(Self {
1851 line: text_layout_cache.layout_str(&line, text_style.font_size, &styles),
1852 invisibles: invisibles.drain(..).collect(),
1853 });
1854
1855 line.clear();
1856 styles.clear();
1857 row += 1;
1858 line_exceeded_max_len = false;
1859 non_whitespace_added = false;
1860 if row == max_line_count {
1861 return layouts;
1862 }
1863 }
1864
1865 if !line_chunk.is_empty() && !line_exceeded_max_len {
1866 let text_style = if let Some(style) = highlighted_chunk.style {
1867 text_style
1868 .clone()
1869 .highlight(style, font_cache)
1870 .map(Cow::Owned)
1871 .unwrap_or_else(|_| Cow::Borrowed(text_style))
1872 } else {
1873 Cow::Borrowed(text_style)
1874 };
1875
1876 if line.len() + line_chunk.len() > max_line_len {
1877 let mut chunk_len = max_line_len - line.len();
1878 while !line_chunk.is_char_boundary(chunk_len) {
1879 chunk_len -= 1;
1880 }
1881 line_chunk = &line_chunk[..chunk_len];
1882 line_exceeded_max_len = true;
1883 }
1884
1885 styles.push((
1886 line_chunk.len(),
1887 RunStyle {
1888 font_id: text_style.font_id,
1889 color: text_style.color,
1890 underline: text_style.underline,
1891 },
1892 ));
1893
1894 if editor_mode == EditorMode::Full {
1895 // Line wrap pads its contents with fake whitespaces,
1896 // avoid printing them
1897 let inside_wrapped_string = line_number_layouts
1898 .get(row)
1899 .and_then(|layout| layout.as_ref())
1900 .is_none();
1901 if highlighted_chunk.is_tab {
1902 if non_whitespace_added || !inside_wrapped_string {
1903 invisibles.push(Invisible::Tab {
1904 line_start_offset: line.len(),
1905 });
1906 }
1907 } else {
1908 invisibles.extend(
1909 line_chunk
1910 .chars()
1911 .enumerate()
1912 .filter(|(_, line_char)| {
1913 let is_whitespace = line_char.is_whitespace();
1914 non_whitespace_added |= !is_whitespace;
1915 is_whitespace
1916 && (non_whitespace_added || !inside_wrapped_string)
1917 })
1918 .map(|(whitespace_index, _)| Invisible::Whitespace {
1919 line_offset: line.len() + whitespace_index,
1920 }),
1921 )
1922 }
1923 }
1924
1925 line.push_str(line_chunk);
1926 }
1927 }
1928 }
1929
1930 layouts
1931 }
1932
1933 fn draw(
1934 &self,
1935 layout: &LayoutState,
1936 row: u32,
1937 scroll_top: f32,
1938 scene: &mut SceneBuilder,
1939 content_origin: Vector2F,
1940 scroll_left: f32,
1941 visible_text_bounds: RectF,
1942 whitespace_setting: ShowWhitespaceSetting,
1943 selection_ranges: &[Range<DisplayPoint>],
1944 visible_bounds: RectF,
1945 cx: &mut ViewContext<Editor>,
1946 ) {
1947 let line_height = layout.position_map.line_height;
1948 let line_y = row as f32 * line_height - scroll_top;
1949
1950 self.line.paint(
1951 scene,
1952 content_origin + vec2f(-scroll_left, line_y),
1953 visible_text_bounds,
1954 line_height,
1955 cx,
1956 );
1957
1958 self.draw_invisibles(
1959 &selection_ranges,
1960 layout,
1961 content_origin,
1962 scroll_left,
1963 line_y,
1964 row,
1965 scene,
1966 visible_bounds,
1967 line_height,
1968 whitespace_setting,
1969 cx,
1970 );
1971 }
1972
1973 fn draw_invisibles(
1974 &self,
1975 selection_ranges: &[Range<DisplayPoint>],
1976 layout: &LayoutState,
1977 content_origin: Vector2F,
1978 scroll_left: f32,
1979 line_y: f32,
1980 row: u32,
1981 scene: &mut SceneBuilder,
1982 visible_bounds: RectF,
1983 line_height: f32,
1984 whitespace_setting: ShowWhitespaceSetting,
1985 cx: &mut ViewContext<Editor>,
1986 ) {
1987 let allowed_invisibles_regions = match whitespace_setting {
1988 ShowWhitespaceSetting::None => return,
1989 ShowWhitespaceSetting::Selection => Some(selection_ranges),
1990 ShowWhitespaceSetting::All => None,
1991 };
1992
1993 for invisible in &self.invisibles {
1994 let (&token_offset, invisible_symbol) = match invisible {
1995 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
1996 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
1997 };
1998
1999 let x_offset = self.line.x_for_index(token_offset);
2000 let invisible_offset =
2001 (layout.position_map.em_width - invisible_symbol.width()).max(0.0) / 2.0;
2002 let origin = content_origin + vec2f(-scroll_left + x_offset + invisible_offset, line_y);
2003
2004 if let Some(allowed_regions) = allowed_invisibles_regions {
2005 let invisible_point = DisplayPoint::new(row, token_offset as u32);
2006 if !allowed_regions
2007 .iter()
2008 .any(|region| region.start <= invisible_point && invisible_point < region.end)
2009 {
2010 continue;
2011 }
2012 }
2013 invisible_symbol.paint(scene, origin, visible_bounds, line_height, cx);
2014 }
2015 }
2016}
2017
2018#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2019enum Invisible {
2020 Tab { line_start_offset: usize },
2021 Whitespace { line_offset: usize },
2022}
2023
2024impl Element<Editor> for EditorElement {
2025 type LayoutState = LayoutState;
2026 type PaintState = ();
2027
2028 fn layout(
2029 &mut self,
2030 constraint: SizeConstraint,
2031 editor: &mut Editor,
2032 cx: &mut LayoutContext<Editor>,
2033 ) -> (Vector2F, Self::LayoutState) {
2034 let mut size = constraint.max;
2035 if size.x().is_infinite() {
2036 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
2037 }
2038
2039 let snapshot = editor.snapshot(cx);
2040 let style = self.style.clone();
2041
2042 let line_height = (style.text.font_size * style.line_height_scalar).round();
2043
2044 let gutter_padding;
2045 let gutter_width;
2046 let gutter_margin;
2047 if snapshot.show_gutter {
2048 let em_width = style.text.em_width(cx.font_cache());
2049 gutter_padding = (em_width * style.gutter_padding_factor).round();
2050 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
2051 gutter_margin = -style.text.descent(cx.font_cache());
2052 } else {
2053 gutter_padding = 0.0;
2054 gutter_width = 0.0;
2055 gutter_margin = 0.0;
2056 };
2057
2058 let text_width = size.x() - gutter_width;
2059 let em_width = style.text.em_width(cx.font_cache());
2060 let em_advance = style.text.em_advance(cx.font_cache());
2061 let overscroll = vec2f(em_width, 0.);
2062 let snapshot = {
2063 editor.set_visible_line_count(size.y() / line_height, cx);
2064
2065 let editor_width = text_width - gutter_margin - overscroll.x() - em_width;
2066 let wrap_width = match editor.soft_wrap_mode(cx) {
2067 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
2068 SoftWrap::EditorWidth => editor_width,
2069 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
2070 };
2071
2072 if editor.set_wrap_width(Some(wrap_width), cx) {
2073 editor.snapshot(cx)
2074 } else {
2075 snapshot
2076 }
2077 };
2078
2079 let wrap_guides = editor
2080 .wrap_guides(cx)
2081 .iter()
2082 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
2083 .collect();
2084
2085 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
2086 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
2087 size.set_y(
2088 scroll_height
2089 .min(constraint.max_along(Axis::Vertical))
2090 .max(constraint.min_along(Axis::Vertical))
2091 .min(line_height * max_lines as f32),
2092 )
2093 } else if let EditorMode::SingleLine = snapshot.mode {
2094 size.set_y(
2095 line_height
2096 .min(constraint.max_along(Axis::Vertical))
2097 .max(constraint.min_along(Axis::Vertical)),
2098 )
2099 } else if size.y().is_infinite() {
2100 size.set_y(scroll_height);
2101 }
2102 let gutter_size = vec2f(gutter_width, size.y());
2103 let text_size = vec2f(text_width, size.y());
2104
2105 let autoscroll_horizontally = editor.autoscroll_vertically(size.y(), line_height, cx);
2106 let mut snapshot = editor.snapshot(cx);
2107
2108 let scroll_position = snapshot.scroll_position();
2109 // The scroll position is a fractional point, the whole number of which represents
2110 // the top of the window in terms of display rows.
2111 let start_row = scroll_position.y() as u32;
2112 let height_in_lines = size.y() / line_height;
2113 let max_row = snapshot.max_point().row();
2114
2115 // Add 1 to ensure selections bleed off screen
2116 let end_row = 1 + cmp::min(
2117 (scroll_position.y() + height_in_lines).ceil() as u32,
2118 max_row,
2119 );
2120
2121 let start_anchor = if start_row == 0 {
2122 Anchor::min()
2123 } else {
2124 snapshot
2125 .buffer_snapshot
2126 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
2127 };
2128 let end_anchor = if end_row > max_row {
2129 Anchor::max()
2130 } else {
2131 snapshot
2132 .buffer_snapshot
2133 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
2134 };
2135
2136 let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
2137 let mut active_rows = BTreeMap::new();
2138 let mut fold_ranges = Vec::new();
2139 let is_singleton = editor.is_singleton(cx);
2140
2141 let highlighted_rows = editor.highlighted_rows();
2142 let theme = theme::current(cx);
2143 let highlighted_ranges = editor.background_highlights_in_range(
2144 start_anchor..end_anchor,
2145 &snapshot.display_snapshot,
2146 theme.as_ref(),
2147 );
2148
2149 fold_ranges.extend(
2150 snapshot
2151 .folds_in_range(start_anchor..end_anchor)
2152 .map(|anchor| {
2153 let start = anchor.start.to_point(&snapshot.buffer_snapshot);
2154 (
2155 start.row,
2156 start.to_display_point(&snapshot.display_snapshot)
2157 ..anchor.end.to_display_point(&snapshot),
2158 )
2159 }),
2160 );
2161
2162 let mut remote_selections = HashMap::default();
2163 for (replica_id, line_mode, cursor_shape, selection) in snapshot
2164 .buffer_snapshot
2165 .remote_selections_in_range(&(start_anchor..end_anchor))
2166 {
2167 // The local selections match the leader's selections.
2168 if Some(replica_id) == editor.leader_replica_id {
2169 continue;
2170 }
2171 remote_selections
2172 .entry(replica_id)
2173 .or_insert(Vec::new())
2174 .push(SelectionLayout::new(
2175 selection,
2176 line_mode,
2177 cursor_shape,
2178 &snapshot.display_snapshot,
2179 false,
2180 ));
2181 }
2182 selections.extend(remote_selections);
2183
2184 if editor.show_local_selections {
2185 let mut local_selections = editor
2186 .selections
2187 .disjoint_in_range(start_anchor..end_anchor, cx);
2188 local_selections.extend(editor.selections.pending(cx));
2189 let newest = editor.selections.newest(cx);
2190 for selection in &local_selections {
2191 let is_empty = selection.start == selection.end;
2192 let selection_start = snapshot.prev_line_boundary(selection.start).1;
2193 let mut selection_end = snapshot.next_line_boundary(selection.end).1;
2194
2195 // in vim visual mode the newline is considered at the end of the previous line
2196 // instead of at the start of the current line
2197 if editor.cursor_shape == CursorShape::Block
2198 && !is_empty
2199 && !selection.reversed
2200 && selection.end.column == 0
2201 && selection_end.row() > 0
2202 && selection_end.row() < snapshot.max_buffer_row()
2203 {
2204 selection_end = DisplayPoint::new(selection_end.row() - 1, 0);
2205 }
2206 for row in cmp::max(selection_start.row(), start_row)
2207 ..=cmp::min(selection_end.row(), end_row)
2208 {
2209 let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2210 *contains_non_empty_selection |= !is_empty;
2211 }
2212 }
2213
2214 // Render the local selections in the leader's color when following.
2215 let local_replica_id = editor
2216 .leader_replica_id
2217 .unwrap_or_else(|| editor.replica_id(cx));
2218
2219 selections.push((
2220 local_replica_id,
2221 local_selections
2222 .into_iter()
2223 .map(|selection| {
2224 let is_newest = selection == newest;
2225 SelectionLayout::new(
2226 selection,
2227 editor.selections.line_mode,
2228 editor.cursor_shape,
2229 &snapshot.display_snapshot,
2230 is_newest,
2231 )
2232 })
2233 .collect(),
2234 ));
2235 }
2236
2237 let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
2238 let show_scrollbars = match scrollbar_settings.show {
2239 ShowScrollbar::Auto => {
2240 // Git
2241 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2242 ||
2243 // Selections
2244 (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty())
2245 // Scrollmanager
2246 || editor.scroll_manager.scrollbars_visible()
2247 }
2248 ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2249 ShowScrollbar::Always => true,
2250 ShowScrollbar::Never => false,
2251 };
2252
2253 let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2254 .into_iter()
2255 .map(|(id, fold)| {
2256 let color = self
2257 .style
2258 .folds
2259 .ellipses
2260 .background
2261 .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
2262 .color;
2263
2264 (id, fold, color)
2265 })
2266 .collect();
2267
2268 let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2269 start_row..end_row,
2270 &active_rows,
2271 is_singleton,
2272 &snapshot,
2273 cx,
2274 );
2275
2276 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2277
2278 let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
2279
2280 let mut max_visible_line_width = 0.0;
2281 let line_layouts =
2282 self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2283 for line_with_invisibles in &line_layouts {
2284 if line_with_invisibles.line.width() > max_visible_line_width {
2285 max_visible_line_width = line_with_invisibles.line.width();
2286 }
2287 }
2288
2289 let style = self.style.clone();
2290 let longest_line_width = layout_line(
2291 snapshot.longest_row(),
2292 &snapshot,
2293 &style,
2294 cx.text_layout_cache(),
2295 )
2296 .width();
2297 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
2298 let em_width = style.text.em_width(cx.font_cache());
2299 let (scroll_width, blocks) = self.layout_blocks(
2300 start_row..end_row,
2301 &snapshot,
2302 size.x(),
2303 scroll_width,
2304 gutter_padding,
2305 gutter_width,
2306 em_width,
2307 gutter_width + gutter_margin,
2308 line_height,
2309 &style,
2310 &line_layouts,
2311 editor,
2312 cx,
2313 );
2314
2315 let scroll_max = vec2f(
2316 ((scroll_width - text_size.x()) / em_width).max(0.0),
2317 max_row as f32,
2318 );
2319
2320 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x());
2321
2322 let autoscrolled = if autoscroll_horizontally {
2323 editor.autoscroll_horizontally(
2324 start_row,
2325 text_size.x(),
2326 scroll_width,
2327 em_width,
2328 &line_layouts,
2329 cx,
2330 )
2331 } else {
2332 false
2333 };
2334
2335 if clamped || autoscrolled {
2336 snapshot = editor.snapshot(cx);
2337 }
2338
2339 let newest_selection_head = editor
2340 .selections
2341 .newest::<usize>(cx)
2342 .head()
2343 .to_display_point(&snapshot);
2344 let style = editor.style(cx);
2345
2346 let mut context_menu = None;
2347 let mut code_actions_indicator = None;
2348 if (start_row..end_row).contains(&newest_selection_head.row()) {
2349 if editor.context_menu_visible() {
2350 context_menu = editor.render_context_menu(newest_selection_head, style.clone(), cx);
2351 }
2352
2353 let active = matches!(
2354 editor.context_menu,
2355 Some(crate::ContextMenu::CodeActions(_))
2356 );
2357
2358 code_actions_indicator = editor
2359 .render_code_actions_indicator(&style, active, cx)
2360 .map(|indicator| (newest_selection_head.row(), indicator));
2361 }
2362
2363 let visible_rows = start_row..start_row + line_layouts.len() as u32;
2364 let mut hover = editor
2365 .hover_state
2366 .render(&snapshot, &style, visible_rows, cx);
2367 let mode = editor.mode;
2368
2369 let mut fold_indicators = editor.render_fold_indicators(
2370 fold_statuses,
2371 &style,
2372 editor.gutter_hovered,
2373 line_height,
2374 gutter_margin,
2375 cx,
2376 );
2377
2378 if let Some((_, context_menu)) = context_menu.as_mut() {
2379 context_menu.layout(
2380 SizeConstraint {
2381 min: Vector2F::zero(),
2382 max: vec2f(
2383 cx.window_size().x() * 0.7,
2384 (12. * line_height).min((size.y() - line_height) / 2.),
2385 ),
2386 },
2387 editor,
2388 cx,
2389 );
2390 }
2391
2392 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
2393 indicator.layout(
2394 SizeConstraint::strict_along(
2395 Axis::Vertical,
2396 line_height * style.code_actions.vertical_scale,
2397 ),
2398 editor,
2399 cx,
2400 );
2401 }
2402
2403 for fold_indicator in fold_indicators.iter_mut() {
2404 if let Some(indicator) = fold_indicator.as_mut() {
2405 indicator.layout(
2406 SizeConstraint::strict_along(
2407 Axis::Vertical,
2408 line_height * style.code_actions.vertical_scale,
2409 ),
2410 editor,
2411 cx,
2412 );
2413 }
2414 }
2415
2416 if let Some((_, hover_popovers)) = hover.as_mut() {
2417 for hover_popover in hover_popovers.iter_mut() {
2418 hover_popover.layout(
2419 SizeConstraint {
2420 min: Vector2F::zero(),
2421 max: vec2f(
2422 (120. * em_width) // Default size
2423 .min(size.x() / 2.) // Shrink to half of the editor width
2424 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2425 (16. * line_height) // Default size
2426 .min(size.y() / 2.) // Shrink to half of the editor height
2427 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2428 ),
2429 },
2430 editor,
2431 cx,
2432 );
2433 }
2434 }
2435
2436 let invisible_symbol_font_size = self.style.text.font_size / 2.0;
2437 let invisible_symbol_style = RunStyle {
2438 color: self.style.whitespace,
2439 font_id: self.style.text.font_id,
2440 underline: Default::default(),
2441 };
2442
2443 (
2444 size,
2445 LayoutState {
2446 mode,
2447 position_map: Arc::new(PositionMap {
2448 size,
2449 scroll_max,
2450 line_layouts,
2451 line_height,
2452 em_width,
2453 em_advance,
2454 snapshot,
2455 }),
2456 visible_display_row_range: start_row..end_row,
2457 wrap_guides,
2458 gutter_size,
2459 gutter_padding,
2460 text_size,
2461 scrollbar_row_range,
2462 show_scrollbars,
2463 is_singleton,
2464 max_row,
2465 gutter_margin,
2466 active_rows,
2467 highlighted_rows,
2468 highlighted_ranges,
2469 fold_ranges,
2470 line_number_layouts,
2471 display_hunks,
2472 blocks,
2473 selections,
2474 context_menu,
2475 code_actions_indicator,
2476 fold_indicators,
2477 tab_invisible: cx.text_layout_cache().layout_str(
2478 "→",
2479 invisible_symbol_font_size,
2480 &[("→".len(), invisible_symbol_style)],
2481 ),
2482 space_invisible: cx.text_layout_cache().layout_str(
2483 "•",
2484 invisible_symbol_font_size,
2485 &[("•".len(), invisible_symbol_style)],
2486 ),
2487 hover_popovers: hover,
2488 },
2489 )
2490 }
2491
2492 fn paint(
2493 &mut self,
2494 scene: &mut SceneBuilder,
2495 bounds: RectF,
2496 visible_bounds: RectF,
2497 layout: &mut Self::LayoutState,
2498 editor: &mut Editor,
2499 cx: &mut ViewContext<Editor>,
2500 ) -> Self::PaintState {
2501 let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2502 scene.push_layer(Some(visible_bounds));
2503
2504 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
2505 let text_bounds = RectF::new(
2506 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2507 layout.text_size,
2508 );
2509
2510 Self::attach_mouse_handlers(
2511 scene,
2512 &layout.position_map,
2513 layout.hover_popovers.is_some(),
2514 visible_bounds,
2515 text_bounds,
2516 gutter_bounds,
2517 bounds,
2518 cx,
2519 );
2520
2521 self.paint_background(scene, gutter_bounds, text_bounds, layout);
2522 if layout.gutter_size.x() > 0. {
2523 self.paint_gutter(scene, gutter_bounds, visible_bounds, layout, editor, cx);
2524 }
2525 self.paint_text(scene, text_bounds, visible_bounds, layout, editor, cx);
2526
2527 scene.push_layer(Some(bounds));
2528 if !layout.blocks.is_empty() {
2529 self.paint_blocks(scene, bounds, visible_bounds, layout, editor, cx);
2530 }
2531 self.paint_scrollbar(scene, bounds, layout, cx, &editor);
2532 scene.pop_layer();
2533
2534 scene.pop_layer();
2535 }
2536
2537 fn rect_for_text_range(
2538 &self,
2539 range_utf16: Range<usize>,
2540 bounds: RectF,
2541 _: RectF,
2542 layout: &Self::LayoutState,
2543 _: &Self::PaintState,
2544 _: &Editor,
2545 _: &ViewContext<Editor>,
2546 ) -> Option<RectF> {
2547 let text_bounds = RectF::new(
2548 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2549 layout.text_size,
2550 );
2551 let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
2552 let scroll_position = layout.position_map.snapshot.scroll_position();
2553 let start_row = scroll_position.y() as u32;
2554 let scroll_top = scroll_position.y() * layout.position_map.line_height;
2555 let scroll_left = scroll_position.x() * layout.position_map.em_width;
2556
2557 let range_start = OffsetUtf16(range_utf16.start)
2558 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2559 if range_start.row() < start_row {
2560 return None;
2561 }
2562
2563 let line = &layout
2564 .position_map
2565 .line_layouts
2566 .get((range_start.row() - start_row) as usize)?
2567 .line;
2568 let range_start_x = line.x_for_index(range_start.column() as usize);
2569 let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
2570 Some(RectF::new(
2571 content_origin
2572 + vec2f(
2573 range_start_x,
2574 range_start_y + layout.position_map.line_height,
2575 )
2576 - vec2f(scroll_left, scroll_top),
2577 vec2f(
2578 layout.position_map.em_width,
2579 layout.position_map.line_height,
2580 ),
2581 ))
2582 }
2583
2584 fn debug(
2585 &self,
2586 bounds: RectF,
2587 _: &Self::LayoutState,
2588 _: &Self::PaintState,
2589 _: &Editor,
2590 _: &ViewContext<Editor>,
2591 ) -> json::Value {
2592 json!({
2593 "type": "BufferElement",
2594 "bounds": bounds.to_json()
2595 })
2596 }
2597}
2598
2599type BufferRow = u32;
2600
2601pub struct LayoutState {
2602 position_map: Arc<PositionMap>,
2603 gutter_size: Vector2F,
2604 gutter_padding: f32,
2605 gutter_margin: f32,
2606 text_size: Vector2F,
2607 mode: EditorMode,
2608 wrap_guides: SmallVec<[(f32, bool); 2]>,
2609 visible_display_row_range: Range<u32>,
2610 active_rows: BTreeMap<u32, bool>,
2611 highlighted_rows: Option<Range<u32>>,
2612 line_number_layouts: Vec<Option<text_layout::Line>>,
2613 display_hunks: Vec<DisplayDiffHunk>,
2614 blocks: Vec<BlockLayout>,
2615 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2616 fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)>,
2617 selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
2618 scrollbar_row_range: Range<f32>,
2619 show_scrollbars: bool,
2620 is_singleton: bool,
2621 max_row: u32,
2622 context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
2623 code_actions_indicator: Option<(u32, AnyElement<Editor>)>,
2624 hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
2625 fold_indicators: Vec<Option<AnyElement<Editor>>>,
2626 tab_invisible: Line,
2627 space_invisible: Line,
2628}
2629
2630struct PositionMap {
2631 size: Vector2F,
2632 line_height: f32,
2633 scroll_max: Vector2F,
2634 em_width: f32,
2635 em_advance: f32,
2636 line_layouts: Vec<LineWithInvisibles>,
2637 snapshot: EditorSnapshot,
2638}
2639
2640impl PositionMap {
2641 /// Returns two display points:
2642 /// 1. The nearest *valid* position in the editor
2643 /// 2. An unclipped, potentially *invalid* position that maps directly to
2644 /// the given pixel position.
2645 fn point_for_position(
2646 &self,
2647 text_bounds: RectF,
2648 position: Vector2F,
2649 ) -> (DisplayPoint, DisplayPoint) {
2650 let scroll_position = self.snapshot.scroll_position();
2651 let position = position - text_bounds.origin();
2652 let y = position.y().max(0.0).min(self.size.y());
2653 let x = position.x() + (scroll_position.x() * self.em_width);
2654 let row = (y / self.line_height + scroll_position.y()) as u32;
2655 let (column, x_overshoot) = if let Some(line) = self
2656 .line_layouts
2657 .get(row as usize - scroll_position.y() as usize)
2658 .map(|line_with_spaces| &line_with_spaces.line)
2659 {
2660 if let Some(ix) = line.index_for_x(x) {
2661 (ix as u32, 0.0)
2662 } else {
2663 (line.len() as u32, 0f32.max(x - line.width()))
2664 }
2665 } else {
2666 (0, x)
2667 };
2668
2669 let mut target_point = DisplayPoint::new(row, column);
2670 let point = self.snapshot.clip_point(target_point, Bias::Left);
2671 *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
2672
2673 (point, target_point)
2674 }
2675}
2676
2677struct BlockLayout {
2678 row: u32,
2679 element: AnyElement<Editor>,
2680 style: BlockStyle,
2681}
2682
2683fn layout_line(
2684 row: u32,
2685 snapshot: &EditorSnapshot,
2686 style: &EditorStyle,
2687 layout_cache: &TextLayoutCache,
2688) -> text_layout::Line {
2689 let mut line = snapshot.line(row);
2690
2691 if line.len() > MAX_LINE_LEN {
2692 let mut len = MAX_LINE_LEN;
2693 while !line.is_char_boundary(len) {
2694 len -= 1;
2695 }
2696
2697 line.truncate(len);
2698 }
2699
2700 layout_cache.layout_str(
2701 &line,
2702 style.text.font_size,
2703 &[(
2704 snapshot.line_len(row) as usize,
2705 RunStyle {
2706 font_id: style.text.font_id,
2707 color: Color::black(),
2708 underline: Default::default(),
2709 },
2710 )],
2711 )
2712}
2713
2714#[derive(Debug)]
2715pub struct Cursor {
2716 origin: Vector2F,
2717 block_width: f32,
2718 line_height: f32,
2719 color: Color,
2720 shape: CursorShape,
2721 block_text: Option<Line>,
2722}
2723
2724impl Cursor {
2725 pub fn new(
2726 origin: Vector2F,
2727 block_width: f32,
2728 line_height: f32,
2729 color: Color,
2730 shape: CursorShape,
2731 block_text: Option<Line>,
2732 ) -> Cursor {
2733 Cursor {
2734 origin,
2735 block_width,
2736 line_height,
2737 color,
2738 shape,
2739 block_text,
2740 }
2741 }
2742
2743 pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2744 RectF::new(
2745 self.origin + origin,
2746 vec2f(self.block_width, self.line_height),
2747 )
2748 }
2749
2750 pub fn paint(&self, scene: &mut SceneBuilder, origin: Vector2F, cx: &mut WindowContext) {
2751 let bounds = match self.shape {
2752 CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2753 CursorShape::Block | CursorShape::Hollow => RectF::new(
2754 self.origin + origin,
2755 vec2f(self.block_width, self.line_height),
2756 ),
2757 CursorShape::Underscore => RectF::new(
2758 self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2759 vec2f(self.block_width, 2.0),
2760 ),
2761 };
2762
2763 //Draw background or border quad
2764 if matches!(self.shape, CursorShape::Hollow) {
2765 scene.push_quad(Quad {
2766 bounds,
2767 background: None,
2768 border: Border::all(1., self.color),
2769 corner_radius: 0.,
2770 });
2771 } else {
2772 scene.push_quad(Quad {
2773 bounds,
2774 background: Some(self.color),
2775 border: Default::default(),
2776 corner_radius: 0.,
2777 });
2778 }
2779
2780 if let Some(block_text) = &self.block_text {
2781 block_text.paint(scene, self.origin + origin, bounds, self.line_height, cx);
2782 }
2783 }
2784
2785 pub fn shape(&self) -> CursorShape {
2786 self.shape
2787 }
2788}
2789
2790#[derive(Debug)]
2791pub struct HighlightedRange {
2792 pub start_y: f32,
2793 pub line_height: f32,
2794 pub lines: Vec<HighlightedRangeLine>,
2795 pub color: Color,
2796 pub corner_radius: f32,
2797}
2798
2799#[derive(Debug)]
2800pub struct HighlightedRangeLine {
2801 pub start_x: f32,
2802 pub end_x: f32,
2803}
2804
2805impl HighlightedRange {
2806 pub fn paint(&self, bounds: RectF, scene: &mut SceneBuilder) {
2807 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2808 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2809 self.paint_lines(
2810 self.start_y + self.line_height,
2811 &self.lines[1..],
2812 bounds,
2813 scene,
2814 );
2815 } else {
2816 self.paint_lines(self.start_y, &self.lines, bounds, scene);
2817 }
2818 }
2819
2820 fn paint_lines(
2821 &self,
2822 start_y: f32,
2823 lines: &[HighlightedRangeLine],
2824 bounds: RectF,
2825 scene: &mut SceneBuilder,
2826 ) {
2827 if lines.is_empty() {
2828 return;
2829 }
2830
2831 let mut path = PathBuilder::new();
2832 let first_line = lines.first().unwrap();
2833 let last_line = lines.last().unwrap();
2834
2835 let first_top_left = vec2f(first_line.start_x, start_y);
2836 let first_top_right = vec2f(first_line.end_x, start_y);
2837
2838 let curve_height = vec2f(0., self.corner_radius);
2839 let curve_width = |start_x: f32, end_x: f32| {
2840 let max = (end_x - start_x) / 2.;
2841 let width = if max < self.corner_radius {
2842 max
2843 } else {
2844 self.corner_radius
2845 };
2846
2847 vec2f(width, 0.)
2848 };
2849
2850 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2851 path.reset(first_top_right - top_curve_width);
2852 path.curve_to(first_top_right + curve_height, first_top_right);
2853
2854 let mut iter = lines.iter().enumerate().peekable();
2855 while let Some((ix, line)) = iter.next() {
2856 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2857
2858 if let Some((_, next_line)) = iter.peek() {
2859 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2860
2861 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2862 Ordering::Equal => {
2863 path.line_to(bottom_right);
2864 }
2865 Ordering::Less => {
2866 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2867 path.line_to(bottom_right - curve_height);
2868 if self.corner_radius > 0. {
2869 path.curve_to(bottom_right - curve_width, bottom_right);
2870 }
2871 path.line_to(next_top_right + curve_width);
2872 if self.corner_radius > 0. {
2873 path.curve_to(next_top_right + curve_height, next_top_right);
2874 }
2875 }
2876 Ordering::Greater => {
2877 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2878 path.line_to(bottom_right - curve_height);
2879 if self.corner_radius > 0. {
2880 path.curve_to(bottom_right + curve_width, bottom_right);
2881 }
2882 path.line_to(next_top_right - curve_width);
2883 if self.corner_radius > 0. {
2884 path.curve_to(next_top_right + curve_height, next_top_right);
2885 }
2886 }
2887 }
2888 } else {
2889 let curve_width = curve_width(line.start_x, line.end_x);
2890 path.line_to(bottom_right - curve_height);
2891 if self.corner_radius > 0. {
2892 path.curve_to(bottom_right - curve_width, bottom_right);
2893 }
2894
2895 let bottom_left = vec2f(line.start_x, bottom_right.y());
2896 path.line_to(bottom_left + curve_width);
2897 if self.corner_radius > 0. {
2898 path.curve_to(bottom_left - curve_height, bottom_left);
2899 }
2900 }
2901 }
2902
2903 if first_line.start_x > last_line.start_x {
2904 let curve_width = curve_width(last_line.start_x, first_line.start_x);
2905 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2906 path.line_to(second_top_left + curve_height);
2907 if self.corner_radius > 0. {
2908 path.curve_to(second_top_left + curve_width, second_top_left);
2909 }
2910 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2911 path.line_to(first_bottom_left - curve_width);
2912 if self.corner_radius > 0. {
2913 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2914 }
2915 }
2916
2917 path.line_to(first_top_left + curve_height);
2918 if self.corner_radius > 0. {
2919 path.curve_to(first_top_left + top_curve_width, first_top_left);
2920 }
2921 path.line_to(first_top_right - top_curve_width);
2922
2923 scene.push_path(path.build(self.color, Some(bounds)));
2924 }
2925}
2926
2927fn position_to_display_point(
2928 position: Vector2F,
2929 text_bounds: RectF,
2930 position_map: &PositionMap,
2931) -> Option<DisplayPoint> {
2932 if text_bounds.contains_point(position) {
2933 let (point, target_point) = position_map.point_for_position(text_bounds, position);
2934 if point == target_point {
2935 Some(point)
2936 } else {
2937 None
2938 }
2939 } else {
2940 None
2941 }
2942}
2943
2944fn range_to_bounds(
2945 range: &Range<DisplayPoint>,
2946 content_origin: Vector2F,
2947 scroll_left: f32,
2948 scroll_top: f32,
2949 visible_row_range: &Range<u32>,
2950 line_end_overshoot: f32,
2951 position_map: &PositionMap,
2952) -> impl Iterator<Item = RectF> {
2953 let mut bounds: SmallVec<[RectF; 1]> = SmallVec::new();
2954
2955 if range.start == range.end {
2956 return bounds.into_iter();
2957 }
2958
2959 let start_row = visible_row_range.start;
2960 let end_row = visible_row_range.end;
2961
2962 let row_range = if range.end.column() == 0 {
2963 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2964 } else {
2965 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2966 };
2967
2968 let first_y =
2969 content_origin.y() + row_range.start as f32 * position_map.line_height - scroll_top;
2970
2971 for (idx, row) in row_range.enumerate() {
2972 let line_layout = &position_map.line_layouts[(row - start_row) as usize].line;
2973
2974 let start_x = if row == range.start.row() {
2975 content_origin.x() + line_layout.x_for_index(range.start.column() as usize)
2976 - scroll_left
2977 } else {
2978 content_origin.x() - scroll_left
2979 };
2980
2981 let end_x = if row == range.end.row() {
2982 content_origin.x() + line_layout.x_for_index(range.end.column() as usize) - scroll_left
2983 } else {
2984 content_origin.x() + line_layout.width() + line_end_overshoot - scroll_left
2985 };
2986
2987 bounds.push(RectF::from_points(
2988 vec2f(start_x, first_y + position_map.line_height * idx as f32),
2989 vec2f(end_x, first_y + position_map.line_height * (idx + 1) as f32),
2990 ))
2991 }
2992
2993 bounds.into_iter()
2994}
2995
2996pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2997 delta.powf(1.5) / 100.0
2998}
2999
3000fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
3001 delta.powf(1.2) / 300.0
3002}
3003
3004#[cfg(test)]
3005mod tests {
3006 use super::*;
3007 use crate::{
3008 display_map::{BlockDisposition, BlockProperties},
3009 editor_tests::{init_test, update_test_language_settings},
3010 Editor, MultiBuffer,
3011 };
3012 use gpui::TestAppContext;
3013 use language::language_settings;
3014 use log::info;
3015 use std::{num::NonZeroU32, sync::Arc};
3016 use util::test::sample_text;
3017
3018 #[gpui::test]
3019 fn test_layout_line_numbers(cx: &mut TestAppContext) {
3020 init_test(cx, |_| {});
3021
3022 let (_, editor) = cx.add_window(|cx| {
3023 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3024 Editor::new(EditorMode::Full, buffer, None, None, cx)
3025 });
3026 let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3027
3028 let layouts = editor.update(cx, |editor, cx| {
3029 let snapshot = editor.snapshot(cx);
3030 element
3031 .layout_line_numbers(0..6, &Default::default(), false, &snapshot, cx)
3032 .0
3033 });
3034 assert_eq!(layouts.len(), 6);
3035 }
3036
3037 #[gpui::test]
3038 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
3039 init_test(cx, |_| {});
3040
3041 let (_, editor) = cx.add_window(|cx| {
3042 let buffer = MultiBuffer::build_simple("", cx);
3043 Editor::new(EditorMode::Full, buffer, None, None, cx)
3044 });
3045
3046 editor.update(cx, |editor, cx| {
3047 editor.set_placeholder_text("hello", cx);
3048 editor.insert_blocks(
3049 [BlockProperties {
3050 style: BlockStyle::Fixed,
3051 disposition: BlockDisposition::Above,
3052 height: 3,
3053 position: Anchor::min(),
3054 render: Arc::new(|_| Empty::new().into_any()),
3055 }],
3056 None,
3057 cx,
3058 );
3059
3060 // Blur the editor so that it displays placeholder text.
3061 cx.blur();
3062 });
3063
3064 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3065 let (size, mut state) = editor.update(cx, |editor, cx| {
3066 let mut new_parents = Default::default();
3067 let mut notify_views_if_parents_change = Default::default();
3068 let mut layout_cx = LayoutContext::new(
3069 cx,
3070 &mut new_parents,
3071 &mut notify_views_if_parents_change,
3072 false,
3073 );
3074 element.layout(
3075 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
3076 editor,
3077 &mut layout_cx,
3078 )
3079 });
3080
3081 assert_eq!(state.position_map.line_layouts.len(), 4);
3082 assert_eq!(
3083 state
3084 .line_number_layouts
3085 .iter()
3086 .map(Option::is_some)
3087 .collect::<Vec<_>>(),
3088 &[false, false, false, true]
3089 );
3090
3091 // Don't panic.
3092 let mut scene = SceneBuilder::new(1.0);
3093 let bounds = RectF::new(Default::default(), size);
3094 editor.update(cx, |editor, cx| {
3095 element.paint(&mut scene, bounds, bounds, &mut state, editor, cx);
3096 });
3097 }
3098
3099 #[gpui::test]
3100 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3101 const TAB_SIZE: u32 = 4;
3102
3103 let input_text = "\t \t|\t| a b";
3104 let expected_invisibles = vec![
3105 Invisible::Tab {
3106 line_start_offset: 0,
3107 },
3108 Invisible::Whitespace {
3109 line_offset: TAB_SIZE as usize,
3110 },
3111 Invisible::Tab {
3112 line_start_offset: TAB_SIZE as usize + 1,
3113 },
3114 Invisible::Tab {
3115 line_start_offset: TAB_SIZE as usize * 2 + 1,
3116 },
3117 Invisible::Whitespace {
3118 line_offset: TAB_SIZE as usize * 3 + 1,
3119 },
3120 Invisible::Whitespace {
3121 line_offset: TAB_SIZE as usize * 3 + 3,
3122 },
3123 ];
3124 assert_eq!(
3125 expected_invisibles.len(),
3126 input_text
3127 .chars()
3128 .filter(|initial_char| initial_char.is_whitespace())
3129 .count(),
3130 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3131 );
3132
3133 init_test(cx, |s| {
3134 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3135 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
3136 });
3137
3138 let actual_invisibles =
3139 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
3140
3141 assert_eq!(expected_invisibles, actual_invisibles);
3142 }
3143
3144 #[gpui::test]
3145 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
3146 init_test(cx, |s| {
3147 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3148 s.defaults.tab_size = NonZeroU32::new(4);
3149 });
3150
3151 for editor_mode_without_invisibles in [
3152 EditorMode::SingleLine,
3153 EditorMode::AutoHeight { max_lines: 100 },
3154 ] {
3155 let invisibles = collect_invisibles_from_new_editor(
3156 cx,
3157 editor_mode_without_invisibles,
3158 "\t\t\t| | a b",
3159 500.0,
3160 );
3161 assert!(invisibles.is_empty(),
3162 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
3163 }
3164 }
3165
3166 #[gpui::test]
3167 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
3168 let tab_size = 4;
3169 let input_text = "a\tbcd ".repeat(9);
3170 let repeated_invisibles = [
3171 Invisible::Tab {
3172 line_start_offset: 1,
3173 },
3174 Invisible::Whitespace {
3175 line_offset: tab_size as usize + 3,
3176 },
3177 Invisible::Whitespace {
3178 line_offset: tab_size as usize + 4,
3179 },
3180 Invisible::Whitespace {
3181 line_offset: tab_size as usize + 5,
3182 },
3183 ];
3184 let expected_invisibles = std::iter::once(repeated_invisibles)
3185 .cycle()
3186 .take(9)
3187 .flatten()
3188 .collect::<Vec<_>>();
3189 assert_eq!(
3190 expected_invisibles.len(),
3191 input_text
3192 .chars()
3193 .filter(|initial_char| initial_char.is_whitespace())
3194 .count(),
3195 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3196 );
3197 info!("Expected invisibles: {expected_invisibles:?}");
3198
3199 init_test(cx, |_| {});
3200
3201 // Put the same string with repeating whitespace pattern into editors of various size,
3202 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
3203 let resize_step = 10.0;
3204 let mut editor_width = 200.0;
3205 while editor_width <= 1000.0 {
3206 update_test_language_settings(cx, |s| {
3207 s.defaults.tab_size = NonZeroU32::new(tab_size);
3208 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3209 s.defaults.preferred_line_length = Some(editor_width as u32);
3210 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
3211 });
3212
3213 let actual_invisibles =
3214 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
3215
3216 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
3217 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
3218 let mut i = 0;
3219 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
3220 i = actual_index;
3221 match expected_invisibles.get(i) {
3222 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
3223 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
3224 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
3225 _ => {
3226 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
3227 }
3228 },
3229 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
3230 }
3231 }
3232 let missing_expected_invisibles = &expected_invisibles[i + 1..];
3233 assert!(
3234 missing_expected_invisibles.is_empty(),
3235 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
3236 );
3237
3238 editor_width += resize_step;
3239 }
3240 }
3241
3242 fn collect_invisibles_from_new_editor(
3243 cx: &mut TestAppContext,
3244 editor_mode: EditorMode,
3245 input_text: &str,
3246 editor_width: f32,
3247 ) -> Vec<Invisible> {
3248 info!(
3249 "Creating editor with mode {editor_mode:?}, width {editor_width} and text '{input_text}'"
3250 );
3251 let (_, editor) = cx.add_window(|cx| {
3252 let buffer = MultiBuffer::build_simple(&input_text, cx);
3253 Editor::new(editor_mode, buffer, None, None, cx)
3254 });
3255
3256 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3257 let (_, layout_state) = editor.update(cx, |editor, cx| {
3258 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
3259 editor.set_wrap_width(Some(editor_width), cx);
3260
3261 let mut new_parents = Default::default();
3262 let mut notify_views_if_parents_change = Default::default();
3263 let mut layout_cx = LayoutContext::new(
3264 cx,
3265 &mut new_parents,
3266 &mut notify_views_if_parents_change,
3267 false,
3268 );
3269 element.layout(
3270 SizeConstraint::new(vec2f(editor_width, 500.), vec2f(editor_width, 500.)),
3271 editor,
3272 &mut layout_cx,
3273 )
3274 });
3275
3276 layout_state
3277 .position_map
3278 .line_layouts
3279 .iter()
3280 .map(|line_with_invisibles| &line_with_invisibles.invisibles)
3281 .flatten()
3282 .cloned()
3283 .collect()
3284 }
3285}