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 git::{diff_hunk_to_display, DisplayDiffHunk},
9 hover_popover::{
10 hide_hover, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH,
11 MIN_POPOVER_LINE_HEIGHT,
12 },
13 link_go_to_definition::{
14 go_to_fetched_definition, go_to_fetched_type_definition, update_go_to_definition_link,
15 },
16 mouse_context_menu, EditorStyle, GutterHover, UnfoldAt,
17};
18use clock::ReplicaId;
19use collections::{BTreeMap, HashMap};
20use git::diff::DiffHunkStatus;
21use gpui::{
22 color::Color,
23 elements::*,
24 fonts::{HighlightStyle, Underline},
25 geometry::{
26 rect::RectF,
27 vector::{vec2f, Vector2F},
28 PathBuilder,
29 },
30 json::{self, ToJson},
31 platform::{CursorStyle, Modifiers, MouseButton, MouseButtonEvent, MouseMovedEvent},
32 text_layout::{self, Line, RunStyle, TextLayoutCache},
33 AnyElement, Axis, Border, CursorRegion, Element, EventContext, LayoutContext, MouseRegion,
34 Quad, SceneBuilder, SizeConstraint, ViewContext, WindowContext,
35};
36use itertools::Itertools;
37use json::json;
38use language::{Bias, CursorShape, DiagnosticSeverity, OffsetUtf16, Selection};
39use project::ProjectPath;
40use settings::{GitGutter, Settings};
41use smallvec::SmallVec;
42use std::{
43 cmp::{self, Ordering},
44 fmt::Write,
45 iter,
46 ops::Range,
47 sync::Arc,
48};
49use workspace::item::Item;
50
51enum FoldMarkers {}
52
53struct SelectionLayout {
54 head: DisplayPoint,
55 cursor_shape: CursorShape,
56 range: Range<DisplayPoint>,
57}
58
59impl SelectionLayout {
60 fn new<T: ToPoint + ToDisplayPoint + Clone>(
61 selection: Selection<T>,
62 line_mode: bool,
63 cursor_shape: CursorShape,
64 map: &DisplaySnapshot,
65 ) -> Self {
66 if line_mode {
67 let selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
68 let point_range = map.expand_to_line(selection.range());
69 Self {
70 head: selection.head().to_display_point(map),
71 cursor_shape,
72 range: point_range.start.to_display_point(map)
73 ..point_range.end.to_display_point(map),
74 }
75 } else {
76 let selection = selection.map(|p| p.to_display_point(map));
77 Self {
78 head: selection.head(),
79 cursor_shape,
80 range: selection.range(),
81 }
82 }
83 }
84}
85
86#[derive(Clone)]
87pub struct EditorElement {
88 style: Arc<EditorStyle>,
89}
90
91impl EditorElement {
92 pub fn new(style: EditorStyle) -> Self {
93 Self {
94 style: Arc::new(style),
95 }
96 }
97
98 fn attach_mouse_handlers(
99 scene: &mut SceneBuilder,
100 position_map: &Arc<PositionMap>,
101 has_popovers: bool,
102 visible_bounds: RectF,
103 text_bounds: RectF,
104 gutter_bounds: RectF,
105 bounds: RectF,
106 cx: &mut ViewContext<Editor>,
107 ) {
108 enum EditorElementMouseHandlers {}
109 scene.push_mouse_region(
110 MouseRegion::new::<EditorElementMouseHandlers>(
111 cx.view_id(),
112 cx.view_id(),
113 visible_bounds,
114 )
115 .on_down(MouseButton::Left, {
116 let position_map = position_map.clone();
117 move |event, editor, cx| {
118 if !Self::mouse_down(
119 editor,
120 event.platform_event,
121 position_map.as_ref(),
122 text_bounds,
123 gutter_bounds,
124 cx,
125 ) {
126 cx.propagate_event();
127 }
128 }
129 })
130 .on_down(MouseButton::Right, {
131 let position_map = position_map.clone();
132 move |event, editor, cx| {
133 if !Self::mouse_right_down(
134 editor,
135 event.position,
136 position_map.as_ref(),
137 text_bounds,
138 cx,
139 ) {
140 cx.propagate_event();
141 }
142 }
143 })
144 .on_up(MouseButton::Left, {
145 let position_map = position_map.clone();
146 move |event, editor, cx| {
147 if !Self::mouse_up(
148 editor,
149 event.position,
150 event.cmd,
151 event.shift,
152 position_map.as_ref(),
153 text_bounds,
154 cx,
155 ) {
156 cx.propagate_event()
157 }
158 }
159 })
160 .on_drag(MouseButton::Left, {
161 let position_map = position_map.clone();
162 move |event, editor, cx| {
163 if !Self::mouse_dragged(
164 editor,
165 event.platform_event,
166 position_map.as_ref(),
167 text_bounds,
168 cx,
169 ) {
170 cx.propagate_event()
171 }
172 }
173 })
174 .on_move({
175 let position_map = position_map.clone();
176 move |event, editor, cx| {
177 if !Self::mouse_moved(
178 editor,
179 event.platform_event,
180 &position_map,
181 text_bounds,
182 cx,
183 ) {
184 cx.propagate_event()
185 }
186 }
187 })
188 .on_move_out(move |_, editor: &mut Editor, cx| {
189 if has_popovers {
190 hide_hover(editor, cx);
191 }
192 })
193 .on_scroll({
194 let position_map = position_map.clone();
195 move |event, editor, cx| {
196 if !Self::scroll(
197 editor,
198 event.position,
199 *event.delta.raw(),
200 event.delta.precise(),
201 &position_map,
202 bounds,
203 cx,
204 ) {
205 cx.propagate_event()
206 }
207 }
208 }),
209 );
210
211 enum GutterHandlers {}
212 scene.push_mouse_region(
213 MouseRegion::new::<GutterHandlers>(cx.view_id(), cx.view_id() + 1, gutter_bounds)
214 .on_hover(|hover, editor: &mut Editor, cx| {
215 editor.gutter_hover(
216 &GutterHover {
217 hovered: hover.started,
218 },
219 cx,
220 );
221 }),
222 )
223 }
224
225 fn mouse_down(
226 editor: &mut Editor,
227 MouseButtonEvent {
228 position,
229 modifiers:
230 Modifiers {
231 shift,
232 ctrl,
233 alt,
234 cmd,
235 ..
236 },
237 mut click_count,
238 ..
239 }: MouseButtonEvent,
240 position_map: &PositionMap,
241 text_bounds: RectF,
242 gutter_bounds: RectF,
243 cx: &mut EventContext<Editor>,
244 ) -> bool {
245 if gutter_bounds.contains_point(position) {
246 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
247 } else if !text_bounds.contains_point(position) {
248 return false;
249 }
250
251 let (position, target_position) = position_map.point_for_position(text_bounds, position);
252
253 if shift && alt {
254 editor.select(
255 SelectPhase::BeginColumnar {
256 position,
257 goal_column: target_position.column(),
258 },
259 cx,
260 );
261 } else if shift && !ctrl && !alt && !cmd {
262 editor.select(
263 SelectPhase::Extend {
264 position,
265 click_count,
266 },
267 cx,
268 );
269 } else {
270 editor.select(
271 SelectPhase::Begin {
272 position,
273 add: alt,
274 click_count,
275 },
276 cx,
277 );
278 }
279
280 true
281 }
282
283 fn mouse_right_down(
284 editor: &mut Editor,
285 position: Vector2F,
286 position_map: &PositionMap,
287 text_bounds: RectF,
288 cx: &mut EventContext<Editor>,
289 ) -> bool {
290 if !text_bounds.contains_point(position) {
291 return false;
292 }
293
294 let (point, _) = position_map.point_for_position(text_bounds, position);
295 mouse_context_menu::deploy_context_menu(editor, position, point, cx);
296 true
297 }
298
299 fn mouse_up(
300 editor: &mut Editor,
301 position: Vector2F,
302 cmd: bool,
303 shift: bool,
304 position_map: &PositionMap,
305 text_bounds: RectF,
306 cx: &mut EventContext<Editor>,
307 ) -> bool {
308 let end_selection = editor.has_pending_selection();
309 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
310
311 if end_selection {
312 editor.select(SelectPhase::End, cx);
313 }
314
315 if !pending_nonempty_selections && cmd && text_bounds.contains_point(position) {
316 let (point, target_point) = position_map.point_for_position(text_bounds, position);
317
318 if point == target_point {
319 if shift {
320 go_to_fetched_type_definition(editor, point, cx);
321 } else {
322 go_to_fetched_definition(editor, point, cx);
323 }
324
325 return true;
326 }
327 }
328
329 end_selection
330 }
331
332 fn mouse_dragged(
333 editor: &mut Editor,
334 MouseMovedEvent {
335 modifiers: Modifiers { cmd, shift, .. },
336 position,
337 ..
338 }: MouseMovedEvent,
339 position_map: &PositionMap,
340 text_bounds: RectF,
341 cx: &mut EventContext<Editor>,
342 ) -> bool {
343 // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
344 // Don't trigger hover popover if mouse is hovering over context menu
345 let point = if text_bounds.contains_point(position) {
346 let (point, target_point) = position_map.point_for_position(text_bounds, position);
347 if point == target_point {
348 Some(point)
349 } else {
350 None
351 }
352 } else {
353 None
354 };
355
356 update_go_to_definition_link(editor, point, cmd, shift, cx);
357
358 if editor.has_pending_selection() {
359 let mut scroll_delta = Vector2F::zero();
360
361 let vertical_margin = position_map.line_height.min(text_bounds.height() / 3.0);
362 let top = text_bounds.origin_y() + vertical_margin;
363 let bottom = text_bounds.lower_left().y() - vertical_margin;
364 if position.y() < top {
365 scroll_delta.set_y(-scale_vertical_mouse_autoscroll_delta(top - position.y()))
366 }
367 if position.y() > bottom {
368 scroll_delta.set_y(scale_vertical_mouse_autoscroll_delta(position.y() - bottom))
369 }
370
371 let horizontal_margin = position_map.line_height.min(text_bounds.width() / 3.0);
372 let left = text_bounds.origin_x() + horizontal_margin;
373 let right = text_bounds.upper_right().x() - horizontal_margin;
374 if position.x() < left {
375 scroll_delta.set_x(-scale_horizontal_mouse_autoscroll_delta(
376 left - position.x(),
377 ))
378 }
379 if position.x() > right {
380 scroll_delta.set_x(scale_horizontal_mouse_autoscroll_delta(
381 position.x() - right,
382 ))
383 }
384
385 let (position, target_position) =
386 position_map.point_for_position(text_bounds, position);
387
388 editor.select(
389 SelectPhase::Update {
390 position,
391 goal_column: target_position.column(),
392 scroll_position: (position_map.snapshot.scroll_position() + scroll_delta)
393 .clamp(Vector2F::zero(), position_map.scroll_max),
394 },
395 cx,
396 );
397 hover_at(editor, point, cx);
398 true
399 } else {
400 hover_at(editor, point, cx);
401 false
402 }
403 }
404
405 fn mouse_moved(
406 editor: &mut Editor,
407 MouseMovedEvent {
408 modifiers: Modifiers { shift, cmd, .. },
409 position,
410 ..
411 }: MouseMovedEvent,
412 position_map: &PositionMap,
413 text_bounds: RectF,
414 cx: &mut ViewContext<Editor>,
415 ) -> bool {
416 // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
417 // Don't trigger hover popover if mouse is hovering over context menu
418 let point = position_to_display_point(position, text_bounds, position_map);
419
420 update_go_to_definition_link(editor, point, cmd, shift, cx);
421 hover_at(editor, point, cx);
422
423 true
424 }
425
426 fn scroll(
427 editor: &mut Editor,
428 position: Vector2F,
429 mut delta: Vector2F,
430 precise: bool,
431 position_map: &PositionMap,
432 bounds: RectF,
433 cx: &mut ViewContext<Editor>,
434 ) -> bool {
435 if !bounds.contains_point(position) {
436 return false;
437 }
438
439 let line_height = position_map.line_height;
440 let max_glyph_width = position_map.em_width;
441
442 let axis = if precise {
443 //Trackpad
444 position_map.snapshot.ongoing_scroll.filter(&mut delta)
445 } else {
446 //Not trackpad
447 delta *= vec2f(max_glyph_width, line_height);
448 None //Resets ongoing scroll
449 };
450
451 let scroll_position = position_map.snapshot.scroll_position();
452 let x = (scroll_position.x() * max_glyph_width - delta.x()) / max_glyph_width;
453 let y = (scroll_position.y() * line_height - delta.y()) / line_height;
454 let scroll_position = vec2f(x, y).clamp(Vector2F::zero(), position_map.scroll_max);
455 editor.scroll(scroll_position, axis, cx);
456
457 true
458 }
459
460 fn paint_background(
461 &self,
462 scene: &mut SceneBuilder,
463 gutter_bounds: RectF,
464 text_bounds: RectF,
465 layout: &LayoutState,
466 ) {
467 let bounds = gutter_bounds.union_rect(text_bounds);
468 let scroll_top =
469 layout.position_map.snapshot.scroll_position().y() * layout.position_map.line_height;
470 scene.push_quad(Quad {
471 bounds: gutter_bounds,
472 background: Some(self.style.gutter_background),
473 border: Border::new(0., Color::transparent_black()),
474 corner_radius: 0.,
475 });
476 scene.push_quad(Quad {
477 bounds: text_bounds,
478 background: Some(self.style.background),
479 border: Border::new(0., Color::transparent_black()),
480 corner_radius: 0.,
481 });
482
483 if let EditorMode::Full = layout.mode {
484 let mut active_rows = layout.active_rows.iter().peekable();
485 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
486 let mut end_row = *start_row;
487 while active_rows.peek().map_or(false, |r| {
488 *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
489 }) {
490 active_rows.next().unwrap();
491 end_row += 1;
492 }
493
494 if !contains_non_empty_selection {
495 let origin = vec2f(
496 bounds.origin_x(),
497 bounds.origin_y() + (layout.position_map.line_height * *start_row as f32)
498 - scroll_top,
499 );
500 let size = vec2f(
501 bounds.width(),
502 layout.position_map.line_height * (end_row - start_row + 1) as f32,
503 );
504 scene.push_quad(Quad {
505 bounds: RectF::new(origin, size),
506 background: Some(self.style.active_line_background),
507 border: Border::default(),
508 corner_radius: 0.,
509 });
510 }
511 }
512
513 if let Some(highlighted_rows) = &layout.highlighted_rows {
514 let origin = vec2f(
515 bounds.origin_x(),
516 bounds.origin_y()
517 + (layout.position_map.line_height * highlighted_rows.start as f32)
518 - scroll_top,
519 );
520 let size = vec2f(
521 bounds.width(),
522 layout.position_map.line_height * highlighted_rows.len() as f32,
523 );
524 scene.push_quad(Quad {
525 bounds: RectF::new(origin, size),
526 background: Some(self.style.highlighted_line_background),
527 border: Border::default(),
528 corner_radius: 0.,
529 });
530 }
531 }
532 }
533
534 fn paint_gutter(
535 &mut self,
536 scene: &mut SceneBuilder,
537 bounds: RectF,
538 visible_bounds: RectF,
539 layout: &mut LayoutState,
540 editor: &mut Editor,
541 cx: &mut ViewContext<Editor>,
542 ) {
543 let line_height = layout.position_map.line_height;
544
545 let scroll_position = layout.position_map.snapshot.scroll_position();
546 let scroll_top = scroll_position.y() * line_height;
547
548 let show_gutter = matches!(
549 &cx.global::<Settings>()
550 .git_overrides
551 .git_gutter
552 .unwrap_or_default(),
553 GitGutter::TrackedFiles
554 );
555
556 if show_gutter {
557 Self::paint_diff_hunks(scene, bounds, layout, cx);
558 }
559
560 for (ix, line) in layout.line_number_layouts.iter().enumerate() {
561 if let Some(line) = line {
562 let line_origin = bounds.origin()
563 + vec2f(
564 bounds.width() - line.width() - layout.gutter_padding,
565 ix as f32 * line_height - (scroll_top % line_height),
566 );
567
568 line.paint(scene, line_origin, visible_bounds, line_height, cx);
569 }
570 }
571
572 for (ix, fold_indicator) in layout.fold_indicators.iter_mut().enumerate() {
573 if let Some(indicator) = fold_indicator.as_mut() {
574 let position = vec2f(
575 bounds.width() - layout.gutter_padding,
576 ix as f32 * line_height - (scroll_top % line_height),
577 );
578 let centering_offset = vec2f(
579 (layout.gutter_padding + layout.gutter_margin - indicator.size().x()) / 2.,
580 (line_height - indicator.size().y()) / 2.,
581 );
582
583 let indicator_origin = bounds.origin() + position + centering_offset;
584
585 indicator.paint(scene, indicator_origin, visible_bounds, editor, cx);
586 }
587 }
588
589 if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
590 let mut x = 0.;
591 let mut y = *row as f32 * line_height - scroll_top;
592 x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
593 y += (line_height - indicator.size().y()) / 2.;
594 indicator.paint(
595 scene,
596 bounds.origin() + vec2f(x, y),
597 visible_bounds,
598 editor,
599 cx,
600 );
601 }
602 }
603
604 fn paint_diff_hunks(
605 scene: &mut SceneBuilder,
606 bounds: RectF,
607 layout: &mut LayoutState,
608 cx: &mut ViewContext<Editor>,
609 ) {
610 let diff_style = &cx.global::<Settings>().theme.editor.diff.clone();
611 let line_height = layout.position_map.line_height;
612
613 let scroll_position = layout.position_map.snapshot.scroll_position();
614 let scroll_top = scroll_position.y() * line_height;
615
616 for hunk in &layout.display_hunks {
617 let (display_row_range, status) = match hunk {
618 //TODO: This rendering is entirely a horrible hack
619 &DisplayDiffHunk::Folded { display_row: row } => {
620 let start_y = row as f32 * line_height - scroll_top;
621 let end_y = start_y + line_height;
622
623 let width = diff_style.removed_width_em * line_height;
624 let highlight_origin = bounds.origin() + vec2f(-width, start_y);
625 let highlight_size = vec2f(width * 2., end_y - start_y);
626 let highlight_bounds = RectF::new(highlight_origin, highlight_size);
627
628 scene.push_quad(Quad {
629 bounds: highlight_bounds,
630 background: Some(diff_style.modified),
631 border: Border::new(0., Color::transparent_black()),
632 corner_radius: 1. * line_height,
633 });
634
635 continue;
636 }
637
638 DisplayDiffHunk::Unfolded {
639 display_row_range,
640 status,
641 } => (display_row_range, status),
642 };
643
644 let color = match status {
645 DiffHunkStatus::Added => diff_style.inserted,
646 DiffHunkStatus::Modified => diff_style.modified,
647
648 //TODO: This rendering is entirely a horrible hack
649 DiffHunkStatus::Removed => {
650 let row = *display_row_range.start();
651
652 let offset = line_height / 2.;
653 let start_y = row as f32 * line_height - offset - scroll_top;
654 let end_y = start_y + line_height;
655
656 let width = diff_style.removed_width_em * line_height;
657 let highlight_origin = bounds.origin() + vec2f(-width, start_y);
658 let highlight_size = vec2f(width * 2., end_y - start_y);
659 let highlight_bounds = RectF::new(highlight_origin, highlight_size);
660
661 scene.push_quad(Quad {
662 bounds: highlight_bounds,
663 background: Some(diff_style.deleted),
664 border: Border::new(0., Color::transparent_black()),
665 corner_radius: 1. * line_height,
666 });
667
668 continue;
669 }
670 };
671
672 let start_row = *display_row_range.start();
673 let end_row = *display_row_range.end();
674
675 let start_y = start_row as f32 * line_height - scroll_top;
676 let end_y = end_row as f32 * line_height - scroll_top + line_height;
677
678 let width = diff_style.width_em * line_height;
679 let highlight_origin = bounds.origin() + vec2f(-width, start_y);
680 let highlight_size = vec2f(width * 2., end_y - start_y);
681 let highlight_bounds = RectF::new(highlight_origin, highlight_size);
682
683 scene.push_quad(Quad {
684 bounds: highlight_bounds,
685 background: Some(color),
686 border: Border::new(0., Color::transparent_black()),
687 corner_radius: diff_style.corner_radius * line_height,
688 });
689 }
690 }
691
692 fn paint_text(
693 &mut self,
694 scene: &mut SceneBuilder,
695 bounds: RectF,
696 visible_bounds: RectF,
697 layout: &mut LayoutState,
698 editor: &mut Editor,
699 cx: &mut ViewContext<Editor>,
700 ) {
701 let style = &self.style;
702 let local_replica_id = editor.replica_id(cx);
703 let scroll_position = layout.position_map.snapshot.scroll_position();
704 let start_row = layout.visible_display_row_range.start;
705 let scroll_top = scroll_position.y() * layout.position_map.line_height;
706 let max_glyph_width = layout.position_map.em_width;
707 let scroll_left = scroll_position.x() * max_glyph_width;
708 let content_origin = bounds.origin() + vec2f(layout.gutter_margin, 0.);
709 let line_end_overshoot = 0.15 * layout.position_map.line_height;
710
711 scene.push_layer(Some(bounds));
712
713 scene.push_cursor_region(CursorRegion {
714 bounds,
715 style: if !editor.link_go_to_definition_state.definitions.is_empty() {
716 CursorStyle::PointingHand
717 } else {
718 CursorStyle::IBeam
719 },
720 });
721
722 let fold_corner_radius =
723 self.style.folds.ellipses.corner_radius_factor * layout.position_map.line_height;
724 for (id, range, color) in layout.fold_ranges.iter() {
725 self.paint_highlighted_range(
726 scene,
727 range.clone(),
728 *color,
729 fold_corner_radius,
730 fold_corner_radius * 2.,
731 layout,
732 content_origin,
733 scroll_top,
734 scroll_left,
735 bounds,
736 );
737
738 for bound in range_to_bounds(
739 &range,
740 content_origin,
741 scroll_left,
742 scroll_top,
743 &layout.visible_display_row_range,
744 line_end_overshoot,
745 &layout.position_map,
746 ) {
747 scene.push_cursor_region(CursorRegion {
748 bounds: bound,
749 style: CursorStyle::PointingHand,
750 });
751
752 let display_row = range.start.row();
753
754 let buffer_row = DisplayPoint::new(display_row, 0)
755 .to_point(&layout.position_map.snapshot.display_snapshot)
756 .row;
757
758 scene.push_mouse_region(
759 MouseRegion::new::<FoldMarkers>(cx.view_id(), *id as usize, bound)
760 .on_click(MouseButton::Left, move |_, editor: &mut Editor, cx| {
761 editor.unfold_at(&UnfoldAt { buffer_row }, cx)
762 })
763 .with_notify_on_hover(true)
764 .with_notify_on_click(true),
765 )
766 }
767 }
768
769 for (range, color) in &layout.highlighted_ranges {
770 self.paint_highlighted_range(
771 scene,
772 range.clone(),
773 *color,
774 0.,
775 line_end_overshoot,
776 layout,
777 content_origin,
778 scroll_top,
779 scroll_left,
780 bounds,
781 );
782 }
783
784 let mut cursors = SmallVec::<[Cursor; 32]>::new();
785 let corner_radius = 0.15 * layout.position_map.line_height;
786
787 for (replica_id, selections) in &layout.selections {
788 let selection_style = style.replica_selection_style(*replica_id);
789
790 for selection in selections {
791 self.paint_highlighted_range(
792 scene,
793 selection.range.clone(),
794 selection_style.selection,
795 corner_radius,
796 corner_radius * 2.,
797 layout,
798 content_origin,
799 scroll_top,
800 scroll_left,
801 bounds,
802 );
803
804 if editor.show_local_cursors(cx) || *replica_id != local_replica_id {
805 let cursor_position = selection.head;
806 if layout
807 .visible_display_row_range
808 .contains(&cursor_position.row())
809 {
810 let cursor_row_layout = &layout.position_map.line_layouts
811 [(cursor_position.row() - start_row) as usize];
812 let cursor_column = cursor_position.column() as usize;
813
814 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
815 let mut block_width =
816 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
817 if block_width == 0.0 {
818 block_width = layout.position_map.em_width;
819 }
820 let block_text = if let CursorShape::Block = selection.cursor_shape {
821 layout
822 .position_map
823 .snapshot
824 .chars_at(cursor_position)
825 .next()
826 .and_then(|(character, _)| {
827 let font_id =
828 cursor_row_layout.font_for_index(cursor_column)?;
829 let text = character.to_string();
830
831 Some(cx.text_layout_cache().layout_str(
832 &text,
833 cursor_row_layout.font_size(),
834 &[(
835 text.len(),
836 RunStyle {
837 font_id,
838 color: style.background,
839 underline: Default::default(),
840 },
841 )],
842 ))
843 })
844 } else {
845 None
846 };
847
848 let x = cursor_character_x - scroll_left;
849 let y = cursor_position.row() as f32 * layout.position_map.line_height
850 - scroll_top;
851 cursors.push(Cursor {
852 color: selection_style.cursor,
853 block_width,
854 origin: vec2f(x, y),
855 line_height: layout.position_map.line_height,
856 shape: selection.cursor_shape,
857 block_text,
858 });
859 }
860 }
861 }
862 }
863
864 if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
865 // Draw glyphs
866 for (ix, line) in layout.position_map.line_layouts.iter().enumerate() {
867 let row = start_row + ix as u32;
868 line.paint(
869 scene,
870 content_origin
871 + vec2f(
872 -scroll_left,
873 row as f32 * layout.position_map.line_height - scroll_top,
874 ),
875 visible_text_bounds,
876 layout.position_map.line_height,
877 cx,
878 );
879 }
880 }
881
882 scene.paint_layer(Some(bounds), |scene| {
883 for cursor in cursors {
884 cursor.paint(scene, content_origin, cx);
885 }
886 });
887
888 if let Some((position, context_menu)) = layout.context_menu.as_mut() {
889 scene.push_stacking_context(None, None);
890 let cursor_row_layout =
891 &layout.position_map.line_layouts[(position.row() - start_row) as usize];
892 let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
893 let y = (position.row() + 1) as f32 * layout.position_map.line_height - scroll_top;
894 let mut list_origin = content_origin + vec2f(x, y);
895 let list_width = context_menu.size().x();
896 let list_height = context_menu.size().y();
897
898 // Snap the right edge of the list to the right edge of the window if
899 // its horizontal bounds overflow.
900 if list_origin.x() + list_width > cx.window_size().x() {
901 list_origin.set_x((cx.window_size().x() - list_width).max(0.));
902 }
903
904 if list_origin.y() + list_height > bounds.max_y() {
905 list_origin.set_y(list_origin.y() - layout.position_map.line_height - list_height);
906 }
907
908 context_menu.paint(
909 scene,
910 list_origin,
911 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
912 editor,
913 cx,
914 );
915
916 scene.pop_stacking_context();
917 }
918
919 if let Some((position, hover_popovers)) = layout.hover_popovers.as_mut() {
920 scene.push_stacking_context(None, None);
921
922 // This is safe because we check on layout whether the required row is available
923 let hovered_row_layout =
924 &layout.position_map.line_layouts[(position.row() - start_row) as usize];
925
926 // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
927 // height. This is the size we will use to decide whether to render popovers above or below
928 // the hovered line.
929 let first_size = hover_popovers[0].size();
930 let height_to_reserve = first_size.y()
931 + 1.5 * MIN_POPOVER_LINE_HEIGHT as f32 * layout.position_map.line_height;
932
933 // Compute Hovered Point
934 let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
935 let y = position.row() as f32 * layout.position_map.line_height - scroll_top;
936 let hovered_point = content_origin + vec2f(x, y);
937
938 if hovered_point.y() - height_to_reserve > 0.0 {
939 // There is enough space above. Render popovers above the hovered point
940 let mut current_y = hovered_point.y();
941 for hover_popover in hover_popovers {
942 let size = hover_popover.size();
943 let mut popover_origin = vec2f(hovered_point.x(), current_y - size.y());
944
945 let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
946 if x_out_of_bounds < 0.0 {
947 popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
948 }
949
950 hover_popover.paint(
951 scene,
952 popover_origin,
953 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
954 editor,
955 cx,
956 );
957
958 current_y = popover_origin.y() - HOVER_POPOVER_GAP;
959 }
960 } else {
961 // There is not enough space above. Render popovers below the hovered point
962 let mut current_y = hovered_point.y() + layout.position_map.line_height;
963 for hover_popover in hover_popovers {
964 let size = hover_popover.size();
965 let mut popover_origin = vec2f(hovered_point.x(), current_y);
966
967 let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
968 if x_out_of_bounds < 0.0 {
969 popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
970 }
971
972 hover_popover.paint(
973 scene,
974 popover_origin,
975 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
976 editor,
977 cx,
978 );
979
980 current_y = popover_origin.y() + size.y() + HOVER_POPOVER_GAP;
981 }
982 }
983
984 scene.pop_stacking_context();
985 }
986
987 scene.pop_layer();
988 }
989
990 fn paint_scrollbar(
991 &mut self,
992 scene: &mut SceneBuilder,
993 bounds: RectF,
994 layout: &mut LayoutState,
995 cx: &mut ViewContext<Editor>,
996 ) {
997 enum ScrollbarMouseHandlers {}
998 if layout.mode != EditorMode::Full {
999 return;
1000 }
1001
1002 let style = &self.style.theme.scrollbar;
1003
1004 let top = bounds.min_y();
1005 let bottom = bounds.max_y();
1006 let right = bounds.max_x();
1007 let left = right - style.width;
1008 let row_range = &layout.scrollbar_row_range;
1009 let max_row = layout.max_row as f32 + (row_range.end - row_range.start);
1010
1011 let mut height = bounds.height();
1012 let mut first_row_y_offset = 0.0;
1013
1014 // Impose a minimum height on the scrollbar thumb
1015 let min_thumb_height =
1016 style.min_height_factor * cx.font_cache.line_height(self.style.text.font_size);
1017 let thumb_height = (row_range.end - row_range.start) * height / max_row;
1018 if thumb_height < min_thumb_height {
1019 first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
1020 height -= min_thumb_height - thumb_height;
1021 }
1022
1023 let y_for_row = |row: f32| -> f32 { top + first_row_y_offset + row * height / max_row };
1024
1025 let thumb_top = y_for_row(row_range.start) - first_row_y_offset;
1026 let thumb_bottom = y_for_row(row_range.end) + first_row_y_offset;
1027 let track_bounds = RectF::from_points(vec2f(left, top), vec2f(right, bottom));
1028 let thumb_bounds = RectF::from_points(vec2f(left, thumb_top), vec2f(right, thumb_bottom));
1029
1030 if layout.show_scrollbars {
1031 scene.push_quad(Quad {
1032 bounds: track_bounds,
1033 border: style.track.border,
1034 background: style.track.background_color,
1035 ..Default::default()
1036 });
1037 scene.push_quad(Quad {
1038 bounds: thumb_bounds,
1039 border: style.thumb.border,
1040 background: style.thumb.background_color,
1041 corner_radius: style.thumb.corner_radius,
1042 });
1043 }
1044
1045 scene.push_cursor_region(CursorRegion {
1046 bounds: track_bounds,
1047 style: CursorStyle::Arrow,
1048 });
1049 scene.push_mouse_region(
1050 MouseRegion::new::<ScrollbarMouseHandlers>(cx.view_id(), cx.view_id(), track_bounds)
1051 .on_move(move |_, editor: &mut Editor, cx| {
1052 editor.scroll_manager.show_scrollbar(cx);
1053 })
1054 .on_down(MouseButton::Left, {
1055 let row_range = row_range.clone();
1056 move |event, editor: &mut Editor, cx| {
1057 let y = event.position.y();
1058 if y < thumb_top || thumb_bottom < y {
1059 let center_row = ((y - top) * max_row as f32 / height).round() as u32;
1060 let top_row = center_row
1061 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
1062 let mut position = editor.scroll_position(cx);
1063 position.set_y(top_row as f32);
1064 editor.set_scroll_position(position, cx);
1065 } else {
1066 editor.scroll_manager.show_scrollbar(cx);
1067 }
1068 }
1069 })
1070 .on_drag(MouseButton::Left, {
1071 move |event, editor: &mut Editor, cx| {
1072 let y = event.prev_mouse_position.y();
1073 let new_y = event.position.y();
1074 if thumb_top < y && y < thumb_bottom {
1075 let mut position = editor.scroll_position(cx);
1076 position.set_y(position.y() + (new_y - y) * (max_row as f32) / height);
1077 if position.y() < 0.0 {
1078 position.set_y(0.);
1079 }
1080 editor.set_scroll_position(position, cx);
1081 }
1082 }
1083 }),
1084 );
1085 }
1086
1087 #[allow(clippy::too_many_arguments)]
1088 fn paint_highlighted_range(
1089 &self,
1090 scene: &mut SceneBuilder,
1091 range: Range<DisplayPoint>,
1092 color: Color,
1093 corner_radius: f32,
1094 line_end_overshoot: f32,
1095 layout: &LayoutState,
1096 content_origin: Vector2F,
1097 scroll_top: f32,
1098 scroll_left: f32,
1099 bounds: RectF,
1100 ) {
1101 let start_row = layout.visible_display_row_range.start;
1102 let end_row = layout.visible_display_row_range.end;
1103 if range.start != range.end {
1104 let row_range = if range.end.column() == 0 {
1105 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
1106 } else {
1107 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
1108 };
1109
1110 let highlighted_range = HighlightedRange {
1111 color,
1112 line_height: layout.position_map.line_height,
1113 corner_radius,
1114 start_y: content_origin.y()
1115 + row_range.start as f32 * layout.position_map.line_height
1116 - scroll_top,
1117 lines: row_range
1118 .into_iter()
1119 .map(|row| {
1120 let line_layout =
1121 &layout.position_map.line_layouts[(row - start_row) as usize];
1122 HighlightedRangeLine {
1123 start_x: if row == range.start.row() {
1124 content_origin.x()
1125 + line_layout.x_for_index(range.start.column() as usize)
1126 - scroll_left
1127 } else {
1128 content_origin.x() - scroll_left
1129 },
1130 end_x: if row == range.end.row() {
1131 content_origin.x()
1132 + line_layout.x_for_index(range.end.column() as usize)
1133 - scroll_left
1134 } else {
1135 content_origin.x() + line_layout.width() + line_end_overshoot
1136 - scroll_left
1137 },
1138 }
1139 })
1140 .collect(),
1141 };
1142
1143 highlighted_range.paint(bounds, scene);
1144 }
1145 }
1146
1147 fn paint_blocks(
1148 &mut self,
1149 scene: &mut SceneBuilder,
1150 bounds: RectF,
1151 visible_bounds: RectF,
1152 layout: &mut LayoutState,
1153 editor: &mut Editor,
1154 cx: &mut ViewContext<Editor>,
1155 ) {
1156 let scroll_position = layout.position_map.snapshot.scroll_position();
1157 let scroll_left = scroll_position.x() * layout.position_map.em_width;
1158 let scroll_top = scroll_position.y() * layout.position_map.line_height;
1159
1160 for block in &mut layout.blocks {
1161 let mut origin = bounds.origin()
1162 + vec2f(
1163 0.,
1164 block.row as f32 * layout.position_map.line_height - scroll_top,
1165 );
1166 if !matches!(block.style, BlockStyle::Sticky) {
1167 origin += vec2f(-scroll_left, 0.);
1168 }
1169 block
1170 .element
1171 .paint(scene, origin, visible_bounds, editor, cx);
1172 }
1173 }
1174
1175 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &ViewContext<Editor>) -> f32 {
1176 let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
1177 let style = &self.style;
1178
1179 cx.text_layout_cache()
1180 .layout_str(
1181 "1".repeat(digit_count).as_str(),
1182 style.text.font_size,
1183 &[(
1184 digit_count,
1185 RunStyle {
1186 font_id: style.text.font_id,
1187 color: Color::black(),
1188 underline: Default::default(),
1189 },
1190 )],
1191 )
1192 .width()
1193 }
1194
1195 //Folds contained in a hunk are ignored apart from shrinking visual size
1196 //If a fold contains any hunks then that fold line is marked as modified
1197 fn layout_git_gutters(
1198 &self,
1199 display_rows: Range<u32>,
1200 snapshot: &EditorSnapshot,
1201 ) -> Vec<DisplayDiffHunk> {
1202 let buffer_snapshot = &snapshot.buffer_snapshot;
1203
1204 let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1205 .to_point(snapshot)
1206 .row;
1207 let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1208 .to_point(snapshot)
1209 .row;
1210
1211 buffer_snapshot
1212 .git_diff_hunks_in_range(buffer_start_row..buffer_end_row, false)
1213 .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1214 .dedup()
1215 .collect()
1216 }
1217
1218 fn layout_line_numbers(
1219 &self,
1220 rows: Range<u32>,
1221 active_rows: &BTreeMap<u32, bool>,
1222 is_singleton: bool,
1223 snapshot: &EditorSnapshot,
1224 cx: &ViewContext<Editor>,
1225 ) -> (
1226 Vec<Option<text_layout::Line>>,
1227 Vec<Option<(FoldStatus, BufferRow, bool)>>,
1228 ) {
1229 let style = &self.style;
1230 let include_line_numbers = snapshot.mode == EditorMode::Full;
1231 let mut line_number_layouts = Vec::with_capacity(rows.len());
1232 let mut fold_statuses = Vec::with_capacity(rows.len());
1233 let mut line_number = String::new();
1234 for (ix, row) in snapshot
1235 .buffer_rows(rows.start)
1236 .take((rows.end - rows.start) as usize)
1237 .enumerate()
1238 {
1239 let display_row = rows.start + ix as u32;
1240 let (active, color) = if active_rows.contains_key(&display_row) {
1241 (true, style.line_number_active)
1242 } else {
1243 (false, style.line_number)
1244 };
1245 if let Some(buffer_row) = row {
1246 if include_line_numbers {
1247 line_number.clear();
1248 write!(&mut line_number, "{}", buffer_row + 1).unwrap();
1249 line_number_layouts.push(Some(cx.text_layout_cache().layout_str(
1250 &line_number,
1251 style.text.font_size,
1252 &[(
1253 line_number.len(),
1254 RunStyle {
1255 font_id: style.text.font_id,
1256 color,
1257 underline: Default::default(),
1258 },
1259 )],
1260 )));
1261 fold_statuses.push(
1262 is_singleton
1263 .then(|| {
1264 snapshot
1265 .fold_for_line(buffer_row)
1266 .map(|fold_status| (fold_status, buffer_row, active))
1267 })
1268 .flatten(),
1269 )
1270 }
1271 } else {
1272 fold_statuses.push(None);
1273 line_number_layouts.push(None);
1274 }
1275 }
1276
1277 (line_number_layouts, fold_statuses)
1278 }
1279
1280 fn layout_lines(
1281 &mut self,
1282 rows: Range<u32>,
1283 snapshot: &EditorSnapshot,
1284 cx: &ViewContext<Editor>,
1285 ) -> Vec<text_layout::Line> {
1286 if rows.start >= rows.end {
1287 return Vec::new();
1288 }
1289
1290 // When the editor is empty and unfocused, then show the placeholder.
1291 if snapshot.is_empty() {
1292 let placeholder_style = self
1293 .style
1294 .placeholder_text
1295 .as_ref()
1296 .unwrap_or(&self.style.text);
1297 let placeholder_text = snapshot.placeholder_text();
1298 let placeholder_lines = placeholder_text
1299 .as_ref()
1300 .map_or("", AsRef::as_ref)
1301 .split('\n')
1302 .skip(rows.start as usize)
1303 .chain(iter::repeat(""))
1304 .take(rows.len());
1305 placeholder_lines
1306 .map(|line| {
1307 cx.text_layout_cache().layout_str(
1308 line,
1309 placeholder_style.font_size,
1310 &[(
1311 line.len(),
1312 RunStyle {
1313 font_id: placeholder_style.font_id,
1314 color: placeholder_style.color,
1315 underline: Default::default(),
1316 },
1317 )],
1318 )
1319 })
1320 .collect()
1321 } else {
1322 let style = &self.style;
1323 let chunks = snapshot
1324 .chunks(rows.clone(), true, Some(style.theme.suggestion))
1325 .map(|chunk| {
1326 let mut highlight_style = chunk
1327 .syntax_highlight_id
1328 .and_then(|id| id.style(&style.syntax));
1329
1330 if let Some(chunk_highlight) = chunk.highlight_style {
1331 if let Some(highlight_style) = highlight_style.as_mut() {
1332 highlight_style.highlight(chunk_highlight);
1333 } else {
1334 highlight_style = Some(chunk_highlight);
1335 }
1336 }
1337
1338 let mut diagnostic_highlight = HighlightStyle::default();
1339
1340 if chunk.is_unnecessary {
1341 diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
1342 }
1343
1344 if let Some(severity) = chunk.diagnostic_severity {
1345 // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
1346 if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
1347 let diagnostic_style = super::diagnostic_style(severity, true, style);
1348 diagnostic_highlight.underline = Some(Underline {
1349 color: Some(diagnostic_style.message.text.color),
1350 thickness: 1.0.into(),
1351 squiggly: true,
1352 });
1353 }
1354 }
1355
1356 if let Some(highlight_style) = highlight_style.as_mut() {
1357 highlight_style.highlight(diagnostic_highlight);
1358 } else {
1359 highlight_style = Some(diagnostic_highlight);
1360 }
1361
1362 (chunk.text, highlight_style)
1363 });
1364 layout_highlighted_chunks(
1365 chunks,
1366 &style.text,
1367 cx.text_layout_cache(),
1368 cx.font_cache(),
1369 MAX_LINE_LEN,
1370 rows.len() as usize,
1371 )
1372 }
1373 }
1374
1375 #[allow(clippy::too_many_arguments)]
1376 fn layout_blocks(
1377 &mut self,
1378 rows: Range<u32>,
1379 snapshot: &EditorSnapshot,
1380 editor_width: f32,
1381 scroll_width: f32,
1382 gutter_padding: f32,
1383 gutter_width: f32,
1384 em_width: f32,
1385 text_x: f32,
1386 line_height: f32,
1387 style: &EditorStyle,
1388 line_layouts: &[text_layout::Line],
1389 include_root: bool,
1390 editor: &mut Editor,
1391 cx: &mut LayoutContext<Editor>,
1392 ) -> (f32, Vec<BlockLayout>) {
1393 let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
1394 let scroll_x = snapshot.scroll_anchor.offset.x();
1395 let (fixed_blocks, non_fixed_blocks) = snapshot
1396 .blocks_in_range(rows.clone())
1397 .partition::<Vec<_>, _>(|(_, block)| match block {
1398 TransformBlock::ExcerptHeader { .. } => false,
1399 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1400 });
1401 let mut render_block = |block: &TransformBlock, width: f32| {
1402 let mut element = match block {
1403 TransformBlock::Custom(block) => {
1404 let align_to = block
1405 .position()
1406 .to_point(&snapshot.buffer_snapshot)
1407 .to_display_point(snapshot);
1408 let anchor_x = text_x
1409 + if rows.contains(&align_to.row()) {
1410 line_layouts[(align_to.row() - rows.start) as usize]
1411 .x_for_index(align_to.column() as usize)
1412 } else {
1413 layout_line(align_to.row(), snapshot, style, cx.text_layout_cache())
1414 .x_for_index(align_to.column() as usize)
1415 };
1416
1417 block.render(&mut BlockContext {
1418 view_context: cx,
1419 anchor_x,
1420 gutter_padding,
1421 line_height,
1422 scroll_x,
1423 gutter_width,
1424 em_width,
1425 })
1426 }
1427 TransformBlock::ExcerptHeader {
1428 id,
1429 buffer,
1430 range,
1431 starts_new_buffer,
1432 ..
1433 } => {
1434 let id = *id;
1435 let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1436 let jump_path = ProjectPath {
1437 worktree_id: file.worktree_id(cx),
1438 path: file.path.clone(),
1439 };
1440 let jump_anchor = range
1441 .primary
1442 .as_ref()
1443 .map_or(range.context.start, |primary| primary.start);
1444 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1445
1446 enum JumpIcon {}
1447 MouseEventHandler::<JumpIcon, _>::new(id.into(), cx, |state, _| {
1448 let style = style.jump_icon.style_for(state, false);
1449 Svg::new("icons/arrow_up_right_8.svg")
1450 .with_color(style.color)
1451 .constrained()
1452 .with_width(style.icon_width)
1453 .aligned()
1454 .contained()
1455 .with_style(style.container)
1456 .constrained()
1457 .with_width(style.button_width)
1458 .with_height(style.button_width)
1459 })
1460 .with_cursor_style(CursorStyle::PointingHand)
1461 .on_click(MouseButton::Left, move |_, editor, cx| {
1462 if let Some(workspace) = editor
1463 .workspace
1464 .as_ref()
1465 .and_then(|(workspace, _)| workspace.upgrade(cx))
1466 {
1467 workspace.update(cx, |workspace, cx| {
1468 Editor::jump(
1469 workspace,
1470 jump_path.clone(),
1471 jump_position,
1472 jump_anchor,
1473 cx,
1474 );
1475 });
1476 }
1477 })
1478 .with_tooltip::<JumpIcon>(
1479 id.into(),
1480 "Jump to Buffer".to_string(),
1481 Some(Box::new(crate::OpenExcerpts)),
1482 tooltip_style.clone(),
1483 cx,
1484 )
1485 .aligned()
1486 .flex_float()
1487 });
1488
1489 if *starts_new_buffer {
1490 let style = &self.style.diagnostic_path_header;
1491 let font_size =
1492 (style.text_scale_factor * self.style.text.font_size).round();
1493
1494 let path = buffer.resolve_file_path(cx, include_root);
1495 let mut filename = None;
1496 let mut parent_path = None;
1497 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1498 if let Some(path) = path {
1499 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1500 parent_path =
1501 path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1502 }
1503
1504 Flex::row()
1505 .with_child(
1506 Label::new(
1507 filename.unwrap_or_else(|| "untitled".to_string()),
1508 style.filename.text.clone().with_font_size(font_size),
1509 )
1510 .contained()
1511 .with_style(style.filename.container)
1512 .aligned(),
1513 )
1514 .with_children(parent_path.map(|path| {
1515 Label::new(path, style.path.text.clone().with_font_size(font_size))
1516 .contained()
1517 .with_style(style.path.container)
1518 .aligned()
1519 }))
1520 .with_children(jump_icon)
1521 .contained()
1522 .with_style(style.container)
1523 .with_padding_left(gutter_padding)
1524 .with_padding_right(gutter_padding)
1525 .expanded()
1526 .into_any_named("path header block")
1527 } else {
1528 let text_style = self.style.text.clone();
1529 Flex::row()
1530 .with_child(Label::new("⋯", text_style))
1531 .with_children(jump_icon)
1532 .contained()
1533 .with_padding_left(gutter_padding)
1534 .with_padding_right(gutter_padding)
1535 .expanded()
1536 .into_any_named("collapsed context")
1537 }
1538 }
1539 };
1540
1541 element.layout(
1542 SizeConstraint {
1543 min: Vector2F::zero(),
1544 max: vec2f(width, block.height() as f32 * line_height),
1545 },
1546 editor,
1547 cx,
1548 );
1549 element
1550 };
1551
1552 let mut fixed_block_max_width = 0f32;
1553 let mut blocks = Vec::new();
1554 for (row, block) in fixed_blocks {
1555 let element = render_block(block, f32::INFINITY);
1556 fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1557 blocks.push(BlockLayout {
1558 row,
1559 element,
1560 style: BlockStyle::Fixed,
1561 });
1562 }
1563 for (row, block) in non_fixed_blocks {
1564 let style = match block {
1565 TransformBlock::Custom(block) => block.style(),
1566 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1567 };
1568 let width = match style {
1569 BlockStyle::Sticky => editor_width,
1570 BlockStyle::Flex => editor_width
1571 .max(fixed_block_max_width)
1572 .max(gutter_width + scroll_width),
1573 BlockStyle::Fixed => unreachable!(),
1574 };
1575 let element = render_block(block, width);
1576 blocks.push(BlockLayout {
1577 row,
1578 element,
1579 style,
1580 });
1581 }
1582 (
1583 scroll_width.max(fixed_block_max_width - gutter_width),
1584 blocks,
1585 )
1586 }
1587}
1588
1589impl Element<Editor> for EditorElement {
1590 type LayoutState = LayoutState;
1591 type PaintState = ();
1592
1593 fn layout(
1594 &mut self,
1595 constraint: SizeConstraint,
1596 editor: &mut Editor,
1597 cx: &mut LayoutContext<Editor>,
1598 ) -> (Vector2F, Self::LayoutState) {
1599 let mut size = constraint.max;
1600 if size.x().is_infinite() {
1601 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1602 }
1603
1604 let snapshot = editor.snapshot(cx);
1605 let style = self.style.clone();
1606 let line_height = style.text.line_height(cx.font_cache());
1607
1608 let gutter_padding;
1609 let gutter_width;
1610 let gutter_margin;
1611 if snapshot.mode == EditorMode::Full {
1612 let em_width = style.text.em_width(cx.font_cache());
1613 gutter_padding = (em_width * style.gutter_padding_factor).round();
1614 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1615 gutter_margin = -style.text.descent(cx.font_cache());
1616 } else {
1617 gutter_padding = 0.0;
1618 gutter_width = 0.0;
1619 gutter_margin = 0.0;
1620 };
1621
1622 let text_width = size.x() - gutter_width;
1623 let em_width = style.text.em_width(cx.font_cache());
1624 let em_advance = style.text.em_advance(cx.font_cache());
1625 let overscroll = vec2f(em_width, 0.);
1626 let snapshot = {
1627 editor.set_visible_line_count(size.y() / line_height);
1628
1629 let editor_width = text_width - gutter_margin - overscroll.x() - em_width;
1630 let wrap_width = match editor.soft_wrap_mode(cx) {
1631 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
1632 SoftWrap::EditorWidth => editor_width,
1633 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
1634 };
1635
1636 if editor.set_wrap_width(Some(wrap_width), cx) {
1637 editor.snapshot(cx)
1638 } else {
1639 snapshot
1640 }
1641 };
1642
1643 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1644 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1645 size.set_y(
1646 scroll_height
1647 .min(constraint.max_along(Axis::Vertical))
1648 .max(constraint.min_along(Axis::Vertical))
1649 .min(line_height * max_lines as f32),
1650 )
1651 } else if let EditorMode::SingleLine = snapshot.mode {
1652 size.set_y(
1653 line_height
1654 .min(constraint.max_along(Axis::Vertical))
1655 .max(constraint.min_along(Axis::Vertical)),
1656 )
1657 } else if size.y().is_infinite() {
1658 size.set_y(scroll_height);
1659 }
1660 let gutter_size = vec2f(gutter_width, size.y());
1661 let text_size = vec2f(text_width, size.y());
1662
1663 let autoscroll_horizontally = editor.autoscroll_vertically(size.y(), line_height, cx);
1664 let mut snapshot = editor.snapshot(cx);
1665
1666 let scroll_position = snapshot.scroll_position();
1667 // The scroll position is a fractional point, the whole number of which represents
1668 // the top of the window in terms of display rows.
1669 let start_row = scroll_position.y() as u32;
1670 let height_in_lines = size.y() / line_height;
1671 let max_row = snapshot.max_point().row();
1672
1673 // Add 1 to ensure selections bleed off screen
1674 let end_row = 1 + cmp::min(
1675 (scroll_position.y() + height_in_lines).ceil() as u32,
1676 max_row,
1677 );
1678
1679 let start_anchor = if start_row == 0 {
1680 Anchor::min()
1681 } else {
1682 snapshot
1683 .buffer_snapshot
1684 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1685 };
1686 let end_anchor = if end_row > max_row {
1687 Anchor::max()
1688 } else {
1689 snapshot
1690 .buffer_snapshot
1691 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1692 };
1693
1694 let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1695 let mut active_rows = BTreeMap::new();
1696 let mut fold_ranges = Vec::new();
1697 let is_singleton = editor.is_singleton(cx);
1698
1699 let highlighted_rows = editor.highlighted_rows();
1700 let theme = cx.global::<Settings>().theme.as_ref();
1701 let highlighted_ranges = editor.background_highlights_in_range(
1702 start_anchor..end_anchor,
1703 &snapshot.display_snapshot,
1704 theme,
1705 );
1706
1707 fold_ranges.extend(
1708 snapshot
1709 .folds_in_range(start_anchor..end_anchor)
1710 .map(|anchor| {
1711 let start = anchor.start.to_point(&snapshot.buffer_snapshot);
1712 (
1713 start.row,
1714 start.to_display_point(&snapshot.display_snapshot)
1715 ..anchor.end.to_display_point(&snapshot),
1716 )
1717 }),
1718 );
1719
1720 let mut remote_selections = HashMap::default();
1721 for (replica_id, line_mode, cursor_shape, selection) in snapshot
1722 .buffer_snapshot
1723 .remote_selections_in_range(&(start_anchor..end_anchor))
1724 {
1725 // The local selections match the leader's selections.
1726 if Some(replica_id) == editor.leader_replica_id {
1727 continue;
1728 }
1729 remote_selections
1730 .entry(replica_id)
1731 .or_insert(Vec::new())
1732 .push(SelectionLayout::new(
1733 selection,
1734 line_mode,
1735 cursor_shape,
1736 &snapshot.display_snapshot,
1737 ));
1738 }
1739 selections.extend(remote_selections);
1740
1741 if editor.show_local_selections {
1742 let mut local_selections = editor
1743 .selections
1744 .disjoint_in_range(start_anchor..end_anchor, cx);
1745 local_selections.extend(editor.selections.pending(cx));
1746 for selection in &local_selections {
1747 let is_empty = selection.start == selection.end;
1748 let selection_start = snapshot.prev_line_boundary(selection.start).1;
1749 let selection_end = snapshot.next_line_boundary(selection.end).1;
1750 for row in cmp::max(selection_start.row(), start_row)
1751 ..=cmp::min(selection_end.row(), end_row)
1752 {
1753 let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
1754 *contains_non_empty_selection |= !is_empty;
1755 }
1756 }
1757
1758 // Render the local selections in the leader's color when following.
1759 let local_replica_id = editor
1760 .leader_replica_id
1761 .unwrap_or_else(|| editor.replica_id(cx));
1762
1763 selections.push((
1764 local_replica_id,
1765 local_selections
1766 .into_iter()
1767 .map(|selection| {
1768 SelectionLayout::new(
1769 selection,
1770 editor.selections.line_mode,
1771 editor.cursor_shape,
1772 &snapshot.display_snapshot,
1773 )
1774 })
1775 .collect(),
1776 ));
1777 }
1778
1779 let show_scrollbars = editor.scroll_manager.scrollbars_visible();
1780 let include_root = editor
1781 .project
1782 .as_ref()
1783 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1784 .unwrap_or_default();
1785
1786 let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
1787 .into_iter()
1788 .map(|(id, fold)| {
1789 let color = self
1790 .style
1791 .folds
1792 .ellipses
1793 .background
1794 .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize), false)
1795 .color;
1796
1797 (id, fold, color)
1798 })
1799 .collect();
1800
1801 let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
1802 start_row..end_row,
1803 &active_rows,
1804 is_singleton,
1805 &snapshot,
1806 cx,
1807 );
1808
1809 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
1810
1811 let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
1812
1813 let mut max_visible_line_width = 0.0;
1814 let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1815 for line in &line_layouts {
1816 if line.width() > max_visible_line_width {
1817 max_visible_line_width = line.width();
1818 }
1819 }
1820
1821 let style = self.style.clone();
1822 let longest_line_width = layout_line(
1823 snapshot.longest_row(),
1824 &snapshot,
1825 &style,
1826 cx.text_layout_cache(),
1827 )
1828 .width();
1829 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1830 let em_width = style.text.em_width(cx.font_cache());
1831 let (scroll_width, blocks) = self.layout_blocks(
1832 start_row..end_row,
1833 &snapshot,
1834 size.x(),
1835 scroll_width,
1836 gutter_padding,
1837 gutter_width,
1838 em_width,
1839 gutter_width + gutter_margin,
1840 line_height,
1841 &style,
1842 &line_layouts,
1843 include_root,
1844 editor,
1845 cx,
1846 );
1847
1848 let scroll_max = vec2f(
1849 ((scroll_width - text_size.x()) / em_width).max(0.0),
1850 max_row as f32,
1851 );
1852
1853 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x());
1854
1855 let autoscrolled = if autoscroll_horizontally {
1856 editor.autoscroll_horizontally(
1857 start_row,
1858 text_size.x(),
1859 scroll_width,
1860 em_width,
1861 &line_layouts,
1862 cx,
1863 )
1864 } else {
1865 false
1866 };
1867
1868 if clamped || autoscrolled {
1869 snapshot = editor.snapshot(cx);
1870 }
1871
1872 let newest_selection_head = editor
1873 .selections
1874 .newest::<usize>(cx)
1875 .head()
1876 .to_display_point(&snapshot);
1877 let style = editor.style(cx);
1878
1879 let mut context_menu = None;
1880 let mut code_actions_indicator = None;
1881 if (start_row..end_row).contains(&newest_selection_head.row()) {
1882 if editor.context_menu_visible() {
1883 context_menu = editor.render_context_menu(newest_selection_head, style.clone(), cx);
1884 }
1885
1886 let active = matches!(
1887 editor.context_menu,
1888 Some(crate::ContextMenu::CodeActions(_))
1889 );
1890
1891 code_actions_indicator = editor
1892 .render_code_actions_indicator(&style, active, cx)
1893 .map(|indicator| (newest_selection_head.row(), indicator));
1894 }
1895
1896 let visible_rows = start_row..start_row + line_layouts.len() as u32;
1897 let mut hover = editor
1898 .hover_state
1899 .render(&snapshot, &style, visible_rows, cx);
1900 let mode = editor.mode;
1901
1902 let mut fold_indicators = editor.render_fold_indicators(
1903 fold_statuses,
1904 &style,
1905 editor.gutter_hovered,
1906 line_height,
1907 gutter_margin,
1908 cx,
1909 );
1910
1911 if let Some((_, context_menu)) = context_menu.as_mut() {
1912 context_menu.layout(
1913 SizeConstraint {
1914 min: Vector2F::zero(),
1915 max: vec2f(
1916 cx.window_size().x() * 0.7,
1917 (12. * line_height).min((size.y() - line_height) / 2.),
1918 ),
1919 },
1920 editor,
1921 cx,
1922 );
1923 }
1924
1925 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1926 indicator.layout(
1927 SizeConstraint::strict_along(
1928 Axis::Vertical,
1929 line_height * style.code_actions.vertical_scale,
1930 ),
1931 editor,
1932 cx,
1933 );
1934 }
1935
1936 for fold_indicator in fold_indicators.iter_mut() {
1937 if let Some(indicator) = fold_indicator.as_mut() {
1938 indicator.layout(
1939 SizeConstraint::strict_along(
1940 Axis::Vertical,
1941 line_height * style.code_actions.vertical_scale,
1942 ),
1943 editor,
1944 cx,
1945 );
1946 }
1947 }
1948
1949 if let Some((_, hover_popovers)) = hover.as_mut() {
1950 for hover_popover in hover_popovers.iter_mut() {
1951 hover_popover.layout(
1952 SizeConstraint {
1953 min: Vector2F::zero(),
1954 max: vec2f(
1955 (120. * em_width) // Default size
1956 .min(size.x() / 2.) // Shrink to half of the editor width
1957 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1958 (16. * line_height) // Default size
1959 .min(size.y() / 2.) // Shrink to half of the editor height
1960 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1961 ),
1962 },
1963 editor,
1964 cx,
1965 );
1966 }
1967 }
1968
1969 (
1970 size,
1971 LayoutState {
1972 mode,
1973 position_map: Arc::new(PositionMap {
1974 size,
1975 scroll_max,
1976 line_layouts,
1977 line_height,
1978 em_width,
1979 em_advance,
1980 snapshot,
1981 }),
1982 visible_display_row_range: start_row..end_row,
1983 gutter_size,
1984 gutter_padding,
1985 text_size,
1986 scrollbar_row_range,
1987 show_scrollbars,
1988 max_row,
1989 gutter_margin,
1990 active_rows,
1991 highlighted_rows,
1992 highlighted_ranges,
1993 fold_ranges,
1994 line_number_layouts,
1995 display_hunks,
1996 blocks,
1997 selections,
1998 context_menu,
1999 code_actions_indicator,
2000 fold_indicators,
2001 hover_popovers: hover,
2002 },
2003 )
2004 }
2005
2006 fn paint(
2007 &mut self,
2008 scene: &mut SceneBuilder,
2009 bounds: RectF,
2010 visible_bounds: RectF,
2011 layout: &mut Self::LayoutState,
2012 editor: &mut Editor,
2013 cx: &mut ViewContext<Editor>,
2014 ) -> Self::PaintState {
2015 let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2016 scene.push_layer(Some(visible_bounds));
2017
2018 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
2019 let text_bounds = RectF::new(
2020 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2021 layout.text_size,
2022 );
2023
2024 Self::attach_mouse_handlers(
2025 scene,
2026 &layout.position_map,
2027 layout.hover_popovers.is_some(),
2028 visible_bounds,
2029 text_bounds,
2030 gutter_bounds,
2031 bounds,
2032 cx,
2033 );
2034
2035 self.paint_background(scene, gutter_bounds, text_bounds, layout);
2036 if layout.gutter_size.x() > 0. {
2037 self.paint_gutter(scene, gutter_bounds, visible_bounds, layout, editor, cx);
2038 }
2039 self.paint_text(scene, text_bounds, visible_bounds, layout, editor, cx);
2040
2041 scene.push_layer(Some(bounds));
2042 if !layout.blocks.is_empty() {
2043 self.paint_blocks(scene, bounds, visible_bounds, layout, editor, cx);
2044 }
2045 self.paint_scrollbar(scene, bounds, layout, cx);
2046 scene.pop_layer();
2047
2048 scene.pop_layer();
2049 }
2050
2051 fn rect_for_text_range(
2052 &self,
2053 range_utf16: Range<usize>,
2054 bounds: RectF,
2055 _: RectF,
2056 layout: &Self::LayoutState,
2057 _: &Self::PaintState,
2058 _: &Editor,
2059 _: &ViewContext<Editor>,
2060 ) -> Option<RectF> {
2061 let text_bounds = RectF::new(
2062 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2063 layout.text_size,
2064 );
2065 let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
2066 let scroll_position = layout.position_map.snapshot.scroll_position();
2067 let start_row = scroll_position.y() as u32;
2068 let scroll_top = scroll_position.y() * layout.position_map.line_height;
2069 let scroll_left = scroll_position.x() * layout.position_map.em_width;
2070
2071 let range_start = OffsetUtf16(range_utf16.start)
2072 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2073 if range_start.row() < start_row {
2074 return None;
2075 }
2076
2077 let line = layout
2078 .position_map
2079 .line_layouts
2080 .get((range_start.row() - start_row) as usize)?;
2081 let range_start_x = line.x_for_index(range_start.column() as usize);
2082 let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
2083 Some(RectF::new(
2084 content_origin
2085 + vec2f(
2086 range_start_x,
2087 range_start_y + layout.position_map.line_height,
2088 )
2089 - vec2f(scroll_left, scroll_top),
2090 vec2f(
2091 layout.position_map.em_width,
2092 layout.position_map.line_height,
2093 ),
2094 ))
2095 }
2096
2097 fn debug(
2098 &self,
2099 bounds: RectF,
2100 _: &Self::LayoutState,
2101 _: &Self::PaintState,
2102 _: &Editor,
2103 _: &ViewContext<Editor>,
2104 ) -> json::Value {
2105 json!({
2106 "type": "BufferElement",
2107 "bounds": bounds.to_json()
2108 })
2109 }
2110}
2111
2112type BufferRow = u32;
2113
2114pub struct LayoutState {
2115 position_map: Arc<PositionMap>,
2116 gutter_size: Vector2F,
2117 gutter_padding: f32,
2118 gutter_margin: f32,
2119 text_size: Vector2F,
2120 mode: EditorMode,
2121 visible_display_row_range: Range<u32>,
2122 active_rows: BTreeMap<u32, bool>,
2123 highlighted_rows: Option<Range<u32>>,
2124 line_number_layouts: Vec<Option<text_layout::Line>>,
2125 display_hunks: Vec<DisplayDiffHunk>,
2126 blocks: Vec<BlockLayout>,
2127 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2128 fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)>,
2129 selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
2130 scrollbar_row_range: Range<f32>,
2131 show_scrollbars: bool,
2132 max_row: u32,
2133 context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
2134 code_actions_indicator: Option<(u32, AnyElement<Editor>)>,
2135 hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
2136 fold_indicators: Vec<Option<AnyElement<Editor>>>,
2137}
2138
2139pub struct PositionMap {
2140 size: Vector2F,
2141 line_height: f32,
2142 scroll_max: Vector2F,
2143 em_width: f32,
2144 em_advance: f32,
2145 line_layouts: Vec<text_layout::Line>,
2146 snapshot: EditorSnapshot,
2147}
2148
2149impl PositionMap {
2150 /// Returns two display points:
2151 /// 1. The nearest *valid* position in the editor
2152 /// 2. An unclipped, potentially *invalid* position that maps directly to
2153 /// the given pixel position.
2154 fn point_for_position(
2155 &self,
2156 text_bounds: RectF,
2157 position: Vector2F,
2158 ) -> (DisplayPoint, DisplayPoint) {
2159 let scroll_position = self.snapshot.scroll_position();
2160 let position = position - text_bounds.origin();
2161 let y = position.y().max(0.0).min(self.size.y());
2162 let x = position.x() + (scroll_position.x() * self.em_width);
2163 let row = (y / self.line_height + scroll_position.y()) as u32;
2164 let (column, x_overshoot) = if let Some(line) = self
2165 .line_layouts
2166 .get(row as usize - scroll_position.y() as usize)
2167 {
2168 if let Some(ix) = line.index_for_x(x) {
2169 (ix as u32, 0.0)
2170 } else {
2171 (line.len() as u32, 0f32.max(x - line.width()))
2172 }
2173 } else {
2174 (0, x)
2175 };
2176
2177 let mut target_point = DisplayPoint::new(row, column);
2178 let point = self.snapshot.clip_point(target_point, Bias::Left);
2179 *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
2180
2181 (point, target_point)
2182 }
2183}
2184
2185struct BlockLayout {
2186 row: u32,
2187 element: AnyElement<Editor>,
2188 style: BlockStyle,
2189}
2190
2191fn layout_line(
2192 row: u32,
2193 snapshot: &EditorSnapshot,
2194 style: &EditorStyle,
2195 layout_cache: &TextLayoutCache,
2196) -> text_layout::Line {
2197 let mut line = snapshot.line(row);
2198
2199 if line.len() > MAX_LINE_LEN {
2200 let mut len = MAX_LINE_LEN;
2201 while !line.is_char_boundary(len) {
2202 len -= 1;
2203 }
2204
2205 line.truncate(len);
2206 }
2207
2208 layout_cache.layout_str(
2209 &line,
2210 style.text.font_size,
2211 &[(
2212 snapshot.line_len(row) as usize,
2213 RunStyle {
2214 font_id: style.text.font_id,
2215 color: Color::black(),
2216 underline: Default::default(),
2217 },
2218 )],
2219 )
2220}
2221
2222#[derive(Debug)]
2223pub struct Cursor {
2224 origin: Vector2F,
2225 block_width: f32,
2226 line_height: f32,
2227 color: Color,
2228 shape: CursorShape,
2229 block_text: Option<Line>,
2230}
2231
2232impl Cursor {
2233 pub fn new(
2234 origin: Vector2F,
2235 block_width: f32,
2236 line_height: f32,
2237 color: Color,
2238 shape: CursorShape,
2239 block_text: Option<Line>,
2240 ) -> Cursor {
2241 Cursor {
2242 origin,
2243 block_width,
2244 line_height,
2245 color,
2246 shape,
2247 block_text,
2248 }
2249 }
2250
2251 pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2252 RectF::new(
2253 self.origin + origin,
2254 vec2f(self.block_width, self.line_height),
2255 )
2256 }
2257
2258 pub fn paint(&self, scene: &mut SceneBuilder, origin: Vector2F, cx: &mut WindowContext) {
2259 let bounds = match self.shape {
2260 CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2261 CursorShape::Block | CursorShape::Hollow => RectF::new(
2262 self.origin + origin,
2263 vec2f(self.block_width, self.line_height),
2264 ),
2265 CursorShape::Underscore => RectF::new(
2266 self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2267 vec2f(self.block_width, 2.0),
2268 ),
2269 };
2270
2271 //Draw background or border quad
2272 if matches!(self.shape, CursorShape::Hollow) {
2273 scene.push_quad(Quad {
2274 bounds,
2275 background: None,
2276 border: Border::all(1., self.color),
2277 corner_radius: 0.,
2278 });
2279 } else {
2280 scene.push_quad(Quad {
2281 bounds,
2282 background: Some(self.color),
2283 border: Default::default(),
2284 corner_radius: 0.,
2285 });
2286 }
2287
2288 if let Some(block_text) = &self.block_text {
2289 block_text.paint(scene, self.origin + origin, bounds, self.line_height, cx);
2290 }
2291 }
2292
2293 pub fn shape(&self) -> CursorShape {
2294 self.shape
2295 }
2296}
2297
2298#[derive(Debug)]
2299pub struct HighlightedRange {
2300 pub start_y: f32,
2301 pub line_height: f32,
2302 pub lines: Vec<HighlightedRangeLine>,
2303 pub color: Color,
2304 pub corner_radius: f32,
2305}
2306
2307#[derive(Debug)]
2308pub struct HighlightedRangeLine {
2309 pub start_x: f32,
2310 pub end_x: f32,
2311}
2312
2313impl HighlightedRange {
2314 pub fn paint(&self, bounds: RectF, scene: &mut SceneBuilder) {
2315 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2316 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2317 self.paint_lines(
2318 self.start_y + self.line_height,
2319 &self.lines[1..],
2320 bounds,
2321 scene,
2322 );
2323 } else {
2324 self.paint_lines(self.start_y, &self.lines, bounds, scene);
2325 }
2326 }
2327
2328 fn paint_lines(
2329 &self,
2330 start_y: f32,
2331 lines: &[HighlightedRangeLine],
2332 bounds: RectF,
2333 scene: &mut SceneBuilder,
2334 ) {
2335 if lines.is_empty() {
2336 return;
2337 }
2338
2339 let mut path = PathBuilder::new();
2340 let first_line = lines.first().unwrap();
2341 let last_line = lines.last().unwrap();
2342
2343 let first_top_left = vec2f(first_line.start_x, start_y);
2344 let first_top_right = vec2f(first_line.end_x, start_y);
2345
2346 let curve_height = vec2f(0., self.corner_radius);
2347 let curve_width = |start_x: f32, end_x: f32| {
2348 let max = (end_x - start_x) / 2.;
2349 let width = if max < self.corner_radius {
2350 max
2351 } else {
2352 self.corner_radius
2353 };
2354
2355 vec2f(width, 0.)
2356 };
2357
2358 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2359 path.reset(first_top_right - top_curve_width);
2360 path.curve_to(first_top_right + curve_height, first_top_right);
2361
2362 let mut iter = lines.iter().enumerate().peekable();
2363 while let Some((ix, line)) = iter.next() {
2364 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2365
2366 if let Some((_, next_line)) = iter.peek() {
2367 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2368
2369 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2370 Ordering::Equal => {
2371 path.line_to(bottom_right);
2372 }
2373 Ordering::Less => {
2374 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2375 path.line_to(bottom_right - curve_height);
2376 if self.corner_radius > 0. {
2377 path.curve_to(bottom_right - curve_width, bottom_right);
2378 }
2379 path.line_to(next_top_right + curve_width);
2380 if self.corner_radius > 0. {
2381 path.curve_to(next_top_right + curve_height, next_top_right);
2382 }
2383 }
2384 Ordering::Greater => {
2385 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2386 path.line_to(bottom_right - curve_height);
2387 if self.corner_radius > 0. {
2388 path.curve_to(bottom_right + curve_width, bottom_right);
2389 }
2390 path.line_to(next_top_right - curve_width);
2391 if self.corner_radius > 0. {
2392 path.curve_to(next_top_right + curve_height, next_top_right);
2393 }
2394 }
2395 }
2396 } else {
2397 let curve_width = curve_width(line.start_x, line.end_x);
2398 path.line_to(bottom_right - curve_height);
2399 if self.corner_radius > 0. {
2400 path.curve_to(bottom_right - curve_width, bottom_right);
2401 }
2402
2403 let bottom_left = vec2f(line.start_x, bottom_right.y());
2404 path.line_to(bottom_left + curve_width);
2405 if self.corner_radius > 0. {
2406 path.curve_to(bottom_left - curve_height, bottom_left);
2407 }
2408 }
2409 }
2410
2411 if first_line.start_x > last_line.start_x {
2412 let curve_width = curve_width(last_line.start_x, first_line.start_x);
2413 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2414 path.line_to(second_top_left + curve_height);
2415 if self.corner_radius > 0. {
2416 path.curve_to(second_top_left + curve_width, second_top_left);
2417 }
2418 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2419 path.line_to(first_bottom_left - curve_width);
2420 if self.corner_radius > 0. {
2421 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2422 }
2423 }
2424
2425 path.line_to(first_top_left + curve_height);
2426 if self.corner_radius > 0. {
2427 path.curve_to(first_top_left + top_curve_width, first_top_left);
2428 }
2429 path.line_to(first_top_right - top_curve_width);
2430
2431 scene.push_path(path.build(self.color, Some(bounds)));
2432 }
2433}
2434
2435pub fn position_to_display_point(
2436 position: Vector2F,
2437 text_bounds: RectF,
2438 position_map: &PositionMap,
2439) -> Option<DisplayPoint> {
2440 if text_bounds.contains_point(position) {
2441 let (point, target_point) = position_map.point_for_position(text_bounds, position);
2442 if point == target_point {
2443 Some(point)
2444 } else {
2445 None
2446 }
2447 } else {
2448 None
2449 }
2450}
2451
2452pub fn range_to_bounds(
2453 range: &Range<DisplayPoint>,
2454 content_origin: Vector2F,
2455 scroll_left: f32,
2456 scroll_top: f32,
2457 visible_row_range: &Range<u32>,
2458 line_end_overshoot: f32,
2459 position_map: &PositionMap,
2460) -> impl Iterator<Item = RectF> {
2461 let mut bounds: SmallVec<[RectF; 1]> = SmallVec::new();
2462
2463 if range.start == range.end {
2464 return bounds.into_iter();
2465 }
2466
2467 let start_row = visible_row_range.start;
2468 let end_row = visible_row_range.end;
2469
2470 let row_range = if range.end.column() == 0 {
2471 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2472 } else {
2473 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2474 };
2475
2476 let first_y =
2477 content_origin.y() + row_range.start as f32 * position_map.line_height - scroll_top;
2478
2479 for (idx, row) in row_range.enumerate() {
2480 let line_layout = &position_map.line_layouts[(row - start_row) as usize];
2481
2482 let start_x = if row == range.start.row() {
2483 content_origin.x() + line_layout.x_for_index(range.start.column() as usize)
2484 - scroll_left
2485 } else {
2486 content_origin.x() - scroll_left
2487 };
2488
2489 let end_x = if row == range.end.row() {
2490 content_origin.x() + line_layout.x_for_index(range.end.column() as usize) - scroll_left
2491 } else {
2492 content_origin.x() + line_layout.width() + line_end_overshoot - scroll_left
2493 };
2494
2495 bounds.push(RectF::from_points(
2496 vec2f(start_x, first_y + position_map.line_height * idx as f32),
2497 vec2f(end_x, first_y + position_map.line_height * (idx + 1) as f32),
2498 ))
2499 }
2500
2501 bounds.into_iter()
2502}
2503
2504pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2505 delta.powf(1.5) / 100.0
2506}
2507
2508fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
2509 delta.powf(1.2) / 300.0
2510}
2511
2512#[cfg(test)]
2513mod tests {
2514 use super::*;
2515 use crate::{
2516 display_map::{BlockDisposition, BlockProperties},
2517 Editor, MultiBuffer,
2518 };
2519 use gpui::TestAppContext;
2520 use settings::Settings;
2521 use std::sync::Arc;
2522 use util::test::sample_text;
2523
2524 #[gpui::test]
2525 fn test_layout_line_numbers(cx: &mut TestAppContext) {
2526 cx.update(|cx| cx.set_global(Settings::test(cx)));
2527 let (_, editor) = cx.add_window(|cx| {
2528 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
2529 Editor::new(EditorMode::Full, buffer, None, None, cx)
2530 });
2531 let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
2532
2533 let layouts = editor.update(cx, |editor, cx| {
2534 let snapshot = editor.snapshot(cx);
2535 element
2536 .layout_line_numbers(0..6, &Default::default(), false, &snapshot, cx)
2537 .0
2538 });
2539 assert_eq!(layouts.len(), 6);
2540 }
2541
2542 #[gpui::test]
2543 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
2544 cx.update(|cx| cx.set_global(Settings::test(cx)));
2545 let (_, editor) = cx.add_window(|cx| {
2546 let buffer = MultiBuffer::build_simple("", cx);
2547 Editor::new(EditorMode::Full, buffer, None, None, cx)
2548 });
2549
2550 editor.update(cx, |editor, cx| {
2551 editor.set_placeholder_text("hello", cx);
2552 editor.insert_blocks(
2553 [BlockProperties {
2554 style: BlockStyle::Fixed,
2555 disposition: BlockDisposition::Above,
2556 height: 3,
2557 position: Anchor::min(),
2558 render: Arc::new(|_| Empty::new().into_any()),
2559 }],
2560 cx,
2561 );
2562
2563 // Blur the editor so that it displays placeholder text.
2564 cx.blur();
2565 });
2566
2567 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
2568 let (size, mut state) = editor.update(cx, |editor, cx| {
2569 let mut new_parents = Default::default();
2570 let mut notify_views_if_parents_change = Default::default();
2571 let mut layout_cx = LayoutContext::new(
2572 cx,
2573 &mut new_parents,
2574 &mut notify_views_if_parents_change,
2575 false,
2576 );
2577 element.layout(
2578 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
2579 editor,
2580 &mut layout_cx,
2581 )
2582 });
2583
2584 assert_eq!(state.position_map.line_layouts.len(), 4);
2585 assert_eq!(
2586 state
2587 .line_number_layouts
2588 .iter()
2589 .map(Option::is_some)
2590 .collect::<Vec<_>>(),
2591 &[false, false, false, true]
2592 );
2593
2594 // Don't panic.
2595 let mut scene = SceneBuilder::new(1.0);
2596 let bounds = RectF::new(Default::default(), size);
2597 editor.update(cx, |editor, cx| {
2598 element.paint(&mut scene, bounds, bounds, &mut state, editor, cx);
2599 });
2600 }
2601}