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 HighlightedChunk {
1363 chunk: chunk.text,
1364 style: highlight_style,
1365 is_tab: chunk.is_tab,
1366 }
1367 });
1368
1369 let settings = cx.global::<Settings>();
1370 let show_invisibles = settings
1371 .editor_overrides
1372 .show_invisibles
1373 .or(settings.editor_defaults.show_invisibles)
1374 .unwrap_or_default()
1375 == settings::ShowInvisibles::All;
1376 layout_highlighted_chunks(
1377 chunks,
1378 &style.text,
1379 cx.text_layout_cache(),
1380 cx.font_cache(),
1381 MAX_LINE_LEN,
1382 rows.len() as usize,
1383 show_invisibles,
1384 )
1385 }
1386 }
1387
1388 #[allow(clippy::too_many_arguments)]
1389 fn layout_blocks(
1390 &mut self,
1391 rows: Range<u32>,
1392 snapshot: &EditorSnapshot,
1393 editor_width: f32,
1394 scroll_width: f32,
1395 gutter_padding: f32,
1396 gutter_width: f32,
1397 em_width: f32,
1398 text_x: f32,
1399 line_height: f32,
1400 style: &EditorStyle,
1401 line_layouts: &[text_layout::Line],
1402 include_root: bool,
1403 editor: &mut Editor,
1404 cx: &mut LayoutContext<Editor>,
1405 ) -> (f32, Vec<BlockLayout>) {
1406 let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
1407 let scroll_x = snapshot.scroll_anchor.offset.x();
1408 let (fixed_blocks, non_fixed_blocks) = snapshot
1409 .blocks_in_range(rows.clone())
1410 .partition::<Vec<_>, _>(|(_, block)| match block {
1411 TransformBlock::ExcerptHeader { .. } => false,
1412 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1413 });
1414 let mut render_block = |block: &TransformBlock, width: f32| {
1415 let mut element = match block {
1416 TransformBlock::Custom(block) => {
1417 let align_to = block
1418 .position()
1419 .to_point(&snapshot.buffer_snapshot)
1420 .to_display_point(snapshot);
1421 let anchor_x = text_x
1422 + if rows.contains(&align_to.row()) {
1423 line_layouts[(align_to.row() - rows.start) as usize]
1424 .x_for_index(align_to.column() as usize)
1425 } else {
1426 layout_line(align_to.row(), snapshot, style, cx.text_layout_cache())
1427 .x_for_index(align_to.column() as usize)
1428 };
1429
1430 block.render(&mut BlockContext {
1431 view_context: cx,
1432 anchor_x,
1433 gutter_padding,
1434 line_height,
1435 scroll_x,
1436 gutter_width,
1437 em_width,
1438 })
1439 }
1440 TransformBlock::ExcerptHeader {
1441 id,
1442 buffer,
1443 range,
1444 starts_new_buffer,
1445 ..
1446 } => {
1447 let id = *id;
1448 let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1449 let jump_path = ProjectPath {
1450 worktree_id: file.worktree_id(cx),
1451 path: file.path.clone(),
1452 };
1453 let jump_anchor = range
1454 .primary
1455 .as_ref()
1456 .map_or(range.context.start, |primary| primary.start);
1457 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1458
1459 enum JumpIcon {}
1460 MouseEventHandler::<JumpIcon, _>::new(id.into(), cx, |state, _| {
1461 let style = style.jump_icon.style_for(state, false);
1462 Svg::new("icons/arrow_up_right_8.svg")
1463 .with_color(style.color)
1464 .constrained()
1465 .with_width(style.icon_width)
1466 .aligned()
1467 .contained()
1468 .with_style(style.container)
1469 .constrained()
1470 .with_width(style.button_width)
1471 .with_height(style.button_width)
1472 })
1473 .with_cursor_style(CursorStyle::PointingHand)
1474 .on_click(MouseButton::Left, move |_, editor, cx| {
1475 if let Some(workspace) = editor
1476 .workspace
1477 .as_ref()
1478 .and_then(|(workspace, _)| workspace.upgrade(cx))
1479 {
1480 workspace.update(cx, |workspace, cx| {
1481 Editor::jump(
1482 workspace,
1483 jump_path.clone(),
1484 jump_position,
1485 jump_anchor,
1486 cx,
1487 );
1488 });
1489 }
1490 })
1491 .with_tooltip::<JumpIcon>(
1492 id.into(),
1493 "Jump to Buffer".to_string(),
1494 Some(Box::new(crate::OpenExcerpts)),
1495 tooltip_style.clone(),
1496 cx,
1497 )
1498 .aligned()
1499 .flex_float()
1500 });
1501
1502 if *starts_new_buffer {
1503 let style = &self.style.diagnostic_path_header;
1504 let font_size =
1505 (style.text_scale_factor * self.style.text.font_size).round();
1506
1507 let path = buffer.resolve_file_path(cx, include_root);
1508 let mut filename = None;
1509 let mut parent_path = None;
1510 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1511 if let Some(path) = path {
1512 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1513 parent_path =
1514 path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1515 }
1516
1517 Flex::row()
1518 .with_child(
1519 Label::new(
1520 filename.unwrap_or_else(|| "untitled".to_string()),
1521 style.filename.text.clone().with_font_size(font_size),
1522 )
1523 .contained()
1524 .with_style(style.filename.container)
1525 .aligned(),
1526 )
1527 .with_children(parent_path.map(|path| {
1528 Label::new(path, style.path.text.clone().with_font_size(font_size))
1529 .contained()
1530 .with_style(style.path.container)
1531 .aligned()
1532 }))
1533 .with_children(jump_icon)
1534 .contained()
1535 .with_style(style.container)
1536 .with_padding_left(gutter_padding)
1537 .with_padding_right(gutter_padding)
1538 .expanded()
1539 .into_any_named("path header block")
1540 } else {
1541 let text_style = self.style.text.clone();
1542 Flex::row()
1543 .with_child(Label::new("⋯", text_style))
1544 .with_children(jump_icon)
1545 .contained()
1546 .with_padding_left(gutter_padding)
1547 .with_padding_right(gutter_padding)
1548 .expanded()
1549 .into_any_named("collapsed context")
1550 }
1551 }
1552 };
1553
1554 element.layout(
1555 SizeConstraint {
1556 min: Vector2F::zero(),
1557 max: vec2f(width, block.height() as f32 * line_height),
1558 },
1559 editor,
1560 cx,
1561 );
1562 element
1563 };
1564
1565 let mut fixed_block_max_width = 0f32;
1566 let mut blocks = Vec::new();
1567 for (row, block) in fixed_blocks {
1568 let element = render_block(block, f32::INFINITY);
1569 fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1570 blocks.push(BlockLayout {
1571 row,
1572 element,
1573 style: BlockStyle::Fixed,
1574 });
1575 }
1576 for (row, block) in non_fixed_blocks {
1577 let style = match block {
1578 TransformBlock::Custom(block) => block.style(),
1579 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1580 };
1581 let width = match style {
1582 BlockStyle::Sticky => editor_width,
1583 BlockStyle::Flex => editor_width
1584 .max(fixed_block_max_width)
1585 .max(gutter_width + scroll_width),
1586 BlockStyle::Fixed => unreachable!(),
1587 };
1588 let element = render_block(block, width);
1589 blocks.push(BlockLayout {
1590 row,
1591 element,
1592 style,
1593 });
1594 }
1595 (
1596 scroll_width.max(fixed_block_max_width - gutter_width),
1597 blocks,
1598 )
1599 }
1600}
1601
1602impl Element<Editor> for EditorElement {
1603 type LayoutState = LayoutState;
1604 type PaintState = ();
1605
1606 fn layout(
1607 &mut self,
1608 constraint: SizeConstraint,
1609 editor: &mut Editor,
1610 cx: &mut LayoutContext<Editor>,
1611 ) -> (Vector2F, Self::LayoutState) {
1612 let mut size = constraint.max;
1613 if size.x().is_infinite() {
1614 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1615 }
1616
1617 let snapshot = editor.snapshot(cx);
1618 let style = self.style.clone();
1619 let line_height = style.text.line_height(cx.font_cache());
1620
1621 let gutter_padding;
1622 let gutter_width;
1623 let gutter_margin;
1624 if snapshot.mode == EditorMode::Full {
1625 let em_width = style.text.em_width(cx.font_cache());
1626 gutter_padding = (em_width * style.gutter_padding_factor).round();
1627 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1628 gutter_margin = -style.text.descent(cx.font_cache());
1629 } else {
1630 gutter_padding = 0.0;
1631 gutter_width = 0.0;
1632 gutter_margin = 0.0;
1633 };
1634
1635 let text_width = size.x() - gutter_width;
1636 let em_width = style.text.em_width(cx.font_cache());
1637 let em_advance = style.text.em_advance(cx.font_cache());
1638 let overscroll = vec2f(em_width, 0.);
1639 let snapshot = {
1640 editor.set_visible_line_count(size.y() / line_height);
1641
1642 let editor_width = text_width - gutter_margin - overscroll.x() - em_width;
1643 let wrap_width = match editor.soft_wrap_mode(cx) {
1644 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
1645 SoftWrap::EditorWidth => editor_width,
1646 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
1647 };
1648
1649 if editor.set_wrap_width(Some(wrap_width), cx) {
1650 editor.snapshot(cx)
1651 } else {
1652 snapshot
1653 }
1654 };
1655
1656 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1657 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1658 size.set_y(
1659 scroll_height
1660 .min(constraint.max_along(Axis::Vertical))
1661 .max(constraint.min_along(Axis::Vertical))
1662 .min(line_height * max_lines as f32),
1663 )
1664 } else if let EditorMode::SingleLine = snapshot.mode {
1665 size.set_y(
1666 line_height
1667 .min(constraint.max_along(Axis::Vertical))
1668 .max(constraint.min_along(Axis::Vertical)),
1669 )
1670 } else if size.y().is_infinite() {
1671 size.set_y(scroll_height);
1672 }
1673 let gutter_size = vec2f(gutter_width, size.y());
1674 let text_size = vec2f(text_width, size.y());
1675
1676 let autoscroll_horizontally = editor.autoscroll_vertically(size.y(), line_height, cx);
1677 let mut snapshot = editor.snapshot(cx);
1678
1679 let scroll_position = snapshot.scroll_position();
1680 // The scroll position is a fractional point, the whole number of which represents
1681 // the top of the window in terms of display rows.
1682 let start_row = scroll_position.y() as u32;
1683 let height_in_lines = size.y() / line_height;
1684 let max_row = snapshot.max_point().row();
1685
1686 // Add 1 to ensure selections bleed off screen
1687 let end_row = 1 + cmp::min(
1688 (scroll_position.y() + height_in_lines).ceil() as u32,
1689 max_row,
1690 );
1691
1692 let start_anchor = if start_row == 0 {
1693 Anchor::min()
1694 } else {
1695 snapshot
1696 .buffer_snapshot
1697 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1698 };
1699 let end_anchor = if end_row > max_row {
1700 Anchor::max()
1701 } else {
1702 snapshot
1703 .buffer_snapshot
1704 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1705 };
1706
1707 let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1708 let mut active_rows = BTreeMap::new();
1709 let mut fold_ranges = Vec::new();
1710 let is_singleton = editor.is_singleton(cx);
1711
1712 let highlighted_rows = editor.highlighted_rows();
1713 let theme = cx.global::<Settings>().theme.as_ref();
1714 let highlighted_ranges = editor.background_highlights_in_range(
1715 start_anchor..end_anchor,
1716 &snapshot.display_snapshot,
1717 theme,
1718 );
1719
1720 fold_ranges.extend(
1721 snapshot
1722 .folds_in_range(start_anchor..end_anchor)
1723 .map(|anchor| {
1724 let start = anchor.start.to_point(&snapshot.buffer_snapshot);
1725 (
1726 start.row,
1727 start.to_display_point(&snapshot.display_snapshot)
1728 ..anchor.end.to_display_point(&snapshot),
1729 )
1730 }),
1731 );
1732
1733 let mut remote_selections = HashMap::default();
1734 for (replica_id, line_mode, cursor_shape, selection) in snapshot
1735 .buffer_snapshot
1736 .remote_selections_in_range(&(start_anchor..end_anchor))
1737 {
1738 // The local selections match the leader's selections.
1739 if Some(replica_id) == editor.leader_replica_id {
1740 continue;
1741 }
1742 remote_selections
1743 .entry(replica_id)
1744 .or_insert(Vec::new())
1745 .push(SelectionLayout::new(
1746 selection,
1747 line_mode,
1748 cursor_shape,
1749 &snapshot.display_snapshot,
1750 ));
1751 }
1752 selections.extend(remote_selections);
1753
1754 if editor.show_local_selections {
1755 let mut local_selections = editor
1756 .selections
1757 .disjoint_in_range(start_anchor..end_anchor, cx);
1758 local_selections.extend(editor.selections.pending(cx));
1759 for selection in &local_selections {
1760 let is_empty = selection.start == selection.end;
1761 let selection_start = snapshot.prev_line_boundary(selection.start).1;
1762 let selection_end = snapshot.next_line_boundary(selection.end).1;
1763 for row in cmp::max(selection_start.row(), start_row)
1764 ..=cmp::min(selection_end.row(), end_row)
1765 {
1766 let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
1767 *contains_non_empty_selection |= !is_empty;
1768 }
1769 }
1770
1771 // Render the local selections in the leader's color when following.
1772 let local_replica_id = editor
1773 .leader_replica_id
1774 .unwrap_or_else(|| editor.replica_id(cx));
1775
1776 selections.push((
1777 local_replica_id,
1778 local_selections
1779 .into_iter()
1780 .map(|selection| {
1781 SelectionLayout::new(
1782 selection,
1783 editor.selections.line_mode,
1784 editor.cursor_shape,
1785 &snapshot.display_snapshot,
1786 )
1787 })
1788 .collect(),
1789 ));
1790 }
1791
1792 let show_scrollbars = editor.scroll_manager.scrollbars_visible();
1793 let include_root = editor
1794 .project
1795 .as_ref()
1796 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1797 .unwrap_or_default();
1798
1799 let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
1800 .into_iter()
1801 .map(|(id, fold)| {
1802 let color = self
1803 .style
1804 .folds
1805 .ellipses
1806 .background
1807 .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize), false)
1808 .color;
1809
1810 (id, fold, color)
1811 })
1812 .collect();
1813
1814 let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
1815 start_row..end_row,
1816 &active_rows,
1817 is_singleton,
1818 &snapshot,
1819 cx,
1820 );
1821
1822 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
1823
1824 let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
1825
1826 let mut max_visible_line_width = 0.0;
1827 let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1828 for line in &line_layouts {
1829 if line.width() > max_visible_line_width {
1830 max_visible_line_width = line.width();
1831 }
1832 }
1833
1834 let style = self.style.clone();
1835 let longest_line_width = layout_line(
1836 snapshot.longest_row(),
1837 &snapshot,
1838 &style,
1839 cx.text_layout_cache(),
1840 )
1841 .width();
1842 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1843 let em_width = style.text.em_width(cx.font_cache());
1844 let (scroll_width, blocks) = self.layout_blocks(
1845 start_row..end_row,
1846 &snapshot,
1847 size.x(),
1848 scroll_width,
1849 gutter_padding,
1850 gutter_width,
1851 em_width,
1852 gutter_width + gutter_margin,
1853 line_height,
1854 &style,
1855 &line_layouts,
1856 include_root,
1857 editor,
1858 cx,
1859 );
1860
1861 let scroll_max = vec2f(
1862 ((scroll_width - text_size.x()) / em_width).max(0.0),
1863 max_row as f32,
1864 );
1865
1866 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x());
1867
1868 let autoscrolled = if autoscroll_horizontally {
1869 editor.autoscroll_horizontally(
1870 start_row,
1871 text_size.x(),
1872 scroll_width,
1873 em_width,
1874 &line_layouts,
1875 cx,
1876 )
1877 } else {
1878 false
1879 };
1880
1881 if clamped || autoscrolled {
1882 snapshot = editor.snapshot(cx);
1883 }
1884
1885 let newest_selection_head = editor
1886 .selections
1887 .newest::<usize>(cx)
1888 .head()
1889 .to_display_point(&snapshot);
1890 let style = editor.style(cx);
1891
1892 let mut context_menu = None;
1893 let mut code_actions_indicator = None;
1894 if (start_row..end_row).contains(&newest_selection_head.row()) {
1895 if editor.context_menu_visible() {
1896 context_menu = editor.render_context_menu(newest_selection_head, style.clone(), cx);
1897 }
1898
1899 let active = matches!(
1900 editor.context_menu,
1901 Some(crate::ContextMenu::CodeActions(_))
1902 );
1903
1904 code_actions_indicator = editor
1905 .render_code_actions_indicator(&style, active, cx)
1906 .map(|indicator| (newest_selection_head.row(), indicator));
1907 }
1908
1909 let visible_rows = start_row..start_row + line_layouts.len() as u32;
1910 let mut hover = editor
1911 .hover_state
1912 .render(&snapshot, &style, visible_rows, cx);
1913 let mode = editor.mode;
1914
1915 let mut fold_indicators = editor.render_fold_indicators(
1916 fold_statuses,
1917 &style,
1918 editor.gutter_hovered,
1919 line_height,
1920 gutter_margin,
1921 cx,
1922 );
1923
1924 if let Some((_, context_menu)) = context_menu.as_mut() {
1925 context_menu.layout(
1926 SizeConstraint {
1927 min: Vector2F::zero(),
1928 max: vec2f(
1929 cx.window_size().x() * 0.7,
1930 (12. * line_height).min((size.y() - line_height) / 2.),
1931 ),
1932 },
1933 editor,
1934 cx,
1935 );
1936 }
1937
1938 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1939 indicator.layout(
1940 SizeConstraint::strict_along(
1941 Axis::Vertical,
1942 line_height * style.code_actions.vertical_scale,
1943 ),
1944 editor,
1945 cx,
1946 );
1947 }
1948
1949 for fold_indicator in fold_indicators.iter_mut() {
1950 if let Some(indicator) = fold_indicator.as_mut() {
1951 indicator.layout(
1952 SizeConstraint::strict_along(
1953 Axis::Vertical,
1954 line_height * style.code_actions.vertical_scale,
1955 ),
1956 editor,
1957 cx,
1958 );
1959 }
1960 }
1961
1962 if let Some((_, hover_popovers)) = hover.as_mut() {
1963 for hover_popover in hover_popovers.iter_mut() {
1964 hover_popover.layout(
1965 SizeConstraint {
1966 min: Vector2F::zero(),
1967 max: vec2f(
1968 (120. * em_width) // Default size
1969 .min(size.x() / 2.) // Shrink to half of the editor width
1970 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1971 (16. * line_height) // Default size
1972 .min(size.y() / 2.) // Shrink to half of the editor height
1973 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1974 ),
1975 },
1976 editor,
1977 cx,
1978 );
1979 }
1980 }
1981
1982 (
1983 size,
1984 LayoutState {
1985 mode,
1986 position_map: Arc::new(PositionMap {
1987 size,
1988 scroll_max,
1989 line_layouts,
1990 line_height,
1991 em_width,
1992 em_advance,
1993 snapshot,
1994 }),
1995 visible_display_row_range: start_row..end_row,
1996 gutter_size,
1997 gutter_padding,
1998 text_size,
1999 scrollbar_row_range,
2000 show_scrollbars,
2001 max_row,
2002 gutter_margin,
2003 active_rows,
2004 highlighted_rows,
2005 highlighted_ranges,
2006 fold_ranges,
2007 line_number_layouts,
2008 display_hunks,
2009 blocks,
2010 selections,
2011 context_menu,
2012 code_actions_indicator,
2013 fold_indicators,
2014 hover_popovers: hover,
2015 },
2016 )
2017 }
2018
2019 fn paint(
2020 &mut self,
2021 scene: &mut SceneBuilder,
2022 bounds: RectF,
2023 visible_bounds: RectF,
2024 layout: &mut Self::LayoutState,
2025 editor: &mut Editor,
2026 cx: &mut ViewContext<Editor>,
2027 ) -> Self::PaintState {
2028 let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2029 scene.push_layer(Some(visible_bounds));
2030
2031 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
2032 let text_bounds = RectF::new(
2033 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2034 layout.text_size,
2035 );
2036
2037 Self::attach_mouse_handlers(
2038 scene,
2039 &layout.position_map,
2040 layout.hover_popovers.is_some(),
2041 visible_bounds,
2042 text_bounds,
2043 gutter_bounds,
2044 bounds,
2045 cx,
2046 );
2047
2048 self.paint_background(scene, gutter_bounds, text_bounds, layout);
2049 if layout.gutter_size.x() > 0. {
2050 self.paint_gutter(scene, gutter_bounds, visible_bounds, layout, editor, cx);
2051 }
2052 self.paint_text(scene, text_bounds, visible_bounds, layout, editor, cx);
2053
2054 scene.push_layer(Some(bounds));
2055 if !layout.blocks.is_empty() {
2056 self.paint_blocks(scene, bounds, visible_bounds, layout, editor, cx);
2057 }
2058 self.paint_scrollbar(scene, bounds, layout, cx);
2059 scene.pop_layer();
2060
2061 scene.pop_layer();
2062 }
2063
2064 fn rect_for_text_range(
2065 &self,
2066 range_utf16: Range<usize>,
2067 bounds: RectF,
2068 _: RectF,
2069 layout: &Self::LayoutState,
2070 _: &Self::PaintState,
2071 _: &Editor,
2072 _: &ViewContext<Editor>,
2073 ) -> Option<RectF> {
2074 let text_bounds = RectF::new(
2075 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2076 layout.text_size,
2077 );
2078 let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
2079 let scroll_position = layout.position_map.snapshot.scroll_position();
2080 let start_row = scroll_position.y() as u32;
2081 let scroll_top = scroll_position.y() * layout.position_map.line_height;
2082 let scroll_left = scroll_position.x() * layout.position_map.em_width;
2083
2084 let range_start = OffsetUtf16(range_utf16.start)
2085 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2086 if range_start.row() < start_row {
2087 return None;
2088 }
2089
2090 let line = layout
2091 .position_map
2092 .line_layouts
2093 .get((range_start.row() - start_row) as usize)?;
2094 let range_start_x = line.x_for_index(range_start.column() as usize);
2095 let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
2096 Some(RectF::new(
2097 content_origin
2098 + vec2f(
2099 range_start_x,
2100 range_start_y + layout.position_map.line_height,
2101 )
2102 - vec2f(scroll_left, scroll_top),
2103 vec2f(
2104 layout.position_map.em_width,
2105 layout.position_map.line_height,
2106 ),
2107 ))
2108 }
2109
2110 fn debug(
2111 &self,
2112 bounds: RectF,
2113 _: &Self::LayoutState,
2114 _: &Self::PaintState,
2115 _: &Editor,
2116 _: &ViewContext<Editor>,
2117 ) -> json::Value {
2118 json!({
2119 "type": "BufferElement",
2120 "bounds": bounds.to_json()
2121 })
2122 }
2123}
2124
2125type BufferRow = u32;
2126
2127pub struct LayoutState {
2128 position_map: Arc<PositionMap>,
2129 gutter_size: Vector2F,
2130 gutter_padding: f32,
2131 gutter_margin: f32,
2132 text_size: Vector2F,
2133 mode: EditorMode,
2134 visible_display_row_range: Range<u32>,
2135 active_rows: BTreeMap<u32, bool>,
2136 highlighted_rows: Option<Range<u32>>,
2137 line_number_layouts: Vec<Option<text_layout::Line>>,
2138 display_hunks: Vec<DisplayDiffHunk>,
2139 blocks: Vec<BlockLayout>,
2140 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2141 fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)>,
2142 selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
2143 scrollbar_row_range: Range<f32>,
2144 show_scrollbars: bool,
2145 max_row: u32,
2146 context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
2147 code_actions_indicator: Option<(u32, AnyElement<Editor>)>,
2148 hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
2149 fold_indicators: Vec<Option<AnyElement<Editor>>>,
2150}
2151
2152pub struct PositionMap {
2153 size: Vector2F,
2154 line_height: f32,
2155 scroll_max: Vector2F,
2156 em_width: f32,
2157 em_advance: f32,
2158 line_layouts: Vec<text_layout::Line>,
2159 snapshot: EditorSnapshot,
2160}
2161
2162impl PositionMap {
2163 /// Returns two display points:
2164 /// 1. The nearest *valid* position in the editor
2165 /// 2. An unclipped, potentially *invalid* position that maps directly to
2166 /// the given pixel position.
2167 fn point_for_position(
2168 &self,
2169 text_bounds: RectF,
2170 position: Vector2F,
2171 ) -> (DisplayPoint, DisplayPoint) {
2172 let scroll_position = self.snapshot.scroll_position();
2173 let position = position - text_bounds.origin();
2174 let y = position.y().max(0.0).min(self.size.y());
2175 let x = position.x() + (scroll_position.x() * self.em_width);
2176 let row = (y / self.line_height + scroll_position.y()) as u32;
2177 let (column, x_overshoot) = if let Some(line) = self
2178 .line_layouts
2179 .get(row as usize - scroll_position.y() as usize)
2180 {
2181 if let Some(ix) = line.index_for_x(x) {
2182 (ix as u32, 0.0)
2183 } else {
2184 (line.len() as u32, 0f32.max(x - line.width()))
2185 }
2186 } else {
2187 (0, x)
2188 };
2189
2190 let mut target_point = DisplayPoint::new(row, column);
2191 let point = self.snapshot.clip_point(target_point, Bias::Left);
2192 *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
2193
2194 (point, target_point)
2195 }
2196}
2197
2198struct BlockLayout {
2199 row: u32,
2200 element: AnyElement<Editor>,
2201 style: BlockStyle,
2202}
2203
2204fn layout_line(
2205 row: u32,
2206 snapshot: &EditorSnapshot,
2207 style: &EditorStyle,
2208 layout_cache: &TextLayoutCache,
2209) -> text_layout::Line {
2210 let mut line = snapshot.line(row);
2211
2212 if line.len() > MAX_LINE_LEN {
2213 let mut len = MAX_LINE_LEN;
2214 while !line.is_char_boundary(len) {
2215 len -= 1;
2216 }
2217
2218 line.truncate(len);
2219 }
2220
2221 layout_cache.layout_str(
2222 &line,
2223 style.text.font_size,
2224 &[(
2225 snapshot.line_len(row) as usize,
2226 RunStyle {
2227 font_id: style.text.font_id,
2228 color: Color::black(),
2229 underline: Default::default(),
2230 },
2231 )],
2232 )
2233}
2234
2235#[derive(Debug)]
2236pub struct Cursor {
2237 origin: Vector2F,
2238 block_width: f32,
2239 line_height: f32,
2240 color: Color,
2241 shape: CursorShape,
2242 block_text: Option<Line>,
2243}
2244
2245impl Cursor {
2246 pub fn new(
2247 origin: Vector2F,
2248 block_width: f32,
2249 line_height: f32,
2250 color: Color,
2251 shape: CursorShape,
2252 block_text: Option<Line>,
2253 ) -> Cursor {
2254 Cursor {
2255 origin,
2256 block_width,
2257 line_height,
2258 color,
2259 shape,
2260 block_text,
2261 }
2262 }
2263
2264 pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2265 RectF::new(
2266 self.origin + origin,
2267 vec2f(self.block_width, self.line_height),
2268 )
2269 }
2270
2271 pub fn paint(&self, scene: &mut SceneBuilder, origin: Vector2F, cx: &mut WindowContext) {
2272 let bounds = match self.shape {
2273 CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2274 CursorShape::Block | CursorShape::Hollow => RectF::new(
2275 self.origin + origin,
2276 vec2f(self.block_width, self.line_height),
2277 ),
2278 CursorShape::Underscore => RectF::new(
2279 self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2280 vec2f(self.block_width, 2.0),
2281 ),
2282 };
2283
2284 //Draw background or border quad
2285 if matches!(self.shape, CursorShape::Hollow) {
2286 scene.push_quad(Quad {
2287 bounds,
2288 background: None,
2289 border: Border::all(1., self.color),
2290 corner_radius: 0.,
2291 });
2292 } else {
2293 scene.push_quad(Quad {
2294 bounds,
2295 background: Some(self.color),
2296 border: Default::default(),
2297 corner_radius: 0.,
2298 });
2299 }
2300
2301 if let Some(block_text) = &self.block_text {
2302 block_text.paint(scene, self.origin + origin, bounds, self.line_height, cx);
2303 }
2304 }
2305
2306 pub fn shape(&self) -> CursorShape {
2307 self.shape
2308 }
2309}
2310
2311#[derive(Debug)]
2312pub struct HighlightedRange {
2313 pub start_y: f32,
2314 pub line_height: f32,
2315 pub lines: Vec<HighlightedRangeLine>,
2316 pub color: Color,
2317 pub corner_radius: f32,
2318}
2319
2320#[derive(Debug)]
2321pub struct HighlightedRangeLine {
2322 pub start_x: f32,
2323 pub end_x: f32,
2324}
2325
2326impl HighlightedRange {
2327 pub fn paint(&self, bounds: RectF, scene: &mut SceneBuilder) {
2328 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2329 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2330 self.paint_lines(
2331 self.start_y + self.line_height,
2332 &self.lines[1..],
2333 bounds,
2334 scene,
2335 );
2336 } else {
2337 self.paint_lines(self.start_y, &self.lines, bounds, scene);
2338 }
2339 }
2340
2341 fn paint_lines(
2342 &self,
2343 start_y: f32,
2344 lines: &[HighlightedRangeLine],
2345 bounds: RectF,
2346 scene: &mut SceneBuilder,
2347 ) {
2348 if lines.is_empty() {
2349 return;
2350 }
2351
2352 let mut path = PathBuilder::new();
2353 let first_line = lines.first().unwrap();
2354 let last_line = lines.last().unwrap();
2355
2356 let first_top_left = vec2f(first_line.start_x, start_y);
2357 let first_top_right = vec2f(first_line.end_x, start_y);
2358
2359 let curve_height = vec2f(0., self.corner_radius);
2360 let curve_width = |start_x: f32, end_x: f32| {
2361 let max = (end_x - start_x) / 2.;
2362 let width = if max < self.corner_radius {
2363 max
2364 } else {
2365 self.corner_radius
2366 };
2367
2368 vec2f(width, 0.)
2369 };
2370
2371 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2372 path.reset(first_top_right - top_curve_width);
2373 path.curve_to(first_top_right + curve_height, first_top_right);
2374
2375 let mut iter = lines.iter().enumerate().peekable();
2376 while let Some((ix, line)) = iter.next() {
2377 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2378
2379 if let Some((_, next_line)) = iter.peek() {
2380 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2381
2382 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2383 Ordering::Equal => {
2384 path.line_to(bottom_right);
2385 }
2386 Ordering::Less => {
2387 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2388 path.line_to(bottom_right - curve_height);
2389 if self.corner_radius > 0. {
2390 path.curve_to(bottom_right - curve_width, bottom_right);
2391 }
2392 path.line_to(next_top_right + curve_width);
2393 if self.corner_radius > 0. {
2394 path.curve_to(next_top_right + curve_height, next_top_right);
2395 }
2396 }
2397 Ordering::Greater => {
2398 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2399 path.line_to(bottom_right - curve_height);
2400 if self.corner_radius > 0. {
2401 path.curve_to(bottom_right + curve_width, bottom_right);
2402 }
2403 path.line_to(next_top_right - curve_width);
2404 if self.corner_radius > 0. {
2405 path.curve_to(next_top_right + curve_height, next_top_right);
2406 }
2407 }
2408 }
2409 } else {
2410 let curve_width = curve_width(line.start_x, line.end_x);
2411 path.line_to(bottom_right - curve_height);
2412 if self.corner_radius > 0. {
2413 path.curve_to(bottom_right - curve_width, bottom_right);
2414 }
2415
2416 let bottom_left = vec2f(line.start_x, bottom_right.y());
2417 path.line_to(bottom_left + curve_width);
2418 if self.corner_radius > 0. {
2419 path.curve_to(bottom_left - curve_height, bottom_left);
2420 }
2421 }
2422 }
2423
2424 if first_line.start_x > last_line.start_x {
2425 let curve_width = curve_width(last_line.start_x, first_line.start_x);
2426 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2427 path.line_to(second_top_left + curve_height);
2428 if self.corner_radius > 0. {
2429 path.curve_to(second_top_left + curve_width, second_top_left);
2430 }
2431 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2432 path.line_to(first_bottom_left - curve_width);
2433 if self.corner_radius > 0. {
2434 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2435 }
2436 }
2437
2438 path.line_to(first_top_left + curve_height);
2439 if self.corner_radius > 0. {
2440 path.curve_to(first_top_left + top_curve_width, first_top_left);
2441 }
2442 path.line_to(first_top_right - top_curve_width);
2443
2444 scene.push_path(path.build(self.color, Some(bounds)));
2445 }
2446}
2447
2448pub fn position_to_display_point(
2449 position: Vector2F,
2450 text_bounds: RectF,
2451 position_map: &PositionMap,
2452) -> Option<DisplayPoint> {
2453 if text_bounds.contains_point(position) {
2454 let (point, target_point) = position_map.point_for_position(text_bounds, position);
2455 if point == target_point {
2456 Some(point)
2457 } else {
2458 None
2459 }
2460 } else {
2461 None
2462 }
2463}
2464
2465pub fn range_to_bounds(
2466 range: &Range<DisplayPoint>,
2467 content_origin: Vector2F,
2468 scroll_left: f32,
2469 scroll_top: f32,
2470 visible_row_range: &Range<u32>,
2471 line_end_overshoot: f32,
2472 position_map: &PositionMap,
2473) -> impl Iterator<Item = RectF> {
2474 let mut bounds: SmallVec<[RectF; 1]> = SmallVec::new();
2475
2476 if range.start == range.end {
2477 return bounds.into_iter();
2478 }
2479
2480 let start_row = visible_row_range.start;
2481 let end_row = visible_row_range.end;
2482
2483 let row_range = if range.end.column() == 0 {
2484 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2485 } else {
2486 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2487 };
2488
2489 let first_y =
2490 content_origin.y() + row_range.start as f32 * position_map.line_height - scroll_top;
2491
2492 for (idx, row) in row_range.enumerate() {
2493 let line_layout = &position_map.line_layouts[(row - start_row) as usize];
2494
2495 let start_x = if row == range.start.row() {
2496 content_origin.x() + line_layout.x_for_index(range.start.column() as usize)
2497 - scroll_left
2498 } else {
2499 content_origin.x() - scroll_left
2500 };
2501
2502 let end_x = if row == range.end.row() {
2503 content_origin.x() + line_layout.x_for_index(range.end.column() as usize) - scroll_left
2504 } else {
2505 content_origin.x() + line_layout.width() + line_end_overshoot - scroll_left
2506 };
2507
2508 bounds.push(RectF::from_points(
2509 vec2f(start_x, first_y + position_map.line_height * idx as f32),
2510 vec2f(end_x, first_y + position_map.line_height * (idx + 1) as f32),
2511 ))
2512 }
2513
2514 bounds.into_iter()
2515}
2516
2517pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2518 delta.powf(1.5) / 100.0
2519}
2520
2521fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
2522 delta.powf(1.2) / 300.0
2523}
2524
2525#[cfg(test)]
2526mod tests {
2527 use super::*;
2528 use crate::{
2529 display_map::{BlockDisposition, BlockProperties},
2530 Editor, MultiBuffer,
2531 };
2532 use gpui::TestAppContext;
2533 use settings::Settings;
2534 use std::sync::Arc;
2535 use util::test::sample_text;
2536
2537 #[gpui::test]
2538 fn test_layout_line_numbers(cx: &mut TestAppContext) {
2539 cx.update(|cx| cx.set_global(Settings::test(cx)));
2540 let (_, editor) = cx.add_window(|cx| {
2541 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
2542 Editor::new(EditorMode::Full, buffer, None, None, cx)
2543 });
2544 let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
2545
2546 let layouts = editor.update(cx, |editor, cx| {
2547 let snapshot = editor.snapshot(cx);
2548 element
2549 .layout_line_numbers(0..6, &Default::default(), false, &snapshot, cx)
2550 .0
2551 });
2552 assert_eq!(layouts.len(), 6);
2553 }
2554
2555 #[gpui::test]
2556 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
2557 cx.update(|cx| cx.set_global(Settings::test(cx)));
2558 let (_, editor) = cx.add_window(|cx| {
2559 let buffer = MultiBuffer::build_simple("", cx);
2560 Editor::new(EditorMode::Full, buffer, None, None, cx)
2561 });
2562
2563 editor.update(cx, |editor, cx| {
2564 editor.set_placeholder_text("hello", cx);
2565 editor.insert_blocks(
2566 [BlockProperties {
2567 style: BlockStyle::Fixed,
2568 disposition: BlockDisposition::Above,
2569 height: 3,
2570 position: Anchor::min(),
2571 render: Arc::new(|_| Empty::new().into_any()),
2572 }],
2573 cx,
2574 );
2575
2576 // Blur the editor so that it displays placeholder text.
2577 cx.blur();
2578 });
2579
2580 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
2581 let (size, mut state) = editor.update(cx, |editor, cx| {
2582 let mut new_parents = Default::default();
2583 let mut notify_views_if_parents_change = Default::default();
2584 let mut layout_cx = LayoutContext::new(
2585 cx,
2586 &mut new_parents,
2587 &mut notify_views_if_parents_change,
2588 false,
2589 );
2590 element.layout(
2591 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
2592 editor,
2593 &mut layout_cx,
2594 )
2595 });
2596
2597 assert_eq!(state.position_map.line_layouts.len(), 4);
2598 assert_eq!(
2599 state
2600 .line_number_layouts
2601 .iter()
2602 .map(Option::is_some)
2603 .collect::<Vec<_>>(),
2604 &[false, false, false, true]
2605 );
2606
2607 // Don't panic.
2608 let mut scene = SceneBuilder::new(1.0);
2609 let bounds = RectF::new(Default::default(), size);
2610 editor.update(cx, |editor, cx| {
2611 element.paint(&mut scene, bounds, bounds, &mut state, editor, cx);
2612 });
2613 }
2614}