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