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