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