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